agglomerative-clustering 3.2.0 → 3.4.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 +28 -21
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +41 -17
- package/dist/index.d.cts +30 -8
- package/dist/index.d.ts +30 -8
- package/dist/index.mjs +38 -15
- package/dist/shared.cjs +103 -9
- package/dist/shared.mjs +101 -8
- package/dist/worker-thread.mjs +21 -5
- package/dist/worker.cjs +82 -26
- package/dist/worker.d.cts +22 -4
- package/dist/worker.d.ts +22 -4
- package/dist/worker.mjs +79 -24
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import createWasmModule from './clustering.js';
|
|
2
|
-
import { parseDither, version, fail, colorSpaceCodes, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, imageHint, latestVersion, imageFormats, channels, hasAlpha, formatNames, detachedError, describe, readHeader, checkPalette, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, sizeText, tooLarge } from "./shared.mjs";
|
|
2
|
+
import { parseDither, version, fail, colorSpaceCodes, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, setEngine, imageHint, latestVersion, imageFormats, channels, hasAlpha, formatNames, detachedError, describe, readHeader, checkPalette, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, sizeText, tooLarge } from "./shared.mjs";
|
|
3
3
|
|
|
4
4
|
// The library's version, the stored-data format version, and the Palette and Clustering types (see shared.js).
|
|
5
5
|
export { version, Palette, Clustering, errorCodes, isCodedError, ditherMethods, ditherSteps, colorSpaces, imageFormats, alphaModes } from "./shared.mjs";
|
|
@@ -478,7 +478,7 @@ const checkSize = (pixels, size, name, argument) => {
|
|
|
478
478
|
};
|
|
479
479
|
const load = image => {
|
|
480
480
|
if (isClustering(image) || isPalette(image)) {
|
|
481
|
-
const what = isClustering(image) ? 'a clustering (from
|
|
481
|
+
const what = isClustering(image) ? 'a clustering (from buildClustering)' : 'a palette';
|
|
482
482
|
const fix = isClustering(image) ? 'To cut a palette from it, use getPaletteFromClustering (or quantizeFromClustering to map an image with it).' : 'To map an image to it, use quantizeWithPalette(image, palette).';
|
|
483
483
|
throw fail('invalid-argument', `Invalid image: this is ${what}, not pixels. ${fix}`, 'image');
|
|
484
484
|
}
|
|
@@ -637,7 +637,7 @@ const parseOptions = (options, allowed, image) => {
|
|
|
637
637
|
options = snapshot(options);
|
|
638
638
|
for (const key of Object.keys(options)) {
|
|
639
639
|
if (!allowed.includes(key)) {
|
|
640
|
-
const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' : '';
|
|
640
|
+
const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' : key === 'onProgress' && allowed.includes('signal') ? ' The functions that only map pixels take just signal: they finish in milliseconds, with no progress to report.' : '';
|
|
641
641
|
throw fail('invalid-argument', `Invalid option '${key}': expected one of ${allowed.join(', ')}.${hint}`, `options.${key}`);
|
|
642
642
|
}
|
|
643
643
|
}
|
|
@@ -888,9 +888,12 @@ const clusterInSlices = async (wasm, image, o, report, share) => {
|
|
|
888
888
|
|
|
889
889
|
// The functions that read a clustering take no options: a clustering already says how it was made. An options object passed
|
|
890
890
|
// anyway (say { colorSpace: 'oklab' }, expecting it to apply) would be silently ignored, so it is an error. undefined is fine.
|
|
891
|
+
// `name` is how the caller wrote the call: the function, or the method (`clustering.getPalette`), whose message points at
|
|
892
|
+
// the method form of mapping.
|
|
891
893
|
const noOptions = (name, extra) => {
|
|
892
894
|
if (extra.some(value => value !== undefined)) {
|
|
893
|
-
|
|
895
|
+
const alternative = name.startsWith('clustering.') ? 'clustering.quantize' : 'quantizeFromClustering';
|
|
896
|
+
throw fail('invalid-argument', `Invalid arguments: ${name} takes no options (a clustering already records its colour space, precision and cutoff). To map pixels with other options, use ${alternative}.`, 'options');
|
|
894
897
|
}
|
|
895
898
|
};
|
|
896
899
|
|
|
@@ -898,7 +901,7 @@ const noOptions = (name, extra) => {
|
|
|
898
901
|
// already loaded, `Module || await acquire()` doesn't wait, and the work up to the first slice of a long clustering
|
|
899
902
|
// happens before the call returns.
|
|
900
903
|
|
|
901
|
-
export const
|
|
904
|
+
export const buildClustering = async (image, options) => {
|
|
902
905
|
image = load(image);
|
|
903
906
|
const o = parseOptions(options, clusterOptions, image);
|
|
904
907
|
const wasm = Module || (await acquire());
|
|
@@ -910,7 +913,9 @@ export const getClustering = async (image, options) => {
|
|
|
910
913
|
}
|
|
911
914
|
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));
|
|
912
915
|
};
|
|
913
|
-
|
|
916
|
+
/** @deprecated The same function as buildClustering, its name before 3.4.0. Removed in 4.0. */
|
|
917
|
+
export const getClustering = buildClustering;
|
|
918
|
+
export const buildPalette = async (image, k, options) => {
|
|
914
919
|
image = load(image);
|
|
915
920
|
k = check(k);
|
|
916
921
|
const o = parseOptions(options, clusterOptions, image);
|
|
@@ -925,14 +930,19 @@ export const getPalette = async (image, k, options) => {
|
|
|
925
930
|
}
|
|
926
931
|
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));
|
|
927
932
|
};
|
|
928
|
-
|
|
933
|
+
/** @deprecated The same function as buildPalette, its name before 3.4.0. Removed in 4.0. */
|
|
934
|
+
export const getPalette = buildPalette;
|
|
935
|
+
|
|
936
|
+
// The cuts take the name they were called by, for their messages: the functions below, or the methods on Clustering.
|
|
937
|
+
const cutPalette = async (name, clustering, k, extra) => {
|
|
929
938
|
const header = readHeader(clustering);
|
|
930
939
|
k = check(k);
|
|
931
|
-
noOptions(
|
|
940
|
+
noOptions(name, extra);
|
|
932
941
|
clustering = held(clustering);
|
|
933
942
|
const wasm = Module || (await acquire());
|
|
934
943
|
return markPalette(call(wasm, [clustering], clusteringPointer => wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k)), colorSpaceName(header.colorSpace));
|
|
935
944
|
};
|
|
945
|
+
export const getPaletteFromClustering = (clustering, k, ...extra) => cutPalette('getPaletteFromClustering', clustering, k, extra);
|
|
936
946
|
|
|
937
947
|
// The weight of each colour in the k-colour cut, in pixels (opacity-weighted), read from the clustering's records.
|
|
938
948
|
const weightsOf = (wasm, clustering, header, k) => {
|
|
@@ -954,10 +964,10 @@ const needsWeights = header => {
|
|
|
954
964
|
// A palette with the weight and share of the image of each of its colours, from one cut of one clustering, so the three
|
|
955
965
|
// arrays line up by construction. Weights are pixels: fully transparent pixels count 0 and partly transparent ones in
|
|
956
966
|
// proportion to their opacity, as in clustering. Shares are the weights divided by their total, so they sum to 1.
|
|
957
|
-
|
|
967
|
+
const cutSwatches = async (name, clustering, k, extra) => {
|
|
958
968
|
const header = readHeader(clustering);
|
|
959
969
|
k = check(k);
|
|
960
|
-
noOptions(
|
|
970
|
+
noOptions(name, extra);
|
|
961
971
|
needsWeights(header);
|
|
962
972
|
clustering = held(clustering);
|
|
963
973
|
const wasm = Module || (await acquire());
|
|
@@ -979,21 +989,24 @@ export const getSwatchesFromClustering = async (clustering, k, ...extra) => {
|
|
|
979
989
|
shares
|
|
980
990
|
};
|
|
981
991
|
};
|
|
992
|
+
export const getSwatchesFromClustering = (clustering, k, ...extra) => cutSwatches('getSwatchesFromClustering', clustering, k, extra);
|
|
982
993
|
|
|
983
994
|
// The same for an image: clusters it, then cuts, like getPalette.
|
|
984
|
-
export const
|
|
995
|
+
export const buildSwatches = async (image, k, options) => {
|
|
985
996
|
// Arguments are checked in the order they are given (image, then k, then options), as in every other function.
|
|
986
997
|
load(image);
|
|
987
998
|
k = check(k);
|
|
988
|
-
return getSwatchesFromClustering(await
|
|
999
|
+
return getSwatchesFromClustering(await buildClustering(image, options), k);
|
|
989
1000
|
};
|
|
1001
|
+
/** @deprecated The same function as buildSwatches, its name before 3.4.0. Removed in 4.0. */
|
|
1002
|
+
export const getSwatches = buildSwatches;
|
|
990
1003
|
|
|
991
1004
|
// What a clustering holds, read from its header and records without the WASM module. `mse[k - 1]` is the mean
|
|
992
1005
|
// squared error per channel of the k-colour clustering: each pixel's squared distance to its cluster's colour,
|
|
993
1006
|
// weighted as in clustering, in 8-bit RGB values (RGB) or OKLab units (OKLab).
|
|
994
|
-
|
|
1007
|
+
const readInfo = async (name, clustering, extra) => {
|
|
995
1008
|
const header = readHeader(clustering);
|
|
996
|
-
noOptions(
|
|
1009
|
+
noOptions(name, extra);
|
|
997
1010
|
needsWeights(header);
|
|
998
1011
|
const colors = header.merges + (clustering.length >= header.headerLength + 3 ? 1 : 0);
|
|
999
1012
|
const info = {
|
|
@@ -1034,6 +1047,7 @@ export const getClusteringInfo = async (clustering, ...extra) => {
|
|
|
1034
1047
|
}
|
|
1035
1048
|
return info;
|
|
1036
1049
|
};
|
|
1050
|
+
export const getClusteringInfo = (clustering, ...extra) => readInfo('getClusteringInfo', clustering, extra);
|
|
1037
1051
|
export const quantize = async (image, k, options) => {
|
|
1038
1052
|
const wrap = getWrapper(image);
|
|
1039
1053
|
image = load(image);
|
|
@@ -1121,4 +1135,13 @@ export const quantizeToIndicesWithPalette = async (image, palette, options) => {
|
|
|
1121
1135
|
checkAborted(o.signal);
|
|
1122
1136
|
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);
|
|
1123
1137
|
return result;
|
|
1124
|
-
};
|
|
1138
|
+
};
|
|
1139
|
+
|
|
1140
|
+
// The methods on Clustering (shared.js) run through these. Only this entry fills the slot, so the methods need it loaded.
|
|
1141
|
+
setEngine({
|
|
1142
|
+
cut: cutPalette,
|
|
1143
|
+
cutSwatches,
|
|
1144
|
+
info: readInfo,
|
|
1145
|
+
quantizeFromClustering,
|
|
1146
|
+
quantizeToIndicesFromClustering
|
|
1147
|
+
});
|
package/dist/shared.cjs
CHANGED
|
@@ -6,14 +6,14 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
6
6
|
exports.Clustering = Clustering;
|
|
7
7
|
exports.MARK = void 0;
|
|
8
8
|
exports.Palette = Palette;
|
|
9
|
-
exports.version = exports.tooLarge = exports.snapshot = exports.sizeText = exports.revive = exports.readHeader = exports.parseDither = exports.maxBytes = exports.markPalette = exports.markClustering = exports.mark = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isImageData = exports.isDetached = exports.isCodedError = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageFormats = exports.imageDataLike = exports.hasAlpha = exports.formatVersion = exports.formatNames = exports.fail = exports.errorCodes = exports.ditherSteps = exports.ditherMethods = exports.detachedError = exports.describe = exports.colorSpaces = exports.colorSpaceName = exports.colorSpaceCodes = exports.checkPalette = exports.checkImageDataPixels = exports.channels = exports.alphaModes = void 0;
|
|
9
|
+
exports.version = exports.tooLarge = exports.snapshot = exports.sizeText = exports.setEngine = exports.revive = exports.readHeader = exports.parseDither = exports.maxBytes = exports.markPalette = exports.markClustering = exports.mark = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isImageData = exports.isDetached = exports.isCodedError = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageFormats = exports.imageDataLike = exports.hasAlpha = exports.formatVersion = exports.formatNames = exports.fail = exports.errorCodes = exports.ditherSteps = exports.ditherMethods = exports.detachedError = exports.describe = exports.colorSpaces = exports.colorSpaceName = exports.colorSpaceCodes = exports.checkPalette = exports.checkImageDataPixels = exports.channels = exports.alphaModes = void 0;
|
|
10
10
|
// Shared by both entries (index.js and worker.js) and the worker thread: errors, option snapshots, reading a clustering's
|
|
11
11
|
// header, the Palette and Clustering types, and the markers that carry those types across the worker boundary. Imported as
|
|
12
12
|
// './shared.js'; the build rewrites that to './shared.mjs' or './shared.cjs' (scripts/babel-import-extensions.cjs).
|
|
13
13
|
|
|
14
14
|
// The library's version: package.json is the source, and scripts/sync-version.mjs keeps this line (and the copy the .wasm
|
|
15
15
|
// is built from, src/version.hpp) in step with it. Do not edit it by hand.
|
|
16
|
-
const version = exports.version = '3.
|
|
16
|
+
const version = exports.version = '3.4.0';
|
|
17
17
|
const colorSpaceCodes = exports.colorSpaceCodes = {
|
|
18
18
|
'rgb': 0,
|
|
19
19
|
'oklab': 1
|
|
@@ -328,7 +328,100 @@ const markPalette = (bytes, colorSpace) => {
|
|
|
328
328
|
});
|
|
329
329
|
return bytes;
|
|
330
330
|
};
|
|
331
|
+
// Methods on a clustering: `clustering.getPalette(k)` is `getPaletteFromClustering(clustering, k)`, and so on. They are
|
|
332
|
+
// non-enumerable own properties, added with the tags, so a clustering stays a plain Uint8Array (`toEqual` and
|
|
333
|
+
// `deepStrictEqual` against plain bytes still pass), and slices and clones drop them as they drop the tags. They run on the
|
|
334
|
+
// calling thread with the main entry's functions, which the main entry puts in `engine` when it is evaluated; the worker
|
|
335
|
+
// entry puts nothing there, so in a worker-only app the methods reject and say what to import. Each copy of this file (the
|
|
336
|
+
// ES module and the CommonJS build) has its own slot, filled by the main entry of the same module system.
|
|
331
337
|
exports.markPalette = markPalette;
|
|
338
|
+
let engine = null;
|
|
339
|
+
// The first main entry evaluated keeps the slot: it is the one an app loads and gives `init({ wasm })`, so a later copy
|
|
340
|
+
// (a duplicated chunk, a query-string import) doesn't re-point every clustering at a module of its own that isn't set up.
|
|
341
|
+
const setEngine = value => {
|
|
342
|
+
if (engine === null) {
|
|
343
|
+
engine = value;
|
|
344
|
+
}
|
|
345
|
+
};
|
|
346
|
+
// Each method's call shape and its function form, for messages.
|
|
347
|
+
exports.setEngine = setEngine;
|
|
348
|
+
const methodNames = {
|
|
349
|
+
getPalette: ['getPalette(k)', 'getPaletteFromClustering(clustering, k)'],
|
|
350
|
+
getSwatches: ['getSwatches(k)', 'getSwatchesFromClustering(clustering, k)'],
|
|
351
|
+
getClusteringInfo: ['getClusteringInfo()', 'getClusteringInfo(clustering)'],
|
|
352
|
+
quantize: ['quantize(image, k)', 'quantizeFromClustering(image, clustering, k)'],
|
|
353
|
+
quantizeToIndices: ['quantizeToIndices(image, k)', 'quantizeToIndicesFromClustering(image, clustering, k)']
|
|
354
|
+
};
|
|
355
|
+
// Checks the receiver before anything else, since it is written first, then (for the mapping methods) that the image isn't
|
|
356
|
+
// the worker handle's `k`, then that the main entry is loaded.
|
|
357
|
+
const receive = (name, receiver, image) => {
|
|
358
|
+
const [shape, form] = methodNames[name];
|
|
359
|
+
if (!isUint8Array(receiver)) {
|
|
360
|
+
throw fail('invalid-clustering', `Invalid clustering: ${name} was called without its clustering (this is ${receiver === undefined ? 'undefined' : describe(receiver)}). Call it as clustering.${shape}, or use ${form}.`, 'clustering');
|
|
361
|
+
}
|
|
362
|
+
readHeader(receiver);
|
|
363
|
+
if (image !== undefined) {
|
|
364
|
+
checkImageFirst(name, image.value);
|
|
365
|
+
}
|
|
366
|
+
if (engine === null) {
|
|
367
|
+
throw fail('wasm-load-failed', `clustering.${name} can't run here: a clustering's methods run on the calling thread with the main entry, 'agglomerative-clustering', of the copy of the package that made it, and that entry isn't loaded on this thread (this clustering came from the worker entry, or from another copy, such as the other module system's build). Import 'agglomerative-clustering' in this thread (and call its init({ wasm }) if you set where the module comes from), wrap the bytes with new Clustering(bytes) from the main entry you use, or call ${form} from 'agglomerative-clustering/worker', which runs in the worker.`);
|
|
368
|
+
}
|
|
369
|
+
return engine;
|
|
370
|
+
};
|
|
371
|
+
// The worker handle's quantize(k) maps the image it holds; this one takes the image first, so a number there is that mistake.
|
|
372
|
+
const checkImageFirst = (name, image) => {
|
|
373
|
+
if (typeof image === 'number') {
|
|
374
|
+
throw fail('invalid-argument', `Invalid image: got ${image}. clustering.${name} takes the image first: clustering.${name}(image, k). (A worker handle's ${name}(k) maps the image it holds.)`, 'image');
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
// Plain functions (they read `this`) that return a promise and never throw: errors are rejections, as from the functions.
|
|
378
|
+
const methods = {
|
|
379
|
+
getPalette(k, ...extra) {
|
|
380
|
+
try {
|
|
381
|
+
return receive('getPalette', this).cut('clustering.getPalette', this, k, extra);
|
|
382
|
+
} catch (error) {
|
|
383
|
+
return Promise.reject(error);
|
|
384
|
+
}
|
|
385
|
+
},
|
|
386
|
+
getSwatches(k, ...extra) {
|
|
387
|
+
try {
|
|
388
|
+
return receive('getSwatches', this).cutSwatches('clustering.getSwatches', this, k, extra);
|
|
389
|
+
} catch (error) {
|
|
390
|
+
return Promise.reject(error);
|
|
391
|
+
}
|
|
392
|
+
},
|
|
393
|
+
getClusteringInfo(...extra) {
|
|
394
|
+
try {
|
|
395
|
+
return receive('getClusteringInfo', this).info('clustering.getClusteringInfo', this, extra);
|
|
396
|
+
} catch (error) {
|
|
397
|
+
return Promise.reject(error);
|
|
398
|
+
}
|
|
399
|
+
},
|
|
400
|
+
quantize(image, k, options) {
|
|
401
|
+
try {
|
|
402
|
+
return receive('quantize', this, {
|
|
403
|
+
value: image
|
|
404
|
+
}).quantizeFromClustering(image, this, k, options);
|
|
405
|
+
} catch (error) {
|
|
406
|
+
return Promise.reject(error);
|
|
407
|
+
}
|
|
408
|
+
},
|
|
409
|
+
quantizeToIndices(image, k, options) {
|
|
410
|
+
try {
|
|
411
|
+
return receive('quantizeToIndices', this, {
|
|
412
|
+
value: image
|
|
413
|
+
}).quantizeToIndicesFromClustering(image, this, k, options);
|
|
414
|
+
} catch (error) {
|
|
415
|
+
return Promise.reject(error);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
};
|
|
419
|
+
// Writable and configurable like any method (so `vi.spyOn(clustering, 'getPalette')` works), and not enumerable.
|
|
420
|
+
const methodDescriptors = Object.fromEntries(Object.entries(methods).map(([name, value]) => [name, {
|
|
421
|
+
value,
|
|
422
|
+
writable: true,
|
|
423
|
+
configurable: true
|
|
424
|
+
}]));
|
|
332
425
|
const markClustering = bytes => {
|
|
333
426
|
// Made by this library (or checked by `Clustering`), so its checksum needn't be checked again (see readHeader).
|
|
334
427
|
checked.add(bytes);
|
|
@@ -338,6 +431,7 @@ const markClustering = bytes => {
|
|
|
338
431
|
Object.defineProperty(bytes, inspect, {
|
|
339
432
|
value: clusteringView
|
|
340
433
|
});
|
|
434
|
+
Object.defineProperties(bytes, methodDescriptors);
|
|
341
435
|
return bytes;
|
|
342
436
|
};
|
|
343
437
|
|
|
@@ -376,7 +470,7 @@ function Clustering(...args) {
|
|
|
376
470
|
// would coerce. A plain array must hold byte values, as for a palette.
|
|
377
471
|
const isBuffer = isArrayBufferLike(source);
|
|
378
472
|
if (!isUint8Array(source) && !isUint8ClampedArray(source) && !isBuffer && !Array.isArray(source)) {
|
|
379
|
-
throw fail('invalid-clustering', "Invalid clustering: expected its bytes (a Uint8Array, or an ArrayBuffer with an optional offset and length) from
|
|
473
|
+
throw fail('invalid-clustering', "Invalid clustering: expected its bytes (a Uint8Array, or an ArrayBuffer with an optional offset and length) from buildClustering.", 'clustering');
|
|
380
474
|
}
|
|
381
475
|
if (Array.isArray(source) && !source.every(value => Number.isInteger(value) && value >= 0 && value <= 255)) {
|
|
382
476
|
throw fail('invalid-clustering', "Invalid clustering: a plain array must hold byte values, integers from 0 to 255.", 'clustering');
|
|
@@ -455,26 +549,26 @@ const crc32 = bytes => {
|
|
|
455
549
|
return (crc ^ 0xFFFFFFFF) >>> 0;
|
|
456
550
|
};
|
|
457
551
|
const checked = new WeakSet();
|
|
458
|
-
const damaged = () => fail('invalid-clustering', "Invalid clustering: its bytes are damaged (the checksum doesn't match): it was truncated, changed or mixed up with other data after
|
|
552
|
+
const damaged = () => fail('invalid-clustering', "Invalid clustering: its bytes are damaged (the checksum doesn't match): it was truncated, changed or mixed up with other data after buildClustering made it. Cluster the image again.", 'clustering');
|
|
459
553
|
|
|
460
554
|
// The message for bytes that aren't a clustering: 1.x clusterings are mentioned only for bytes that could be one (no header,
|
|
461
555
|
// and a length of 0 or 3 more than a multiple of 9).
|
|
462
556
|
const notAClustering = clustering => {
|
|
463
557
|
const length = clustering.length;
|
|
464
558
|
if (clustering[0] !== 0xAC && (length % 9 === 0 || length % 9 === 3)) {
|
|
465
|
-
return fail('invalid-clustering', "Invalid clustering: not a clustering from
|
|
559
|
+
return fail('invalid-clustering', "Invalid clustering: not a clustering from buildClustering. If it was stored by agglomerative-clustering 1.x, that format is no longer read: cluster the image again.", 'clustering');
|
|
466
560
|
}
|
|
467
561
|
if (clustering[0] === 0xAC && length >= 2 && (clustering[1] === 2 || clustering[1] === 3)) {
|
|
468
562
|
return fail('invalid-clustering', `Invalid clustering: it starts like a format ${clustering[1]} clustering, but its length or header doesn't fit one (${length} bytes): it was probably truncated or damaged. Cluster the image again.`, 'clustering');
|
|
469
563
|
}
|
|
470
|
-
return fail('invalid-clustering', `Invalid clustering: not a clustering from
|
|
564
|
+
return fail('invalid-clustering', `Invalid clustering: not a clustering from buildClustering (${length} bytes that don't start with a clustering header).`, 'clustering');
|
|
471
565
|
};
|
|
472
566
|
const readHeader = clustering => {
|
|
473
567
|
if (isPalette(clustering)) {
|
|
474
|
-
throw fail('invalid-clustering', "Invalid clustering: this is a palette, not a clustering. Palettes come from
|
|
568
|
+
throw fail('invalid-clustering', "Invalid clustering: this is a palette, not a clustering. Palettes come from buildPalette and getPaletteFromClustering; a clustering comes from buildClustering.", 'clustering');
|
|
475
569
|
}
|
|
476
570
|
if (!isUint8Array(clustering)) {
|
|
477
|
-
throw fail('invalid-clustering', "Invalid clustering: must be a Uint8Array from
|
|
571
|
+
throw fail('invalid-clustering', "Invalid clustering: must be a Uint8Array from buildClustering.", 'clustering');
|
|
478
572
|
}
|
|
479
573
|
const length = clustering.length;
|
|
480
574
|
if (length >= 4 && clustering[0] === 0xAC) {
|
|
@@ -538,7 +632,7 @@ const readHeader = clustering => {
|
|
|
538
632
|
exports.readHeader = readHeader;
|
|
539
633
|
const checkPalette = palette => {
|
|
540
634
|
if (isClustering(palette)) {
|
|
541
|
-
throw fail('invalid-argument', "Invalid palette: this is a clustering (from
|
|
635
|
+
throw fail('invalid-argument', "Invalid palette: this is a clustering (from buildClustering), not a palette. Cut a palette from it with getPaletteFromClustering, or map with quantizeFromClustering.", 'palette');
|
|
542
636
|
}
|
|
543
637
|
if (!isUint8Array(palette) && !isUint8ClampedArray(palette) && !Array.isArray(palette)) {
|
|
544
638
|
throw fail('invalid-argument', "Invalid palette: must be a Uint8Array of RGB bytes.", 'palette');
|
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.4.0';
|
|
8
8
|
export const colorSpaceCodes = {
|
|
9
9
|
'rgb': 0,
|
|
10
10
|
'oklab': 1
|
|
@@ -297,6 +297,98 @@ export const markPalette = (bytes, colorSpace) => {
|
|
|
297
297
|
});
|
|
298
298
|
return bytes;
|
|
299
299
|
};
|
|
300
|
+
// Methods on a clustering: `clustering.getPalette(k)` is `getPaletteFromClustering(clustering, k)`, and so on. They are
|
|
301
|
+
// non-enumerable own properties, added with the tags, so a clustering stays a plain Uint8Array (`toEqual` and
|
|
302
|
+
// `deepStrictEqual` against plain bytes still pass), and slices and clones drop them as they drop the tags. They run on the
|
|
303
|
+
// calling thread with the main entry's functions, which the main entry puts in `engine` when it is evaluated; the worker
|
|
304
|
+
// entry puts nothing there, so in a worker-only app the methods reject and say what to import. Each copy of this file (the
|
|
305
|
+
// ES module and the CommonJS build) has its own slot, filled by the main entry of the same module system.
|
|
306
|
+
let engine = null;
|
|
307
|
+
// The first main entry evaluated keeps the slot: it is the one an app loads and gives `init({ wasm })`, so a later copy
|
|
308
|
+
// (a duplicated chunk, a query-string import) doesn't re-point every clustering at a module of its own that isn't set up.
|
|
309
|
+
export const setEngine = value => {
|
|
310
|
+
if (engine === null) {
|
|
311
|
+
engine = value;
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
// Each method's call shape and its function form, for messages.
|
|
315
|
+
const methodNames = {
|
|
316
|
+
getPalette: ['getPalette(k)', 'getPaletteFromClustering(clustering, k)'],
|
|
317
|
+
getSwatches: ['getSwatches(k)', 'getSwatchesFromClustering(clustering, k)'],
|
|
318
|
+
getClusteringInfo: ['getClusteringInfo()', 'getClusteringInfo(clustering)'],
|
|
319
|
+
quantize: ['quantize(image, k)', 'quantizeFromClustering(image, clustering, k)'],
|
|
320
|
+
quantizeToIndices: ['quantizeToIndices(image, k)', 'quantizeToIndicesFromClustering(image, clustering, k)']
|
|
321
|
+
};
|
|
322
|
+
// Checks the receiver before anything else, since it is written first, then (for the mapping methods) that the image isn't
|
|
323
|
+
// the worker handle's `k`, then that the main entry is loaded.
|
|
324
|
+
const receive = (name, receiver, image) => {
|
|
325
|
+
const [shape, form] = methodNames[name];
|
|
326
|
+
if (!isUint8Array(receiver)) {
|
|
327
|
+
throw fail('invalid-clustering', `Invalid clustering: ${name} was called without its clustering (this is ${receiver === undefined ? 'undefined' : describe(receiver)}). Call it as clustering.${shape}, or use ${form}.`, 'clustering');
|
|
328
|
+
}
|
|
329
|
+
readHeader(receiver);
|
|
330
|
+
if (image !== undefined) {
|
|
331
|
+
checkImageFirst(name, image.value);
|
|
332
|
+
}
|
|
333
|
+
if (engine === null) {
|
|
334
|
+
throw fail('wasm-load-failed', `clustering.${name} can't run here: a clustering's methods run on the calling thread with the main entry, 'agglomerative-clustering', of the copy of the package that made it, and that entry isn't loaded on this thread (this clustering came from the worker entry, or from another copy, such as the other module system's build). Import 'agglomerative-clustering' in this thread (and call its init({ wasm }) if you set where the module comes from), wrap the bytes with new Clustering(bytes) from the main entry you use, or call ${form} from 'agglomerative-clustering/worker', which runs in the worker.`);
|
|
335
|
+
}
|
|
336
|
+
return engine;
|
|
337
|
+
};
|
|
338
|
+
// The worker handle's quantize(k) maps the image it holds; this one takes the image first, so a number there is that mistake.
|
|
339
|
+
const checkImageFirst = (name, image) => {
|
|
340
|
+
if (typeof image === 'number') {
|
|
341
|
+
throw fail('invalid-argument', `Invalid image: got ${image}. clustering.${name} takes the image first: clustering.${name}(image, k). (A worker handle's ${name}(k) maps the image it holds.)`, 'image');
|
|
342
|
+
}
|
|
343
|
+
};
|
|
344
|
+
// Plain functions (they read `this`) that return a promise and never throw: errors are rejections, as from the functions.
|
|
345
|
+
const methods = {
|
|
346
|
+
getPalette(k, ...extra) {
|
|
347
|
+
try {
|
|
348
|
+
return receive('getPalette', this).cut('clustering.getPalette', this, k, extra);
|
|
349
|
+
} catch (error) {
|
|
350
|
+
return Promise.reject(error);
|
|
351
|
+
}
|
|
352
|
+
},
|
|
353
|
+
getSwatches(k, ...extra) {
|
|
354
|
+
try {
|
|
355
|
+
return receive('getSwatches', this).cutSwatches('clustering.getSwatches', this, k, extra);
|
|
356
|
+
} catch (error) {
|
|
357
|
+
return Promise.reject(error);
|
|
358
|
+
}
|
|
359
|
+
},
|
|
360
|
+
getClusteringInfo(...extra) {
|
|
361
|
+
try {
|
|
362
|
+
return receive('getClusteringInfo', this).info('clustering.getClusteringInfo', this, extra);
|
|
363
|
+
} catch (error) {
|
|
364
|
+
return Promise.reject(error);
|
|
365
|
+
}
|
|
366
|
+
},
|
|
367
|
+
quantize(image, k, options) {
|
|
368
|
+
try {
|
|
369
|
+
return receive('quantize', this, {
|
|
370
|
+
value: image
|
|
371
|
+
}).quantizeFromClustering(image, this, k, options);
|
|
372
|
+
} catch (error) {
|
|
373
|
+
return Promise.reject(error);
|
|
374
|
+
}
|
|
375
|
+
},
|
|
376
|
+
quantizeToIndices(image, k, options) {
|
|
377
|
+
try {
|
|
378
|
+
return receive('quantizeToIndices', this, {
|
|
379
|
+
value: image
|
|
380
|
+
}).quantizeToIndicesFromClustering(image, this, k, options);
|
|
381
|
+
} catch (error) {
|
|
382
|
+
return Promise.reject(error);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
};
|
|
386
|
+
// Writable and configurable like any method (so `vi.spyOn(clustering, 'getPalette')` works), and not enumerable.
|
|
387
|
+
const methodDescriptors = Object.fromEntries(Object.entries(methods).map(([name, value]) => [name, {
|
|
388
|
+
value,
|
|
389
|
+
writable: true,
|
|
390
|
+
configurable: true
|
|
391
|
+
}]));
|
|
300
392
|
export const markClustering = bytes => {
|
|
301
393
|
// Made by this library (or checked by `Clustering`), so its checksum needn't be checked again (see readHeader).
|
|
302
394
|
checked.add(bytes);
|
|
@@ -306,6 +398,7 @@ export const markClustering = bytes => {
|
|
|
306
398
|
Object.defineProperty(bytes, inspect, {
|
|
307
399
|
value: clusteringView
|
|
308
400
|
});
|
|
401
|
+
Object.defineProperties(bytes, methodDescriptors);
|
|
309
402
|
return bytes;
|
|
310
403
|
};
|
|
311
404
|
|
|
@@ -343,7 +436,7 @@ export function Clustering(...args) {
|
|
|
343
436
|
// would coerce. A plain array must hold byte values, as for a palette.
|
|
344
437
|
const isBuffer = isArrayBufferLike(source);
|
|
345
438
|
if (!isUint8Array(source) && !isUint8ClampedArray(source) && !isBuffer && !Array.isArray(source)) {
|
|
346
|
-
throw fail('invalid-clustering', "Invalid clustering: expected its bytes (a Uint8Array, or an ArrayBuffer with an optional offset and length) from
|
|
439
|
+
throw fail('invalid-clustering', "Invalid clustering: expected its bytes (a Uint8Array, or an ArrayBuffer with an optional offset and length) from buildClustering.", 'clustering');
|
|
347
440
|
}
|
|
348
441
|
if (Array.isArray(source) && !source.every(value => Number.isInteger(value) && value >= 0 && value <= 255)) {
|
|
349
442
|
throw fail('invalid-clustering', "Invalid clustering: a plain array must hold byte values, integers from 0 to 255.", 'clustering');
|
|
@@ -422,26 +515,26 @@ const crc32 = bytes => {
|
|
|
422
515
|
return (crc ^ 0xFFFFFFFF) >>> 0;
|
|
423
516
|
};
|
|
424
517
|
const checked = new WeakSet();
|
|
425
|
-
const damaged = () => fail('invalid-clustering', "Invalid clustering: its bytes are damaged (the checksum doesn't match): it was truncated, changed or mixed up with other data after
|
|
518
|
+
const damaged = () => fail('invalid-clustering', "Invalid clustering: its bytes are damaged (the checksum doesn't match): it was truncated, changed or mixed up with other data after buildClustering made it. Cluster the image again.", 'clustering');
|
|
426
519
|
|
|
427
520
|
// The message for bytes that aren't a clustering: 1.x clusterings are mentioned only for bytes that could be one (no header,
|
|
428
521
|
// and a length of 0 or 3 more than a multiple of 9).
|
|
429
522
|
const notAClustering = clustering => {
|
|
430
523
|
const length = clustering.length;
|
|
431
524
|
if (clustering[0] !== 0xAC && (length % 9 === 0 || length % 9 === 3)) {
|
|
432
|
-
return fail('invalid-clustering', "Invalid clustering: not a clustering from
|
|
525
|
+
return fail('invalid-clustering', "Invalid clustering: not a clustering from buildClustering. If it was stored by agglomerative-clustering 1.x, that format is no longer read: cluster the image again.", 'clustering');
|
|
433
526
|
}
|
|
434
527
|
if (clustering[0] === 0xAC && length >= 2 && (clustering[1] === 2 || clustering[1] === 3)) {
|
|
435
528
|
return fail('invalid-clustering', `Invalid clustering: it starts like a format ${clustering[1]} clustering, but its length or header doesn't fit one (${length} bytes): it was probably truncated or damaged. Cluster the image again.`, 'clustering');
|
|
436
529
|
}
|
|
437
|
-
return fail('invalid-clustering', `Invalid clustering: not a clustering from
|
|
530
|
+
return fail('invalid-clustering', `Invalid clustering: not a clustering from buildClustering (${length} bytes that don't start with a clustering header).`, 'clustering');
|
|
438
531
|
};
|
|
439
532
|
export const readHeader = clustering => {
|
|
440
533
|
if (isPalette(clustering)) {
|
|
441
|
-
throw fail('invalid-clustering', "Invalid clustering: this is a palette, not a clustering. Palettes come from
|
|
534
|
+
throw fail('invalid-clustering', "Invalid clustering: this is a palette, not a clustering. Palettes come from buildPalette and getPaletteFromClustering; a clustering comes from buildClustering.", 'clustering');
|
|
442
535
|
}
|
|
443
536
|
if (!isUint8Array(clustering)) {
|
|
444
|
-
throw fail('invalid-clustering', "Invalid clustering: must be a Uint8Array from
|
|
537
|
+
throw fail('invalid-clustering', "Invalid clustering: must be a Uint8Array from buildClustering.", 'clustering');
|
|
445
538
|
}
|
|
446
539
|
const length = clustering.length;
|
|
447
540
|
if (length >= 4 && clustering[0] === 0xAC) {
|
|
@@ -504,7 +597,7 @@ export const readHeader = clustering => {
|
|
|
504
597
|
// image, and quantize maps such an image the same way.
|
|
505
598
|
export const checkPalette = palette => {
|
|
506
599
|
if (isClustering(palette)) {
|
|
507
|
-
throw fail('invalid-argument', "Invalid palette: this is a clustering (from
|
|
600
|
+
throw fail('invalid-argument', "Invalid palette: this is a clustering (from buildClustering), not a palette. Cut a palette from it with getPaletteFromClustering, or map with quantizeFromClustering.", 'palette');
|
|
508
601
|
}
|
|
509
602
|
if (!isUint8Array(palette) && !isUint8ClampedArray(palette) && !Array.isArray(palette)) {
|
|
510
603
|
throw fail('invalid-argument', "Invalid palette: must be a Uint8Array of RGB bytes.", 'palette');
|
package/dist/worker-thread.mjs
CHANGED
|
@@ -109,20 +109,29 @@ const nextTurn = typeof setImmediate === 'function' ? () => new Promise(resolve
|
|
|
109
109
|
channel.port2.postMessage(null);
|
|
110
110
|
});
|
|
111
111
|
})() : () => new Promise(resolve => setTimeout(resolve, 0));
|
|
112
|
+
|
|
113
|
+
// A call sent only to check its arguments (its caller's signal was aborted before it was made): it runs with a signal that
|
|
114
|
+
// is already aborted, so the main entry validates the arguments, reports the first wrong one, and does no work.
|
|
115
|
+
const alreadyAborted = () => {
|
|
116
|
+
const controller = new AbortController();
|
|
117
|
+
controller.abort();
|
|
118
|
+
return controller;
|
|
119
|
+
};
|
|
112
120
|
const respond = async ({
|
|
113
121
|
id,
|
|
114
122
|
method,
|
|
115
123
|
args,
|
|
116
|
-
progress
|
|
124
|
+
progress,
|
|
125
|
+
check
|
|
117
126
|
}, post) => {
|
|
118
|
-
const controller = controllers.get(id);
|
|
127
|
+
const controller = check ? alreadyAborted() : controllers.get(id);
|
|
119
128
|
try {
|
|
120
129
|
// The call before this one may have run in one piece (mapping does), with no turn of the event loop for a cancel
|
|
121
130
|
// of this call to arrive; take one before starting, so a call cancelled while it waited never runs.
|
|
122
131
|
if (controller && !controller.signal.aborted) {
|
|
123
132
|
await nextTurn();
|
|
124
133
|
}
|
|
125
|
-
if (controller && controller.signal.aborted) {
|
|
134
|
+
if (controller && controller.signal.aborted && !check) {
|
|
126
135
|
return;
|
|
127
136
|
}
|
|
128
137
|
if (!Object.prototype.hasOwnProperty.call(methods, method)) {
|
|
@@ -153,8 +162,8 @@ const respond = async ({
|
|
|
153
162
|
result
|
|
154
163
|
}, [...new Set(buffers(result))]);
|
|
155
164
|
} catch (error) {
|
|
156
|
-
// A cancelled call has already been rejected on the other side.
|
|
157
|
-
if (controller && controller.signal.aborted) {
|
|
165
|
+
// A cancelled call has already been rejected on the other side (a check reports what it found).
|
|
166
|
+
if (controller && controller.signal.aborted && !check) {
|
|
158
167
|
return;
|
|
159
168
|
}
|
|
160
169
|
// Errors cross as plain data: the caller's side rebuilds them with the same name, message and code.
|
|
@@ -189,6 +198,13 @@ const onMessage = (data, post) => {
|
|
|
189
198
|
}
|
|
190
199
|
return;
|
|
191
200
|
}
|
|
201
|
+
// A check runs at once, beside whatever is running: its caller has already aborted, so it must not wait for other calls.
|
|
202
|
+
// It only validates: every function checks its signal before it puts anything in the WebAssembly heap, so it can't
|
|
203
|
+
// disturb a clustering running in slices, or grow the heap.
|
|
204
|
+
if (data.check) {
|
|
205
|
+
respond(data, post).catch(() => {});
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
192
208
|
if (data.cancellable) {
|
|
193
209
|
controllers.set(data.id, new AbortController());
|
|
194
210
|
}
|