agglomerative-clustering 3.0.0-beta.6 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -842
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +53 -28
- package/dist/index.d.cts +24 -30
- package/dist/index.d.ts +24 -30
- package/dist/index.mjs +51 -26
- package/dist/shared.cjs +13 -3
- package/dist/shared.mjs +9 -1
- package/dist/worker.cjs +10 -7
- package/dist/worker.d.cts +2 -2
- package/dist/worker.d.ts +2 -2
- package/dist/worker.mjs +11 -8
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import createWasmModule from './clustering.js';
|
|
2
|
-
import { version, fail, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, imageHint, latestVersion, readHeader, checkPalette, isDetached, imageDataLike, isImageData, checkImageDataPixels } from "./shared.mjs";
|
|
2
|
+
import { version, fail, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, imageHint, latestVersion, readHeader, checkPalette, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, sizeText, tooLarge } from "./shared.mjs";
|
|
3
3
|
|
|
4
4
|
// The library's version, the stored-data format version, and the Palette and Clustering types (see shared.js).
|
|
5
5
|
export { version, Palette, Clustering, errorCodes, isCodedError } from "./shared.mjs";
|
|
@@ -110,7 +110,7 @@ const wasmLoadFailed = (cause, given) => {
|
|
|
110
110
|
let advice;
|
|
111
111
|
if (/disallowed by embedder|code generation disallowed/i.test(text) && !isNodeLike && !isBrowserLike()) {
|
|
112
112
|
// Edge runtimes (Cloudflare Workers, Vercel's edge runtime) compile WebAssembly only at build time, from an import.
|
|
113
|
-
advice = "This runtime doesn't compile WebAssembly while it runs, from bytes or from a URL (edge runtimes such as Cloudflare Workers and Vercel's): import clustering.wasm as a module, which the bundler compiles when it builds (in Wrangler a plain import of 'agglomerative-clustering/clustering.wasm'; in Next.js a relative path with ?module), and pass it to init({ wasm }) before the first call, as the
|
|
113
|
+
advice = "This runtime doesn't compile WebAssembly while it runs, from bytes or from a URL (edge runtimes such as Cloudflare Workers and Vercel's): import clustering.wasm as a module, which the bundler compiles when it builds (in Wrangler a plain import of 'agglomerative-clustering/clustering.wasm'; in Next.js a relative path with ?module), and pass it to init({ wasm }) before the first call, as the docs show for Cloudflare Workers and Next.js (https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/environments.md).";
|
|
114
114
|
} else if (/(memory|allocate)/i.test(text) && /(could not|cannot|can't|failed to|out of) (allocate|memory|reserve)/i.test(text)) {
|
|
115
115
|
// A 64-bit engine reserves the module's whole address range up front (about 10 GB of virtual memory per instance),
|
|
116
116
|
// though it only uses what it needs; an address-space limit refuses that reservation.
|
|
@@ -131,6 +131,10 @@ const wasmLoadFailed = (cause, given) => {
|
|
|
131
131
|
reason = `the file loaded as clustering.wasm${where} is not WebAssembly (${reason}): most likely an error page (a 404) or a fallback HTML page served in its place`;
|
|
132
132
|
advice = given ? "Check that URL or path: it must be this package's clustering.wasm, served with the application/wasm type." : "Check that clustering.wasm is served next to the script or emitted by your bundler (open its URL in the browser), or say where it is with init({ wasm }).";
|
|
133
133
|
}
|
|
134
|
+
} else if (isNodeLike && typeof given === 'string' && /^https?:/i.test(given)) {
|
|
135
|
+
// Node fetches an http(s) URL itself (see nodeWasmFile), so the server or the network failed, not a path.
|
|
136
|
+
reason = `the .wasm file could not be fetched${where}: ${reason}`;
|
|
137
|
+
advice = "Check that this machine can reach that URL and that it serves this package's clustering.wasm. On a server, a path to the package's own copy (or its bytes) avoids the request.";
|
|
134
138
|
} else if (/XMLHttpRequest is not defined|both async and sync fetching|failed to fetch|NetworkError|404|ENOENT/i.test(text) && isNodeLike) {
|
|
135
139
|
// In Node the file is read from disk, so the browser's reasons (a CSP, an extension's resources) don't apply.
|
|
136
140
|
reason = given ? `the .wasm file could not be read${where}` : 'the .wasm file could not be read (the package looks for clustering.wasm next to its script)';
|
|
@@ -152,7 +156,7 @@ const wasmLoadFailed = (cause, given) => {
|
|
|
152
156
|
if (/Invalid URL/i.test(reason)) {
|
|
153
157
|
reason = "the package can't tell where clustering.wasm is in this runtime";
|
|
154
158
|
}
|
|
155
|
-
advice = "Give the module to init({ wasm }) before the first call: in an edge runtime (Cloudflare Workers, Vercel's), import clustering.wasm as a compiled module (the
|
|
159
|
+
advice = "Give the module to init({ wasm }) before the first call: in an edge runtime (Cloudflare Workers, Vercel's), import clustering.wasm as a compiled module (the docs show how for Cloudflare Workers and Next.js: https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/environments.md); elsewhere its bytes or URL.";
|
|
156
160
|
} else {
|
|
157
161
|
advice = "Check that clustering.wasm is served next to the script (not a 404, and with the application/wasm type) and allowed by the page's Content-Security-Policy, or say where it is with init({ wasm }).";
|
|
158
162
|
}
|
|
@@ -232,6 +236,14 @@ const nodeWasmFile = async wasm => {
|
|
|
232
236
|
}
|
|
233
237
|
const isFileUrl = /^file:/i.test(text);
|
|
234
238
|
// A string with a scheme (http:, data:, blob:) is a URL; a Windows drive letter (C:\) is a path.
|
|
239
|
+
// An http(s) URL is fetched here: the glue would read it as a file path in Node.
|
|
240
|
+
if (/^https?:/i.test(text)) {
|
|
241
|
+
const response = await fetch(text);
|
|
242
|
+
if (!response.ok) {
|
|
243
|
+
throw new Error(`HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ''}`);
|
|
244
|
+
}
|
|
245
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
246
|
+
}
|
|
235
247
|
if (!isFileUrl && /^[a-z][a-z0-9+.-]+:/i.test(text) && !/^[a-z]:[\\/]/i.test(text)) {
|
|
236
248
|
return null;
|
|
237
249
|
}
|
|
@@ -327,7 +339,23 @@ const retireIfLarge = instance => {
|
|
|
327
339
|
discard(instance);
|
|
328
340
|
}
|
|
329
341
|
};
|
|
330
|
-
|
|
342
|
+
// What to try depends on the call: a large input has to shrink whatever else changes, and `precision: 6` helps only a
|
|
343
|
+
// clustering (`precision` given) that isn't already at 6 or below.
|
|
344
|
+
const outOfMemory = (bytes, precision) => {
|
|
345
|
+
const large = bytes >= 2 ** 28;
|
|
346
|
+
const tries = [];
|
|
347
|
+
if (large) {
|
|
348
|
+
tries.push(`scale the image down (its pixels alone are ${sizeText(bytes)}; a few megapixels give as good a palette)`);
|
|
349
|
+
}
|
|
350
|
+
if (precision > 6) {
|
|
351
|
+
tries.push('try `precision: 6`, which bounds the memory an image with very many colours needs');
|
|
352
|
+
}
|
|
353
|
+
if (!large) {
|
|
354
|
+
tries.push('use a smaller image');
|
|
355
|
+
}
|
|
356
|
+
const text = tries.join(', or ');
|
|
357
|
+
return fail('out-of-memory', `The WebAssembly module ran out of memory (it can use up to 2 GB for one image). ${text[0].toUpperCase()}${text.slice(1)}.`);
|
|
358
|
+
};
|
|
331
359
|
const unpack = (wasm, pointer) => {
|
|
332
360
|
const lengthBuffer = new Uint8Array(wasm.HEAPU8.subarray(pointer, pointer + 4));
|
|
333
361
|
const length = lengthBuffer[0] | lengthBuffer[1] << 8 | lengthBuffer[2] << 16 | lengthBuffer[3] << 24;
|
|
@@ -678,13 +706,6 @@ const checkNotEmpty = (palette, image, cutoff) => {
|
|
|
678
706
|
// The space to match pixels to a palette in: the one the caller names, else the one a Palette was made in, else RGB.
|
|
679
707
|
const matchingSpace = (o, palette) => o.colorSpaceGiven ? o.colorSpace : colorSpaces[isPalette(palette) ? palette.colorSpace : 'rgb'];
|
|
680
708
|
|
|
681
|
-
// The module's memory is at most 2 GB (MAXIMUM_MEMORY in build:wasm) and its allocator takes a 32-bit signed size, so a
|
|
682
|
-
// buffer of 2 GB or more can never be copied in: _malloc would read its length as negative, or (from 4 GB) wrap it to a
|
|
683
|
-
// small number and hand back a block too short for the copy. Such buffers are rejected before any allocation.
|
|
684
|
-
const maxBytes = 2 ** 31;
|
|
685
|
-
const sizeText = bytes => bytes >= 2 ** 30 ? `${(bytes / 2 ** 30).toFixed(2)} GB` : `${Math.round(bytes / 2 ** 20)} MB`;
|
|
686
|
-
const tooLarge = bytes => fail('out-of-memory', `The input is ${sizeText(bytes)}, more than the WebAssembly module can hold: it has at most 2 GB in all, for the pixels and the work on them, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels of RGBA). Scale the image down for its palette (a few megapixels give as good a one), and map a full-size image in strips with quantizeWithPalette.`);
|
|
687
|
-
|
|
688
709
|
// Allocates `length` bytes in the WASM heap, or throws a coded out-of-memory error.
|
|
689
710
|
const allocate = (wasm, length) => {
|
|
690
711
|
if (length >= maxBytes) {
|
|
@@ -698,8 +719,8 @@ const allocate = (wasm, length) => {
|
|
|
698
719
|
};
|
|
699
720
|
|
|
700
721
|
// Copies each buffer into the WASM heap, calls `fn` with their pointers, and returns the unpacked output,
|
|
701
|
-
// freeing everything afterwards.
|
|
702
|
-
const call = (wasm, buffers, fn) => {
|
|
722
|
+
// freeing everything afterwards. `precision` is given for a clustering, for the out-of-memory advice.
|
|
723
|
+
const call = (wasm, buffers, fn, precision) => {
|
|
703
724
|
const pointers = [];
|
|
704
725
|
let outputPointer = 0;
|
|
705
726
|
let aborted = false;
|
|
@@ -722,7 +743,7 @@ const call = (wasm, buffers, fn) => {
|
|
|
722
743
|
}
|
|
723
744
|
aborted = true;
|
|
724
745
|
discard(wasm);
|
|
725
|
-
throw outOfMemory();
|
|
746
|
+
throw outOfMemory(buffers[0].length, precision);
|
|
726
747
|
} finally {
|
|
727
748
|
// After an abort the instance is being thrown away, and its allocator can't be trusted.
|
|
728
749
|
if (!aborted) {
|
|
@@ -818,7 +839,7 @@ const clusterInSlices = async (wasm, image, o, report, share) => {
|
|
|
818
839
|
}
|
|
819
840
|
aborted = true;
|
|
820
841
|
discard(wasm);
|
|
821
|
-
throw outOfMemory();
|
|
842
|
+
throw outOfMemory(image.data.length, o.precision);
|
|
822
843
|
} finally {
|
|
823
844
|
if (!aborted) {
|
|
824
845
|
if (job) {
|
|
@@ -852,7 +873,7 @@ export const getClustering = async (image, options) => {
|
|
|
852
873
|
report(1);
|
|
853
874
|
return markClustering(clustering);
|
|
854
875
|
}
|
|
855
|
-
return markClustering(call(wasm, [image.data], imagePointer => wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent)));
|
|
876
|
+
return markClustering(call(wasm, [image.data], imagePointer => wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent), o.precision));
|
|
856
877
|
};
|
|
857
878
|
export const getPalette = async (image, k, options) => {
|
|
858
879
|
image = load(image);
|
|
@@ -867,7 +888,7 @@ export const getPalette = async (image, k, options) => {
|
|
|
867
888
|
report(1);
|
|
868
889
|
return markPalette(palette, colorSpaceName(o.colorSpace));
|
|
869
890
|
}
|
|
870
|
-
return markPalette(call(wasm, [image.data], imagePointer => wasm._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.transparent)), colorSpaceName(o.colorSpace));
|
|
891
|
+
return markPalette(call(wasm, [image.data], imagePointer => wasm._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.transparent), o.precision), colorSpaceName(o.colorSpace));
|
|
871
892
|
};
|
|
872
893
|
export const getPaletteFromClustering = async (clustering, k, ...extra) => {
|
|
873
894
|
const header = readHeader(clustering);
|
|
@@ -887,6 +908,14 @@ const weightsOf = (wasm, clustering, header, k) => {
|
|
|
887
908
|
return new Float64Array(bytes.buffer, bytes.byteOffset, bytes.length / 8);
|
|
888
909
|
};
|
|
889
910
|
|
|
911
|
+
// The functions that report weights (swatches, the error curve) need a clustering from 3.x: 2.x recorded none. The others
|
|
912
|
+
// (palettes and mapping) still read 2.x clusterings.
|
|
913
|
+
const needsWeights = header => {
|
|
914
|
+
if (header.version < 3) {
|
|
915
|
+
throw fail('unsupported-version', `Unsupported clustering: format version ${header.version} (agglomerative-clustering ${header.version}.x) has no weights. Cluster the image again.`, 'clustering');
|
|
916
|
+
}
|
|
917
|
+
};
|
|
918
|
+
|
|
890
919
|
// A palette with the weight and share of the image of each of its colours, from one cut of one clustering, so the three
|
|
891
920
|
// arrays line up by construction. Weights are pixels: fully transparent pixels count 0 and partly transparent ones in
|
|
892
921
|
// proportion to their opacity, as in clustering. Shares are the weights divided by their total, so they sum to 1.
|
|
@@ -894,9 +923,7 @@ export const getSwatchesFromClustering = async (clustering, k, ...extra) => {
|
|
|
894
923
|
const header = readHeader(clustering);
|
|
895
924
|
k = check(k);
|
|
896
925
|
noOptions('getSwatchesFromClustering', extra);
|
|
897
|
-
|
|
898
|
-
throw fail('unsupported-version', `Unsupported clustering: format version ${header.version} (agglomerative-clustering ${header.version}.x) has no weights. Cluster the image again.`, 'clustering');
|
|
899
|
-
}
|
|
926
|
+
needsWeights(header);
|
|
900
927
|
clustering = held(clustering);
|
|
901
928
|
const wasm = Module || (await acquire());
|
|
902
929
|
const palette = markPalette(call(wasm, [clustering], clusteringPointer => wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k)), colorSpaceName(header.colorSpace));
|
|
@@ -932,6 +959,7 @@ export const getSwatches = async (image, k, options) => {
|
|
|
932
959
|
export const getClusteringInfo = async (clustering, ...extra) => {
|
|
933
960
|
const header = readHeader(clustering);
|
|
934
961
|
noOptions('getClusteringInfo', extra);
|
|
962
|
+
needsWeights(header);
|
|
935
963
|
const colors = header.merges + (clustering.length >= header.headerLength + 3 ? 1 : 0);
|
|
936
964
|
const info = {
|
|
937
965
|
formatVersion: header.version,
|
|
@@ -939,13 +967,10 @@ export const getClusteringInfo = async (clustering, ...extra) => {
|
|
|
939
967
|
precision: header.precision,
|
|
940
968
|
transparent: header.transparent === 0 ? false : header.transparent,
|
|
941
969
|
maxColors: colors,
|
|
942
|
-
totalWeight:
|
|
970
|
+
totalWeight: 0,
|
|
943
971
|
mse: null,
|
|
944
972
|
explained: null
|
|
945
973
|
};
|
|
946
|
-
if (header.version < 3) {
|
|
947
|
-
return info;
|
|
948
|
-
}
|
|
949
974
|
const view = new DataView(clustering.buffer, clustering.byteOffset, clustering.byteLength);
|
|
950
975
|
const pixels = 2 ** clustering[7] / (clustering[6] === 1 ? 255 : 1);
|
|
951
976
|
const total = view.getUint32(8, true);
|
|
@@ -988,7 +1013,7 @@ export const quantize = async (image, k, options) => {
|
|
|
988
1013
|
report(1);
|
|
989
1014
|
return mapped;
|
|
990
1015
|
}
|
|
991
|
-
return wrap(call(wasm, [image.data], imagePointer => wasm._quantize(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.width, o.transparent)));
|
|
1016
|
+
return wrap(call(wasm, [image.data], imagePointer => wasm._quantize(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.width, o.transparent), o.precision));
|
|
992
1017
|
};
|
|
993
1018
|
export const quantizeFromClustering = async (image, clustering, k, options) => {
|
|
994
1019
|
const wrap = getWrapper(image);
|
|
@@ -1030,7 +1055,7 @@ export const quantizeToIndices = async (image, k, options) => {
|
|
|
1030
1055
|
report(1);
|
|
1031
1056
|
return indexed;
|
|
1032
1057
|
}
|
|
1033
|
-
return unpackIndices(call(wasm, [image.data], imagePointer => wasm._quantize_indices(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.width, o.transparent)), original, colorSpaceName(o.colorSpace));
|
|
1058
|
+
return unpackIndices(call(wasm, [image.data], imagePointer => wasm._quantize_indices(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.width, o.transparent), o.precision), original, colorSpaceName(o.colorSpace));
|
|
1034
1059
|
};
|
|
1035
1060
|
export const quantizeToIndicesFromClustering = async (image, clustering, k, options) => {
|
|
1036
1061
|
const original = image;
|
package/dist/shared.cjs
CHANGED
|
@@ -6,14 +6,14 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
6
6
|
exports.Clustering = Clustering;
|
|
7
7
|
exports.MARK = void 0;
|
|
8
8
|
exports.Palette = Palette;
|
|
9
|
-
exports.version = exports.snapshot = exports.revive = exports.readHeader = exports.markPalette = exports.markClustering = exports.mark = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isImageData = exports.isDetached = exports.isCodedError = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageDataLike = exports.formatVersion = exports.fail = exports.errorCodes = exports.colorSpaces = exports.colorSpaceName = exports.checkPalette = exports.checkImageDataPixels = void 0;
|
|
9
|
+
exports.version = exports.tooLarge = exports.snapshot = exports.sizeText = exports.revive = exports.readHeader = exports.maxBytes = exports.markPalette = exports.markClustering = exports.mark = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isImageData = exports.isDetached = exports.isCodedError = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageDataLike = exports.formatVersion = exports.fail = exports.errorCodes = exports.colorSpaces = exports.colorSpaceName = exports.checkPalette = exports.checkImageDataPixels = void 0;
|
|
10
10
|
// Shared by both entries (index.js and worker.js) and the worker thread: errors, option snapshots, reading a clustering's
|
|
11
11
|
// header, the Palette and Clustering types, and the markers that carry those types across the worker boundary. Imported as
|
|
12
12
|
// './shared.js'; the build rewrites that to './shared.mjs' or './shared.cjs' (scripts/babel-import-extensions.cjs).
|
|
13
13
|
|
|
14
14
|
// The library's version: package.json is the source, and scripts/sync-version.mjs keeps this line (and the copy the .wasm
|
|
15
15
|
// is built from, src/version.hpp) in step with it. Do not edit it by hand.
|
|
16
|
-
const version = exports.version = '3.0.0
|
|
16
|
+
const version = exports.version = '3.0.0';
|
|
17
17
|
const colorSpaces = exports.colorSpaces = {
|
|
18
18
|
'rgb': 0,
|
|
19
19
|
'oklab': 1
|
|
@@ -42,9 +42,19 @@ const fail = (code, message, argument) => Object.assign(new Error(message), argu
|
|
|
42
42
|
argument
|
|
43
43
|
});
|
|
44
44
|
|
|
45
|
+
// The module's memory is at most 2 GB (MAXIMUM_MEMORY in build:wasm) and its allocator takes a 32-bit signed size, so a
|
|
46
|
+
// buffer of 2 GB or more can never be copied in: _malloc would read its length as negative, or (from 4 GB) wrap it to a
|
|
47
|
+
// small number and hand back a block too short for the copy. Such buffers are rejected before any allocation, and the
|
|
48
|
+
// worker entry rejects them before sending, as the main entry does (from 4 GB a buffer can't even be cloned to send).
|
|
49
|
+
exports.fail = fail;
|
|
50
|
+
const maxBytes = exports.maxBytes = 2 ** 31;
|
|
51
|
+
const sizeText = bytes => bytes >= 2 ** 30 ? `${(bytes / 2 ** 30).toFixed(2)} GB` : `${Math.round(bytes / 2 ** 20)} MB`;
|
|
52
|
+
exports.sizeText = sizeText;
|
|
53
|
+
const tooLarge = bytes => fail('out-of-memory', `The input is ${sizeText(bytes)}, more than the WebAssembly module can hold: it has at most 2 GB in all, for the pixels and the work on them, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels of RGBA). Scale the image down for its palette (a few megapixels give as good a one), and map a full-size image in strips with quantizeWithPalette.`);
|
|
54
|
+
|
|
45
55
|
// Type checks by tag rather than `instanceof`, so values from another realm (an iframe, a vm context, a test sandbox,
|
|
46
56
|
// whose Uint8Array is a different constructor) are recognised. A Node Buffer is a Uint8Array by tag too.
|
|
47
|
-
exports.
|
|
57
|
+
exports.tooLarge = tooLarge;
|
|
48
58
|
const tag = value => Object.prototype.toString.call(value);
|
|
49
59
|
const isUint8Array = value => ArrayBuffer.isView(value) && tag(value) === '[object Uint8Array]';
|
|
50
60
|
exports.isUint8Array = isUint8Array;
|
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.0.0
|
|
7
|
+
export const version = '3.0.0';
|
|
8
8
|
export const colorSpaces = {
|
|
9
9
|
'rgb': 0,
|
|
10
10
|
'oklab': 1
|
|
@@ -31,6 +31,14 @@ export const fail = (code, message, argument) => Object.assign(new Error(message
|
|
|
31
31
|
argument
|
|
32
32
|
});
|
|
33
33
|
|
|
34
|
+
// The module's memory is at most 2 GB (MAXIMUM_MEMORY in build:wasm) and its allocator takes a 32-bit signed size, so a
|
|
35
|
+
// buffer of 2 GB or more can never be copied in: _malloc would read its length as negative, or (from 4 GB) wrap it to a
|
|
36
|
+
// small number and hand back a block too short for the copy. Such buffers are rejected before any allocation, and the
|
|
37
|
+
// worker entry rejects them before sending, as the main entry does (from 4 GB a buffer can't even be cloned to send).
|
|
38
|
+
export const maxBytes = 2 ** 31;
|
|
39
|
+
export const sizeText = bytes => bytes >= 2 ** 30 ? `${(bytes / 2 ** 30).toFixed(2)} GB` : `${Math.round(bytes / 2 ** 20)} MB`;
|
|
40
|
+
export const tooLarge = bytes => fail('out-of-memory', `The input is ${sizeText(bytes)}, more than the WebAssembly module can hold: it has at most 2 GB in all, for the pixels and the work on them, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels of RGBA). Scale the image down for its palette (a few megapixels give as good a one), and map a full-size image in strips with quantizeWithPalette.`);
|
|
41
|
+
|
|
34
42
|
// Type checks by tag rather than `instanceof`, so values from another realm (an iframe, a vm context, a test sandbox,
|
|
35
43
|
// whose Uint8Array is a different constructor) are recognised. A Node Buffer is a Uint8Array by tag too.
|
|
36
44
|
const tag = value => Object.prototype.toString.call(value);
|
package/dist/worker.cjs
CHANGED
|
@@ -293,6 +293,10 @@ const send = image => {
|
|
|
293
293
|
if (pixels && (0, _shared.isDetached)(pixels)) {
|
|
294
294
|
throw (0, _shared.fail)('invalid-argument', "Invalid image: its pixels were transferred away (detached), for example to a worker created with transfer: true, so it has none left. Pass a copy if you need to keep using it.", 'image');
|
|
295
295
|
}
|
|
296
|
+
// Too large for the module, as the main entry reports it, before a copy is made to send (or, from 4 GB, fails to be).
|
|
297
|
+
if (pixels && pixels.byteLength >= _shared.maxBytes) {
|
|
298
|
+
throw (0, _shared.tooLarge)(pixels.byteLength);
|
|
299
|
+
}
|
|
296
300
|
if ((0, _shared.isImageData)(image)) {
|
|
297
301
|
(0, _shared.checkImageDataPixels)(image);
|
|
298
302
|
const data = image.data;
|
|
@@ -672,8 +676,8 @@ const makeWorker = (options, allowScript) => {
|
|
|
672
676
|
}
|
|
673
677
|
const waitingFor = startingGeneration;
|
|
674
678
|
const started = await starting;
|
|
679
|
+
// terminate() stops the worker that was starting itself, once (not once per call that waited for it).
|
|
675
680
|
if (terminated) {
|
|
676
|
-
started.terminate();
|
|
677
681
|
throw (0, _shared.fail)('worker-terminated', "Worker terminated.");
|
|
678
682
|
}
|
|
679
683
|
// The worker may have failed in the instant between starting and being adopted; it has been dropped then.
|
|
@@ -946,11 +950,10 @@ const makeWorker = (options, allowScript) => {
|
|
|
946
950
|
})();
|
|
947
951
|
};
|
|
948
952
|
|
|
949
|
-
// Stops the worker. Calls still waiting are rejected, and later calls fail.
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
}
|
|
953
|
+
// Stops the worker. Calls still waiting are rejected, and later calls fail. Every call of it returns the same promise,
|
|
954
|
+
// so a second terminate() made while the first is running also waits until the thread has gone.
|
|
955
|
+
let stopping = null;
|
|
956
|
+
const stop = () => stopping = stopping || (async () => {
|
|
954
957
|
terminated = true;
|
|
955
958
|
for (const call of pending.values()) {
|
|
956
959
|
call.cleanup();
|
|
@@ -964,7 +967,7 @@ const makeWorker = (options, allowScript) => {
|
|
|
964
967
|
(await starting).terminate();
|
|
965
968
|
} catch (ignored) {/* it never started */}
|
|
966
969
|
}
|
|
967
|
-
};
|
|
970
|
+
})();
|
|
968
971
|
// An abandoned worker is stopped once nothing can use it any more (see `abandoned`).
|
|
969
972
|
const stopIfAbandoned = () => {
|
|
970
973
|
if (abandoned && active === 0 && liveHandles === 0 && !terminated) {
|
package/dist/worker.d.cts
CHANGED
|
@@ -24,11 +24,11 @@ export { isCodedError } from './index.cjs';
|
|
|
24
24
|
export const version: string;
|
|
25
25
|
|
|
26
26
|
/** The version of the data this library stores (clusterings): the same value as the main entry's `formatVersion`. */
|
|
27
|
-
export const formatVersion:
|
|
27
|
+
export const formatVersion: number;
|
|
28
28
|
|
|
29
29
|
export type {
|
|
30
30
|
ImageFormat, RawImage, ImageLike, PaletteLike, PlatformImageData, ImageResult, WasmModule, ColorSpace, AlphaMode, ClusteringOptions, MappingOptions, QuantizeOptions,
|
|
31
|
-
ErrorCode, ErrorArgument, CodedError, InitOptions,
|
|
31
|
+
ErrorCode, ErrorArgument, CodedError, InitOptions, ProgressOptions, CancelOptions, IndexOptions, QuantizeIndexOptions, MappingIndexOptions, IndexedImage, ClusteringInfo, Swatches,
|
|
32
32
|
} from './index.cjs';
|
|
33
33
|
|
|
34
34
|
/** Options for `createWorker`. */
|
package/dist/worker.d.ts
CHANGED
|
@@ -24,11 +24,11 @@ export { isCodedError } from './index.js';
|
|
|
24
24
|
export const version: string;
|
|
25
25
|
|
|
26
26
|
/** The version of the data this library stores (clusterings): the same value as the main entry's `formatVersion`. */
|
|
27
|
-
export const formatVersion:
|
|
27
|
+
export const formatVersion: number;
|
|
28
28
|
|
|
29
29
|
export type {
|
|
30
30
|
ImageFormat, RawImage, ImageLike, PaletteLike, PlatformImageData, ImageResult, WasmModule, ColorSpace, AlphaMode, ClusteringOptions, MappingOptions, QuantizeOptions,
|
|
31
|
-
ErrorCode, ErrorArgument, CodedError, InitOptions,
|
|
31
|
+
ErrorCode, ErrorArgument, CodedError, InitOptions, ProgressOptions, CancelOptions, IndexOptions, QuantizeIndexOptions, MappingIndexOptions, IndexedImage, ClusteringInfo, Swatches,
|
|
32
32
|
} from './index.js';
|
|
33
33
|
|
|
34
34
|
/** Options for `createWorker`. */
|
package/dist/worker.mjs
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// handle, so re-cutting and re-mapping it copies nothing across. The functions exported directly use one shared
|
|
5
5
|
// worker, started on first use.
|
|
6
6
|
|
|
7
|
-
import { fail, isOptionsObject, snapshot, mark, revive, latestVersion, imageHint, isDetached, imageDataLike, isImageData, checkImageDataPixels } from "./shared.mjs";
|
|
7
|
+
import { fail, isOptionsObject, snapshot, mark, revive, latestVersion, imageHint, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, tooLarge } from "./shared.mjs";
|
|
8
8
|
|
|
9
9
|
// The same version, types and data-format version as the main entry (one implementation, in shared.js).
|
|
10
10
|
export { version, Palette, Clustering, errorCodes, isCodedError } from "./shared.mjs";
|
|
@@ -256,6 +256,10 @@ const send = image => {
|
|
|
256
256
|
if (pixels && isDetached(pixels)) {
|
|
257
257
|
throw fail('invalid-argument', "Invalid image: its pixels were transferred away (detached), for example to a worker created with transfer: true, so it has none left. Pass a copy if you need to keep using it.", 'image');
|
|
258
258
|
}
|
|
259
|
+
// Too large for the module, as the main entry reports it, before a copy is made to send (or, from 4 GB, fails to be).
|
|
260
|
+
if (pixels && pixels.byteLength >= maxBytes) {
|
|
261
|
+
throw tooLarge(pixels.byteLength);
|
|
262
|
+
}
|
|
259
263
|
if (isImageData(image)) {
|
|
260
264
|
checkImageDataPixels(image);
|
|
261
265
|
const data = image.data;
|
|
@@ -635,8 +639,8 @@ const makeWorker = (options, allowScript) => {
|
|
|
635
639
|
}
|
|
636
640
|
const waitingFor = startingGeneration;
|
|
637
641
|
const started = await starting;
|
|
642
|
+
// terminate() stops the worker that was starting itself, once (not once per call that waited for it).
|
|
638
643
|
if (terminated) {
|
|
639
|
-
started.terminate();
|
|
640
644
|
throw fail('worker-terminated', "Worker terminated.");
|
|
641
645
|
}
|
|
642
646
|
// The worker may have failed in the instant between starting and being adopted; it has been dropped then.
|
|
@@ -909,11 +913,10 @@ const makeWorker = (options, allowScript) => {
|
|
|
909
913
|
})();
|
|
910
914
|
};
|
|
911
915
|
|
|
912
|
-
// Stops the worker. Calls still waiting are rejected, and later calls fail.
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
}
|
|
916
|
+
// Stops the worker. Calls still waiting are rejected, and later calls fail. Every call of it returns the same promise,
|
|
917
|
+
// so a second terminate() made while the first is running also waits until the thread has gone.
|
|
918
|
+
let stopping = null;
|
|
919
|
+
const stop = () => stopping = stopping || (async () => {
|
|
917
920
|
terminated = true;
|
|
918
921
|
for (const call of pending.values()) {
|
|
919
922
|
call.cleanup();
|
|
@@ -927,7 +930,7 @@ const makeWorker = (options, allowScript) => {
|
|
|
927
930
|
(await starting).terminate();
|
|
928
931
|
} catch (ignored) {/* it never started */}
|
|
929
932
|
}
|
|
930
|
-
};
|
|
933
|
+
})();
|
|
931
934
|
// An abandoned worker is stopped once nothing can use it any more (see `abandoned`).
|
|
932
935
|
const stopIfAbandoned = () => {
|
|
933
936
|
if (abandoned && active === 0 && liveHandles === 0 && !terminated) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agglomerative-clustering",
|
|
3
|
-
"version": "3.0.0
|
|
3
|
+
"version": "3.0.0",
|
|
4
4
|
"description": "Colour palette extraction and image quantization with exact Ward clustering, in WebAssembly. Cluster an image once, then cut it to a palette of any size.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Rohan Fredriksson",
|