agglomerative-clustering 3.6.0 → 3.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/clustering.cjs +1 -1
- package/dist/clustering.js +1 -1
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +148 -17
- package/dist/index.d.cts +13 -15
- package/dist/index.d.ts +13 -15
- package/dist/index.mjs +148 -17
- package/dist/shared.cjs +1 -1
- package/dist/shared.mjs +1 -1
- package/dist/worker-thread.mjs +2 -2
- package/dist/worker.cjs +6 -8
- package/dist/worker.mjs +6 -8
- package/package.json +2 -2
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
|
|
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
|
|
package/dist/clustering.cjs
CHANGED
|
@@ -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;
|
package/dist/clustering.js
CHANGED
|
@@ -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;
|
package/dist/clustering.wasm
CHANGED
|
Binary file
|
package/dist/index.cjs
CHANGED
|
@@ -190,7 +190,13 @@ const isBrowserLike = () => typeof document !== 'undefined' || typeof WorkerGlob
|
|
|
190
190
|
const deployAdvice = "In a serverless deployment (AWS Lambda, Vercel or Netlify functions), the bundler or file tracer may have left the package's dist/ files out: include node_modules/agglomerative-clustering/dist in the function's files, or leave the package unbundled (external).";
|
|
191
191
|
// Emscripten appends advice about its own debug build, which doesn't apply to this package's users.
|
|
192
192
|
const assertionsAdvice = /\s*\(?Build with -sASSERTIONS for more info\.?\)?/;
|
|
193
|
-
|
|
193
|
+
// Whether init({ wasm }) was given bytes that start with gzip's magic (1f 8b): a gzipped module passed without decompressing.
|
|
194
|
+
const isGzipped = wasm => {
|
|
195
|
+
const tag = Object.prototype.toString.call(wasm);
|
|
196
|
+
const bytes = tag === '[object ArrayBuffer]' ? new Uint8Array(wasm) : ArrayBuffer.isView(wasm) ? new Uint8Array(wasm.buffer, wasm.byteOffset, wasm.byteLength) : null;
|
|
197
|
+
return bytes !== null && bytes.length >= 2 && bytes[0] === 0x1f && bytes[1] === 0x8b;
|
|
198
|
+
};
|
|
199
|
+
const wasmLoadFailed = (cause, given, gzipped = false) => {
|
|
194
200
|
const text = String(cause && cause.message !== undefined ? cause.message : cause).split('\n')[0];
|
|
195
201
|
// Emscripten wraps a failed compile in Aborted(...), which is how it stops itself, not part of the reason.
|
|
196
202
|
let reason = text.replace(assertionsAdvice, '').trim().replace(/\.+$/, '');
|
|
@@ -221,6 +227,10 @@ const wasmLoadFailed = (cause, given) => {
|
|
|
221
227
|
advice = "A Content-Security-Policy blocks compiling WebAssembly: add 'wasm-unsafe-eval' to the script-src of the policy that applies. That is the page's for a page and for the worker entry's worker (also when started from a content script, whose worker follows the page's policy); for a browser extension's own pages, offscreen document and service worker, it is content_security_policy.extension_pages in the manifest.";
|
|
222
228
|
} else if (!hasSimd()) {
|
|
223
229
|
advice = "This engine has no WebAssembly SIMD, which the module needs (Chrome and Edge 91, Firefox 89, Safari 16.4, Node 16.4 or newer).";
|
|
230
|
+
} else if (gzipped) {
|
|
231
|
+
// Engines word this differently (V8 and Firefox name the magic number, Safari doesn't), so it goes by the bytes.
|
|
232
|
+
reason = `the bytes given to init({ wasm }) are gzipped (they start with 1f 8b), not a WebAssembly module (${reason})`;
|
|
233
|
+
advice = "Decompress them first, for example with new Response(new Blob([bytes]).stream().pipeThrough(new DecompressionStream('gzip'))).arrayBuffer(), and pass the result (see Plugins and single-file hosts in https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/environments.md).";
|
|
224
234
|
} else if (/magic (word|number)|BufferSource argument is empty|wasm validation error: at offset [0-4]:/i.test(text)) {
|
|
225
235
|
// What a 404 page, or a server's fallback HTML page, looks like once it has been compiled as WebAssembly.
|
|
226
236
|
if (given === true) {
|
|
@@ -398,13 +408,16 @@ const acquire = async options => {
|
|
|
398
408
|
// way Node resolves packages, from the working directory; if that fails too, the first error is reported.
|
|
399
409
|
const fallback = wasm === undefined && isNodeLike ? await packagedWasm().catch(() => null) : null;
|
|
400
410
|
if (!fallback) {
|
|
401
|
-
throw wasmLoadFailed(error, typeof wasm === 'string' ? wasm : isURL(wasm) ? wasm.href : wasm !== undefined);
|
|
411
|
+
throw wasmLoadFailed(error, typeof wasm === 'string' ? wasm : isURL(wasm) ? wasm.href : wasm !== undefined, isGzipped(wasm));
|
|
402
412
|
}
|
|
403
413
|
instance = await instantiate(fallback).catch(() => {
|
|
404
414
|
throw wasmLoadFailed(error, false);
|
|
405
415
|
});
|
|
406
416
|
}
|
|
407
417
|
checkWasmVersion(instance);
|
|
418
|
+
if (instance.HEAPU8) {
|
|
419
|
+
startSizes.set(instance, instance.HEAPU8.length);
|
|
420
|
+
}
|
|
408
421
|
Module = instance;
|
|
409
422
|
return instance;
|
|
410
423
|
})().catch(error => {
|
|
@@ -436,10 +449,14 @@ const discard = instance => {
|
|
|
436
449
|
// WebAssembly memory only grows: an instance that once held a huge image keeps all that memory for the life of the process.
|
|
437
450
|
// So when a call leaves the heap larger than this, the instance is retired like an aborted one: calls already running keep
|
|
438
451
|
// it, the next call loads a fresh one (a few milliseconds, next to the seconds such an image took), and the old memory is
|
|
439
|
-
// freed when nothing uses it any more.
|
|
440
|
-
|
|
452
|
+
// freed when nothing uses it any more. The limit counts growth from the size the instance started at (32 MB in the
|
|
453
|
+
// release build), so a build that starts larger, such as the sanitized one scripts/asan-test.sh uses (512 MB, for its
|
|
454
|
+
// shadow memory), isn't retired after every call.
|
|
455
|
+
const releaseStart = 32 * 1024 * 1024; // INITIAL_MEMORY in build:wasm
|
|
456
|
+
const retireAfter = 256 * 1024 * 1024 - releaseStart; // so the release build retires above 256 MB, as before
|
|
457
|
+
const startSizes = new WeakMap();
|
|
441
458
|
const retireIfLarge = instance => {
|
|
442
|
-
if (instance.HEAPU8 && instance.HEAPU8.length >
|
|
459
|
+
if (instance.HEAPU8 && instance.HEAPU8.length > (startSizes.get(instance) ?? releaseStart) + retireAfter) {
|
|
443
460
|
discard(instance);
|
|
444
461
|
}
|
|
445
462
|
};
|
|
@@ -645,7 +662,8 @@ const check = k => {
|
|
|
645
662
|
// precision: bits per channel, 1-8 (default 8, exact); lower values group similar colours before clustering
|
|
646
663
|
// dither: false (default), true or a strength in [0, 1] (Floyd-Steinberg), a method name, or { method, strength, steps } (see parseDither)
|
|
647
664
|
// 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
|
|
665
|
+
// signal, onProgress: an AbortSignal and a progress callback, which make the clustering and the mapping run in slices
|
|
666
|
+
// (see clusterInSlices and mapInSlices)
|
|
649
667
|
// 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
668
|
// indexed output also gives them their own entry, which counts towards k
|
|
651
669
|
|
|
@@ -662,7 +680,7 @@ const parseOptions = (options, allowed, image) => {
|
|
|
662
680
|
options = (0, _shared.snapshot)(options);
|
|
663
681
|
for (const key of Object.keys(options)) {
|
|
664
682
|
if (!allowed.includes(key)) {
|
|
665
|
-
const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' :
|
|
683
|
+
const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' : '';
|
|
666
684
|
throw (0, _shared.fail)('invalid-argument', `Invalid option '${key}': expected one of ${allowed.join(', ')}.${hint}`, `options.${key}`);
|
|
667
685
|
}
|
|
668
686
|
}
|
|
@@ -740,9 +758,7 @@ const parseOptions = (options, allowed, image) => {
|
|
|
740
758
|
const controlOptions = ['signal', 'onProgress'];
|
|
741
759
|
const clusterOptions = ['colorSpace', 'precision', 'alpha', 'transparent', ...controlOptions];
|
|
742
760
|
const quantizeOptions = [...clusterOptions, 'dither', 'width'];
|
|
743
|
-
|
|
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'];
|
|
761
|
+
const mapOptions = ['colorSpace', 'dither', 'width', ...controlOptions];
|
|
746
762
|
const quantizeIndexOptions = quantizeOptions;
|
|
747
763
|
const mapIndexOptions = [...mapOptions, 'transparent'];
|
|
748
764
|
|
|
@@ -819,7 +835,7 @@ const call = (wasm, buffers, fn, precision) => {
|
|
|
819
835
|
};
|
|
820
836
|
|
|
821
837
|
// ----- Interruptible work -------------------------------------------------------------------------------------------
|
|
822
|
-
// A call given a `signal` or an `onProgress` runs its clustering in slices of about `sliceMs` milliseconds, giving the
|
|
838
|
+
// A call given a `signal` or an `onProgress` runs its clustering and its mapping in slices of about `sliceMs` milliseconds, giving the
|
|
823
839
|
// event loop a turn between them: the signal is checked (and progress reported) each time, other tasks can run, and
|
|
824
840
|
// in a worker thread the cancel message is read. Without either the call runs in one go, as it always did. The
|
|
825
841
|
// result is the same either way: the slices are the same steps in the same order.
|
|
@@ -868,6 +884,20 @@ const reporter = o => {
|
|
|
868
884
|
};
|
|
869
885
|
const isControlled = o => o.signal !== undefined || o.onProgress !== undefined;
|
|
870
886
|
|
|
887
|
+
// The share of quantize's and quantizeToIndices' progress that clustering takes, the rest being mapping. It only shapes
|
|
888
|
+
// the progress bar, so it is internal and can be retuned. Mapping's time relative to clustering's, measured on the 24
|
|
889
|
+
// Kodak photos (medians; bench/spikes/slicing-mapping/split.mjs → results-split.txt): undithered 0.1, Floyd–Steinberg
|
|
890
|
+
// 0.45, Atkinson 0.37, ordered 0.8 at 16 steps and about proportional to the steps; clustering below full precision is
|
|
891
|
+
// about 2.5 times faster. Steps not given are 64 for a palette of two colours, else 16, as in the C.
|
|
892
|
+
const mappingCost = [0.45, 0.37];
|
|
893
|
+
const clusteringShare = (o, k) => {
|
|
894
|
+
const dithered = o.dither > 0 && o.width > 0;
|
|
895
|
+
const ordered = dithered && o.ditherMethod === 2;
|
|
896
|
+
const steps = o.ditherSteps || (k <= 2 ? 64 : 16);
|
|
897
|
+
const cost = (!dithered ? 0.1 : ordered ? 0.8 * steps / 16 : mappingCost[o.ditherMethod]) * (o.precision < 8 ? 2.5 : 1);
|
|
898
|
+
return 1 / (1 + cost);
|
|
899
|
+
};
|
|
900
|
+
|
|
871
901
|
// Clusters in slices and returns the clustering. `share` is the part of the whole call's progress this takes.
|
|
872
902
|
const clusterInSlices = async (wasm, image, o, report, share) => {
|
|
873
903
|
checkAborted(o.signal);
|
|
@@ -911,6 +941,67 @@ const clusterInSlices = async (wasm, image, o, report, share) => {
|
|
|
911
941
|
}
|
|
912
942
|
};
|
|
913
943
|
|
|
944
|
+
// Maps in slices and returns the output's payload, as `call` does for the one-shot exports. The palette is
|
|
945
|
+
// `source.palette`, or cut from `source.clustering` to `source.k` colours (a negative `colorSpace` then matches in the
|
|
946
|
+
// clustering's space). `indices` chooses indexed output, with `cutoff`. Progress goes from `from` to 1. A call that
|
|
947
|
+
// finishes in its first slice doesn't yield.
|
|
948
|
+
const mapInSlices = async (wasm, image, source, colorSpace, indices, cutoff, o, report, from) => {
|
|
949
|
+
checkAborted(o.signal);
|
|
950
|
+
const bytes = source.palette || source.clustering;
|
|
951
|
+
const imagePointer = allocate(wasm, image.data.length);
|
|
952
|
+
let sourcePointer = 0;
|
|
953
|
+
let job = 0;
|
|
954
|
+
let aborted = false;
|
|
955
|
+
try {
|
|
956
|
+
sourcePointer = allocate(wasm, bytes.length);
|
|
957
|
+
wasm.HEAPU8.set(image.data, imagePointer);
|
|
958
|
+
wasm.HEAPU8.set(bytes, sourcePointer);
|
|
959
|
+
const palette = source.palette ? sourcePointer : 0,
|
|
960
|
+
clustering = source.clustering ? sourcePointer : 0;
|
|
961
|
+
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);
|
|
962
|
+
if (!job) {
|
|
963
|
+
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');
|
|
964
|
+
}
|
|
965
|
+
// The job has its own copy of the palette, so the source can go now.
|
|
966
|
+
wasm._free(sourcePointer);
|
|
967
|
+
sourcePointer = 0;
|
|
968
|
+
report(from);
|
|
969
|
+
while (true) {
|
|
970
|
+
const progress = wasm._mapping_job_step(job, sliceMs);
|
|
971
|
+
if (progress >= 1000) {
|
|
972
|
+
break;
|
|
973
|
+
}
|
|
974
|
+
report(from + (1 - from) * progress / 1000);
|
|
975
|
+
await yieldNow();
|
|
976
|
+
checkAborted(o.signal);
|
|
977
|
+
}
|
|
978
|
+
const pointer = wasm._mapping_job_result(job);
|
|
979
|
+
try {
|
|
980
|
+
return unpack(wasm, pointer);
|
|
981
|
+
} finally {
|
|
982
|
+
wasm._free(pointer);
|
|
983
|
+
}
|
|
984
|
+
} catch (error) {
|
|
985
|
+
if (!isAbort(error)) {
|
|
986
|
+
throw error;
|
|
987
|
+
}
|
|
988
|
+
aborted = true;
|
|
989
|
+
discard(wasm);
|
|
990
|
+
throw outOfMemory(image.data.length, o.precision);
|
|
991
|
+
} finally {
|
|
992
|
+
if (!aborted) {
|
|
993
|
+
if (job) {
|
|
994
|
+
wasm._mapping_job_free(job);
|
|
995
|
+
}
|
|
996
|
+
if (sourcePointer) {
|
|
997
|
+
wasm._free(sourcePointer);
|
|
998
|
+
}
|
|
999
|
+
wasm._free(imagePointer);
|
|
1000
|
+
retireIfLarge(wasm);
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
};
|
|
1004
|
+
|
|
914
1005
|
// The functions that read a clustering take no options: a clustering already says how it was made. An options object passed
|
|
915
1006
|
// anyway (say { colorSpace: 'oklab' }, expecting it to apply) would be silently ignored, so it is an error. undefined is fine.
|
|
916
1007
|
// `name` is how the caller wrote the call: the function, or the method (`clustering.getPalette`), whose message points at
|
|
@@ -1093,9 +1184,12 @@ const quantize = async (image, k, options) => {
|
|
|
1093
1184
|
const wasm = Module || (await acquire());
|
|
1094
1185
|
if (isControlled(o)) {
|
|
1095
1186
|
const report = reporter(o);
|
|
1096
|
-
const
|
|
1097
|
-
|
|
1098
|
-
const mapped = wrap(
|
|
1187
|
+
const share = clusteringShare(o, k);
|
|
1188
|
+
const clustering = await clusterInSlices(wasm, image, o, report, share);
|
|
1189
|
+
const mapped = wrap(await mapInSlices(wasm, image, {
|
|
1190
|
+
clustering,
|
|
1191
|
+
k
|
|
1192
|
+
}, o.colorSpace, false, 0, o, report, share));
|
|
1099
1193
|
report(1);
|
|
1100
1194
|
return mapped;
|
|
1101
1195
|
}
|
|
@@ -1114,6 +1208,15 @@ const quantizeFromClustering = async (image, clustering, k, options) => {
|
|
|
1114
1208
|
const wasm = Module || (await acquire());
|
|
1115
1209
|
checkAborted(o.signal);
|
|
1116
1210
|
const colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
|
|
1211
|
+
if (isControlled(o)) {
|
|
1212
|
+
const report = reporter(o);
|
|
1213
|
+
const mapped = wrap(await mapInSlices(wasm, image, {
|
|
1214
|
+
clustering,
|
|
1215
|
+
k
|
|
1216
|
+
}, colorSpace, false, 0, o, report, 0));
|
|
1217
|
+
report(1);
|
|
1218
|
+
return mapped;
|
|
1219
|
+
}
|
|
1117
1220
|
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
1221
|
return result;
|
|
1119
1222
|
};
|
|
@@ -1130,6 +1233,14 @@ const quantizeWithPalette = async (image, palette, options) => {
|
|
|
1130
1233
|
warn(o.signal);
|
|
1131
1234
|
const wasm = Module || (await acquire());
|
|
1132
1235
|
checkAborted(o.signal);
|
|
1236
|
+
if (isControlled(o)) {
|
|
1237
|
+
const report = reporter(o);
|
|
1238
|
+
const mapped = wrap(await mapInSlices(wasm, image, {
|
|
1239
|
+
palette
|
|
1240
|
+
}, space, false, 0, o, report, 0));
|
|
1241
|
+
report(1);
|
|
1242
|
+
return mapped;
|
|
1243
|
+
}
|
|
1133
1244
|
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
1245
|
return result;
|
|
1135
1246
|
};
|
|
@@ -1144,9 +1255,12 @@ const quantizeToIndices = async (image, k, options) => {
|
|
|
1144
1255
|
const wasm = Module || (await acquire());
|
|
1145
1256
|
if (isControlled(o)) {
|
|
1146
1257
|
const report = reporter(o);
|
|
1147
|
-
const
|
|
1148
|
-
|
|
1149
|
-
const indexed = unpackIndices(
|
|
1258
|
+
const share = clusteringShare(o, k);
|
|
1259
|
+
const clustering = await clusterInSlices(wasm, image, o, report, share);
|
|
1260
|
+
const indexed = unpackIndices(await mapInSlices(wasm, image, {
|
|
1261
|
+
clustering,
|
|
1262
|
+
k
|
|
1263
|
+
}, o.colorSpace, true, o.transparent, o, report, share), original, (0, _shared.colorSpaceName)(o.colorSpace));
|
|
1150
1264
|
report(1);
|
|
1151
1265
|
return indexed;
|
|
1152
1266
|
}
|
|
@@ -1168,6 +1282,15 @@ const quantizeToIndicesFromClustering = async (image, clustering, k, options) =>
|
|
|
1168
1282
|
|
|
1169
1283
|
// The cutoff the clustering was made with is the default, so clustering and mapping agree unless a cutoff is named.
|
|
1170
1284
|
const cutoff = o.transparentGiven ? o.transparent : header.transparent;
|
|
1285
|
+
if (isControlled(o)) {
|
|
1286
|
+
const report = reporter(o);
|
|
1287
|
+
const indexed = unpackIndices(await mapInSlices(wasm, image, {
|
|
1288
|
+
clustering,
|
|
1289
|
+
k
|
|
1290
|
+
}, colorSpace, true, cutoff, o, report, 0), original, (0, _shared.colorSpaceName)(header.colorSpace));
|
|
1291
|
+
report(1);
|
|
1292
|
+
return indexed;
|
|
1293
|
+
}
|
|
1171
1294
|
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
1295
|
return result;
|
|
1173
1296
|
};
|
|
@@ -1185,6 +1308,14 @@ const quantizeToIndicesWithPalette = async (image, palette, options) => {
|
|
|
1185
1308
|
warn(o.signal);
|
|
1186
1309
|
const wasm = Module || (await acquire());
|
|
1187
1310
|
checkAborted(o.signal);
|
|
1311
|
+
if (isControlled(o)) {
|
|
1312
|
+
const report = reporter(o);
|
|
1313
|
+
const indexed = unpackIndices(await mapInSlices(wasm, image, {
|
|
1314
|
+
palette
|
|
1315
|
+
}, space, true, o.transparent, o, report, 0), original, paletteSpace);
|
|
1316
|
+
report(1);
|
|
1317
|
+
return indexed;
|
|
1318
|
+
}
|
|
1188
1319
|
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
1320
|
return result;
|
|
1190
1321
|
};
|
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
|
|
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
|
|
182
|
-
*
|
|
183
|
-
*
|
|
184
|
-
*
|
|
185
|
-
*
|
|
186
|
-
*
|
|
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
|
|
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:
|
|
197
|
-
* backwards, ending with 1. It is approximate and not linear in time. Giving
|
|
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`.
|
|
261
|
-
export interface MappingOptions extends
|
|
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
|
|
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
|
|
182
|
-
*
|
|
183
|
-
*
|
|
184
|
-
*
|
|
185
|
-
*
|
|
186
|
-
*
|
|
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
|
|
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:
|
|
197
|
-
* backwards, ending with 1. It is approximate and not linear in time. Giving
|
|
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`.
|
|
261
|
-
export interface MappingOptions extends
|
|
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.mjs
CHANGED
|
@@ -115,7 +115,13 @@ const isBrowserLike = () => typeof document !== 'undefined' || typeof WorkerGlob
|
|
|
115
115
|
const deployAdvice = "In a serverless deployment (AWS Lambda, Vercel or Netlify functions), the bundler or file tracer may have left the package's dist/ files out: include node_modules/agglomerative-clustering/dist in the function's files, or leave the package unbundled (external).";
|
|
116
116
|
// Emscripten appends advice about its own debug build, which doesn't apply to this package's users.
|
|
117
117
|
const assertionsAdvice = /\s*\(?Build with -sASSERTIONS for more info\.?\)?/;
|
|
118
|
-
|
|
118
|
+
// Whether init({ wasm }) was given bytes that start with gzip's magic (1f 8b): a gzipped module passed without decompressing.
|
|
119
|
+
const isGzipped = wasm => {
|
|
120
|
+
const tag = Object.prototype.toString.call(wasm);
|
|
121
|
+
const bytes = tag === '[object ArrayBuffer]' ? new Uint8Array(wasm) : ArrayBuffer.isView(wasm) ? new Uint8Array(wasm.buffer, wasm.byteOffset, wasm.byteLength) : null;
|
|
122
|
+
return bytes !== null && bytes.length >= 2 && bytes[0] === 0x1f && bytes[1] === 0x8b;
|
|
123
|
+
};
|
|
124
|
+
const wasmLoadFailed = (cause, given, gzipped = false) => {
|
|
119
125
|
const text = String(cause && cause.message !== undefined ? cause.message : cause).split('\n')[0];
|
|
120
126
|
// Emscripten wraps a failed compile in Aborted(...), which is how it stops itself, not part of the reason.
|
|
121
127
|
let reason = text.replace(assertionsAdvice, '').trim().replace(/\.+$/, '');
|
|
@@ -146,6 +152,10 @@ const wasmLoadFailed = (cause, given) => {
|
|
|
146
152
|
advice = "A Content-Security-Policy blocks compiling WebAssembly: add 'wasm-unsafe-eval' to the script-src of the policy that applies. That is the page's for a page and for the worker entry's worker (also when started from a content script, whose worker follows the page's policy); for a browser extension's own pages, offscreen document and service worker, it is content_security_policy.extension_pages in the manifest.";
|
|
147
153
|
} else if (!hasSimd()) {
|
|
148
154
|
advice = "This engine has no WebAssembly SIMD, which the module needs (Chrome and Edge 91, Firefox 89, Safari 16.4, Node 16.4 or newer).";
|
|
155
|
+
} else if (gzipped) {
|
|
156
|
+
// Engines word this differently (V8 and Firefox name the magic number, Safari doesn't), so it goes by the bytes.
|
|
157
|
+
reason = `the bytes given to init({ wasm }) are gzipped (they start with 1f 8b), not a WebAssembly module (${reason})`;
|
|
158
|
+
advice = "Decompress them first, for example with new Response(new Blob([bytes]).stream().pipeThrough(new DecompressionStream('gzip'))).arrayBuffer(), and pass the result (see Plugins and single-file hosts in https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/environments.md).";
|
|
149
159
|
} else if (/magic (word|number)|BufferSource argument is empty|wasm validation error: at offset [0-4]:/i.test(text)) {
|
|
150
160
|
// What a 404 page, or a server's fallback HTML page, looks like once it has been compiled as WebAssembly.
|
|
151
161
|
if (given === true) {
|
|
@@ -323,13 +333,16 @@ const acquire = async options => {
|
|
|
323
333
|
// way Node resolves packages, from the working directory; if that fails too, the first error is reported.
|
|
324
334
|
const fallback = wasm === undefined && isNodeLike ? await packagedWasm().catch(() => null) : null;
|
|
325
335
|
if (!fallback) {
|
|
326
|
-
throw wasmLoadFailed(error, typeof wasm === 'string' ? wasm : isURL(wasm) ? wasm.href : wasm !== undefined);
|
|
336
|
+
throw wasmLoadFailed(error, typeof wasm === 'string' ? wasm : isURL(wasm) ? wasm.href : wasm !== undefined, isGzipped(wasm));
|
|
327
337
|
}
|
|
328
338
|
instance = await instantiate(fallback).catch(() => {
|
|
329
339
|
throw wasmLoadFailed(error, false);
|
|
330
340
|
});
|
|
331
341
|
}
|
|
332
342
|
checkWasmVersion(instance);
|
|
343
|
+
if (instance.HEAPU8) {
|
|
344
|
+
startSizes.set(instance, instance.HEAPU8.length);
|
|
345
|
+
}
|
|
333
346
|
Module = instance;
|
|
334
347
|
return instance;
|
|
335
348
|
})().catch(error => {
|
|
@@ -360,10 +373,14 @@ const discard = instance => {
|
|
|
360
373
|
// WebAssembly memory only grows: an instance that once held a huge image keeps all that memory for the life of the process.
|
|
361
374
|
// So when a call leaves the heap larger than this, the instance is retired like an aborted one: calls already running keep
|
|
362
375
|
// it, the next call loads a fresh one (a few milliseconds, next to the seconds such an image took), and the old memory is
|
|
363
|
-
// freed when nothing uses it any more.
|
|
364
|
-
|
|
376
|
+
// freed when nothing uses it any more. The limit counts growth from the size the instance started at (32 MB in the
|
|
377
|
+
// release build), so a build that starts larger, such as the sanitized one scripts/asan-test.sh uses (512 MB, for its
|
|
378
|
+
// shadow memory), isn't retired after every call.
|
|
379
|
+
const releaseStart = 32 * 1024 * 1024; // INITIAL_MEMORY in build:wasm
|
|
380
|
+
const retireAfter = 256 * 1024 * 1024 - releaseStart; // so the release build retires above 256 MB, as before
|
|
381
|
+
const startSizes = new WeakMap();
|
|
365
382
|
const retireIfLarge = instance => {
|
|
366
|
-
if (instance.HEAPU8 && instance.HEAPU8.length >
|
|
383
|
+
if (instance.HEAPU8 && instance.HEAPU8.length > (startSizes.get(instance) ?? releaseStart) + retireAfter) {
|
|
367
384
|
discard(instance);
|
|
368
385
|
}
|
|
369
386
|
};
|
|
@@ -569,7 +586,8 @@ const check = k => {
|
|
|
569
586
|
// precision: bits per channel, 1-8 (default 8, exact); lower values group similar colours before clustering
|
|
570
587
|
// dither: false (default), true or a strength in [0, 1] (Floyd-Steinberg), a method name, or { method, strength, steps } (see parseDither)
|
|
571
588
|
// width: image width in pixels, needed to dither a Uint8Array or a RawImage without `width`
|
|
572
|
-
// signal, onProgress: an AbortSignal and a progress callback, which make the clustering run in slices
|
|
589
|
+
// signal, onProgress: an AbortSignal and a progress callback, which make the clustering and the mapping run in slices
|
|
590
|
+
// (see clusterInSlices and mapInSlices)
|
|
573
591
|
// 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);
|
|
574
592
|
// indexed output also gives them their own entry, which counts towards k
|
|
575
593
|
|
|
@@ -586,7 +604,7 @@ const parseOptions = (options, allowed, image) => {
|
|
|
586
604
|
options = snapshot(options);
|
|
587
605
|
for (const key of Object.keys(options)) {
|
|
588
606
|
if (!allowed.includes(key)) {
|
|
589
|
-
const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' :
|
|
607
|
+
const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' : '';
|
|
590
608
|
throw fail('invalid-argument', `Invalid option '${key}': expected one of ${allowed.join(', ')}.${hint}`, `options.${key}`);
|
|
591
609
|
}
|
|
592
610
|
}
|
|
@@ -664,9 +682,7 @@ const parseOptions = (options, allowed, image) => {
|
|
|
664
682
|
const controlOptions = ['signal', 'onProgress'];
|
|
665
683
|
const clusterOptions = ['colorSpace', 'precision', 'alpha', 'transparent', ...controlOptions];
|
|
666
684
|
const quantizeOptions = [...clusterOptions, 'dither', 'width'];
|
|
667
|
-
|
|
668
|
-
// for a photo, seconds for a large image dithered; the guides show how to map in strips or cancel through a worker).
|
|
669
|
-
const mapOptions = ['colorSpace', 'dither', 'width', 'signal'];
|
|
685
|
+
const mapOptions = ['colorSpace', 'dither', 'width', ...controlOptions];
|
|
670
686
|
const quantizeIndexOptions = quantizeOptions;
|
|
671
687
|
const mapIndexOptions = [...mapOptions, 'transparent'];
|
|
672
688
|
|
|
@@ -743,7 +759,7 @@ const call = (wasm, buffers, fn, precision) => {
|
|
|
743
759
|
};
|
|
744
760
|
|
|
745
761
|
// ----- Interruptible work -------------------------------------------------------------------------------------------
|
|
746
|
-
// A call given a `signal` or an `onProgress` runs its clustering in slices of about `sliceMs` milliseconds, giving the
|
|
762
|
+
// A call given a `signal` or an `onProgress` runs its clustering and its mapping in slices of about `sliceMs` milliseconds, giving the
|
|
747
763
|
// event loop a turn between them: the signal is checked (and progress reported) each time, other tasks can run, and
|
|
748
764
|
// in a worker thread the cancel message is read. Without either the call runs in one go, as it always did. The
|
|
749
765
|
// result is the same either way: the slices are the same steps in the same order.
|
|
@@ -792,6 +808,20 @@ const reporter = o => {
|
|
|
792
808
|
};
|
|
793
809
|
const isControlled = o => o.signal !== undefined || o.onProgress !== undefined;
|
|
794
810
|
|
|
811
|
+
// The share of quantize's and quantizeToIndices' progress that clustering takes, the rest being mapping. It only shapes
|
|
812
|
+
// the progress bar, so it is internal and can be retuned. Mapping's time relative to clustering's, measured on the 24
|
|
813
|
+
// Kodak photos (medians; bench/spikes/slicing-mapping/split.mjs → results-split.txt): undithered 0.1, Floyd–Steinberg
|
|
814
|
+
// 0.45, Atkinson 0.37, ordered 0.8 at 16 steps and about proportional to the steps; clustering below full precision is
|
|
815
|
+
// about 2.5 times faster. Steps not given are 64 for a palette of two colours, else 16, as in the C.
|
|
816
|
+
const mappingCost = [0.45, 0.37];
|
|
817
|
+
const clusteringShare = (o, k) => {
|
|
818
|
+
const dithered = o.dither > 0 && o.width > 0;
|
|
819
|
+
const ordered = dithered && o.ditherMethod === 2;
|
|
820
|
+
const steps = o.ditherSteps || (k <= 2 ? 64 : 16);
|
|
821
|
+
const cost = (!dithered ? 0.1 : ordered ? 0.8 * steps / 16 : mappingCost[o.ditherMethod]) * (o.precision < 8 ? 2.5 : 1);
|
|
822
|
+
return 1 / (1 + cost);
|
|
823
|
+
};
|
|
824
|
+
|
|
795
825
|
// Clusters in slices and returns the clustering. `share` is the part of the whole call's progress this takes.
|
|
796
826
|
const clusterInSlices = async (wasm, image, o, report, share) => {
|
|
797
827
|
checkAborted(o.signal);
|
|
@@ -835,6 +865,67 @@ const clusterInSlices = async (wasm, image, o, report, share) => {
|
|
|
835
865
|
}
|
|
836
866
|
};
|
|
837
867
|
|
|
868
|
+
// Maps in slices and returns the output's payload, as `call` does for the one-shot exports. The palette is
|
|
869
|
+
// `source.palette`, or cut from `source.clustering` to `source.k` colours (a negative `colorSpace` then matches in the
|
|
870
|
+
// clustering's space). `indices` chooses indexed output, with `cutoff`. Progress goes from `from` to 1. A call that
|
|
871
|
+
// finishes in its first slice doesn't yield.
|
|
872
|
+
const mapInSlices = async (wasm, image, source, colorSpace, indices, cutoff, o, report, from) => {
|
|
873
|
+
checkAborted(o.signal);
|
|
874
|
+
const bytes = source.palette || source.clustering;
|
|
875
|
+
const imagePointer = allocate(wasm, image.data.length);
|
|
876
|
+
let sourcePointer = 0;
|
|
877
|
+
let job = 0;
|
|
878
|
+
let aborted = false;
|
|
879
|
+
try {
|
|
880
|
+
sourcePointer = allocate(wasm, bytes.length);
|
|
881
|
+
wasm.HEAPU8.set(image.data, imagePointer);
|
|
882
|
+
wasm.HEAPU8.set(bytes, sourcePointer);
|
|
883
|
+
const palette = source.palette ? sourcePointer : 0,
|
|
884
|
+
clustering = source.clustering ? sourcePointer : 0;
|
|
885
|
+
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);
|
|
886
|
+
if (!job) {
|
|
887
|
+
throw 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');
|
|
888
|
+
}
|
|
889
|
+
// The job has its own copy of the palette, so the source can go now.
|
|
890
|
+
wasm._free(sourcePointer);
|
|
891
|
+
sourcePointer = 0;
|
|
892
|
+
report(from);
|
|
893
|
+
while (true) {
|
|
894
|
+
const progress = wasm._mapping_job_step(job, sliceMs);
|
|
895
|
+
if (progress >= 1000) {
|
|
896
|
+
break;
|
|
897
|
+
}
|
|
898
|
+
report(from + (1 - from) * progress / 1000);
|
|
899
|
+
await yieldNow();
|
|
900
|
+
checkAborted(o.signal);
|
|
901
|
+
}
|
|
902
|
+
const pointer = wasm._mapping_job_result(job);
|
|
903
|
+
try {
|
|
904
|
+
return unpack(wasm, pointer);
|
|
905
|
+
} finally {
|
|
906
|
+
wasm._free(pointer);
|
|
907
|
+
}
|
|
908
|
+
} catch (error) {
|
|
909
|
+
if (!isAbort(error)) {
|
|
910
|
+
throw error;
|
|
911
|
+
}
|
|
912
|
+
aborted = true;
|
|
913
|
+
discard(wasm);
|
|
914
|
+
throw outOfMemory(image.data.length, o.precision);
|
|
915
|
+
} finally {
|
|
916
|
+
if (!aborted) {
|
|
917
|
+
if (job) {
|
|
918
|
+
wasm._mapping_job_free(job);
|
|
919
|
+
}
|
|
920
|
+
if (sourcePointer) {
|
|
921
|
+
wasm._free(sourcePointer);
|
|
922
|
+
}
|
|
923
|
+
wasm._free(imagePointer);
|
|
924
|
+
retireIfLarge(wasm);
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
};
|
|
928
|
+
|
|
838
929
|
// The functions that read a clustering take no options: a clustering already says how it was made. An options object passed
|
|
839
930
|
// anyway (say { colorSpace: 'oklab' }, expecting it to apply) would be silently ignored, so it is an error. undefined is fine.
|
|
840
931
|
// `name` is how the caller wrote the call: the function, or the method (`clustering.getPalette`), whose message points at
|
|
@@ -1011,9 +1102,12 @@ export const quantize = async (image, k, options) => {
|
|
|
1011
1102
|
const wasm = Module || (await acquire());
|
|
1012
1103
|
if (isControlled(o)) {
|
|
1013
1104
|
const report = reporter(o);
|
|
1014
|
-
const
|
|
1015
|
-
|
|
1016
|
-
const mapped = wrap(
|
|
1105
|
+
const share = clusteringShare(o, k);
|
|
1106
|
+
const clustering = await clusterInSlices(wasm, image, o, report, share);
|
|
1107
|
+
const mapped = wrap(await mapInSlices(wasm, image, {
|
|
1108
|
+
clustering,
|
|
1109
|
+
k
|
|
1110
|
+
}, o.colorSpace, false, 0, o, report, share));
|
|
1017
1111
|
report(1);
|
|
1018
1112
|
return mapped;
|
|
1019
1113
|
}
|
|
@@ -1031,6 +1125,15 @@ export const quantizeFromClustering = async (image, clustering, k, options) => {
|
|
|
1031
1125
|
const wasm = Module || (await acquire());
|
|
1032
1126
|
checkAborted(o.signal);
|
|
1033
1127
|
const colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
|
|
1128
|
+
if (isControlled(o)) {
|
|
1129
|
+
const report = reporter(o);
|
|
1130
|
+
const mapped = wrap(await mapInSlices(wasm, image, {
|
|
1131
|
+
clustering,
|
|
1132
|
+
k
|
|
1133
|
+
}, colorSpace, false, 0, o, report, 0));
|
|
1134
|
+
report(1);
|
|
1135
|
+
return mapped;
|
|
1136
|
+
}
|
|
1034
1137
|
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)));
|
|
1035
1138
|
return result;
|
|
1036
1139
|
};
|
|
@@ -1046,6 +1149,14 @@ export const quantizeWithPalette = async (image, palette, options) => {
|
|
|
1046
1149
|
warn(o.signal);
|
|
1047
1150
|
const wasm = Module || (await acquire());
|
|
1048
1151
|
checkAborted(o.signal);
|
|
1152
|
+
if (isControlled(o)) {
|
|
1153
|
+
const report = reporter(o);
|
|
1154
|
+
const mapped = wrap(await mapInSlices(wasm, image, {
|
|
1155
|
+
palette
|
|
1156
|
+
}, space, false, 0, o, report, 0));
|
|
1157
|
+
report(1);
|
|
1158
|
+
return mapped;
|
|
1159
|
+
}
|
|
1049
1160
|
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)));
|
|
1050
1161
|
return result;
|
|
1051
1162
|
};
|
|
@@ -1059,9 +1170,12 @@ export const quantizeToIndices = async (image, k, options) => {
|
|
|
1059
1170
|
const wasm = Module || (await acquire());
|
|
1060
1171
|
if (isControlled(o)) {
|
|
1061
1172
|
const report = reporter(o);
|
|
1062
|
-
const
|
|
1063
|
-
|
|
1064
|
-
const indexed = unpackIndices(
|
|
1173
|
+
const share = clusteringShare(o, k);
|
|
1174
|
+
const clustering = await clusterInSlices(wasm, image, o, report, share);
|
|
1175
|
+
const indexed = unpackIndices(await mapInSlices(wasm, image, {
|
|
1176
|
+
clustering,
|
|
1177
|
+
k
|
|
1178
|
+
}, o.colorSpace, true, o.transparent, o, report, share), original, colorSpaceName(o.colorSpace));
|
|
1065
1179
|
report(1);
|
|
1066
1180
|
return indexed;
|
|
1067
1181
|
}
|
|
@@ -1082,6 +1196,15 @@ export const quantizeToIndicesFromClustering = async (image, clustering, k, opti
|
|
|
1082
1196
|
|
|
1083
1197
|
// The cutoff the clustering was made with is the default, so clustering and mapping agree unless a cutoff is named.
|
|
1084
1198
|
const cutoff = o.transparentGiven ? o.transparent : header.transparent;
|
|
1199
|
+
if (isControlled(o)) {
|
|
1200
|
+
const report = reporter(o);
|
|
1201
|
+
const indexed = unpackIndices(await mapInSlices(wasm, image, {
|
|
1202
|
+
clustering,
|
|
1203
|
+
k
|
|
1204
|
+
}, colorSpace, true, cutoff, o, report, 0), original, colorSpaceName(header.colorSpace));
|
|
1205
|
+
report(1);
|
|
1206
|
+
return indexed;
|
|
1207
|
+
}
|
|
1085
1208
|
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, colorSpaceName(header.colorSpace));
|
|
1086
1209
|
return result;
|
|
1087
1210
|
};
|
|
@@ -1098,6 +1221,14 @@ export const quantizeToIndicesWithPalette = async (image, palette, options) => {
|
|
|
1098
1221
|
warn(o.signal);
|
|
1099
1222
|
const wasm = Module || (await acquire());
|
|
1100
1223
|
checkAborted(o.signal);
|
|
1224
|
+
if (isControlled(o)) {
|
|
1225
|
+
const report = reporter(o);
|
|
1226
|
+
const indexed = unpackIndices(await mapInSlices(wasm, image, {
|
|
1227
|
+
palette
|
|
1228
|
+
}, space, true, o.transparent, o, report, 0), original, paletteSpace);
|
|
1229
|
+
report(1);
|
|
1230
|
+
return indexed;
|
|
1231
|
+
}
|
|
1101
1232
|
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);
|
|
1102
1233
|
return result;
|
|
1103
1234
|
};
|
package/dist/shared.cjs
CHANGED
|
@@ -13,7 +13,7 @@ exports.warnOnce = exports.version = exports.tooLarge = exports.sniffImageFormat
|
|
|
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.
|
|
16
|
+
const version = exports.version = '3.7.1';
|
|
17
17
|
const colorSpaceCodes = exports.colorSpaceCodes = {
|
|
18
18
|
'rgb': 0,
|
|
19
19
|
'oklab': 1
|
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.
|
|
7
|
+
export const version = '3.7.1';
|
|
8
8
|
export const colorSpaceCodes = {
|
|
9
9
|
'rgb': 0,
|
|
10
10
|
'oklab': 1
|
package/dist/worker-thread.mjs
CHANGED
|
@@ -129,8 +129,8 @@ const respond = async ({
|
|
|
129
129
|
}, post) => {
|
|
130
130
|
const controller = check ? alreadyAborted() : controllers.get(id);
|
|
131
131
|
try {
|
|
132
|
-
// The call before this one may have run in one piece (
|
|
133
|
-
// of this call to arrive; take one before starting, so a call cancelled while it waited never runs.
|
|
132
|
+
// The call before this one may have run in one piece (a call without a signal does), with no turn of the event
|
|
133
|
+
// loop for a cancel of this call to arrive; take one before starting, so a call cancelled while it waited never runs.
|
|
134
134
|
if (controller && !controller.signal.aborted) {
|
|
135
135
|
await nextTurn();
|
|
136
136
|
}
|
package/dist/worker.cjs
CHANGED
|
@@ -471,7 +471,7 @@ const initOptions = (options, allowScript) => {
|
|
|
471
471
|
|
|
472
472
|
// A signal and a progress callback can't cross to the worker, so they stay on this side: the options are sent without
|
|
473
473
|
// them, a cancel message is sent when the signal aborts, and the worker's progress messages call the callback.
|
|
474
|
-
const takeControls = (options,
|
|
474
|
+
const takeControls = (options, ditherAllowed = true) => {
|
|
475
475
|
// Anything but an ordinary object goes on as it is, for the worker's own validation to reject. An ordinary one is copied
|
|
476
476
|
// once first: structured cloning drops inherited properties, and the copy is what gets validated and sent.
|
|
477
477
|
if (!(0, _shared.isOptionsObject)(options)) {
|
|
@@ -504,7 +504,7 @@ const takeControls = (options, progressAllowed = true, ditherAllowed = true) =>
|
|
|
504
504
|
options.dither = copy;
|
|
505
505
|
}
|
|
506
506
|
// The signal and the progress callback can't cross to the worker, so they are kept here and the worker gets its own.
|
|
507
|
-
// A wrong one
|
|
507
|
+
// A wrong one crosses as `null` instead, which the worker's validation
|
|
508
508
|
// rejects with the main entry's error, after the image and k: the main entry checks the options last. (This relies on
|
|
509
509
|
// those messages not echoing the value: if they ever say what they got, send a stand-in that reads the same.)
|
|
510
510
|
const {
|
|
@@ -512,7 +512,7 @@ const takeControls = (options, progressAllowed = true, ditherAllowed = true) =>
|
|
|
512
512
|
onProgress
|
|
513
513
|
} = options;
|
|
514
514
|
const badSignal = signal !== undefined && (signal === null || typeof signal !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function');
|
|
515
|
-
const badProgress = onProgress !== undefined &&
|
|
515
|
+
const badProgress = onProgress !== undefined && typeof onProgress !== 'function';
|
|
516
516
|
const {
|
|
517
517
|
signal: _signal,
|
|
518
518
|
onProgress: _onProgress,
|
|
@@ -577,10 +577,8 @@ const optionsPosition = {
|
|
|
577
577
|
const abortReason = signal => signal.reason !== undefined ? signal.reason : new DOMException('This operation was aborted', 'AbortError');
|
|
578
578
|
const imageFunctions = ['getClustering', 'getPalette', 'getSwatches', 'quantize', 'quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndices', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
|
|
579
579
|
const mappedImageFunctions = ['quantize', 'quantizeFromClustering', 'quantizeWithPalette'];
|
|
580
|
-
// These only map pixels, so they take a signal but no progress callback (see mapOptions in index.js).
|
|
581
580
|
// The functions that only cluster, and so take no dither option.
|
|
582
581
|
const clusteringOnlyFunctions = ['getClustering', 'getPalette', 'getSwatches'];
|
|
583
|
-
const mappingOnlyFunctions = ['quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
|
|
584
582
|
const otherFunctions = ['getPaletteFromClustering', 'getSwatchesFromClustering', 'getClusteringInfo'];
|
|
585
583
|
|
|
586
584
|
// Calls each worker's `abandon` once the worker made by createWorker() has been garbage-collected (see `abandoned`).
|
|
@@ -888,7 +886,7 @@ const makeWorker = (options, allowScript) => {
|
|
|
888
886
|
options,
|
|
889
887
|
signal,
|
|
890
888
|
onProgress
|
|
891
|
-
} = takeControls(rest[position], !
|
|
889
|
+
} = takeControls(rest[position], !clusteringOnlyFunctions.includes(name));
|
|
892
890
|
let args = rest.slice();
|
|
893
891
|
if (position < args.length) {
|
|
894
892
|
args[position] = options;
|
|
@@ -968,7 +966,7 @@ const makeWorker = (options, allowScript) => {
|
|
|
968
966
|
options,
|
|
969
967
|
signal,
|
|
970
968
|
onProgress
|
|
971
|
-
} = takeControls(clusterOptions,
|
|
969
|
+
} = takeControls(clusterOptions, false);
|
|
972
970
|
if (signal && signal.aborted) {
|
|
973
971
|
throw abortReason(signal);
|
|
974
972
|
}
|
|
@@ -1011,7 +1009,7 @@ const makeWorker = (options, allowScript) => {
|
|
|
1011
1009
|
const withControls = (method, leading, mapOptions) => {
|
|
1012
1010
|
let taken;
|
|
1013
1011
|
try {
|
|
1014
|
-
taken = takeControls(mapOptions
|
|
1012
|
+
taken = takeControls(mapOptions);
|
|
1015
1013
|
} catch (error) {
|
|
1016
1014
|
return Promise.reject(error);
|
|
1017
1015
|
}
|
package/dist/worker.mjs
CHANGED
|
@@ -402,7 +402,7 @@ const initOptions = (options, allowScript) => {
|
|
|
402
402
|
|
|
403
403
|
// A signal and a progress callback can't cross to the worker, so they stay on this side: the options are sent without
|
|
404
404
|
// them, a cancel message is sent when the signal aborts, and the worker's progress messages call the callback.
|
|
405
|
-
const takeControls = (options,
|
|
405
|
+
const takeControls = (options, ditherAllowed = true) => {
|
|
406
406
|
// Anything but an ordinary object goes on as it is, for the worker's own validation to reject. An ordinary one is copied
|
|
407
407
|
// once first: structured cloning drops inherited properties, and the copy is what gets validated and sent.
|
|
408
408
|
if (!isOptionsObject(options)) {
|
|
@@ -435,7 +435,7 @@ const takeControls = (options, progressAllowed = true, ditherAllowed = true) =>
|
|
|
435
435
|
options.dither = copy;
|
|
436
436
|
}
|
|
437
437
|
// The signal and the progress callback can't cross to the worker, so they are kept here and the worker gets its own.
|
|
438
|
-
// A wrong one
|
|
438
|
+
// A wrong one crosses as `null` instead, which the worker's validation
|
|
439
439
|
// rejects with the main entry's error, after the image and k: the main entry checks the options last. (This relies on
|
|
440
440
|
// those messages not echoing the value: if they ever say what they got, send a stand-in that reads the same.)
|
|
441
441
|
const {
|
|
@@ -443,7 +443,7 @@ const takeControls = (options, progressAllowed = true, ditherAllowed = true) =>
|
|
|
443
443
|
onProgress
|
|
444
444
|
} = options;
|
|
445
445
|
const badSignal = signal !== undefined && (signal === null || typeof signal !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function');
|
|
446
|
-
const badProgress = onProgress !== undefined &&
|
|
446
|
+
const badProgress = onProgress !== undefined && typeof onProgress !== 'function';
|
|
447
447
|
const {
|
|
448
448
|
signal: _signal,
|
|
449
449
|
onProgress: _onProgress,
|
|
@@ -508,10 +508,8 @@ const optionsPosition = {
|
|
|
508
508
|
const abortReason = signal => signal.reason !== undefined ? signal.reason : new DOMException('This operation was aborted', 'AbortError');
|
|
509
509
|
const imageFunctions = ['getClustering', 'getPalette', 'getSwatches', 'quantize', 'quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndices', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
|
|
510
510
|
const mappedImageFunctions = ['quantize', 'quantizeFromClustering', 'quantizeWithPalette'];
|
|
511
|
-
// These only map pixels, so they take a signal but no progress callback (see mapOptions in index.js).
|
|
512
511
|
// The functions that only cluster, and so take no dither option.
|
|
513
512
|
const clusteringOnlyFunctions = ['getClustering', 'getPalette', 'getSwatches'];
|
|
514
|
-
const mappingOnlyFunctions = ['quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
|
|
515
513
|
const otherFunctions = ['getPaletteFromClustering', 'getSwatchesFromClustering', 'getClusteringInfo'];
|
|
516
514
|
|
|
517
515
|
// Calls each worker's `abandon` once the worker made by createWorker() has been garbage-collected (see `abandoned`).
|
|
@@ -819,7 +817,7 @@ const makeWorker = (options, allowScript) => {
|
|
|
819
817
|
options,
|
|
820
818
|
signal,
|
|
821
819
|
onProgress
|
|
822
|
-
} = takeControls(rest[position], !
|
|
820
|
+
} = takeControls(rest[position], !clusteringOnlyFunctions.includes(name));
|
|
823
821
|
let args = rest.slice();
|
|
824
822
|
if (position < args.length) {
|
|
825
823
|
args[position] = options;
|
|
@@ -899,7 +897,7 @@ const makeWorker = (options, allowScript) => {
|
|
|
899
897
|
options,
|
|
900
898
|
signal,
|
|
901
899
|
onProgress
|
|
902
|
-
} = takeControls(clusterOptions,
|
|
900
|
+
} = takeControls(clusterOptions, false);
|
|
903
901
|
if (signal && signal.aborted) {
|
|
904
902
|
throw abortReason(signal);
|
|
905
903
|
}
|
|
@@ -942,7 +940,7 @@ const makeWorker = (options, allowScript) => {
|
|
|
942
940
|
const withControls = (method, leading, mapOptions) => {
|
|
943
941
|
let taken;
|
|
944
942
|
try {
|
|
945
|
-
taken = takeControls(mapOptions
|
|
943
|
+
taken = takeControls(mapOptions);
|
|
946
944
|
} catch (error) {
|
|
947
945
|
return Promise.reject(error);
|
|
948
946
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agglomerative-clustering",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.7.1",
|
|
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",
|
|
@@ -81,7 +81,7 @@
|
|
|
81
81
|
"README.md"
|
|
82
82
|
],
|
|
83
83
|
"scripts": {
|
|
84
|
-
"build:wasm": "node scripts/check-emsdk.mjs && mkdirp dist && em++ src/clustering.cpp -O3 -msimd128 -s WASM=1 -s MODULARIZE=1 -s EXPORT_ES6=1 -s EXPORT_NAME='createWasmModule' -s ALLOW_MEMORY_GROWTH=1 -s INITIAL_MEMORY=32MB -s MAXIMUM_MEMORY=2147483648 -s EXPORTED_FUNCTIONS=\"['_library_version','_get_clustering','_clustering_job_start','_clustering_job_step','_clustering_job_result','_clustering_job_free','_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','_malloc','_free']\" -s EXPORTED_RUNTIME_METHODS=\"['HEAPU8']\" -o dist/clustering.js && node scripts/patch-glue.mjs",
|
|
84
|
+
"build:wasm": "node scripts/check-emsdk.mjs && mkdirp dist && em++ src/clustering.cpp -O3 -msimd128 -s WASM=1 -s MODULARIZE=1 -s EXPORT_ES6=1 -s EXPORT_NAME='createWasmModule' -s ALLOW_MEMORY_GROWTH=1 -s INITIAL_MEMORY=32MB -s MAXIMUM_MEMORY=2147483648 -s EXPORTED_FUNCTIONS=\"['_library_version','_get_clustering','_clustering_job_start','_clustering_job_step','_clustering_job_result','_clustering_job_free','_mapping_job_start','_mapping_job_step','_mapping_job_result','_mapping_job_free','_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','_malloc','_free']\" -s EXPORTED_RUNTIME_METHODS=\"['HEAPU8']\" -o dist/clustering.js && node scripts/patch-glue.mjs",
|
|
85
85
|
"build:cjs": "cross-env BABEL_ENV=cjs babel src --out-dir dist --extensions \".js\" --ignore \"src/worker-thread.js\" --out-file-extension .cjs && node scripts/patch-cjs.mjs",
|
|
86
86
|
"build:esm": "cross-env BABEL_ENV=esm babel src --out-dir dist --extensions \".js\" --out-file-extension .mjs",
|
|
87
87
|
"build:types": "mkdirp dist && node -e \"const fs = require('fs'); for (const f of ['index.d.ts', 'worker.d.ts']) {fs.copyFileSync('src/' + f, 'dist/' + f);} fs.copyFileSync('src/index.d.ts', 'dist/index.d.cts'); fs.writeFileSync('dist/worker.d.cts', fs.readFileSync('src/worker.d.ts', 'utf8').replaceAll(\\\"'./index.js'\\\", \\\"'./index.cjs'\\\"));\"",
|