agglomerative-clustering 4.0.0-beta.3 → 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,7 +24,7 @@ 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.x, 4.0 removed the get… and …FromClustering functions, turned two warnings into errors (a bare RGB or grey array, 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.
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
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
 
Binary file
package/dist/index.cjs CHANGED
@@ -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
@@ -481,22 +477,14 @@ const bytes = data => (0, _shared.isUint8Array)(data) ? data : new Uint8Array(da
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
479
  const load = image => {
484
- if ((0, _shared.isClustering)(image) || (0, _shared.isPalette)(image)) {
485
- const what = (0, _shared.isClustering)(image) ? 'a clustering (from buildClustering)' : 'a palette';
486
- const fix = (0, _shared.isClustering)(image) ? 'To cut a palette from it, use clustering.getPalette(k) (or clustering.quantize(image, k) to map an image with it).' : 'To map an image to it, use quantizeWithPalette(image, palette).';
487
- throw (0, _shared.fail)('invalid-argument', `Invalid image: this is ${what}, not pixels. ${fix}`, 'image');
488
- }
489
- if (ArrayBuffer.isView(image) && (0, _shared.isDetached)(image)) {
490
- 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
+ }
491
486
  }
492
487
  if ((0, _shared.isUint8Array)(image)) {
493
- const encoded = (0, _shared.sniffImageFormat)(image);
494
- if (encoded) {
495
- 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');
496
- }
497
- if (image.length % 4 !== 0) {
498
- throw (0, _shared.fail)('invalid-argument', "Invalid image data: length must be a multiple of 4 for 'rgba'.", 'image');
499
- }
500
488
  const bare = (0, _shared.bareImageError)(image);
501
489
  if (bare) {
502
490
  throw bare;
@@ -519,9 +507,6 @@ const load = image => {
519
507
  premultiplied: false
520
508
  };
521
509
  }
522
- if (ArrayBuffer.isView(image)) {
523
- 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');
524
- }
525
510
  if (typeof image !== 'object' || !image || !image.data || !image.format) {
526
511
  throw (0, _shared.fail)('invalid-argument', `Invalid image: expected object with \`data\` and \`format\`.${(0, _shared.imageHint)(image)}`, 'image');
527
512
  }
@@ -599,151 +584,6 @@ const unpackIndices = (output, image, colorSpace) => {
599
584
  return result;
600
585
  };
601
586
 
602
- // Returns k, validated. Any k above the number of colours means all of them, so it is capped at the largest value
603
- // the WASM side holds (a larger one would overflow its int).
604
- const check = k => {
605
- if (typeof k !== 'number' || !Number.isInteger(k) || k <= 0) {
606
- // A string is the usual slip (an input's `value`), so it gets its own fix.
607
- 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}.`;
608
- throw (0, _shared.fail)('invalid-argument', `Invalid k: must be a whole number of colours, 1 or more.${got}`, 'k');
609
- }
610
- return Math.min(k, 0x7FFFFFFF);
611
- };
612
-
613
- // Validates `options` against the keys a function accepts and fills in defaults:
614
- // colorSpace: 'rgb' (default) or 'oklab', the space colours are clustered and matched in; when mapping with a
615
- // clustering, the default is the space the clustering was made in (code -1)
616
- // alpha: 'weight' (default) counts RGBA pixels in proportion to their opacity; 'ignore' counts every pixel
617
- // precision: bits per channel, 1-8 (default 8, exact); lower values group similar colours before clustering
618
- // dither: false (default), true or a strength in [0, 1] (Floyd-Steinberg), a method name, or { method, strength, steps } (see parseDither)
619
- // width: image width in pixels, needed to dither a Uint8Array or a RawImage without `width`
620
- // signal, onProgress: an AbortSignal and a progress callback, which make the clustering and the mapping run in slices
621
- // (see clusterInSlices and mapInSlices)
622
- // 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);
623
- // indexed output also gives them their own entry, which counts towards k
624
-
625
- // The settings of dither, which a caller may write as options of their own; naming one of these gets a pointer to the
626
- // object form.
627
- const ditherSettings = ['ditherMethod', 'ditherStrength', 'ditherSteps', 'method', 'strength', 'steps', 'mix'];
628
- const parseOptions = (options, allowed, image) => {
629
- if (options === undefined) {
630
- options = {};
631
- }
632
- if (!(0, _shared.isOptionsObject)(options)) {
633
- throw (0, _shared.fail)('invalid-argument', "Invalid options: expected an object.", 'options');
634
- }
635
- options = (0, _shared.snapshot)(options);
636
- for (const key of Object.keys(options)) {
637
- if (!allowed.includes(key)) {
638
- const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' : '';
639
- throw (0, _shared.fail)('invalid-argument', `Invalid option '${key}': expected one of ${allowed.join(', ')}.${hint}`, `options.${key}`);
640
- }
641
- }
642
- const colorSpace = options.colorSpace === undefined ? 'rgb' : options.colorSpace;
643
- if (!_shared.colorSpaces.includes(colorSpace)) {
644
- throw (0, _shared.fail)('invalid-argument', "Invalid colorSpace: must be 'rgb' or 'oklab'.", 'options.colorSpace');
645
- }
646
- const alpha = options.alpha === undefined ? 'weight' : options.alpha;
647
- if (!Object.keys(alphaModeCodes).includes(alpha)) {
648
- throw (0, _shared.fail)('invalid-argument', "Invalid alpha: must be 'weight' or 'ignore'.", 'options.alpha');
649
- }
650
- const precision = options.precision === undefined ? 8 : options.precision;
651
- if (typeof precision !== 'number' || !Number.isInteger(precision) || precision < 1 || precision > 8) {
652
- throw (0, _shared.fail)('invalid-argument', "Invalid precision: must be an integer from 1 to 8.", 'options.precision');
653
- }
654
- const {
655
- strength: dither,
656
- method: ditherMethod,
657
- steps: ditherSteps
658
- } = (0, _shared.parseDither)(options.dither);
659
-
660
- // The image's own width and options.width are two sources for one fact: they may repeat each other, but not disagree
661
- // (a wrong row length would dither without an error, as long as it divides the pixel count).
662
- if (options.width !== undefined && image && image.width !== undefined && options.width !== image.width) {
663
- throw (0, _shared.fail)('invalid-argument', `Invalid width: options.width (${options.width}) does not match the image's width (${image.width}).`, 'options.width');
664
- }
665
- if (options.width !== undefined && image) {
666
- (0, _shared.checkSize)(image.data.length / (0, _shared.channels)(image.format), options.width, 'width', 'options.width');
667
- }
668
- const width = options.width !== undefined ? options.width : image ? image.width : undefined;
669
- if (dither > 0) {
670
- const stride = (0, _shared.channels)(image.format);
671
- if (typeof width !== 'number' || !Number.isInteger(width) || width <= 0) {
672
- throw (0, _shared.fail)('invalid-argument', "Invalid width: dithering needs the image width, as `options.width` or the image's `width`.", 'options.width');
673
- }
674
- if (image.data.length / stride % width !== 0) {
675
- throw (0, _shared.fail)('invalid-argument', "Invalid width: the image's pixel count is not a multiple of it.", 'options.width');
676
- }
677
- }
678
- const signal = options.signal;
679
- if (signal !== undefined && (signal === null || typeof signal !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function')) {
680
- throw (0, _shared.fail)('invalid-argument', "Invalid signal: must be an AbortSignal.", 'options.signal');
681
- }
682
- const onProgress = options.onProgress;
683
- if (onProgress !== undefined && typeof onProgress !== 'function') {
684
- throw (0, _shared.fail)('invalid-argument', "Invalid onProgress: must be a function.", 'options.onProgress');
685
- }
686
-
687
- // The alpha cutoff for indexed output: 0 for none, else the pixels with alpha below it are transparent.
688
- const transparentOption = options.transparent === undefined ? false : options.transparent;
689
- const transparent = transparentOption === false ? 0 : transparentOption === true ? 128 : transparentOption;
690
- if (!Number.isInteger(transparent) || transparent < 0 || transparent > 255 || transparent === 0 && transparentOption !== false) {
691
- throw (0, _shared.fail)('invalid-argument', "Invalid transparent: must be a boolean or an integer alpha cutoff from 1 to 255.", 'options.transparent');
692
- }
693
- checkTransparentFormat(image, options);
694
-
695
- // A cutoff replaces opacity weighting (pixels count whole or not at all), so naming both would leave one of them ignored.
696
- if (transparent > 0 && options.alpha !== undefined) {
697
- 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');
698
- }
699
- return {
700
- colorSpace: _shared.colorSpaceCodes[colorSpace],
701
- colorSpaceGiven: options.colorSpace !== undefined,
702
- alpha: alphaModeCodes[alpha],
703
- precision,
704
- dither,
705
- ditherMethod,
706
- ditherSteps,
707
- width: dither > 0 ? width : 0,
708
- transparent,
709
- transparentGiven: options.transparent !== undefined,
710
- signal,
711
- onProgress
712
- };
713
- };
714
- const controlOptions = ['signal', 'onProgress'];
715
- // `transparent: true` or a cutoff on a format with no alpha channel can't mean anything (no pixel is transparent), so it is
716
- // an error rather than a silent no-op. Only the call's own options count: a clustering's stored cutoff never reaches here.
717
- const checkTransparentFormat = (image, options) => {
718
- if (!image || (0, _shared.hasAlpha)(image.format) || options.transparent === undefined || options.transparent === false) {
719
- return;
720
- }
721
- const hint = image.format === 'rgbx' || image.format === 'bgrx' ? " If the fourth byte really is alpha, use 'rgba' or 'bgra'." : '';
722
- throw (0, _shared.fail)('invalid-argument', `Invalid transparent: '${image.format}' has no alpha, so no pixel can be transparent. Leave transparent out (false is accepted).${hint}`, 'options.transparent');
723
- };
724
- const clusterOptions = ['colorSpace', 'precision', 'alpha', 'transparent', ...controlOptions];
725
- const quantizeOptions = [...clusterOptions, 'dither', 'width'];
726
- const mapOptions = ['colorSpace', 'dither', 'width', ...controlOptions];
727
- const quantizeIndexOptions = quantizeOptions;
728
- const mapIndexOptions = [...mapOptions, 'transparent'];
729
-
730
- // An empty palette is what getPalette gives for an image with no visible pixels, and mapping such an image with it is
731
- // fine. Mapping visible pixels to it has no answer (they would all come out black), so that is an error. `cutoff` is the
732
- // alpha from which an RGBA pixel needs a colour.
733
- const checkNotEmpty = (palette, image, cutoff) => {
734
- if (palette.length > 0) {
735
- return;
736
- }
737
- const data = image.data;
738
- let visible = (0, _shared.hasAlpha)(image.format) ? false : data.length > 0;
739
- for (let i = 3; !visible && (0, _shared.hasAlpha)(image.format) && i < data.length; i += 4) {
740
- visible = data[i] >= cutoff;
741
- }
742
- if (visible) {
743
- throw (0, _shared.fail)('invalid-argument', "Invalid palette: it is empty, but the image has visible pixels to map to it.", 'palette');
744
- }
745
- };
746
-
747
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.
748
588
  const matchingSpace = (o, palette) => o.colorSpaceGiven ? o.colorSpace : _shared.colorSpaceCodes[(0, _shared.isPalette)(palette) ? palette.colorSpace : 'rgb'];
749
589
 
@@ -1016,7 +856,7 @@ const noOptions = (name, extra) => {
1016
856
  const buildClustering = async (image, options) => {
1017
857
  image = (0, _shared.imageCopy)(image);
1018
858
  image = load(image);
1019
- const o = parseOptions(options, clusterOptions, image);
859
+ const o = (0, _shared.parseOptions)(options, _shared.clusterOptions, image);
1020
860
  const wasm = Module || (await acquire());
1021
861
  if (isControlled(o)) {
1022
862
  const report = reporter(o);
@@ -1030,8 +870,8 @@ exports.buildClustering = buildClustering;
1030
870
  const buildPalette = async (image, k, options) => {
1031
871
  image = (0, _shared.imageCopy)(image);
1032
872
  image = load(image);
1033
- k = check(k);
1034
- const o = parseOptions(options, clusterOptions, image);
873
+ k = (0, _shared.checkK)(k);
874
+ const o = (0, _shared.parseOptions)(options, _shared.clusterOptions, image);
1035
875
  const wasm = Module || (await acquire());
1036
876
  if (isControlled(o)) {
1037
877
  const report = reporter(o);
@@ -1048,7 +888,7 @@ const buildPalette = async (image, k, options) => {
1048
888
  exports.buildPalette = buildPalette;
1049
889
  const cutPalette = async (name, clustering, k, extra) => {
1050
890
  const header = (0, _shared.readHeader)(clustering);
1051
- k = check(k);
891
+ k = (0, _shared.checkK)(k);
1052
892
  noOptions(name, extra);
1053
893
  clustering = held(clustering);
1054
894
  const wasm = Module || (await acquire());
@@ -1077,7 +917,7 @@ const needsWeights = header => {
1077
917
  // proportion to their opacity, as in clustering. Shares are the weights divided by their total, so they sum to 1.
1078
918
  const cutSwatches = async (name, clustering, k, extra) => {
1079
919
  const header = (0, _shared.readHeader)(clustering);
1080
- k = check(k);
920
+ k = (0, _shared.checkK)(k);
1081
921
  noOptions(name, extra);
1082
922
  needsWeights(header);
1083
923
  clustering = held(clustering);
@@ -1107,7 +947,7 @@ const buildSwatches = async (image, k, options) => {
1107
947
  // Arguments are checked in the order they are given (image, then k, then options), as in every other function.
1108
948
  // `load` only validates here (buildClustering loads again); both see the copy, so the caller's fields are read once.
1109
949
  load(image);
1110
- k = check(k);
950
+ k = (0, _shared.checkK)(k);
1111
951
  return cutSwatches('buildSwatches', await buildClustering(image, options), k, []);
1112
952
  };
1113
953
 
@@ -1162,8 +1002,8 @@ const quantize = async (image, k, options) => {
1162
1002
  image = (0, _shared.imageCopy)(image);
1163
1003
  const wrap = getWrapper(image);
1164
1004
  image = load(image);
1165
- k = check(k);
1166
- const o = parseOptions(options, quantizeOptions, image);
1005
+ k = (0, _shared.checkK)(k);
1006
+ const o = (0, _shared.parseOptions)(options, _shared.quantizeOptions, image);
1167
1007
  const wasm = Module || (await acquire());
1168
1008
  if (isControlled(o)) {
1169
1009
  const report = reporter(o);
@@ -1184,8 +1024,8 @@ const quantizeFromClustering = async (image, clustering, k, options) => {
1184
1024
  const wrap = getWrapper(image);
1185
1025
  image = load(image);
1186
1026
  (0, _shared.readHeader)(clustering);
1187
- k = check(k);
1188
- const o = parseOptions(options, mapOptions, image);
1027
+ k = (0, _shared.checkK)(k);
1028
+ const o = (0, _shared.parseOptions)(options, _shared.mapOptions, image);
1189
1029
  clustering = held(clustering);
1190
1030
  const wasm = Module || (await acquire());
1191
1031
  checkAborted(o.signal);
@@ -1207,8 +1047,8 @@ const quantizeWithPalette = async (image, palette, options) => {
1207
1047
  const wrap = getWrapper(image);
1208
1048
  image = load(image);
1209
1049
  (0, _shared.checkPalette)(palette);
1210
- const o = parseOptions(options, mapOptions, image);
1211
- checkNotEmpty(palette, image, 1);
1050
+ const o = (0, _shared.parseOptions)(options, _shared.mapOptions, image);
1051
+ (0, _shared.checkNotEmpty)(palette, image, 1);
1212
1052
  const space = matchingSpace(o, palette);
1213
1053
  palette = held(palette);
1214
1054
  const wasm = Module || (await acquire());
@@ -1229,8 +1069,8 @@ const quantizeToIndices = async (image, k, options) => {
1229
1069
  image = (0, _shared.imageCopy)(image);
1230
1070
  const original = image;
1231
1071
  image = load(image);
1232
- k = check(k);
1233
- const o = parseOptions(options, quantizeIndexOptions, image);
1072
+ k = (0, _shared.checkK)(k);
1073
+ const o = (0, _shared.parseOptions)(options, _shared.quantizeIndexOptions, image);
1234
1074
  const wasm = Module || (await acquire());
1235
1075
  if (isControlled(o)) {
1236
1076
  const report = reporter(o);
@@ -1251,8 +1091,8 @@ const quantizeToIndicesFromClustering = async (image, clustering, k, options) =>
1251
1091
  const original = image;
1252
1092
  image = load(image);
1253
1093
  const header = (0, _shared.readHeader)(clustering);
1254
- k = check(k);
1255
- const o = parseOptions(options, mapIndexOptions, image);
1094
+ k = (0, _shared.checkK)(k);
1095
+ const o = (0, _shared.parseOptions)(options, _shared.mapIndexOptions, image);
1256
1096
  clustering = held(clustering);
1257
1097
  const wasm = Module || (await acquire());
1258
1098
  checkAborted(o.signal);
@@ -1277,8 +1117,8 @@ const quantizeToIndicesWithPalette = async (image, palette, options) => {
1277
1117
  const original = image;
1278
1118
  image = load(image);
1279
1119
  (0, _shared.checkPalette)(palette);
1280
- const o = parseOptions(options, mapIndexOptions, image);
1281
- 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);
1282
1122
  const space = matchingSpace(o, palette);
1283
1123
  const paletteSpace = (0, _shared.isPalette)(palette) ? palette.colorSpace : (0, _shared.colorSpaceName)(space);
1284
1124
  palette = held(palette);
@@ -1301,17 +1141,9 @@ const quantizeToIndicesWithPalette = async (image, palette, options) => {
1301
1141
  exports.quantizeToIndicesWithPalette = quantizeToIndicesWithPalette;
1302
1142
  const chooseFrom = async (name, clustering, palette, k, options) => {
1303
1143
  const header = (0, _shared.readHeader)(clustering);
1304
- (0, _shared.checkPalette)(palette);
1305
- if (palette.length === 0) {
1306
- throw (0, _shared.fail)('invalid-argument', "Invalid palette: it is empty; give at least one RGB entry (3 bytes).", 'palette');
1307
- }
1144
+ k = (0, _shared.checkChoice)(palette, k);
1308
1145
  const entries = Uint8Array.from(palette);
1309
- const count = entries.length / 3;
1310
- k = check(k);
1311
- if (k > count) {
1312
- throw (0, _shared.fail)('invalid-argument', `Invalid k: ${k} is more than the ${count} entries in the palette; use ${count} or fewer.`, 'k');
1313
- }
1314
- const o = parseOptions(options, ['colorSpace', 'signal']);
1146
+ const o = (0, _shared.parseOptions)(options, ['colorSpace', 'signal']);
1315
1147
  needsWeights(header);
1316
1148
  clustering = held(clustering);
1317
1149
  checkAborted(o.signal);
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import createWasmModule from './clustering.js';
2
2
  import { choose } from "./choose.mjs";
3
- 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, sniffImageFormat, bareImageError, checkImageBody, imageCopy, checkSize } from "./shared.mjs";
3
+ import { parseDither, checkK, parseOptions, alphaModeCodes, clusterOptions, quantizeOptions, mapOptions, quantizeIndexOptions, mapIndexOptions, 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, sniffImageFormat, bareImageError, checkImageBody, imageCopy, checkSize, checkPixelArray, checkNotEmpty, checkChoice } from "./shared.mjs";
4
4
 
5
5
  // The library's version, the stored-data format version, and the Palette and Clustering types (see shared.js).
6
6
  export { version, Palette, Clustering, errorCodes, isCodedError, ditherMethods, ditherSteps, colorSpaces, imageFormats, alphaModes } from "./shared.mjs";
@@ -21,10 +21,6 @@ const codes = {
21
21
  'rgbx': 3,
22
22
  'bgrx': 4
23
23
  };
24
- const alphaModeCodes = {
25
- 'ignore': 0,
26
- 'weight': 1
27
- };
28
24
  let Module = null;
29
25
 
30
26
  // Turns init's `wasm` option into the settings the Emscripten glue understands. The glue finds its .wasm file next to
@@ -405,22 +401,14 @@ const bytes = data => isUint8Array(data) ? data : new Uint8Array(data.buffer, da
405
401
  // call returns; until then (the first call) a copy is kept for when it has loaded.
406
402
  const held = data => Module ? data : data.slice();
407
403
  const load = image => {
408
- if (isClustering(image) || isPalette(image)) {
409
- const what = isClustering(image) ? 'a clustering (from buildClustering)' : 'a palette';
410
- const fix = isClustering(image) ? 'To cut a palette from it, use clustering.getPalette(k) (or clustering.quantize(image, k) to map an image with it).' : 'To map an image to it, use quantizeWithPalette(image, palette).';
411
- throw fail('invalid-argument', `Invalid image: this is ${what}, not pixels. ${fix}`, 'image');
412
- }
413
- if (ArrayBuffer.isView(image) && isDetached(image)) {
414
- throw detachedError('bare');
404
+ if (ArrayBuffer.isView(image)) {
405
+ // What a bare typed array must be (see checkPixelArray, which the worker entry runs too); a detached one is reported first.
406
+ checkPixelArray(image);
407
+ if (isDetached(image)) {
408
+ throw detachedError('bare');
409
+ }
415
410
  }
416
411
  if (isUint8Array(image)) {
417
- const encoded = sniffImageFormat(image);
418
- if (encoded) {
419
- throw 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');
420
- }
421
- if (image.length % 4 !== 0) {
422
- throw fail('invalid-argument', "Invalid image data: length must be a multiple of 4 for 'rgba'.", 'image');
423
- }
424
412
  const bare = bareImageError(image);
425
413
  if (bare) {
426
414
  throw bare;
@@ -443,9 +431,6 @@ const load = image => {
443
431
  premultiplied: false
444
432
  };
445
433
  }
446
- if (ArrayBuffer.isView(image)) {
447
- throw 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');
448
- }
449
434
  if (typeof image !== 'object' || !image || !image.data || !image.format) {
450
435
  throw fail('invalid-argument', `Invalid image: expected object with \`data\` and \`format\`.${imageHint(image)}`, 'image');
451
436
  }
@@ -523,151 +508,6 @@ const unpackIndices = (output, image, colorSpace) => {
523
508
  return result;
524
509
  };
525
510
 
526
- // Returns k, validated. Any k above the number of colours means all of them, so it is capped at the largest value
527
- // the WASM side holds (a larger one would overflow its int).
528
- const check = k => {
529
- if (typeof k !== 'number' || !Number.isInteger(k) || k <= 0) {
530
- // A string is the usual slip (an input's `value`), so it gets its own fix.
531
- 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}.`;
532
- throw fail('invalid-argument', `Invalid k: must be a whole number of colours, 1 or more.${got}`, 'k');
533
- }
534
- return Math.min(k, 0x7FFFFFFF);
535
- };
536
-
537
- // Validates `options` against the keys a function accepts and fills in defaults:
538
- // colorSpace: 'rgb' (default) or 'oklab', the space colours are clustered and matched in; when mapping with a
539
- // clustering, the default is the space the clustering was made in (code -1)
540
- // alpha: 'weight' (default) counts RGBA pixels in proportion to their opacity; 'ignore' counts every pixel
541
- // precision: bits per channel, 1-8 (default 8, exact); lower values group similar colours before clustering
542
- // dither: false (default), true or a strength in [0, 1] (Floyd-Steinberg), a method name, or { method, strength, steps } (see parseDither)
543
- // width: image width in pixels, needed to dither a Uint8Array or a RawImage without `width`
544
- // signal, onProgress: an AbortSignal and a progress callback, which make the clustering and the mapping run in slices
545
- // (see clusterInSlices and mapInSlices)
546
- // 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);
547
- // indexed output also gives them their own entry, which counts towards k
548
-
549
- // The settings of dither, which a caller may write as options of their own; naming one of these gets a pointer to the
550
- // object form.
551
- const ditherSettings = ['ditherMethod', 'ditherStrength', 'ditherSteps', 'method', 'strength', 'steps', 'mix'];
552
- const parseOptions = (options, allowed, image) => {
553
- if (options === undefined) {
554
- options = {};
555
- }
556
- if (!isOptionsObject(options)) {
557
- throw fail('invalid-argument', "Invalid options: expected an object.", 'options');
558
- }
559
- options = snapshot(options);
560
- for (const key of Object.keys(options)) {
561
- if (!allowed.includes(key)) {
562
- const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' : '';
563
- throw fail('invalid-argument', `Invalid option '${key}': expected one of ${allowed.join(', ')}.${hint}`, `options.${key}`);
564
- }
565
- }
566
- const colorSpace = options.colorSpace === undefined ? 'rgb' : options.colorSpace;
567
- if (!colorSpaces.includes(colorSpace)) {
568
- throw fail('invalid-argument', "Invalid colorSpace: must be 'rgb' or 'oklab'.", 'options.colorSpace');
569
- }
570
- const alpha = options.alpha === undefined ? 'weight' : options.alpha;
571
- if (!Object.keys(alphaModeCodes).includes(alpha)) {
572
- throw fail('invalid-argument', "Invalid alpha: must be 'weight' or 'ignore'.", 'options.alpha');
573
- }
574
- const precision = options.precision === undefined ? 8 : options.precision;
575
- if (typeof precision !== 'number' || !Number.isInteger(precision) || precision < 1 || precision > 8) {
576
- throw fail('invalid-argument', "Invalid precision: must be an integer from 1 to 8.", 'options.precision');
577
- }
578
- const {
579
- strength: dither,
580
- method: ditherMethod,
581
- steps: ditherSteps
582
- } = parseDither(options.dither);
583
-
584
- // The image's own width and options.width are two sources for one fact: they may repeat each other, but not disagree
585
- // (a wrong row length would dither without an error, as long as it divides the pixel count).
586
- if (options.width !== undefined && image && image.width !== undefined && options.width !== image.width) {
587
- throw fail('invalid-argument', `Invalid width: options.width (${options.width}) does not match the image's width (${image.width}).`, 'options.width');
588
- }
589
- if (options.width !== undefined && image) {
590
- checkSize(image.data.length / channels(image.format), options.width, 'width', 'options.width');
591
- }
592
- const width = options.width !== undefined ? options.width : image ? image.width : undefined;
593
- if (dither > 0) {
594
- const stride = channels(image.format);
595
- if (typeof width !== 'number' || !Number.isInteger(width) || width <= 0) {
596
- throw fail('invalid-argument', "Invalid width: dithering needs the image width, as `options.width` or the image's `width`.", 'options.width');
597
- }
598
- if (image.data.length / stride % width !== 0) {
599
- throw fail('invalid-argument', "Invalid width: the image's pixel count is not a multiple of it.", 'options.width');
600
- }
601
- }
602
- const signal = options.signal;
603
- if (signal !== undefined && (signal === null || typeof signal !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function')) {
604
- throw fail('invalid-argument', "Invalid signal: must be an AbortSignal.", 'options.signal');
605
- }
606
- const onProgress = options.onProgress;
607
- if (onProgress !== undefined && typeof onProgress !== 'function') {
608
- throw fail('invalid-argument', "Invalid onProgress: must be a function.", 'options.onProgress');
609
- }
610
-
611
- // The alpha cutoff for indexed output: 0 for none, else the pixels with alpha below it are transparent.
612
- const transparentOption = options.transparent === undefined ? false : options.transparent;
613
- const transparent = transparentOption === false ? 0 : transparentOption === true ? 128 : transparentOption;
614
- if (!Number.isInteger(transparent) || transparent < 0 || transparent > 255 || transparent === 0 && transparentOption !== false) {
615
- throw fail('invalid-argument', "Invalid transparent: must be a boolean or an integer alpha cutoff from 1 to 255.", 'options.transparent');
616
- }
617
- checkTransparentFormat(image, options);
618
-
619
- // A cutoff replaces opacity weighting (pixels count whole or not at all), so naming both would leave one of them ignored.
620
- if (transparent > 0 && options.alpha !== undefined) {
621
- throw 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');
622
- }
623
- return {
624
- colorSpace: colorSpaceCodes[colorSpace],
625
- colorSpaceGiven: options.colorSpace !== undefined,
626
- alpha: alphaModeCodes[alpha],
627
- precision,
628
- dither,
629
- ditherMethod,
630
- ditherSteps,
631
- width: dither > 0 ? width : 0,
632
- transparent,
633
- transparentGiven: options.transparent !== undefined,
634
- signal,
635
- onProgress
636
- };
637
- };
638
- const controlOptions = ['signal', 'onProgress'];
639
- // `transparent: true` or a cutoff on a format with no alpha channel can't mean anything (no pixel is transparent), so it is
640
- // an error rather than a silent no-op. Only the call's own options count: a clustering's stored cutoff never reaches here.
641
- const checkTransparentFormat = (image, options) => {
642
- if (!image || hasAlpha(image.format) || options.transparent === undefined || options.transparent === false) {
643
- return;
644
- }
645
- const hint = image.format === 'rgbx' || image.format === 'bgrx' ? " If the fourth byte really is alpha, use 'rgba' or 'bgra'." : '';
646
- throw fail('invalid-argument', `Invalid transparent: '${image.format}' has no alpha, so no pixel can be transparent. Leave transparent out (false is accepted).${hint}`, 'options.transparent');
647
- };
648
- const clusterOptions = ['colorSpace', 'precision', 'alpha', 'transparent', ...controlOptions];
649
- const quantizeOptions = [...clusterOptions, 'dither', 'width'];
650
- const mapOptions = ['colorSpace', 'dither', 'width', ...controlOptions];
651
- const quantizeIndexOptions = quantizeOptions;
652
- const mapIndexOptions = [...mapOptions, 'transparent'];
653
-
654
- // An empty palette is what getPalette gives for an image with no visible pixels, and mapping such an image with it is
655
- // fine. Mapping visible pixels to it has no answer (they would all come out black), so that is an error. `cutoff` is the
656
- // alpha from which an RGBA pixel needs a colour.
657
- const checkNotEmpty = (palette, image, cutoff) => {
658
- if (palette.length > 0) {
659
- return;
660
- }
661
- const data = image.data;
662
- let visible = hasAlpha(image.format) ? false : data.length > 0;
663
- for (let i = 3; !visible && hasAlpha(image.format) && i < data.length; i += 4) {
664
- visible = data[i] >= cutoff;
665
- }
666
- if (visible) {
667
- throw fail('invalid-argument', "Invalid palette: it is empty, but the image has visible pixels to map to it.", 'palette');
668
- }
669
- };
670
-
671
511
  // The space to match pixels to a palette in: the one the caller names, else the one a Palette was made in, else RGB.
672
512
  const matchingSpace = (o, palette) => o.colorSpaceGiven ? o.colorSpace : colorSpaceCodes[isPalette(palette) ? palette.colorSpace : 'rgb'];
673
513
 
@@ -953,7 +793,7 @@ export const buildClustering = async (image, options) => {
953
793
  export const buildPalette = async (image, k, options) => {
954
794
  image = imageCopy(image);
955
795
  image = load(image);
956
- k = check(k);
796
+ k = checkK(k);
957
797
  const o = parseOptions(options, clusterOptions, image);
958
798
  const wasm = Module || (await acquire());
959
799
  if (isControlled(o)) {
@@ -970,7 +810,7 @@ export const buildPalette = async (image, k, options) => {
970
810
  // The cuts take the name they were called by, for their messages: the methods on Clustering (or the function that cuts).
971
811
  const cutPalette = async (name, clustering, k, extra) => {
972
812
  const header = readHeader(clustering);
973
- k = check(k);
813
+ k = checkK(k);
974
814
  noOptions(name, extra);
975
815
  clustering = held(clustering);
976
816
  const wasm = Module || (await acquire());
@@ -999,7 +839,7 @@ const needsWeights = header => {
999
839
  // proportion to their opacity, as in clustering. Shares are the weights divided by their total, so they sum to 1.
1000
840
  const cutSwatches = async (name, clustering, k, extra) => {
1001
841
  const header = readHeader(clustering);
1002
- k = check(k);
842
+ k = checkK(k);
1003
843
  noOptions(name, extra);
1004
844
  needsWeights(header);
1005
845
  clustering = held(clustering);
@@ -1029,7 +869,7 @@ export const buildSwatches = async (image, k, options) => {
1029
869
  // Arguments are checked in the order they are given (image, then k, then options), as in every other function.
1030
870
  // `load` only validates here (buildClustering loads again); both see the copy, so the caller's fields are read once.
1031
871
  load(image);
1032
- k = check(k);
872
+ k = checkK(k);
1033
873
  return cutSwatches('buildSwatches', await buildClustering(image, options), k, []);
1034
874
  };
1035
875
 
@@ -1083,7 +923,7 @@ export const quantize = async (image, k, options) => {
1083
923
  image = imageCopy(image);
1084
924
  const wrap = getWrapper(image);
1085
925
  image = load(image);
1086
- k = check(k);
926
+ k = checkK(k);
1087
927
  const o = parseOptions(options, quantizeOptions, image);
1088
928
  const wasm = Module || (await acquire());
1089
929
  if (isControlled(o)) {
@@ -1104,7 +944,7 @@ const quantizeFromClustering = async (image, clustering, k, options) => {
1104
944
  const wrap = getWrapper(image);
1105
945
  image = load(image);
1106
946
  readHeader(clustering);
1107
- k = check(k);
947
+ k = checkK(k);
1108
948
  const o = parseOptions(options, mapOptions, image);
1109
949
  clustering = held(clustering);
1110
950
  const wasm = Module || (await acquire());
@@ -1148,7 +988,7 @@ export const quantizeToIndices = async (image, k, options) => {
1148
988
  image = imageCopy(image);
1149
989
  const original = image;
1150
990
  image = load(image);
1151
- k = check(k);
991
+ k = checkK(k);
1152
992
  const o = parseOptions(options, quantizeIndexOptions, image);
1153
993
  const wasm = Module || (await acquire());
1154
994
  if (isControlled(o)) {
@@ -1169,7 +1009,7 @@ const quantizeToIndicesFromClustering = async (image, clustering, k, options) =>
1169
1009
  const original = image;
1170
1010
  image = load(image);
1171
1011
  const header = readHeader(clustering);
1172
- k = check(k);
1012
+ k = checkK(k);
1173
1013
  const o = parseOptions(options, mapIndexOptions, image);
1174
1014
  clustering = held(clustering);
1175
1015
  const wasm = Module || (await acquire());
@@ -1218,16 +1058,8 @@ export const quantizeToIndicesWithPalette = async (image, palette, options) => {
1218
1058
  // at once), then runs the search in choose.js on this thread with the cuts above.
1219
1059
  const chooseFrom = async (name, clustering, palette, k, options) => {
1220
1060
  const header = readHeader(clustering);
1221
- checkPalette(palette);
1222
- if (palette.length === 0) {
1223
- throw fail('invalid-argument', "Invalid palette: it is empty; give at least one RGB entry (3 bytes).", 'palette');
1224
- }
1061
+ k = checkChoice(palette, k);
1225
1062
  const entries = Uint8Array.from(palette);
1226
- const count = entries.length / 3;
1227
- k = check(k);
1228
- if (k > count) {
1229
- throw fail('invalid-argument', `Invalid k: ${k} is more than the ${count} entries in the palette; use ${count} or fewer.`, 'k');
1230
- }
1231
1063
  const o = parseOptions(options, ['colorSpace', 'signal']);
1232
1064
  needsWeights(header);
1233
1065
  clustering = held(clustering);