agglomerative-clustering 3.7.2 → 4.0.0-beta.1

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.cjs CHANGED
@@ -75,6 +75,7 @@ var _clustering = _interopRequireDefault((() => {
75
75
  return require("./clustering.cjs");
76
76
  }
77
77
  })());
78
+ var _choose = require("./choose.cjs");
78
79
  var _shared = require("./shared.cjs");
79
80
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
80
81
  function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } // The library's version, the stored-data format version, and the Palette and Clustering types (see shared.js).
@@ -95,27 +96,6 @@ const codes = {
95
96
  'rgbx': 3,
96
97
  'bgrx': 4
97
98
  };
98
- // 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
99
- // supported layout.
100
- const formatHint = format => {
101
- if (typeof format !== 'string') {
102
- return '';
103
- }
104
- const lower = format.toLowerCase();
105
- if (lower !== format && _shared.imageFormats.includes(lower)) {
106
- return ` Format names are lower case: '${lower}'.`;
107
- }
108
- if (lower === 'xrgb' || lower === 'rgb24') {
109
- return " Cairo RGB24 (xRGB) is BGRX in memory on little-endian machines: pass 'bgrx'.";
110
- }
111
- if (lower === 'argb' || lower === 'argb32') {
112
- 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).";
113
- }
114
- if (lower === 'bgr' || lower === 'bgr24') {
115
- return " 24-bit BGR isn't supported: widen each pixel to 4 bytes and pass 'bgrx'.";
116
- }
117
- return '';
118
- };
119
99
  const alphaModeCodes = {
120
100
  'ignore': 0,
121
101
  'weight': 1
@@ -501,20 +481,6 @@ const bytes = data => (0, _shared.isUint8Array)(data) ? data : new Uint8Array(da
501
481
  // call returns; until then (the first call) a copy is kept for when it has loaded.
502
482
  const held = data => Module ? data : data.slice();
503
483
 
504
- // width and height are copied to results and used for dithering, so each must make sense on its own: a whole number of
505
- // pixels that divides the pixel count (and, when both are given, account for exactly the pixels in the data).
506
- const checkSize = (pixels, size, name, argument) => {
507
- if (size === undefined) {
508
- return;
509
- }
510
- if (!Number.isInteger(size) || size < 0) {
511
- throw (0, _shared.fail)('invalid-argument', `Invalid ${name}: must be a whole number of pixels.`, argument);
512
- }
513
- if (pixels > 0 && (size === 0 || pixels % size !== 0)) {
514
- throw (0, _shared.fail)('invalid-argument', `Invalid ${name}: ${size} does not divide the image's ${pixels} pixels into whole rows.`, argument);
515
- }
516
- };
517
-
518
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,
519
485
  // just before it starts work, so the one warning isn't spent on a call that fails anyway (PRINCIPLES "Warnings").
520
486
  const noWarning = () => {};
@@ -546,7 +512,8 @@ const load = image => {
546
512
  }
547
513
  return {
548
514
  data: held(image),
549
- format: 'rgba'
515
+ format: 'rgba',
516
+ premultiplied: false
550
517
  };
551
518
  }
552
519
  if ((0, _shared.isImageData)(image)) {
@@ -557,7 +524,8 @@ const load = image => {
557
524
  return {
558
525
  data: held(bytes(image.data)),
559
526
  format: 'rgba',
560
- width: image.width
527
+ width: image.width,
528
+ premultiplied: false
561
529
  };
562
530
  }
563
531
  if (ArrayBuffer.isView(image)) {
@@ -572,23 +540,12 @@ const load = image => {
572
540
  if ((0, _shared.isDetached)(image.data)) {
573
541
  throw (0, _shared.detachedError)('data');
574
542
  }
575
- if (!_shared.imageFormats.includes(image.format)) {
576
- throw (0, _shared.fail)('invalid-argument', `Invalid format: got ${(0, _shared.describe)(image.format)}; it must be ${_shared.formatNames}.${formatHint(image.format)}`, 'image');
577
- }
578
- const stride = (0, _shared.channels)(image.format);
579
- if (image.data.length % stride !== 0) {
580
- throw (0, _shared.fail)('invalid-argument', `Invalid image data: length must be a multiple of ${stride} for '${image.format}'.`, 'image');
581
- }
582
- const pixels = image.data.length / stride;
583
- checkSize(pixels, image.width, 'image width', 'image');
584
- checkSize(pixels, image.height, 'image height', 'image');
585
- if (image.width !== undefined && image.height !== undefined && image.width * image.height !== pixels) {
586
- throw (0, _shared.fail)('invalid-argument', `Invalid image: width x height (${image.width} x ${image.height}) does not match its ${pixels} pixels.`, 'image');
587
- }
543
+ const premultiplied = (0, _shared.checkImageObject)(image);
588
544
  return {
589
545
  data: held(bytes(image.data)),
590
546
  format: image.format,
591
- width: image.width
547
+ width: image.width,
548
+ premultiplied
592
549
  };
593
550
  };
594
551
  const getWrapper = image => {
@@ -600,7 +557,8 @@ const getWrapper = image => {
600
557
  const {
601
558
  format,
602
559
  width,
603
- height
560
+ height,
561
+ premultiplied
604
562
  } = image;
605
563
  return output => {
606
564
  const result = {
@@ -613,6 +571,9 @@ const getWrapper = image => {
613
571
  if (height !== undefined) {
614
572
  result.height = height;
615
573
  }
574
+ if (premultiplied !== undefined) {
575
+ result.premultiplied = premultiplied;
576
+ }
616
577
  return result;
617
578
  };
618
579
  }
@@ -717,7 +678,7 @@ const parseOptions = (options, allowed, image) => {
717
678
  throw (0, _shared.fail)('invalid-argument', `Invalid width: options.width (${options.width}) does not match the image's width (${image.width}).`, 'options.width');
718
679
  }
719
680
  if (options.width !== undefined && image) {
720
- checkSize(image.data.length / (0, _shared.channels)(image.format), options.width, 'width', 'options.width');
681
+ (0, _shared.checkSize)(image.data.length / (0, _shared.channels)(image.format), options.width, 'width', 'options.width');
721
682
  }
722
683
  const width = options.width !== undefined ? options.width : image ? image.width : undefined;
723
684
  if (dither > 0) {
@@ -805,7 +766,9 @@ const allocate = (wasm, length) => {
805
766
 
806
767
  // Copies each buffer into the WASM heap, calls `fn` with their pointers, and returns the unpacked output,
807
768
  // freeing everything afterwards. `precision` is given for a clustering, for the out-of-memory advice.
808
- const call = (wasm, buffers, fn, precision) => {
769
+ // `premultiplied` (the loaded image's flag) un-premultiplies the first buffer after it is copied in; `mapped` also premultiplies
770
+ // the output payload (a mapped image, not indexed output) before it is unpacked.
771
+ const call = (wasm, buffers, fn, precision, premultiplied, mapped) => {
809
772
  const pointers = [];
810
773
  let outputPointer = 0;
811
774
  let aborted = false;
@@ -815,12 +778,18 @@ const call = (wasm, buffers, fn, precision) => {
815
778
  pointers.push(pointer);
816
779
  wasm.HEAPU8.set(buffer, pointer);
817
780
  }
781
+ if (premultiplied) {
782
+ wasm._unpremultiply(pointers[0], 0, buffers[0].length >> 2);
783
+ }
818
784
  outputPointer = fn(...pointers);
819
785
  // Only the functions that read a clustering return nothing: when its records don't fit together (see
820
786
  // _get_palette_from_clustering), which a clustering whose checksum matches never does.
821
787
  if (!outputPointer) {
822
788
  throw (0, _shared.fail)('invalid-clustering', "Invalid clustering: its records don't fit together, so it is damaged or isn't a clustering. Cluster the image again.", 'clustering');
823
789
  }
790
+ if (premultiplied && mapped) {
791
+ wasm._premultiply(outputPointer + 4, 0, buffers[0].length >> 2);
792
+ }
824
793
  return unpack(wasm, outputPointer);
825
794
  } catch (error) {
826
795
  if (!isAbort(error)) {
@@ -891,6 +860,21 @@ const reporter = o => {
891
860
  }
892
861
  };
893
862
  };
863
+
864
+ // The conversion passes in slices of this many pixels, so a long one gives the signal and the event loop a turn like the rest.
865
+ const convertSlice = 65536;
866
+ const convertInSlices = async (convert, pointer, pixels, o) => {
867
+ let last = performance.now();
868
+ for (let start = 0; start < pixels; start += convertSlice) {
869
+ checkAborted(o.signal);
870
+ convert(pointer, start, Math.min(pixels, start + convertSlice));
871
+ // Yield only once a slice's worth of time has gone, so a short pass doesn't pay a turn of the event loop per chunk.
872
+ if (start + convertSlice < pixels && performance.now() - last >= sliceMs) {
873
+ await yieldNow();
874
+ last = performance.now();
875
+ }
876
+ }
877
+ };
894
878
  const isControlled = o => o.signal !== undefined || o.onProgress !== undefined;
895
879
 
896
880
  // The share of quantize's and quantizeToIndices' progress that clustering takes, the rest being mapping. It only shapes
@@ -915,6 +899,9 @@ const clusterInSlices = async (wasm, image, o, report, share) => {
915
899
  let aborted = false;
916
900
  try {
917
901
  wasm.HEAPU8.set(image.data, imagePointer);
902
+ if (image.premultiplied) {
903
+ await convertInSlices(wasm._unpremultiply, imagePointer, image.data.length >> 2, o);
904
+ }
918
905
  job = wasm._clustering_job_start(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent);
919
906
  report(0);
920
907
  while (true) {
@@ -965,6 +952,9 @@ const mapInSlices = async (wasm, image, source, colorSpace, indices, cutoff, o,
965
952
  sourcePointer = allocate(wasm, bytes.length);
966
953
  wasm.HEAPU8.set(image.data, imagePointer);
967
954
  wasm.HEAPU8.set(bytes, sourcePointer);
955
+ if (image.premultiplied) {
956
+ await convertInSlices(wasm._unpremultiply, imagePointer, image.data.length >> 2, o);
957
+ }
968
958
  const palette = source.palette ? sourcePointer : 0,
969
959
  clustering = source.clustering ? sourcePointer : 0;
970
960
  job = wasm._mapping_job_start(imagePointer, image.data.length, codes[image.format], palette, source.palette ? bytes.length : 0, clustering, source.clustering ? bytes.length : 0, source.k || 0, colorSpace, o.dither, o.ditherMethod, o.ditherSteps, o.width, indices ? 1 : 0, cutoff);
@@ -986,6 +976,9 @@ const mapInSlices = async (wasm, image, source, colorSpace, indices, cutoff, o,
986
976
  }
987
977
  const pointer = wasm._mapping_job_result(job);
988
978
  try {
979
+ if (image.premultiplied && !indices) {
980
+ await convertInSlices(wasm._premultiply, pointer + 4, image.data.length >> 2, o);
981
+ }
989
982
  return unpack(wasm, pointer);
990
983
  } finally {
991
984
  wasm._free(pointer);
@@ -1038,7 +1031,7 @@ const buildClustering = async (image, options) => {
1038
1031
  report(1);
1039
1032
  return (0, _shared.markClustering)(clustering);
1040
1033
  }
1041
- 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));
1034
+ 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));
1042
1035
  };
1043
1036
  /** @deprecated The same function as buildClustering, its name before 3.4.0. Removed in 4.0. */
1044
1037
  exports.buildClustering = buildClustering;
@@ -1058,7 +1051,7 @@ const buildPalette = async (image, k, options) => {
1058
1051
  report(1);
1059
1052
  return (0, _shared.markPalette)(palette, (0, _shared.colorSpaceName)(o.colorSpace));
1060
1053
  }
1061
- 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), (0, _shared.colorSpaceName)(o.colorSpace));
1054
+ 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));
1062
1055
  };
1063
1056
  /** @deprecated The same function as buildPalette, its name before 3.4.0. Removed in 4.0. */
1064
1057
  exports.buildPalette = buildPalette;
@@ -1202,7 +1195,7 @@ const quantize = async (image, k, options) => {
1202
1195
  report(1);
1203
1196
  return mapped;
1204
1197
  }
1205
- return wrap(call(wasm, [image.data], imagePointer => wasm._quantize(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent), o.precision));
1198
+ return wrap(call(wasm, [image.data], imagePointer => wasm._quantize(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent), o.precision, image.premultiplied, true));
1206
1199
  };
1207
1200
  exports.quantize = quantize;
1208
1201
  const quantizeFromClustering = async (image, clustering, k, options) => {
@@ -1226,7 +1219,7 @@ const quantizeFromClustering = async (image, clustering, k, options) => {
1226
1219
  report(1);
1227
1220
  return mapped;
1228
1221
  }
1229
- 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)));
1222
+ 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));
1230
1223
  return result;
1231
1224
  };
1232
1225
  exports.quantizeFromClustering = quantizeFromClustering;
@@ -1250,7 +1243,7 @@ const quantizeWithPalette = async (image, palette, options) => {
1250
1243
  report(1);
1251
1244
  return mapped;
1252
1245
  }
1253
- const result = wrap(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.ditherMethod, o.ditherSteps, o.width)));
1246
+ const result = wrap(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.ditherMethod, o.ditherSteps, o.width), undefined, image.premultiplied, true));
1254
1247
  return result;
1255
1248
  };
1256
1249
  exports.quantizeWithPalette = quantizeWithPalette;
@@ -1273,7 +1266,7 @@ const quantizeToIndices = async (image, k, options) => {
1273
1266
  report(1);
1274
1267
  return indexed;
1275
1268
  }
1276
- return unpackIndices(call(wasm, [image.data], imagePointer => wasm._quantize_indices(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent), o.precision), original, (0, _shared.colorSpaceName)(o.colorSpace));
1269
+ return unpackIndices(call(wasm, [image.data], imagePointer => wasm._quantize_indices(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.ditherMethod, o.ditherSteps, o.width, o.transparent), o.precision, image.premultiplied), original, (0, _shared.colorSpaceName)(o.colorSpace));
1277
1270
  };
1278
1271
  exports.quantizeToIndices = quantizeToIndices;
1279
1272
  const quantizeToIndicesFromClustering = async (image, clustering, k, options) => {
@@ -1300,7 +1293,7 @@ const quantizeToIndicesFromClustering = async (image, clustering, k, options) =>
1300
1293
  report(1);
1301
1294
  return indexed;
1302
1295
  }
1303
- 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)), original, (0, _shared.colorSpaceName)(header.colorSpace));
1296
+ 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));
1304
1297
  return result;
1305
1298
  };
1306
1299
  exports.quantizeToIndicesFromClustering = quantizeToIndicesFromClustering;
@@ -1325,16 +1318,62 @@ const quantizeToIndicesWithPalette = async (image, palette, options) => {
1325
1318
  report(1);
1326
1319
  return indexed;
1327
1320
  }
1328
- 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);
1321
+ 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), undefined, image.premultiplied), original, paletteSpace);
1329
1322
  return result;
1330
1323
  };
1331
1324
 
1332
- // The methods on Clustering (shared.js) run through these. Only this entry fills the slot, so the methods need it loaded.
1325
+ // clustering.chooseFrom: validates everything before its first await (the palette is copied, so the caller may change it
1326
+ // at once), then runs the search in choose.js on this thread with the cuts above.
1333
1327
  exports.quantizeToIndicesWithPalette = quantizeToIndicesWithPalette;
1328
+ const chooseFrom = async (name, clustering, palette, k, options) => {
1329
+ const header = (0, _shared.readHeader)(clustering);
1330
+ (0, _shared.checkPalette)(palette);
1331
+ if (palette.length === 0) {
1332
+ throw (0, _shared.fail)('invalid-argument', "Invalid palette: it is empty; give at least one RGB entry (3 bytes).", 'palette');
1333
+ }
1334
+ const entries = Uint8Array.from(palette);
1335
+ const count = entries.length / 3;
1336
+ k = check(k);
1337
+ if (k > count) {
1338
+ throw (0, _shared.fail)('invalid-argument', `Invalid k: ${k} is more than the ${count} entries in the palette; use ${count} or fewer.`, 'k');
1339
+ }
1340
+ const o = parseOptions(options, ['colorSpace', 'signal']);
1341
+ needsWeights(header);
1342
+ clustering = held(clustering);
1343
+ checkAborted(o.signal);
1344
+ const pause = async () => {
1345
+ checkAborted(o.signal);
1346
+ if (o.signal) {
1347
+ await yieldNow();
1348
+ checkAborted(o.signal);
1349
+ }
1350
+ };
1351
+ const indices = await (0, _choose.choose)({
1352
+ cut: size => cutPalette(name, clustering, size, []),
1353
+ swatches: () => cutSwatches(name, clustering, 1024, []),
1354
+ snap: async colours => (await quantizeToIndicesWithPalette({
1355
+ data: colours,
1356
+ format: 'rgb'
1357
+ }, entries, {
1358
+ colorSpace: 'rgb'
1359
+ })).indices,
1360
+ pause
1361
+ }, entries, k, (0, _shared.colorSpaceName)(o.colorSpace));
1362
+ indices.sort((x, y) => x - y);
1363
+ const chosen = new Uint8Array(3 * indices.length);
1364
+ indices.forEach((j, s) => chosen.set(entries.subarray(3 * j, 3 * j + 3), 3 * s));
1365
+ return {
1366
+ indices,
1367
+ palette: (0, _shared.markPalette)(chosen, 'rgb')
1368
+ };
1369
+ };
1370
+
1371
+ // The methods on Clustering (shared.js) run through these. Only this entry fills the slot, so the methods need it loaded.
1334
1372
  (0, _shared.setEngine)({
1335
1373
  cut: cutPalette,
1336
1374
  cutSwatches,
1337
1375
  info: readInfo,
1338
1376
  quantizeFromClustering,
1339
- quantizeToIndicesFromClustering
1377
+ quantizeToIndicesFromClustering,
1378
+ chooseFrom
1340
1379
  });
package/dist/index.d.cts CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * How pixel bytes are laid out:
3
3
  * - `'rgb'`: 3 bytes per pixel, red, green, blue.
4
- * - `'rgba'`, `'bgra'`: 4 bytes, with straight (not premultiplied) alpha last. BGRA is the order of Windows bitmaps and
5
- * Electron's `nativeImage`, whose `toBitmap()` is premultiplied: convert it first (see Input in docs/api.md).
4
+ * - `'rgba'`, `'bgra'`: 4 bytes, with alpha last, straight unless the image object says `premultiplied: true` (canvas
5
+ * surfaces, Electron's `toBitmap()`). BGRA is the order of Windows bitmaps and Electron's `nativeImage`.
6
6
  * - `'rgbx'`, `'bgrx'`: 4 bytes whose last is padding, not alpha (Windows `BI_RGB` bitmaps, WebCodecs `'BGRX'`, ffmpeg
7
7
  * `bgr0`): every pixel is opaque, and mapped output writes 255 there.
8
8
  *
@@ -70,28 +70,61 @@ export const ditherSteps: readonly DitherSteps[];
70
70
  export function isCodedError(value: unknown): value is CodedError;
71
71
 
72
72
  /**
73
- * An image as raw bytes with an explicit layout: for RGB or BGRA data, a `Uint8ClampedArray`, or Node, where there is no
74
- * `ImageData`. Functions that return an image give back an object of this shape with the same `format`.
73
+ * RGBA or BGRA bytes. `premultiplied: true` says the colours are multiplied by alpha (canvas, Electron, WebGL).
74
+ * Internal: name it through `RawImage<'rgba'>` or `RawImage<'bgra'>`.
75
75
  */
76
- export interface RawImage {
76
+ interface RawImageWithAlpha<F extends 'rgba' | 'bgra' = 'rgba' | 'bgra'> {
77
77
  data: Uint8Array | Uint8ClampedArray;
78
- format: ImageFormat;
78
+ format: F;
79
79
  /** Width in pixels. Optional; used for dithering, and copied to `quantize*` results. */
80
80
  width?: number | undefined;
81
81
  /** Height in pixels. Optional; copied to `quantize*` results. */
82
82
  height?: number | undefined;
83
+ /**
84
+ * The colours are multiplied by alpha (what a canvas surface, Electron's `toBitmap()`, WebGL and Cairo hold). They are
85
+ * read as straight colours (divided by alpha), and `quantize*` gives the mapped colours back multiplied, copied as
86
+ * given: the result has the same `premultiplied` as the input. For a straight destination (`ImageData`, PNG encoders),
87
+ * use `quantizeToIndices` and write palette colours with the input's alpha; un-premultiplying the output loses colour. The guides' "Straight pixels from a premultiplied source" has the loop.
88
+ */
89
+ premultiplied?: boolean | undefined;
83
90
  }
84
91
 
92
+ /**
93
+ * Formats without alpha. `premultiplied: false` says nothing; `true` is rejected at run time (there is no alpha).
94
+ * Internal: name it through `RawImage<'rgb'>`, `RawImage<'rgbx'>` or `RawImage<'bgrx'>`.
95
+ */
96
+ interface RawImageWithoutAlpha<F extends 'rgb' | 'rgbx' | 'bgrx' = 'rgb' | 'rgbx' | 'bgrx'> {
97
+ data: Uint8Array | Uint8ClampedArray;
98
+ format: F;
99
+ /** Width in pixels. Optional; used for dithering, and copied to `quantize*` results. */
100
+ width?: number | undefined;
101
+ /** Height in pixels. Optional; copied to `quantize*` results. */
102
+ height?: number | undefined;
103
+ /** Accepted as `false` on any format and does nothing here; `true` is an `invalid-argument` error, since there is no alpha. */
104
+ premultiplied?: boolean | undefined;
105
+ }
106
+
107
+ /**
108
+ * An image as raw bytes with an explicit layout: for RGB or BGRA data, a `Uint8ClampedArray`, or Node, where there is no
109
+ * `ImageData`. `RawImage<'bgra'>` is one format. Functions that return an image give back an object with the input's own
110
+ * keys (`format`, and `width`, `height` and `premultiplied` when given) and a new `data`.
111
+ */
112
+ export type RawImage<F extends ImageFormat = ImageFormat> =
113
+ F extends 'rgba' | 'bgra' ? RawImageWithAlpha<F> : F extends 'rgb' | 'rgbx' | 'bgrx' ? RawImageWithoutAlpha<F> : never;
114
+
85
115
  /**
86
116
  * The platform's `ImageData` class where the global exists (the DOM lib, or typings for a canvas polyfill), and `never`
87
117
  * where it doesn't, so these declarations compile with or without the DOM lib, in browser and Node-only projects.
88
118
  */
89
119
  export type PlatformImageData = typeof globalThis extends { ImageData: { prototype: infer T } } ? T : never;
90
120
 
91
- /** What a function that returns an image gives back for the input it was given: the same kind of thing. */
121
+ /**
122
+ * What a function that returns an image gives back for the input it was given: the same kind of thing. For an image
123
+ * object, one with the input's own keys and a new `data: Uint8Array`.
124
+ */
92
125
  export type ImageResult<I extends ImageLike> =
93
126
  I extends Uint8Array ? Uint8Array
94
- : I extends RawImage ? RawImage
127
+ : I extends RawImage ? Omit<I, 'data'> & { data: Uint8Array }
95
128
  : I extends PlatformImageData ? PlatformImageData
96
129
  : never;
97
130
 
@@ -147,16 +180,33 @@ export class Clustering extends Uint8Array {
147
180
  constructor(buffer: ArrayBufferLike, byteOffset?: number, length?: number);
148
181
  /** Only a type: what makes a `Clustering` different from a palette or other bytes to the compiler. */
149
182
  readonly [clusteringBrand]: true;
150
- /** The k-colour palette, as `getPaletteFromClustering(this, k)`. Takes no options. Runs on the calling thread, with the main entry. */
183
+ /** The k-colour palette of this clustering. Takes no options. Runs on the calling thread, with the main entry. */
151
184
  getPalette(this: Clustering, k: number): Promise<Palette>;
152
- /** Palette, weights and shares, as `getSwatchesFromClustering(this, k)`. Needs a 3.x clustering. Runs on the calling thread, with the main entry. */
185
+ /** Palette, weights and shares of the k-colour cut. Needs a 3.x clustering. Runs on the calling thread, with the main entry. */
153
186
  getSwatches(this: Clustering, k: number): Promise<Swatches>;
154
- /** The error curve and totals, as `getClusteringInfo(this)`. Needs a 3.x clustering. Runs on the calling thread, with the main entry. */
187
+ /** The error curve and totals of this clustering. Needs a 3.x clustering. Runs on the calling thread, with the main entry. */
155
188
  getClusteringInfo(this: Clustering): Promise<ClusteringInfo>;
156
- /** Maps `image` to the k-colour palette, as `quantizeFromClustering(image, this, k, options)`. Runs on the calling thread, with the main entry. */
189
+ /** Maps `image` to this clustering's k-colour palette, returning the image's type. Runs on the calling thread, with the main entry. */
157
190
  quantize<I extends ImageLike>(this: Clustering, image: I, k: number, options?: MappingOptions): Promise<ImageResult<I>>;
158
- /** Indexed output, as `quantizeToIndicesFromClustering(image, this, k, options)`. Runs on the calling thread, with the main entry. */
191
+ /** Maps `image` to this clustering's k-colour palette as palette indices. Runs on the calling thread, with the main entry. */
159
192
  quantizeToIndices(this: Clustering, image: ImageLike, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
193
+ /** Chooses the k entries of `palette` that best represent the clustered image: their positions and colours. Runs on the calling thread, with the main entry. */
194
+ chooseFrom(this: Clustering, palette: PaletteLike, k: number, options?: ChooseOptions): Promise<PaletteChoice>;
195
+ }
196
+
197
+ /** Options of `clustering.chooseFrom`. */
198
+ export interface ChooseOptions {
199
+ /** The space the search measures distance in: 'rgb' (default) or 'oklab'. It doesn't follow the clustering's space. */
200
+ colorSpace?: ColorSpace | undefined;
201
+ signal?: AbortSignal | undefined;
202
+ }
203
+
204
+ /** What `clustering.chooseFrom` returns. */
205
+ export interface PaletteChoice {
206
+ /** Exactly k positions in the palette given, ascending: no ranking (count the mapped pixels for a legend). */
207
+ indices: number[];
208
+ /** The chosen colours, in the order of `indices`: map with it, and index s of the result is entry indices[s]. */
209
+ palette: Palette;
160
210
  }
161
211
 
162
212
  /** What is not a clustering: a `Clustering` is not accepted where a palette is. */
@@ -327,7 +377,8 @@ interface IndexedImageFields {
327
377
 
328
378
  /**
329
379
  * One palette index per pixel in `indices`: a `Uint8Array` up to 256 palette entries, a `Uint16Array` up to 65536, else a
330
- * `Uint32Array`. `indexBits` says which (8, 16 or 32), and checking it narrows `indices` to that array type.
380
+ * `Uint32Array`. `indexBits` says which (8, 16 or 32), and checking it narrows `indices` to that array type. The palette
381
+ * is straight even for a premultiplied input: indexed output has no partial alpha, so there is nothing to premultiply.
331
382
  */
332
383
  export type IndexedImage =
333
384
  | (IndexedImageFields & { indexBits: 8; indices: Uint8Array })
@@ -375,7 +426,7 @@ export function getClustering(image: ImageLike, options?: ClusteringOptions): Pr
375
426
 
376
427
  /**
377
428
  * A palette of at most `k` colours for `image` (fewer if it has fewer distinct colours), as flat RGB bytes in split
378
- * order (see `getPaletteFromClustering`). It clusters the image each time: to try several sizes, call `buildClustering`
429
+ * order (see `clustering.getPalette(k)`). It clusters the image each time: to try several sizes, call `buildClustering`
379
430
  * once and cut it.
380
431
  *
381
432
  * @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
@@ -392,6 +443,8 @@ export function getPalette(image: ImageLike, k: number, options?: ClusteringOpti
392
443
  *
393
444
  * @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
394
445
  * entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
446
+ *
447
+ * @deprecated Use `clustering.getPalette(k)`; off the main thread, `(await worker.load(clustering)).getPalette(k)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
395
448
  */
396
449
  export function getPaletteFromClustering(clustering: Clustering, k: number): Promise<Palette>;
397
450
 
@@ -400,7 +453,7 @@ export function getPaletteFromClustering(clustering: Clustering, k: number): Pro
400
453
  * from one cut of one clustering, so they line up by construction: entry `i` of each describes the same colour.
401
454
  */
402
455
  export interface Swatches {
403
- /** The colours in split order, exactly what `getPaletteFromClustering` gives for the same `k`. */
456
+ /** The colours in split order, exactly what `clustering.getPalette(k)` gives for the same `k`. */
404
457
  palette: Palette;
405
458
  /**
406
459
  * Pixels per colour, counted as in clustering: by default fully transparent pixels count 0 and partly transparent ones
@@ -414,7 +467,7 @@ export interface Swatches {
414
467
 
415
468
  /**
416
469
  * The palette for `image` at `k` colours with each colour's weight and share: one call for swatches with percentages.
417
- * It clusters the image each time; if you already have a clustering, use `getSwatchesFromClustering`.
470
+ * It clusters the image each time; if you already have a clustering, use `clustering.getSwatches(k)`.
418
471
  *
419
472
  * @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
420
473
  * entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
@@ -429,6 +482,8 @@ export function getSwatches(image: ImageLike, k: number, options?: ClusteringOpt
429
482
  *
430
483
  * @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
431
484
  * entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
485
+ *
486
+ * @deprecated Use `clustering.getSwatches(k)`; off the main thread, `(await worker.load(clustering)).getSwatches(k)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
432
487
  */
433
488
  export function getSwatchesFromClustering(clustering: Clustering, k: number): Promise<Swatches>;
434
489
 
@@ -470,8 +525,10 @@ export interface ClusteringInfo {
470
525
 
471
526
  /**
472
527
  * Reads what a clustering holds, including its error curve for choosing a palette size. Needs a clustering from 3.x: a 2.x
473
- * clustering recorded no weights, so it is rejected with `unsupported-version` (as `getSwatchesFromClustering` rejects it);
528
+ * clustering recorded no weights, so it is rejected with `unsupported-version` (as `clustering.getSwatches(k)` rejects it);
474
529
  * the palette and mapping functions still read it.
530
+ *
531
+ * @deprecated Use `clustering.getClusteringInfo()`; off the main thread, `(await worker.load(clustering)).getClusteringInfo()` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
475
532
  */
476
533
  export function getClusteringInfo(clustering: Clustering): Promise<ClusteringInfo>;
477
534
 
@@ -492,6 +549,8 @@ export function quantize<I extends ImageLike>(image: I, k: number, options?: Qua
492
549
  *
493
550
  * @param k The most palette entries in the result (`k` means this in every function). A flat palette has no transparent
494
551
  * entry, so its entries are all colours. Fewer come back when the image has fewer distinct colours.
552
+ *
553
+ * @deprecated Use `clustering.quantize(image, k, options)`; off the main thread, `(await worker.load(clustering)).quantize(image, k, options)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
495
554
  */
496
555
  export function quantizeFromClustering<I extends ImageLike>(image: I, clustering: Clustering, k: number, options?: MappingOptions): Promise<ImageResult<I>>;
497
556
 
@@ -516,12 +575,14 @@ export function quantizeWithPalette<I extends ImageLike>(image: I, palette: Pale
516
575
  export function quantizeToIndices(image: ImageLike, k: number, options?: QuantizeIndexOptions): Promise<IndexedImage>;
517
576
 
518
577
  /**
519
- * Like `quantizeFromClustering`, but returns palette indices. The palette is `getPaletteFromClustering`'s.
578
+ * Like `quantizeFromClustering`, but returns palette indices. The palette is `clustering.getPalette(k)`'s.
520
579
  *
521
580
  * @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
522
581
  * if there is one, so `256` is the most a GIF or palette PNG holds. Fewer come back when the image has fewer distinct colours.
523
582
  * A colour is kept besides the transparent entry whenever the image has visible pixels, so with `transparent`,
524
583
  * `k = 1` can give 2 entries; an image with no visible pixels gives just the transparent entry.
584
+ *
585
+ * @deprecated Use `clustering.quantizeToIndices(image, k, options)`; off the main thread, `(await worker.load(clustering)).quantizeToIndices(image, k, options)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time.
525
586
  */
526
587
  export function quantizeToIndicesFromClustering(image: ImageLike, clustering: Clustering, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
527
588