agglomerative-clustering 4.0.0-beta.2 → 4.0.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -24,9 +24,9 @@ Most colour quantizers answer one question: *give me k colours*. Ask for a diffe
24
24
  npm install agglomerative-clustering
25
25
  ```
26
26
 
27
- Upgrading? See [Migrating](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/migrating.md). From 3.3, three functions have new names, and the old ones keep working until 4.0. From 2.x, one function was renamed, and palettes and images are the same as 2.0's, with one documented exception.
27
+ Upgrading? See [Migrating](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/migrating.md). From 3.x, 4.0 removed the get… and …FromClustering functions, turned two warnings into errors (a bare array that looks like RGB or grey, and `transparent` on a format with no alpha), and needs Node 22.12+: see [From 3.x to 4.0](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/migrating.md#from-3x-to-40). From 2.x, one function was renamed, and palettes and images are the same as 2.0's, with one documented exception.
28
28
 
29
- It runs on Node 20.19+ and 22.12+, and in browsers with WebAssembly SIMD (Chrome and Edge 91, Firefox 89, Safari 16.4). Deno, Bun, Cloudflare Workers, serverless functions, Electron and browser extensions work too: see [Environments](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/environments.md).
29
+ It runs on Node 22.12+, and in browsers with WebAssembly SIMD (Chrome and Edge 91, Firefox 89, Safari 16.4). Deno, Bun, Cloudflare Workers, serverless functions, Electron and browser extensions work too: see [Environments](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/environments.md).
30
30
 
31
31
  ## Usage
32
32
 
@@ -82,7 +82,7 @@ slider.oninput = async () => {
82
82
  };
83
83
  ```
84
84
 
85
- Input is decoded pixels: a bare `Uint8Array` of RGBA bytes, an `ImageData`, or `{ data, format: 'rgb' | 'rgba' | 'bgra' | 'rgbx' | 'bgrx', width?, height? }`: BGRA for Electron's `nativeImage` and Windows bitmaps, and the `x` formats for buffers whose fourth byte isn't alpha (GDI screenshots, WebCodecs `'BGRX'`, ffmpeg `bgr0`). Alpha is straight, or premultiplied (canvas, Electron): pass `premultiplied: true` with `'rgba'` or `'bgra'`; [where pixels come from](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#input) lists common sources and what to pass for each. Mapped output of a premultiplied image comes back premultiplied (palettes and indices are straight), so for an `ImageData` or a PNG encoder use the [straight-output recipe](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#straight-pixels-from-a-premultiplied-source). RGB bytes passed bare are read as RGBA; the library warns when it sees this (an error from 4.0), so pass them as `{ data, format: 'rgb' }`. To start from a PNG, JPEG, WebP or GIF file, decode it first: [Decoding image files](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#decoding-image-files) has a recipe for Node, browsers and edge runtimes. For a page that stays responsive while it clusters, use `agglomerative-clustering/worker`: its functions are the same, and for a slider `createWorker().cluster(image)` keeps the image and its clustering in the worker, behind a handle whose `handle.getPalette(k)` and `handle.quantize(k)` re-cut and re-map without sending the pixels again (see [Workers](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#workers)). The `clustering.…` methods above run on the calling thread, so they don't move work off it.
85
+ Input is decoded pixels: a bare `Uint8Array` of RGBA bytes, an `ImageData`, or `{ data, format: 'rgb' | 'rgba' | 'bgra' | 'rgbx' | 'bgrx', width?, height? }`: BGRA for Electron's `nativeImage` and Windows bitmaps, and the `x` formats for buffers whose fourth byte isn't alpha (GDI screenshots, WebCodecs `'BGRX'`, ffmpeg `bgr0`). Alpha is straight, or premultiplied (canvas, Electron): pass `premultiplied: true` with `'rgba'` or `'bgra'`; [where pixels come from](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#input) lists common sources and what to pass for each. Mapped output of a premultiplied image comes back premultiplied (palettes and indices are straight), so for an `ImageData` or a PNG encoder use the [straight-output recipe](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#straight-pixels-from-a-premultiplied-source). RGB bytes passed bare would be read as RGBA; the library throws when it sees this, so pass them as `{ data, format: 'rgb' }`. To start from a PNG, JPEG, WebP or GIF file, decode it first: [Decoding image files](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#decoding-image-files) has a recipe for Node, browsers and edge runtimes. For a page that stays responsive while it clusters, use `agglomerative-clustering/worker`: its functions are the same, and for a slider `createWorker().cluster(image)` keeps the image and its clustering in the worker, behind a handle whose `handle.getPalette(k)` and `handle.quantize(k)` re-cut and re-map without sending the pixels again (see [Workers](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#workers)). The `clustering.…` methods above run on the calling thread, so they don't move work off it.
86
86
 
87
87
  ## How it works
88
88
 
@@ -105,11 +105,11 @@ The one-shot functions (`buildPalette`, `quantize`, …) do every step for you.
105
105
 
106
106
  A clustering you hold has **methods** that take the colours from it, and **`…WithPalette`** takes colours you supply; with neither, the image is clustered for you. `buildClustering` builds a clustering, and `init` loads the WebAssembly module (optional). Most code only needs the first column.
107
107
 
108
- The verb says how much work a call does. `build…` clusters an image (tens of milliseconds for a photo). `get…` reads or cuts what a clustering or a worker handle already holds (well under a millisecond). `quantize…` maps pixels. So `buildPalette(image, k)` and `clustering.getPalette(k)` give the same kind of result from different starting points. The `build…` names arrived in 3.4.0; [Migrating](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/migrating.md) has the old ones.
108
+ The verb says how much work a call does. `build…` clusters an image (tens of milliseconds for a photo). `get…` reads or cuts what a clustering or a worker handle already holds (well under a millisecond). `quantize…` maps pixels. So `buildPalette(image, k)` and `clustering.getPalette(k)` give the same kind of result from different starting points. [Migrating](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/migrating.md) lists the names 4.0 removed.
109
109
 
110
110
  **Where to call them.** On the main thread, or in a Node script, use the methods: they are the shortest way to cut one clustering many times. **Off the thread, use a handle**: `worker.cluster(image)` keeps an image and its clustering in the worker, and `worker.load(clustering)` keeps a stored clustering (`await using loaded = await worker.load(stored)`, then `loaded.getPalette(k)` and `loaded.quantize(image, k)`). The methods always run on the thread that calls them, with the main entry, and reject with `wasm-load-failed` where only the worker entry is imported.
111
111
 
112
- ¹ The `…FromClustering` functions (`getPaletteFromClustering(clustering, k)`, `quantizeFromClustering(image, clustering, k)` and the rest) do the same as the methods. They are deprecated from 3.8 and removed in 4.0: see [Migrating](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/migrating.md#deprecated-in-38-removed-in-40) for the replacement of each, and [Clustering methods](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#clustering-methods).
112
+ ¹ A clustering from storage is plain bytes: wrap it with `new Clustering(bytes)` to get the methods back, or off the thread load it with `worker.load(bytes)`. See [Clustering methods](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#clustering-methods).
113
113
 
114
114
  Palettes come in **split order**: the palette for `k + 1` is the one for `k` with one colour split in two, so entries keep their place as `k` grows (they are not sorted by share). The options are `precision` (6 is about 3× faster at practically the same quality), `colorSpace` (`'rgb'` or `'oklab'`), `alpha`, `transparent`, `dither` (Floyd–Steinberg, Atkinson, or ordered for animation, which keeps still areas still), `width`, `signal` and `onProgress`: see the [API reference](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md).
115
115
 
Binary file
package/dist/index.cjs CHANGED
@@ -46,7 +46,7 @@ Object.defineProperty(exports, "errorCodes", {
46
46
  return _shared.errorCodes;
47
47
  }
48
48
  });
49
- exports.getSwatchesFromClustering = exports.getSwatches = exports.getPaletteFromClustering = exports.getPalette = exports.getClusteringInfo = exports.getClustering = exports.formatVersion = void 0;
49
+ exports.formatVersion = void 0;
50
50
  Object.defineProperty(exports, "imageFormats", {
51
51
  enumerable: true,
52
52
  get: function () {
@@ -60,7 +60,7 @@ Object.defineProperty(exports, "isCodedError", {
60
60
  return _shared.isCodedError;
61
61
  }
62
62
  });
63
- exports.quantizeWithPalette = exports.quantizeToIndicesWithPalette = exports.quantizeToIndicesFromClustering = exports.quantizeToIndices = exports.quantizeFromClustering = exports.quantize = void 0;
63
+ exports.quantizeWithPalette = exports.quantizeToIndicesWithPalette = exports.quantizeToIndices = exports.quantize = void 0;
64
64
  Object.defineProperty(exports, "version", {
65
65
  enumerable: true,
66
66
  get: function () {
@@ -96,10 +96,6 @@ const codes = {
96
96
  'rgbx': 3,
97
97
  'bgrx': 4
98
98
  };
99
- const alphaModeCodes = {
100
- 'ignore': 0,
101
- 'weight': 1
102
- };
103
99
  let Module = null;
104
100
 
105
101
  // Turns init's `wasm` option into the settings the Emscripten glue understands. The glue finds its .wasm file next to
@@ -165,7 +161,7 @@ const hasSimd = () => {
165
161
  }
166
162
  };
167
163
  // Node itself (or Bun), not a runtime that imitates it: Cloudflare Workers with nodejs_compat and Deno also define
168
- // process.versions.node, but their navigator.userAgent says what they are (Node 20 has no navigator at all).
164
+ // process.versions.node, but their navigator.userAgent says what they are (old Node versions have no navigator at all).
169
165
  const isNodeLike = !!(globalThis.process && globalThis.process.versions && globalThis.process.versions.node) && (typeof navigator === 'undefined' || /^(Node\.js|Bun)\//.test(String(navigator.userAgent)));
170
166
  // A browser page or worker, as opposed to a server-side runtime that isn't Node (Cloudflare Workers, Vercel's edge runtime,
171
167
  // Deno Deploy): only those have a document, a worker scope or a browser's user agent.
@@ -480,35 +476,18 @@ const bytes = data => (0, _shared.isUint8Array)(data) ? data : new Uint8Array(da
480
476
  // or change the array as soon as the call returns. Once the module is loaded the bytes go into its memory before the
481
477
  // call returns; until then (the first call) a copy is kept for when it has loaded.
482
478
  const held = data => Module ? data : data.slice();
483
-
484
- // The bare-image warning (rgb-as-rgba, gray-as-rgba) for an image, decided before load() and given only once the call's own checks have passed,
485
- // just before it starts work, so the one warning isn't spent on a call that fails anyway (PRINCIPLES "Warnings").
486
- const noWarning = () => {};
487
- // A call whose signal is already aborted fails before any work, so it doesn't use the warning up either.
488
- const warningFor = image => {
489
- const warning = (0, _shared.bareImageWarning)(image);
490
- return warning ? signal => {
491
- if (!(signal && signal.aborted)) {
492
- (0, _shared.warnOnce)(warning, image.byteLength);
493
- }
494
- } : noWarning;
495
- };
496
479
  const load = image => {
497
- if ((0, _shared.isClustering)(image) || (0, _shared.isPalette)(image)) {
498
- const what = (0, _shared.isClustering)(image) ? 'a clustering (from buildClustering)' : 'a palette';
499
- const fix = (0, _shared.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).';
500
- throw (0, _shared.fail)('invalid-argument', `Invalid image: this is ${what}, not pixels. ${fix}`, 'image');
501
- }
502
- if (ArrayBuffer.isView(image) && (0, _shared.isDetached)(image)) {
503
- throw (0, _shared.detachedError)('bare');
480
+ if (ArrayBuffer.isView(image)) {
481
+ // What a bare typed array must be (see checkPixelArray, which the worker entry runs too); a detached one is reported first.
482
+ (0, _shared.checkPixelArray)(image);
483
+ if ((0, _shared.isDetached)(image)) {
484
+ throw (0, _shared.detachedError)('bare');
485
+ }
504
486
  }
505
487
  if ((0, _shared.isUint8Array)(image)) {
506
- const encoded = (0, _shared.sniffImageFormat)(image);
507
- if (encoded) {
508
- throw (0, _shared.fail)('invalid-argument', `Invalid image: these bytes are an encoded ${encoded} file, not pixels. Decode them to pixels first and pass those ("Decoding image files" in the guides has a recipe for Node, browsers and edge runtimes). If they really are raw RGBA pixels, pass { data, format: 'rgba' } to say so.`, 'image');
509
- }
510
- if (image.length % 4 !== 0) {
511
- throw (0, _shared.fail)('invalid-argument', "Invalid image data: length must be a multiple of 4 for 'rgba'.", 'image');
488
+ const bare = (0, _shared.bareImageError)(image);
489
+ if (bare) {
490
+ throw bare;
512
491
  }
513
492
  return {
514
493
  data: held(image),
@@ -528,9 +507,6 @@ const load = image => {
528
507
  premultiplied: false
529
508
  };
530
509
  }
531
- if (ArrayBuffer.isView(image)) {
532
- throw (0, _shared.fail)('invalid-argument', "Invalid image: a bare typed array must be a Uint8Array of RGBA bytes. For a Uint8ClampedArray such as imageData.data, pass the ImageData itself or { data, format: 'rgba' }.", 'image');
533
- }
534
510
  if (typeof image !== 'object' || !image || !image.data || !image.format) {
535
511
  throw (0, _shared.fail)('invalid-argument', `Invalid image: expected object with \`data\` and \`format\`.${(0, _shared.imageHint)(image)}`, 'image');
536
512
  }
@@ -608,141 +584,6 @@ const unpackIndices = (output, image, colorSpace) => {
608
584
  return result;
609
585
  };
610
586
 
611
- // Returns k, validated. Any k above the number of colours means all of them, so it is capped at the largest value
612
- // the WASM side holds (a larger one would overflow its int).
613
- const check = k => {
614
- if (typeof k !== 'number' || !Number.isInteger(k) || k <= 0) {
615
- // A string is the usual slip (an input's `value`), so it gets its own fix.
616
- const got = typeof k === 'string' ? ` Got the string ${JSON.stringify(k.length > 20 ? `${k.slice(0, 20)}…` : k)}: convert it first, e.g. Number(input.value).` : typeof k === 'number' ? ` Got ${k}.` : ` Got ${k === null ? 'null' : typeof k}.`;
617
- throw (0, _shared.fail)('invalid-argument', `Invalid k: must be a whole number of colours, 1 or more.${got}`, 'k');
618
- }
619
- return Math.min(k, 0x7FFFFFFF);
620
- };
621
-
622
- // Validates `options` against the keys a function accepts and fills in defaults:
623
- // colorSpace: 'rgb' (default) or 'oklab', the space colours are clustered and matched in; when mapping with a
624
- // clustering, the default is the space the clustering was made in (code -1)
625
- // alpha: 'weight' (default) counts RGBA pixels in proportion to their opacity; 'ignore' counts every pixel
626
- // precision: bits per channel, 1-8 (default 8, exact); lower values group similar colours before clustering
627
- // dither: false (default), true or a strength in [0, 1] (Floyd-Steinberg), a method name, or { method, strength, steps } (see parseDither)
628
- // width: image width in pixels, needed to dither a Uint8Array or a RawImage without `width`
629
- // signal, onProgress: an AbortSignal and a progress callback, which make the clustering and the mapping run in slices
630
- // (see clusterInSlices and mapInSlices)
631
- // transparent: false (default), true (cutoff 128) or a cutoff from 1 to 255: pixels with alpha below it are left out of clustering (and the rest count whole);
632
- // indexed output also gives them their own entry, which counts towards k
633
-
634
- // The settings of dither, which a caller may write as options of their own; naming one of these gets a pointer to the
635
- // object form.
636
- const ditherSettings = ['ditherMethod', 'ditherStrength', 'ditherSteps', 'method', 'strength', 'steps', 'mix'];
637
- const parseOptions = (options, allowed, image) => {
638
- if (options === undefined) {
639
- options = {};
640
- }
641
- if (!(0, _shared.isOptionsObject)(options)) {
642
- throw (0, _shared.fail)('invalid-argument', "Invalid options: expected an object.", 'options');
643
- }
644
- options = (0, _shared.snapshot)(options);
645
- for (const key of Object.keys(options)) {
646
- if (!allowed.includes(key)) {
647
- const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' : '';
648
- throw (0, _shared.fail)('invalid-argument', `Invalid option '${key}': expected one of ${allowed.join(', ')}.${hint}`, `options.${key}`);
649
- }
650
- }
651
- const colorSpace = options.colorSpace === undefined ? 'rgb' : options.colorSpace;
652
- if (!_shared.colorSpaces.includes(colorSpace)) {
653
- throw (0, _shared.fail)('invalid-argument', "Invalid colorSpace: must be 'rgb' or 'oklab'.", 'options.colorSpace');
654
- }
655
- const alpha = options.alpha === undefined ? 'weight' : options.alpha;
656
- if (!Object.keys(alphaModeCodes).includes(alpha)) {
657
- throw (0, _shared.fail)('invalid-argument', "Invalid alpha: must be 'weight' or 'ignore'.", 'options.alpha');
658
- }
659
- const precision = options.precision === undefined ? 8 : options.precision;
660
- if (typeof precision !== 'number' || !Number.isInteger(precision) || precision < 1 || precision > 8) {
661
- throw (0, _shared.fail)('invalid-argument', "Invalid precision: must be an integer from 1 to 8.", 'options.precision');
662
- }
663
- const {
664
- strength: dither,
665
- method: ditherMethod,
666
- steps: ditherSteps
667
- } = (0, _shared.parseDither)(options.dither);
668
-
669
- // The image's own width and options.width are two sources for one fact: they may repeat each other, but not disagree
670
- // (a wrong row length would dither without an error, as long as it divides the pixel count).
671
- if (options.width !== undefined && image && image.width !== undefined && options.width !== image.width) {
672
- throw (0, _shared.fail)('invalid-argument', `Invalid width: options.width (${options.width}) does not match the image's width (${image.width}).`, 'options.width');
673
- }
674
- if (options.width !== undefined && image) {
675
- (0, _shared.checkSize)(image.data.length / (0, _shared.channels)(image.format), options.width, 'width', 'options.width');
676
- }
677
- const width = options.width !== undefined ? options.width : image ? image.width : undefined;
678
- if (dither > 0) {
679
- const stride = (0, _shared.channels)(image.format);
680
- if (typeof width !== 'number' || !Number.isInteger(width) || width <= 0) {
681
- throw (0, _shared.fail)('invalid-argument', "Invalid width: dithering needs the image width, as `options.width` or the image's `width`.", 'options.width');
682
- }
683
- if (image.data.length / stride % width !== 0) {
684
- throw (0, _shared.fail)('invalid-argument', "Invalid width: the image's pixel count is not a multiple of it.", 'options.width');
685
- }
686
- }
687
- const signal = options.signal;
688
- if (signal !== undefined && (signal === null || typeof signal !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function')) {
689
- throw (0, _shared.fail)('invalid-argument', "Invalid signal: must be an AbortSignal.", 'options.signal');
690
- }
691
- const onProgress = options.onProgress;
692
- if (onProgress !== undefined && typeof onProgress !== 'function') {
693
- throw (0, _shared.fail)('invalid-argument', "Invalid onProgress: must be a function.", 'options.onProgress');
694
- }
695
-
696
- // The alpha cutoff for indexed output: 0 for none, else the pixels with alpha below it are transparent.
697
- const transparentOption = options.transparent === undefined ? false : options.transparent;
698
- const transparent = transparentOption === false ? 0 : transparentOption === true ? 128 : transparentOption;
699
- if (!Number.isInteger(transparent) || transparent < 0 || transparent > 255 || transparent === 0 && transparentOption !== false) {
700
- throw (0, _shared.fail)('invalid-argument', "Invalid transparent: must be a boolean or an integer alpha cutoff from 1 to 255.", 'options.transparent');
701
- }
702
-
703
- // A cutoff replaces opacity weighting (pixels count whole or not at all), so naming both would leave one of them ignored.
704
- if (transparent > 0 && options.alpha !== undefined) {
705
- throw (0, _shared.fail)('invalid-argument', "Invalid options: `transparent` replaces `alpha` (with a cutoff, pixels count whole or not at all), so give one or the other.", 'options');
706
- }
707
- return {
708
- colorSpace: _shared.colorSpaceCodes[colorSpace],
709
- colorSpaceGiven: options.colorSpace !== undefined,
710
- alpha: alphaModeCodes[alpha],
711
- precision,
712
- dither,
713
- ditherMethod,
714
- ditherSteps,
715
- width: dither > 0 ? width : 0,
716
- transparent,
717
- transparentGiven: options.transparent !== undefined,
718
- signal,
719
- onProgress
720
- };
721
- };
722
- const controlOptions = ['signal', 'onProgress'];
723
- const clusterOptions = ['colorSpace', 'precision', 'alpha', 'transparent', ...controlOptions];
724
- const quantizeOptions = [...clusterOptions, 'dither', 'width'];
725
- const mapOptions = ['colorSpace', 'dither', 'width', ...controlOptions];
726
- const quantizeIndexOptions = quantizeOptions;
727
- const mapIndexOptions = [...mapOptions, 'transparent'];
728
-
729
- // An empty palette is what getPalette gives for an image with no visible pixels, and mapping such an image with it is
730
- // fine. Mapping visible pixels to it has no answer (they would all come out black), so that is an error. `cutoff` is the
731
- // alpha from which an RGBA pixel needs a colour.
732
- const checkNotEmpty = (palette, image, cutoff) => {
733
- if (palette.length > 0) {
734
- return;
735
- }
736
- const data = image.data;
737
- let visible = (0, _shared.hasAlpha)(image.format) ? false : data.length > 0;
738
- for (let i = 3; !visible && (0, _shared.hasAlpha)(image.format) && i < data.length; i += 4) {
739
- visible = data[i] >= cutoff;
740
- }
741
- if (visible) {
742
- throw (0, _shared.fail)('invalid-argument', "Invalid palette: it is empty, but the image has visible pixels to map to it.", 'palette');
743
- }
744
- };
745
-
746
587
  // The space to match pixels to a palette in: the one the caller names, else the one a Palette was made in, else RGB.
747
588
  const matchingSpace = (o, palette) => o.colorSpaceGiven ? o.colorSpace : _shared.colorSpaceCodes[(0, _shared.isPalette)(palette) ? palette.colorSpace : 'rgb'];
748
589
 
@@ -1000,12 +841,11 @@ const mapInSlices = async (wasm, image, source, colorSpace, indices, cutoff, o,
1000
841
 
1001
842
  // The functions that read a clustering take no options: a clustering already says how it was made. An options object passed
1002
843
  // anyway (say { colorSpace: 'oklab' }, expecting it to apply) would be silently ignored, so it is an error. undefined is fine.
1003
- // `name` is how the caller wrote the call: the function, or the method (`clustering.getPalette`), whose message points at
1004
- // the method form of mapping.
844
+ // `name` is how the caller wrote the call (the method, `clustering.getPalette`), whose message points at the method form
845
+ // of mapping.
1005
846
  const noOptions = (name, extra) => {
1006
847
  if (extra.some(value => value !== undefined)) {
1007
- const alternative = name.startsWith('clustering.') ? 'clustering.quantize' : 'quantizeFromClustering';
1008
- throw (0, _shared.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');
848
+ throw (0, _shared.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 clustering.quantize(image, k, options).`, 'options');
1009
849
  }
1010
850
  };
1011
851
 
@@ -1015,10 +855,8 @@ const noOptions = (name, extra) => {
1015
855
 
1016
856
  const buildClustering = async (image, options) => {
1017
857
  image = (0, _shared.imageCopy)(image);
1018
- const warn = warningFor(image);
1019
858
  image = load(image);
1020
- const o = parseOptions(options, clusterOptions, image);
1021
- warn(o.signal);
859
+ const o = (0, _shared.parseOptions)(options, _shared.clusterOptions, image);
1022
860
  const wasm = Module || (await acquire());
1023
861
  if (isControlled(o)) {
1024
862
  const report = reporter(o);
@@ -1028,16 +866,12 @@ const buildClustering = async (image, options) => {
1028
866
  }
1029
867
  return (0, _shared.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, image.premultiplied));
1030
868
  };
1031
- /** @deprecated The same function as buildClustering, its name before 3.4.0. Removed in 4.0. */
1032
869
  exports.buildClustering = buildClustering;
1033
- const getClustering = exports.getClustering = buildClustering;
1034
870
  const buildPalette = async (image, k, options) => {
1035
871
  image = (0, _shared.imageCopy)(image);
1036
- const warn = warningFor(image);
1037
872
  image = load(image);
1038
- k = check(k);
1039
- const o = parseOptions(options, clusterOptions, image);
1040
- warn(o.signal);
873
+ k = (0, _shared.checkK)(k);
874
+ const o = (0, _shared.parseOptions)(options, _shared.clusterOptions, image);
1041
875
  const wasm = Module || (await acquire());
1042
876
  if (isControlled(o)) {
1043
877
  const report = reporter(o);
@@ -1049,23 +883,19 @@ const buildPalette = async (image, k, options) => {
1049
883
  }
1050
884
  return (0, _shared.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, image.premultiplied), (0, _shared.colorSpaceName)(o.colorSpace));
1051
885
  };
1052
- /** @deprecated The same function as buildPalette, its name before 3.4.0. Removed in 4.0. */
1053
- exports.buildPalette = buildPalette;
1054
- const getPalette = exports.getPalette = buildPalette;
1055
886
 
1056
- // The cuts take the name they were called by, for their messages: the functions below, or the methods on Clustering.
887
+ // The cuts take the name they were called by, for their messages: the methods on Clustering (or the function that cuts).
888
+ exports.buildPalette = buildPalette;
1057
889
  const cutPalette = async (name, clustering, k, extra) => {
1058
890
  const header = (0, _shared.readHeader)(clustering);
1059
- k = check(k);
891
+ k = (0, _shared.checkK)(k);
1060
892
  noOptions(name, extra);
1061
893
  clustering = held(clustering);
1062
894
  const wasm = Module || (await acquire());
1063
895
  return (0, _shared.markPalette)(call(wasm, [clustering], clusteringPointer => wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k)), (0, _shared.colorSpaceName)(header.colorSpace));
1064
896
  };
1065
- const getPaletteFromClustering = (clustering, k, ...extra) => cutPalette('getPaletteFromClustering', clustering, k, extra);
1066
897
 
1067
898
  // The weight of each colour in the k-colour cut, in pixels (opacity-weighted), read from the clustering's records.
1068
- exports.getPaletteFromClustering = getPaletteFromClustering;
1069
899
  const weightsOf = (wasm, clustering, header, k) => {
1070
900
  const bytes = call(wasm, [clustering], clusteringPointer => wasm._get_palette_weights(clusteringPointer, clustering.length, k));
1071
901
  if (header.merges > 0 && bytes.length === 0) {
@@ -1087,7 +917,7 @@ const needsWeights = header => {
1087
917
  // proportion to their opacity, as in clustering. Shares are the weights divided by their total, so they sum to 1.
1088
918
  const cutSwatches = async (name, clustering, k, extra) => {
1089
919
  const header = (0, _shared.readHeader)(clustering);
1090
- k = check(k);
920
+ k = (0, _shared.checkK)(k);
1091
921
  noOptions(name, extra);
1092
922
  needsWeights(header);
1093
923
  clustering = held(clustering);
@@ -1110,25 +940,21 @@ const cutSwatches = async (name, clustering, k, extra) => {
1110
940
  shares
1111
941
  };
1112
942
  };
1113
- const getSwatchesFromClustering = (clustering, k, ...extra) => cutSwatches('getSwatchesFromClustering', clustering, k, extra);
1114
943
 
1115
- // The same for an image: clusters it, then cuts, like getPalette.
1116
- exports.getSwatchesFromClustering = getSwatchesFromClustering;
944
+ // The same for an image: clusters it, then cuts, like buildPalette.
1117
945
  const buildSwatches = async (image, k, options) => {
1118
946
  image = (0, _shared.imageCopy)(image);
1119
947
  // Arguments are checked in the order they are given (image, then k, then options), as in every other function.
1120
948
  // `load` only validates here (buildClustering loads again); both see the copy, so the caller's fields are read once.
1121
949
  load(image);
1122
- k = check(k);
1123
- return getSwatchesFromClustering(await buildClustering(image, options), k);
950
+ k = (0, _shared.checkK)(k);
951
+ return cutSwatches('buildSwatches', await buildClustering(image, options), k, []);
1124
952
  };
1125
- /** @deprecated The same function as buildSwatches, its name before 3.4.0. Removed in 4.0. */
1126
- exports.buildSwatches = buildSwatches;
1127
- const getSwatches = exports.getSwatches = buildSwatches;
1128
953
 
1129
954
  // What a clustering holds, read from its header and records without the WASM module. `mse[k - 1]` is the mean
1130
955
  // squared error per channel of the k-colour clustering: each pixel's squared distance to its cluster's colour,
1131
956
  // weighted as in clustering, in 8-bit RGB values (RGB) or OKLab units (OKLab).
957
+ exports.buildSwatches = buildSwatches;
1132
958
  const readInfo = async (name, clustering, extra) => {
1133
959
  const header = (0, _shared.readHeader)(clustering);
1134
960
  noOptions(name, extra);
@@ -1172,16 +998,12 @@ const readInfo = async (name, clustering, extra) => {
1172
998
  }
1173
999
  return info;
1174
1000
  };
1175
- const getClusteringInfo = (clustering, ...extra) => readInfo('getClusteringInfo', clustering, extra);
1176
- exports.getClusteringInfo = getClusteringInfo;
1177
1001
  const quantize = async (image, k, options) => {
1178
1002
  image = (0, _shared.imageCopy)(image);
1179
- const warn = warningFor(image);
1180
1003
  const wrap = getWrapper(image);
1181
1004
  image = load(image);
1182
- k = check(k);
1183
- const o = parseOptions(options, quantizeOptions, image);
1184
- warn(o.signal);
1005
+ k = (0, _shared.checkK)(k);
1006
+ const o = (0, _shared.parseOptions)(options, _shared.quantizeOptions, image);
1185
1007
  const wasm = Module || (await acquire());
1186
1008
  if (isControlled(o)) {
1187
1009
  const report = reporter(o);
@@ -1199,14 +1021,12 @@ const quantize = async (image, k, options) => {
1199
1021
  exports.quantize = quantize;
1200
1022
  const quantizeFromClustering = async (image, clustering, k, options) => {
1201
1023
  image = (0, _shared.imageCopy)(image);
1202
- const warn = warningFor(image);
1203
1024
  const wrap = getWrapper(image);
1204
1025
  image = load(image);
1205
1026
  (0, _shared.readHeader)(clustering);
1206
- k = check(k);
1207
- const o = parseOptions(options, mapOptions, image);
1027
+ k = (0, _shared.checkK)(k);
1028
+ const o = (0, _shared.parseOptions)(options, _shared.mapOptions, image);
1208
1029
  clustering = held(clustering);
1209
- warn(o.signal);
1210
1030
  const wasm = Module || (await acquire());
1211
1031
  checkAborted(o.signal);
1212
1032
  const colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
@@ -1222,18 +1042,15 @@ const quantizeFromClustering = async (image, clustering, k, options) => {
1222
1042
  const result = wrap(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width), undefined, image.premultiplied, true));
1223
1043
  return result;
1224
1044
  };
1225
- exports.quantizeFromClustering = quantizeFromClustering;
1226
1045
  const quantizeWithPalette = async (image, palette, options) => {
1227
1046
  image = (0, _shared.imageCopy)(image);
1228
- const warn = warningFor(image);
1229
1047
  const wrap = getWrapper(image);
1230
1048
  image = load(image);
1231
1049
  (0, _shared.checkPalette)(palette);
1232
- const o = parseOptions(options, mapOptions, image);
1233
- checkNotEmpty(palette, image, 1);
1050
+ const o = (0, _shared.parseOptions)(options, _shared.mapOptions, image);
1051
+ (0, _shared.checkNotEmpty)(palette, image, 1);
1234
1052
  const space = matchingSpace(o, palette);
1235
1053
  palette = held(palette);
1236
- warn(o.signal);
1237
1054
  const wasm = Module || (await acquire());
1238
1055
  checkAborted(o.signal);
1239
1056
  if (isControlled(o)) {
@@ -1250,12 +1067,10 @@ const quantizeWithPalette = async (image, palette, options) => {
1250
1067
  exports.quantizeWithPalette = quantizeWithPalette;
1251
1068
  const quantizeToIndices = async (image, k, options) => {
1252
1069
  image = (0, _shared.imageCopy)(image);
1253
- const warn = warningFor(image);
1254
1070
  const original = image;
1255
1071
  image = load(image);
1256
- k = check(k);
1257
- const o = parseOptions(options, quantizeIndexOptions, image);
1258
- warn(o.signal);
1072
+ k = (0, _shared.checkK)(k);
1073
+ const o = (0, _shared.parseOptions)(options, _shared.quantizeIndexOptions, image);
1259
1074
  const wasm = Module || (await acquire());
1260
1075
  if (isControlled(o)) {
1261
1076
  const report = reporter(o);
@@ -1273,14 +1088,12 @@ const quantizeToIndices = async (image, k, options) => {
1273
1088
  exports.quantizeToIndices = quantizeToIndices;
1274
1089
  const quantizeToIndicesFromClustering = async (image, clustering, k, options) => {
1275
1090
  image = (0, _shared.imageCopy)(image);
1276
- const warn = warningFor(image);
1277
1091
  const original = image;
1278
1092
  image = load(image);
1279
1093
  const header = (0, _shared.readHeader)(clustering);
1280
- k = check(k);
1281
- const o = parseOptions(options, mapIndexOptions, image);
1094
+ k = (0, _shared.checkK)(k);
1095
+ const o = (0, _shared.parseOptions)(options, _shared.mapIndexOptions, image);
1282
1096
  clustering = held(clustering);
1283
- warn(o.signal);
1284
1097
  const wasm = Module || (await acquire());
1285
1098
  checkAborted(o.signal);
1286
1099
  const colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
@@ -1299,19 +1112,16 @@ const quantizeToIndicesFromClustering = async (image, clustering, k, options) =>
1299
1112
  const result = unpackIndices(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_indices_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width, cutoff), undefined, image.premultiplied), original, (0, _shared.colorSpaceName)(header.colorSpace));
1300
1113
  return result;
1301
1114
  };
1302
- exports.quantizeToIndicesFromClustering = quantizeToIndicesFromClustering;
1303
1115
  const quantizeToIndicesWithPalette = async (image, palette, options) => {
1304
1116
  image = (0, _shared.imageCopy)(image);
1305
- const warn = warningFor(image);
1306
1117
  const original = image;
1307
1118
  image = load(image);
1308
1119
  (0, _shared.checkPalette)(palette);
1309
- const o = parseOptions(options, mapIndexOptions, image);
1310
- checkNotEmpty(palette, image, o.transparent > 0 ? o.transparent : 1);
1120
+ const o = (0, _shared.parseOptions)(options, _shared.mapIndexOptions, image);
1121
+ (0, _shared.checkNotEmpty)(palette, image, o.transparent > 0 ? o.transparent : 1);
1311
1122
  const space = matchingSpace(o, palette);
1312
1123
  const paletteSpace = (0, _shared.isPalette)(palette) ? palette.colorSpace : (0, _shared.colorSpaceName)(space);
1313
1124
  palette = held(palette);
1314
- warn(o.signal);
1315
1125
  const wasm = Module || (await acquire());
1316
1126
  checkAborted(o.signal);
1317
1127
  if (isControlled(o)) {
@@ -1331,17 +1141,9 @@ const quantizeToIndicesWithPalette = async (image, palette, options) => {
1331
1141
  exports.quantizeToIndicesWithPalette = quantizeToIndicesWithPalette;
1332
1142
  const chooseFrom = async (name, clustering, palette, k, options) => {
1333
1143
  const header = (0, _shared.readHeader)(clustering);
1334
- (0, _shared.checkPalette)(palette);
1335
- if (palette.length === 0) {
1336
- throw (0, _shared.fail)('invalid-argument', "Invalid palette: it is empty; give at least one RGB entry (3 bytes).", 'palette');
1337
- }
1144
+ k = (0, _shared.checkChoice)(palette, k);
1338
1145
  const entries = Uint8Array.from(palette);
1339
- const count = entries.length / 3;
1340
- k = check(k);
1341
- if (k > count) {
1342
- throw (0, _shared.fail)('invalid-argument', `Invalid k: ${k} is more than the ${count} entries in the palette; use ${count} or fewer.`, 'k');
1343
- }
1344
- const o = parseOptions(options, ['colorSpace', 'signal']);
1146
+ const o = (0, _shared.parseOptions)(options, ['colorSpace', 'signal']);
1345
1147
  needsWeights(header);
1346
1148
  clustering = held(clustering);
1347
1149
  checkAborted(o.signal);