agglomerative-clustering 3.1.1 → 3.3.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/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import createWasmModule from './clustering.js';
2
- import { parseDither, version, fail, colorSpaceCodes, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, imageHint, latestVersion, readHeader, checkPalette, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, sizeText, tooLarge } from "./shared.mjs";
2
+ import { parseDither, version, fail, colorSpaceCodes, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, 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";
@@ -15,7 +15,31 @@ const isWasmModule = value => typeof value === 'object' && value !== null && (ty
15
15
  const isURL = value => typeof value === 'object' && value !== null && (typeof URL !== 'undefined' && value instanceof URL || tagOf(value) === '[object URL]');
16
16
  const codes = {
17
17
  'rgba': 0,
18
- 'rgb': 1
18
+ 'rgb': 1,
19
+ 'bgra': 2,
20
+ 'rgbx': 3,
21
+ 'bgrx': 4
22
+ };
23
+ // A hint for a format name that isn't one: the right case, the name other libraries use for the same bytes, or the nearest
24
+ // supported layout.
25
+ const formatHint = format => {
26
+ if (typeof format !== 'string') {
27
+ return '';
28
+ }
29
+ const lower = format.toLowerCase();
30
+ if (lower !== format && imageFormats.includes(lower)) {
31
+ return ` Format names are lower case: '${lower}'.`;
32
+ }
33
+ if (lower === 'xrgb' || lower === 'rgb24') {
34
+ return " Cairo RGB24 (xRGB) is BGRX in memory on little-endian machines: pass 'bgrx'.";
35
+ }
36
+ if (lower === 'argb' || lower === 'argb32') {
37
+ return " Cairo and node-canvas ARGB32 is BGRA in memory on little-endian machines, and premultiplied: convert it to straight alpha and pass 'bgra' (see Input in the API docs).";
38
+ }
39
+ if (lower === 'bgr' || lower === 'bgr24') {
40
+ return " 24-bit BGR isn't supported: widen each pixel to 4 bytes and pass 'bgrx'.";
41
+ }
42
+ return '';
19
43
  };
20
44
  const alphaModeCodes = {
21
45
  'ignore': 0,
@@ -131,6 +155,10 @@ const wasmLoadFailed = (cause, given) => {
131
155
  reason = `the file loaded as clustering.wasm${where} is not WebAssembly (${reason}): most likely an error page (a 404) or a fallback HTML page served in its place`;
132
156
  advice = given ? "Check that URL or path: it must be this package's clustering.wasm, served with the application/wasm type." : "Check that clustering.wasm is served next to the script or emitted by your bundler (open its URL in the browser), or say where it is with init({ wasm }).";
133
157
  }
158
+ } else if (/dynamically imported module|node:module/i.test(text)) {
159
+ // The glue took its Node path somewhere that has Node's globals but not Node's module loader.
160
+ reason = `Node's module loader isn't available here, in a page or worker with Node's globals but not its loader (${reason})`;
161
+ advice = "Load the package where it can take its browser path, or report this environment as an issue.";
134
162
  } else if (isNodeLike && typeof given === 'string' && /^https?:/i.test(given)) {
135
163
  // Node fetches an http(s) URL itself (see nodeWasmFile), so the server or the network failed, not a path.
136
164
  reason = `the .wasm file could not be fetched${where}: ${reason}`;
@@ -455,7 +483,7 @@ const load = image => {
455
483
  throw fail('invalid-argument', `Invalid image: this is ${what}, not pixels. ${fix}`, 'image');
456
484
  }
457
485
  if (ArrayBuffer.isView(image) && isDetached(image)) {
458
- throw fail('invalid-argument', "Invalid image: its buffer was transferred away (detached), for example to a worker created with transfer: true, so it has no pixels left. Pass a copy if you need to keep using it.", 'image');
486
+ throw detachedError('bare');
459
487
  }
460
488
  if (isUint8Array(image)) {
461
489
  const encoded = sniffImageFormat(image);
@@ -472,7 +500,7 @@ const load = image => {
472
500
  }
473
501
  if (isImageData(image)) {
474
502
  if (isDetached(image.data)) {
475
- throw fail('invalid-argument', "Invalid image: the ImageData's pixels were transferred away (detached), for example to a worker created with transfer: true.", 'image');
503
+ throw detachedError('imagedata');
476
504
  }
477
505
  checkImageDataPixels(image);
478
506
  return {
@@ -491,16 +519,16 @@ const load = image => {
491
519
  throw fail('invalid-argument', "Invalid image data: must be Uint8Array or Uint8ClampedArray.", 'image');
492
520
  }
493
521
  if (isDetached(image.data)) {
494
- throw fail('invalid-argument', "Invalid image data: its buffer was transferred away (detached), for example to a worker created with transfer: true, so it has no pixels left. Pass a copy if you need to keep using it.", 'image');
522
+ throw detachedError('data');
495
523
  }
496
- if (!Object.keys(codes).includes(image.format)) {
497
- throw fail('invalid-argument', "Invalid format: must be 'rgb' or 'rgba'.", 'image');
524
+ if (!imageFormats.includes(image.format)) {
525
+ throw fail('invalid-argument', `Invalid format: got ${describe(image.format)}; it must be ${formatNames}.${formatHint(image.format)}`, 'image');
498
526
  }
499
- const channels = image.format === 'rgb' ? 3 : 4;
500
- if (image.data.length % channels !== 0) {
501
- throw fail('invalid-argument', `Invalid image data: length must be a multiple of ${channels} for '${image.format}'.`, 'image');
527
+ const stride = channels(image.format);
528
+ if (image.data.length % stride !== 0) {
529
+ throw fail('invalid-argument', `Invalid image data: length must be a multiple of ${stride} for '${image.format}'.`, 'image');
502
530
  }
503
- const pixels = image.data.length / channels;
531
+ const pixels = image.data.length / stride;
504
532
  checkSize(pixels, image.width, 'image width', 'image');
505
533
  checkSize(pixels, image.height, 'image height', 'image');
506
534
  if (image.width !== undefined && image.height !== undefined && image.width * image.height !== pixels) {
@@ -637,15 +665,15 @@ const parseOptions = (options, allowed, image) => {
637
665
  throw fail('invalid-argument', `Invalid width: options.width (${options.width}) does not match the image's width (${image.width}).`, 'options.width');
638
666
  }
639
667
  if (options.width !== undefined && image) {
640
- checkSize(image.data.length / (image.format === 'rgb' ? 3 : 4), options.width, 'width', 'options.width');
668
+ checkSize(image.data.length / channels(image.format), options.width, 'width', 'options.width');
641
669
  }
642
670
  const width = options.width !== undefined ? options.width : image ? image.width : undefined;
643
671
  if (dither > 0) {
644
- const channels = image.format === 'rgb' ? 3 : 4;
672
+ const stride = channels(image.format);
645
673
  if (typeof width !== 'number' || !Number.isInteger(width) || width <= 0) {
646
674
  throw fail('invalid-argument', "Invalid width: dithering needs the image width, as `options.width` or the image's `width`.", 'options.width');
647
675
  }
648
- if (image.data.length / channels % width !== 0) {
676
+ if (image.data.length / stride % width !== 0) {
649
677
  throw fail('invalid-argument', "Invalid width: the image's pixel count is not a multiple of it.", 'options.width');
650
678
  }
651
679
  }
@@ -701,8 +729,8 @@ const checkNotEmpty = (palette, image, cutoff) => {
701
729
  return;
702
730
  }
703
731
  const data = image.data;
704
- let visible = image.format === 'rgb' ? data.length > 0 : false;
705
- for (let i = 3; !visible && i < data.length; i += 4) {
732
+ let visible = hasAlpha(image.format) ? false : data.length > 0;
733
+ for (let i = 3; !visible && hasAlpha(image.format) && i < data.length; i += 4) {
706
734
  visible = data[i] >= cutoff;
707
735
  }
708
736
  if (visible) {
@@ -860,9 +888,12 @@ const clusterInSlices = async (wasm, image, o, report, share) => {
860
888
 
861
889
  // The functions that read a clustering take no options: a clustering already says how it was made. An options object passed
862
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.
863
893
  const noOptions = (name, extra) => {
864
894
  if (extra.some(value => value !== undefined)) {
865
- 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 quantizeFromClustering.`, 'options');
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');
866
897
  }
867
898
  };
868
899
 
@@ -897,14 +928,17 @@ export const getPalette = async (image, k, options) => {
897
928
  }
898
929
  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));
899
930
  };
900
- export const getPaletteFromClustering = async (clustering, k, ...extra) => {
931
+
932
+ // The cuts take the name they were called by, for their messages: the functions below, or the methods on Clustering.
933
+ const cutPalette = async (name, clustering, k, extra) => {
901
934
  const header = readHeader(clustering);
902
935
  k = check(k);
903
- noOptions('getPaletteFromClustering', extra);
936
+ noOptions(name, extra);
904
937
  clustering = held(clustering);
905
938
  const wasm = Module || (await acquire());
906
939
  return markPalette(call(wasm, [clustering], clusteringPointer => wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k)), colorSpaceName(header.colorSpace));
907
940
  };
941
+ export const getPaletteFromClustering = (clustering, k, ...extra) => cutPalette('getPaletteFromClustering', clustering, k, extra);
908
942
 
909
943
  // The weight of each colour in the k-colour cut, in pixels (opacity-weighted), read from the clustering's records.
910
944
  const weightsOf = (wasm, clustering, header, k) => {
@@ -926,10 +960,10 @@ const needsWeights = header => {
926
960
  // A palette with the weight and share of the image of each of its colours, from one cut of one clustering, so the three
927
961
  // arrays line up by construction. Weights are pixels: fully transparent pixels count 0 and partly transparent ones in
928
962
  // proportion to their opacity, as in clustering. Shares are the weights divided by their total, so they sum to 1.
929
- export const getSwatchesFromClustering = async (clustering, k, ...extra) => {
963
+ const cutSwatches = async (name, clustering, k, extra) => {
930
964
  const header = readHeader(clustering);
931
965
  k = check(k);
932
- noOptions('getSwatchesFromClustering', extra);
966
+ noOptions(name, extra);
933
967
  needsWeights(header);
934
968
  clustering = held(clustering);
935
969
  const wasm = Module || (await acquire());
@@ -951,6 +985,7 @@ export const getSwatchesFromClustering = async (clustering, k, ...extra) => {
951
985
  shares
952
986
  };
953
987
  };
988
+ export const getSwatchesFromClustering = (clustering, k, ...extra) => cutSwatches('getSwatchesFromClustering', clustering, k, extra);
954
989
 
955
990
  // The same for an image: clusters it, then cuts, like getPalette.
956
991
  export const getSwatches = async (image, k, options) => {
@@ -963,9 +998,9 @@ export const getSwatches = async (image, k, options) => {
963
998
  // What a clustering holds, read from its header and records without the WASM module. `mse[k - 1]` is the mean
964
999
  // squared error per channel of the k-colour clustering: each pixel's squared distance to its cluster's colour,
965
1000
  // weighted as in clustering, in 8-bit RGB values (RGB) or OKLab units (OKLab).
966
- export const getClusteringInfo = async (clustering, ...extra) => {
1001
+ const readInfo = async (name, clustering, extra) => {
967
1002
  const header = readHeader(clustering);
968
- noOptions('getClusteringInfo', extra);
1003
+ noOptions(name, extra);
969
1004
  needsWeights(header);
970
1005
  const colors = header.merges + (clustering.length >= header.headerLength + 3 ? 1 : 0);
971
1006
  const info = {
@@ -1006,6 +1041,7 @@ export const getClusteringInfo = async (clustering, ...extra) => {
1006
1041
  }
1007
1042
  return info;
1008
1043
  };
1044
+ export const getClusteringInfo = (clustering, ...extra) => readInfo('getClusteringInfo', clustering, extra);
1009
1045
  export const quantize = async (image, k, options) => {
1010
1046
  const wrap = getWrapper(image);
1011
1047
  image = load(image);
@@ -1093,4 +1129,13 @@ export const quantizeToIndicesWithPalette = async (image, palette, options) => {
1093
1129
  checkAborted(o.signal);
1094
1130
  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);
1095
1131
  return result;
1096
- };
1132
+ };
1133
+
1134
+ // The methods on Clustering (shared.js) run through these. Only this entry fills the slot, so the methods need it loaded.
1135
+ setEngine({
1136
+ cut: cutPalette,
1137
+ cutSwatches,
1138
+ info: readInfo,
1139
+ quantizeFromClustering,
1140
+ quantizeToIndicesFromClustering
1141
+ });
package/dist/shared.cjs CHANGED
@@ -6,14 +6,14 @@ Object.defineProperty(exports, "__esModule", {
6
6
  exports.Clustering = Clustering;
7
7
  exports.MARK = void 0;
8
8
  exports.Palette = Palette;
9
- exports.version = exports.tooLarge = exports.snapshot = exports.sizeText = exports.revive = exports.readHeader = exports.parseDither = exports.maxBytes = exports.markPalette = exports.markClustering = exports.mark = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isImageData = exports.isDetached = exports.isCodedError = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageFormats = exports.imageDataLike = exports.formatVersion = exports.fail = exports.errorCodes = exports.ditherSteps = exports.ditherMethods = exports.colorSpaces = exports.colorSpaceName = exports.colorSpaceCodes = exports.checkPalette = exports.checkImageDataPixels = exports.alphaModes = void 0;
9
+ exports.version = exports.tooLarge = exports.snapshot = exports.sizeText = exports.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.1.1';
16
+ const version = exports.version = '3.3.0';
17
17
  const colorSpaceCodes = exports.colorSpaceCodes = {
18
18
  'rgb': 0,
19
19
  'oklab': 1
@@ -21,7 +21,20 @@ const colorSpaceCodes = exports.colorSpaceCodes = {
21
21
  // Every option whose value is one of a fixed set of names has the set exported as a frozen list (like errorCodes,
22
22
  // ditherMethods and ditherSteps), for building a choice from it or checking a value against it.
23
23
  const colorSpaces = exports.colorSpaces = Object.freeze(Object.keys(colorSpaceCodes));
24
- const imageFormats = exports.imageFormats = Object.freeze(['rgb', 'rgba']);
24
+ const imageFormats = exports.imageFormats = Object.freeze(['rgb', 'rgba', 'bgra', 'rgbx', 'bgrx']);
25
+ // Bytes per pixel of an image format: 3 for 'rgb', 4 for the rest.
26
+ const channels = format => format === 'rgb' ? 3 : 4;
27
+ // Whether an image format's fourth byte is alpha ('rgbx' and 'bgrx' have a padding byte there instead).
28
+ exports.channels = channels;
29
+ const hasAlpha = format => format === 'rgba' || format === 'bgra';
30
+ // The accepted formats as text, for messages: 'rgb', 'rgba', 'bgra', 'rgbx' or 'bgrx'.
31
+ exports.hasAlpha = hasAlpha;
32
+ const formatNames = exports.formatNames = imageFormats.map(f => `'${f}'`).join(', ').replace(/, ([^,]*)$/, ' or $1');
33
+
34
+ // The error for an image whose pixels were transferred away (detached): `what` is 'bare' (a typed array passed as the
35
+ // image), 'imagedata' or 'data' (a { data, format } object). Both entries report it in these words.
36
+ const detachedError = what => fail('invalid-argument', what === 'imagedata' ? "Invalid image: the ImageData's pixels were transferred away (detached), for example to a worker created with transfer: true." : `Invalid image${what === 'data' ? ' data' : ''}: its buffer was transferred away (detached), for example to a worker created with transfer: true, so it has no pixels left. Pass a copy if you need to keep using it.`, 'image');
37
+ exports.detachedError = detachedError;
25
38
  const alphaModes = exports.alphaModes = Object.freeze(['weight', 'ignore']);
26
39
  const colorSpaceName = code => code === 1 ? 'oklab' : 'rgb';
27
40
 
@@ -55,7 +68,7 @@ exports.fail = fail;
55
68
  const maxBytes = exports.maxBytes = 2 ** 31;
56
69
  const sizeText = bytes => bytes >= 2 ** 30 ? `${(bytes / 2 ** 30).toFixed(2)} GB` : `${Math.round(bytes / 2 ** 20)} MB`;
57
70
  exports.sizeText = sizeText;
58
- const tooLarge = bytes => fail('out-of-memory', `The input is ${sizeText(bytes)}, more than the WebAssembly module can hold: it has at most 2 GB in all, for the pixels and the work on them, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels of RGBA). Scale the image down for its palette (a few megapixels give as good a one), and map a full-size image in strips with quantizeWithPalette.`);
71
+ const tooLarge = bytes => fail('out-of-memory', `The input is ${sizeText(bytes)}, more than the WebAssembly module can hold: it has at most 2 GB in all, for the pixels and the work on them, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels at 4 bytes per pixel). Scale the image down for its palette (a few megapixels give as good a one), and map a full-size image in strips with quantizeWithPalette.`);
59
72
 
60
73
  // Type checks by tag rather than `instanceof`, so values from another realm (an iframe, a vm context, a test sandbox,
61
74
  // whose Uint8Array is a different constructor) are recognised. A Node Buffer is a Uint8Array by tag too.
@@ -93,6 +106,21 @@ const isImageData = value => typeof value === 'object' && value !== null && (typ
93
106
  exports.isImageData = isImageData;
94
107
  const checkImageDataPixels = image => {
95
108
  if (isUint8ClampedArray(image.data)) {
109
+ // skia-canvas's ImageData can hold other layouts in the same clamped array ({ colorType: 'bgra' }, 'rgb888x',
110
+ // 'gray8', ...), and node-canvas's other pixel formats ('A8', 'RGB16_565') give fewer bytes: read as RGBA, they give
111
+ // swapped colours or the wrong pixel count, so they are rejected, with the { data, format } to pass where one fits.
112
+ // skia-canvas stores short and canonical spellings ('rgba' or 'RGBA8888', 'bgra' or 'BGRA8888', 'rgb' or 'RGB888x').
113
+ const colorType = image.colorType;
114
+ const kind = typeof colorType === 'string' ? colorType.toLowerCase() : colorType;
115
+ if (kind !== undefined && kind !== 'rgba' && kind !== 'rgba8888') {
116
+ const format = kind === 'bgra' || kind === 'bgra8888' ? 'bgra' : kind === 'rgb' || kind === 'rgb888x' ? 'rgbx' : null;
117
+ const instead = format ? ` Pass { data: imageData.data, format: '${format}', width, height } instead.` : " Ask for colorType 'rgba'.";
118
+ throw fail('invalid-argument', `Invalid image: this ImageData holds ${describe(colorType)} pixels, and an ImageData is read as 8-bit RGBA.${instead}`, 'image');
119
+ }
120
+ const needed = image.width * image.height * 4;
121
+ if (image.data.length !== needed) {
122
+ throw fail('invalid-argument', `Invalid image: this ImageData's data has ${image.data.length} bytes, but ${image.width} x ${image.height} RGBA pixels need ${needed}.`, 'image');
123
+ }
96
124
  return;
97
125
  }
98
126
  const format = typeof image.pixelFormat === 'string' ? ` (pixelFormat: '${image.pixelFormat}')` : '';
@@ -144,11 +172,14 @@ const imageHint = image => {
144
172
  if (typeof image.arrayBuffer === 'function' && typeof image.type === 'string') {
145
173
  return " Got a Blob or File, which is an encoded image:" + decode + " (createImageBitmap(blob), draw it to a canvas, then getImageData()).";
146
174
  }
175
+ if (typeof image.copyTo === 'function' && typeof image.codedWidth === 'number') {
176
+ return " Got a VideoFrame: copy its pixels with frame.copyTo(buffer, { format: 'BGRA' }) and pass { data: buffer, format: 'bgra', width: frame.visibleRect.width, height: frame.visibleRect.height } (or 'BGRX' and 'bgrx' for frames without alpha).";
177
+ }
147
178
  if (typeof image.close === 'function' || typeof image.nodeName === 'string') {
148
179
  return " Got an image element or ImageBitmap: draw it to a canvas (or OffscreenCanvas) and pass getImageData().";
149
180
  }
150
181
  if (image.data && !image.format) {
151
- return " It has `data` but no `format`: add format: 'rgba' (or 'rgb') to use it as a RawImage.";
182
+ return ` It has \`data\` but no \`format\`: add format: 'rgba' (or another of ${formatNames}) to use it as a RawImage.`;
152
183
  }
153
184
  return '';
154
185
  };
@@ -191,6 +222,7 @@ const describe = value => typeof value === 'string' ? `'${value}'` : typeof valu
191
222
  // Reads every form of the dither option: false/undefined (off), true or a strength from 0 to 1 (Floyd-Steinberg, as in
192
223
  // 3.0), a method name, or an object { method, strength, steps } that the plain forms are shorthands for.
193
224
  // Returns {strength, method, steps}, with strength 0 meaning no dithering and steps 0 meaning the default.
225
+ exports.describe = describe;
194
226
  const parseDither = value => {
195
227
  const invalid = (key, message) => fail('invalid-argument', message, key === undefined ? 'options.dither' : `options.dither.${key}`);
196
228
  // What a value from a form most likely meant: 'none' for no dithering, or a number given as a string.
@@ -296,7 +328,100 @@ const markPalette = (bytes, colorSpace) => {
296
328
  });
297
329
  return bytes;
298
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.
299
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
+ }]));
300
425
  const markClustering = bytes => {
301
426
  // Made by this library (or checked by `Clustering`), so its checksum needn't be checked again (see readHeader).
302
427
  checked.add(bytes);
@@ -306,6 +431,7 @@ const markClustering = bytes => {
306
431
  Object.defineProperty(bytes, inspect, {
307
432
  value: clusteringView
308
433
  });
434
+ Object.defineProperties(bytes, methodDescriptors);
309
435
  return bytes;
310
436
  };
311
437
 
package/dist/shared.mjs CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  // The library's version: package.json is the source, and scripts/sync-version.mjs keeps this line (and the copy the .wasm
6
6
  // is built from, src/version.hpp) in step with it. Do not edit it by hand.
7
- export const version = '3.1.1';
7
+ export const version = '3.3.0';
8
8
  export const colorSpaceCodes = {
9
9
  'rgb': 0,
10
10
  'oklab': 1
@@ -12,7 +12,17 @@ export const colorSpaceCodes = {
12
12
  // Every option whose value is one of a fixed set of names has the set exported as a frozen list (like errorCodes,
13
13
  // ditherMethods and ditherSteps), for building a choice from it or checking a value against it.
14
14
  export const colorSpaces = Object.freeze(Object.keys(colorSpaceCodes));
15
- export const imageFormats = Object.freeze(['rgb', 'rgba']);
15
+ export const imageFormats = Object.freeze(['rgb', 'rgba', 'bgra', 'rgbx', 'bgrx']);
16
+ // Bytes per pixel of an image format: 3 for 'rgb', 4 for the rest.
17
+ export const channels = format => format === 'rgb' ? 3 : 4;
18
+ // Whether an image format's fourth byte is alpha ('rgbx' and 'bgrx' have a padding byte there instead).
19
+ export const hasAlpha = format => format === 'rgba' || format === 'bgra';
20
+ // The accepted formats as text, for messages: 'rgb', 'rgba', 'bgra', 'rgbx' or 'bgrx'.
21
+ export const formatNames = imageFormats.map(f => `'${f}'`).join(', ').replace(/, ([^,]*)$/, ' or $1');
22
+
23
+ // The error for an image whose pixels were transferred away (detached): `what` is 'bare' (a typed array passed as the
24
+ // image), 'imagedata' or 'data' (a { data, format } object). Both entries report it in these words.
25
+ export const detachedError = what => fail('invalid-argument', what === 'imagedata' ? "Invalid image: the ImageData's pixels were transferred away (detached), for example to a worker created with transfer: true." : `Invalid image${what === 'data' ? ' data' : ''}: its buffer was transferred away (detached), for example to a worker created with transfer: true, so it has no pixels left. Pass a copy if you need to keep using it.`, 'image');
16
26
  export const alphaModes = Object.freeze(['weight', 'ignore']);
17
27
  export const colorSpaceName = code => code === 1 ? 'oklab' : 'rgb';
18
28
 
@@ -42,7 +52,7 @@ export const fail = (code, message, argument) => Object.assign(new Error(message
42
52
  // worker entry rejects them before sending, as the main entry does (from 4 GB a buffer can't even be cloned to send).
43
53
  export const maxBytes = 2 ** 31;
44
54
  export const sizeText = bytes => bytes >= 2 ** 30 ? `${(bytes / 2 ** 30).toFixed(2)} GB` : `${Math.round(bytes / 2 ** 20)} MB`;
45
- export const tooLarge = bytes => fail('out-of-memory', `The input is ${sizeText(bytes)}, more than the WebAssembly module can hold: it has at most 2 GB in all, for the pixels and the work on them, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels of RGBA). Scale the image down for its palette (a few megapixels give as good a one), and map a full-size image in strips with quantizeWithPalette.`);
55
+ export const tooLarge = bytes => fail('out-of-memory', `The input is ${sizeText(bytes)}, more than the WebAssembly module can hold: it has at most 2 GB in all, for the pixels and the work on them, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels at 4 bytes per pixel). Scale the image down for its palette (a few megapixels give as good a one), and map a full-size image in strips with quantizeWithPalette.`);
46
56
 
47
57
  // Type checks by tag rather than `instanceof`, so values from another realm (an iframe, a vm context, a test sandbox,
48
58
  // whose Uint8Array is a different constructor) are recognised. A Node Buffer is a Uint8Array by tag too.
@@ -74,6 +84,21 @@ export const isImageData = value => typeof value === 'object' && value !== null
74
84
  // pixels). The library reads 8-bit RGBA only, so those are rejected, rather than read as the bytes of their floats.
75
85
  export const checkImageDataPixels = image => {
76
86
  if (isUint8ClampedArray(image.data)) {
87
+ // skia-canvas's ImageData can hold other layouts in the same clamped array ({ colorType: 'bgra' }, 'rgb888x',
88
+ // 'gray8', ...), and node-canvas's other pixel formats ('A8', 'RGB16_565') give fewer bytes: read as RGBA, they give
89
+ // swapped colours or the wrong pixel count, so they are rejected, with the { data, format } to pass where one fits.
90
+ // skia-canvas stores short and canonical spellings ('rgba' or 'RGBA8888', 'bgra' or 'BGRA8888', 'rgb' or 'RGB888x').
91
+ const colorType = image.colorType;
92
+ const kind = typeof colorType === 'string' ? colorType.toLowerCase() : colorType;
93
+ if (kind !== undefined && kind !== 'rgba' && kind !== 'rgba8888') {
94
+ const format = kind === 'bgra' || kind === 'bgra8888' ? 'bgra' : kind === 'rgb' || kind === 'rgb888x' ? 'rgbx' : null;
95
+ const instead = format ? ` Pass { data: imageData.data, format: '${format}', width, height } instead.` : " Ask for colorType 'rgba'.";
96
+ throw fail('invalid-argument', `Invalid image: this ImageData holds ${describe(colorType)} pixels, and an ImageData is read as 8-bit RGBA.${instead}`, 'image');
97
+ }
98
+ const needed = image.width * image.height * 4;
99
+ if (image.data.length !== needed) {
100
+ throw fail('invalid-argument', `Invalid image: this ImageData's data has ${image.data.length} bytes, but ${image.width} x ${image.height} RGBA pixels need ${needed}.`, 'image');
101
+ }
77
102
  return;
78
103
  }
79
104
  const format = typeof image.pixelFormat === 'string' ? ` (pixelFormat: '${image.pixelFormat}')` : '';
@@ -123,11 +148,14 @@ export const imageHint = image => {
123
148
  if (typeof image.arrayBuffer === 'function' && typeof image.type === 'string') {
124
149
  return " Got a Blob or File, which is an encoded image:" + decode + " (createImageBitmap(blob), draw it to a canvas, then getImageData()).";
125
150
  }
151
+ if (typeof image.copyTo === 'function' && typeof image.codedWidth === 'number') {
152
+ return " Got a VideoFrame: copy its pixels with frame.copyTo(buffer, { format: 'BGRA' }) and pass { data: buffer, format: 'bgra', width: frame.visibleRect.width, height: frame.visibleRect.height } (or 'BGRX' and 'bgrx' for frames without alpha).";
153
+ }
126
154
  if (typeof image.close === 'function' || typeof image.nodeName === 'string') {
127
155
  return " Got an image element or ImageBitmap: draw it to a canvas (or OffscreenCanvas) and pass getImageData().";
128
156
  }
129
157
  if (image.data && !image.format) {
130
- return " It has `data` but no `format`: add format: 'rgba' (or 'rgb') to use it as a RawImage.";
158
+ return ` It has \`data\` but no \`format\`: add format: 'rgba' (or another of ${formatNames}) to use it as a RawImage.`;
131
159
  }
132
160
  return '';
133
161
  };
@@ -162,7 +190,7 @@ export const ditherMethods = Object.freeze(Object.keys(ditherMethodCodes));
162
190
  export const ditherSteps = Object.freeze([2, 4, 8, 16, 32, 64]);
163
191
 
164
192
  // A short description of a value for an error message.
165
- const describe = value => typeof value === 'string' ? `'${value}'` : typeof value === 'number' || typeof value === 'boolean' || value === null ? String(value) : Array.isArray(value) ? 'an array' : typeof value === 'object' ? `a ${Object.prototype.toString.call(value).slice(8, -1)}` : `a ${typeof value}`;
193
+ export const describe = value => typeof value === 'string' ? `'${value}'` : typeof value === 'number' || typeof value === 'boolean' || value === null ? String(value) : Array.isArray(value) ? 'an array' : typeof value === 'object' ? `a ${Object.prototype.toString.call(value).slice(8, -1)}` : `a ${typeof value}`;
166
194
 
167
195
  // Reads every form of the dither option: false/undefined (off), true or a strength from 0 to 1 (Floyd-Steinberg, as in
168
196
  // 3.0), a method name, or an object { method, strength, steps } that the plain forms are shorthands for.
@@ -269,6 +297,98 @@ export const markPalette = (bytes, colorSpace) => {
269
297
  });
270
298
  return bytes;
271
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
+ }]));
272
392
  export const markClustering = bytes => {
273
393
  // Made by this library (or checked by `Clustering`), so its checksum needn't be checked again (see readHeader).
274
394
  checked.add(bytes);
@@ -278,6 +398,7 @@ export const markClustering = bytes => {
278
398
  Object.defineProperty(bytes, inspect, {
279
399
  value: clusteringView
280
400
  });
401
+ Object.defineProperties(bytes, methodDescriptors);
281
402
  return bytes;
282
403
  };
283
404
 
package/dist/worker.cjs CHANGED
@@ -85,7 +85,9 @@ const formatVersion = exports.formatVersion = _shared.latestVersion;
85
85
  // bundlers don't take this for a use of Node's `process` and add a polyfill (Parcel installs one).
86
86
  const runtime = globalThis.process;
87
87
  const scriptUrl = typeof __agglomerativeWorkerUrl === 'string' ? __agglomerativeWorkerUrl : '';
88
- const hasNode = !!(runtime && runtime.versions && runtime.versions.node) && (typeof window === 'undefined' || typeof Worker !== 'function');
88
+ // Electron's pages, their Web Workers and service-worker preload realms (process.type 'renderer', 'worker' and
89
+ // 'service-worker') have Node's globals but no worker_threads.
90
+ const hasNode = !!(runtime && runtime.versions && runtime.versions.node) && !['renderer', 'worker', 'service-worker'].includes(runtime.type) && (typeof window === 'undefined' || typeof Worker !== 'function');
89
91
  const isNode = hasNode && scriptUrl.startsWith('file:');
90
92
  // Node itself (or Bun) with this script bundled into CommonJS, where __agglomerativeWorkerUrl is gone: worker_threads still works, with
91
93
  // the script given, or the package's own copy. Runtimes that imitate Node say what they are in navigator.userAgent.
@@ -322,7 +324,7 @@ const send = image => {
322
324
  // A detached buffer (transferred to a worker created with transfer: true, say) is reported as the main entry reports it.
323
325
  const pixels = ArrayBuffer.isView(image) ? image : image && typeof image === 'object' && ArrayBuffer.isView(image.data) ? image.data : null;
324
326
  if (pixels && (0, _shared.isDetached)(pixels)) {
325
- throw (0, _shared.fail)('invalid-argument', "Invalid image: its pixels were transferred away (detached), for example to a worker created with transfer: true, so it has none left. Pass a copy if you need to keep using it.", 'image');
327
+ throw (0, _shared.detachedError)(ArrayBuffer.isView(image) ? 'bare' : (0, _shared.isImageData)(image) ? 'imagedata' : 'data');
326
328
  }
327
329
  // Too large for the module, as the main entry reports it, before a copy is made to send (or, from 4 GB, fails to be).
328
330
  if (pixels && pixels.byteLength >= _shared.maxBytes) {