agglomerative-clustering 3.8.0 → 4.0.0-beta.2

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.d.ts 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
+ */
76
+ interface RawImageWithAlpha<F extends 'rgba' | 'bgra' = 'rgba' | 'bgra'> {
77
+ data: Uint8Array | Uint8ClampedArray;
78
+ format: F;
79
+ /** Width in pixels. Optional; used for dithering, and copied to `quantize*` results. */
80
+ width?: number | undefined;
81
+ /** Height in pixels. Optional; copied to `quantize*` results. */
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;
90
+ }
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'>`.
75
95
  */
76
- export interface RawImage {
96
+ interface RawImageWithoutAlpha<F extends 'rgb' | 'rgbx' | 'bgrx' = 'rgb' | 'rgbx' | 'bgrx'> {
77
97
  data: Uint8Array | Uint8ClampedArray;
78
- format: ImageFormat;
98
+ format: F;
79
99
  /** Width in pixels. Optional; used for dithering, and copied to `quantize*` results. */
80
100
  width?: number | undefined;
81
101
  /** Height in pixels. Optional; copied to `quantize*` results. */
82
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;
83
105
  }
84
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
 
@@ -344,7 +377,8 @@ interface IndexedImageFields {
344
377
 
345
378
  /**
346
379
  * One palette index per pixel in `indices`: a `Uint8Array` up to 256 palette entries, a `Uint16Array` up to 65536, else a
347
- * `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.
348
382
  */
349
383
  export type IndexedImage =
350
384
  | (IndexedImageFields & { indexBits: 8; indices: Uint8Array })
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, bareImageWarning, warnOnce } from "./shared.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, bareImageWarning, warnOnce, checkImageBody, imageCopy, checkSize, formatHint } 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,27 +21,6 @@ const codes = {
21
21
  'rgbx': 3,
22
22
  'bgrx': 4
23
23
  };
24
- // 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
25
- // supported layout.
26
- const formatHint = format => {
27
- if (typeof format !== 'string') {
28
- return '';
29
- }
30
- const lower = format.toLowerCase();
31
- if (lower !== format && imageFormats.includes(lower)) {
32
- return ` Format names are lower case: '${lower}'.`;
33
- }
34
- if (lower === 'xrgb' || lower === 'rgb24') {
35
- return " Cairo RGB24 (xRGB) is BGRX in memory on little-endian machines: pass 'bgrx'.";
36
- }
37
- if (lower === 'argb' || lower === 'argb32') {
38
- 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).";
39
- }
40
- if (lower === 'bgr' || lower === 'bgr24') {
41
- return " 24-bit BGR isn't supported: widen each pixel to 4 bytes and pass 'bgrx'.";
42
- }
43
- return '';
44
- };
45
24
  const alphaModeCodes = {
46
25
  'ignore': 0,
47
26
  'weight': 1
@@ -426,20 +405,6 @@ const bytes = data => isUint8Array(data) ? data : new Uint8Array(data.buffer, da
426
405
  // call returns; until then (the first call) a copy is kept for when it has loaded.
427
406
  const held = data => Module ? data : data.slice();
428
407
 
429
- // width and height are copied to results and used for dithering, so each must make sense on its own: a whole number of
430
- // pixels that divides the pixel count (and, when both are given, account for exactly the pixels in the data).
431
- const checkSize = (pixels, size, name, argument) => {
432
- if (size === undefined) {
433
- return;
434
- }
435
- if (!Number.isInteger(size) || size < 0) {
436
- throw fail('invalid-argument', `Invalid ${name}: must be a whole number of pixels.`, argument);
437
- }
438
- if (pixels > 0 && (size === 0 || pixels % size !== 0)) {
439
- throw fail('invalid-argument', `Invalid ${name}: ${size} does not divide the image's ${pixels} pixels into whole rows.`, argument);
440
- }
441
- };
442
-
443
408
  // 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,
444
409
  // just before it starts work, so the one warning isn't spent on a call that fails anyway (PRINCIPLES "Warnings").
445
410
  const noWarning = () => {};
@@ -471,7 +436,8 @@ const load = image => {
471
436
  }
472
437
  return {
473
438
  data: held(image),
474
- format: 'rgba'
439
+ format: 'rgba',
440
+ premultiplied: false
475
441
  };
476
442
  }
477
443
  if (isImageData(image)) {
@@ -482,7 +448,8 @@ const load = image => {
482
448
  return {
483
449
  data: held(bytes(image.data)),
484
450
  format: 'rgba',
485
- width: image.width
451
+ width: image.width,
452
+ premultiplied: false
486
453
  };
487
454
  }
488
455
  if (ArrayBuffer.isView(image)) {
@@ -491,29 +458,12 @@ const load = image => {
491
458
  if (typeof image !== 'object' || !image || !image.data || !image.format) {
492
459
  throw fail('invalid-argument', `Invalid image: expected object with \`data\` and \`format\`.${imageHint(image)}`, 'image');
493
460
  }
494
- if (!isUint8Array(image.data) && !isUint8ClampedArray(image.data)) {
495
- throw fail('invalid-argument', "Invalid image data: must be Uint8Array or Uint8ClampedArray.", 'image');
496
- }
497
- if (isDetached(image.data)) {
498
- throw detachedError('data');
499
- }
500
- if (!imageFormats.includes(image.format)) {
501
- throw fail('invalid-argument', `Invalid format: got ${describe(image.format)}; it must be ${formatNames}.${formatHint(image.format)}`, 'image');
502
- }
503
- const stride = channels(image.format);
504
- if (image.data.length % stride !== 0) {
505
- throw fail('invalid-argument', `Invalid image data: length must be a multiple of ${stride} for '${image.format}'.`, 'image');
506
- }
507
- const pixels = image.data.length / stride;
508
- checkSize(pixels, image.width, 'image width', 'image');
509
- checkSize(pixels, image.height, 'image height', 'image');
510
- if (image.width !== undefined && image.height !== undefined && image.width * image.height !== pixels) {
511
- throw fail('invalid-argument', `Invalid image: width x height (${image.width} x ${image.height}) does not match its ${pixels} pixels.`, 'image');
512
- }
461
+ const premultiplied = checkImageBody(image);
513
462
  return {
514
463
  data: held(bytes(image.data)),
515
464
  format: image.format,
516
- width: image.width
465
+ width: image.width,
466
+ premultiplied
517
467
  };
518
468
  };
519
469
  const getWrapper = image => {
@@ -525,7 +475,8 @@ const getWrapper = image => {
525
475
  const {
526
476
  format,
527
477
  width,
528
- height
478
+ height,
479
+ premultiplied
529
480
  } = image;
530
481
  return output => {
531
482
  const result = {
@@ -538,6 +489,9 @@ const getWrapper = image => {
538
489
  if (height !== undefined) {
539
490
  result.height = height;
540
491
  }
492
+ if (premultiplied !== undefined) {
493
+ result.premultiplied = premultiplied;
494
+ }
541
495
  return result;
542
496
  };
543
497
  }
@@ -730,7 +684,9 @@ const allocate = (wasm, length) => {
730
684
 
731
685
  // Copies each buffer into the WASM heap, calls `fn` with their pointers, and returns the unpacked output,
732
686
  // freeing everything afterwards. `precision` is given for a clustering, for the out-of-memory advice.
733
- const call = (wasm, buffers, fn, precision) => {
687
+ // `premultiplied` (the loaded image's flag) un-premultiplies the first buffer after it is copied in; `mapped` also premultiplies
688
+ // the output payload (a mapped image, not indexed output) before it is unpacked.
689
+ const call = (wasm, buffers, fn, precision, premultiplied, mapped) => {
734
690
  const pointers = [];
735
691
  let outputPointer = 0;
736
692
  let aborted = false;
@@ -740,12 +696,18 @@ const call = (wasm, buffers, fn, precision) => {
740
696
  pointers.push(pointer);
741
697
  wasm.HEAPU8.set(buffer, pointer);
742
698
  }
699
+ if (premultiplied) {
700
+ wasm._unpremultiply(pointers[0], 0, buffers[0].length >> 2);
701
+ }
743
702
  outputPointer = fn(...pointers);
744
703
  // Only the functions that read a clustering return nothing: when its records don't fit together (see
745
704
  // _get_palette_from_clustering), which a clustering whose checksum matches never does.
746
705
  if (!outputPointer) {
747
706
  throw 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');
748
707
  }
708
+ if (premultiplied && mapped) {
709
+ wasm._premultiply(outputPointer + 4, 0, buffers[0].length >> 2);
710
+ }
749
711
  return unpack(wasm, outputPointer);
750
712
  } catch (error) {
751
713
  if (!isAbort(error)) {
@@ -816,6 +778,21 @@ const reporter = o => {
816
778
  }
817
779
  };
818
780
  };
781
+
782
+ // 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.
783
+ const convertSlice = 65536;
784
+ const convertInSlices = async (convert, pointer, pixels, o) => {
785
+ let last = performance.now();
786
+ for (let start = 0; start < pixels; start += convertSlice) {
787
+ checkAborted(o.signal);
788
+ convert(pointer, start, Math.min(pixels, start + convertSlice));
789
+ // 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.
790
+ if (start + convertSlice < pixels && performance.now() - last >= sliceMs) {
791
+ await yieldNow();
792
+ last = performance.now();
793
+ }
794
+ }
795
+ };
819
796
  const isControlled = o => o.signal !== undefined || o.onProgress !== undefined;
820
797
 
821
798
  // The share of quantize's and quantizeToIndices' progress that clustering takes, the rest being mapping. It only shapes
@@ -840,6 +817,9 @@ const clusterInSlices = async (wasm, image, o, report, share) => {
840
817
  let aborted = false;
841
818
  try {
842
819
  wasm.HEAPU8.set(image.data, imagePointer);
820
+ if (image.premultiplied) {
821
+ await convertInSlices(wasm._unpremultiply, imagePointer, image.data.length >> 2, o);
822
+ }
843
823
  job = wasm._clustering_job_start(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent);
844
824
  report(0);
845
825
  while (true) {
@@ -890,6 +870,9 @@ const mapInSlices = async (wasm, image, source, colorSpace, indices, cutoff, o,
890
870
  sourcePointer = allocate(wasm, bytes.length);
891
871
  wasm.HEAPU8.set(image.data, imagePointer);
892
872
  wasm.HEAPU8.set(bytes, sourcePointer);
873
+ if (image.premultiplied) {
874
+ await convertInSlices(wasm._unpremultiply, imagePointer, image.data.length >> 2, o);
875
+ }
893
876
  const palette = source.palette ? sourcePointer : 0,
894
877
  clustering = source.clustering ? sourcePointer : 0;
895
878
  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);
@@ -911,6 +894,9 @@ const mapInSlices = async (wasm, image, source, colorSpace, indices, cutoff, o,
911
894
  }
912
895
  const pointer = wasm._mapping_job_result(job);
913
896
  try {
897
+ if (image.premultiplied && !indices) {
898
+ await convertInSlices(wasm._premultiply, pointer + 4, image.data.length >> 2, o);
899
+ }
914
900
  return unpack(wasm, pointer);
915
901
  } finally {
916
902
  wasm._free(pointer);
@@ -952,6 +938,7 @@ const noOptions = (name, extra) => {
952
938
  // happens before the call returns.
953
939
 
954
940
  export const buildClustering = async (image, options) => {
941
+ image = imageCopy(image);
955
942
  const warn = warningFor(image);
956
943
  image = load(image);
957
944
  const o = parseOptions(options, clusterOptions, image);
@@ -963,11 +950,12 @@ export const buildClustering = async (image, options) => {
963
950
  report(1);
964
951
  return markClustering(clustering);
965
952
  }
966
- return markClustering(call(wasm, [image.data], imagePointer => wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent), o.precision));
953
+ return markClustering(call(wasm, [image.data], imagePointer => wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent), o.precision, image.premultiplied));
967
954
  };
968
955
  /** @deprecated The same function as buildClustering, its name before 3.4.0. Removed in 4.0. */
969
956
  export const getClustering = buildClustering;
970
957
  export const buildPalette = async (image, k, options) => {
958
+ image = imageCopy(image);
971
959
  const warn = warningFor(image);
972
960
  image = load(image);
973
961
  k = check(k);
@@ -982,7 +970,7 @@ export const buildPalette = async (image, k, options) => {
982
970
  report(1);
983
971
  return markPalette(palette, colorSpaceName(o.colorSpace));
984
972
  }
985
- return markPalette(call(wasm, [image.data], imagePointer => wasm._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.transparent), o.precision), colorSpaceName(o.colorSpace));
973
+ return markPalette(call(wasm, [image.data], imagePointer => wasm._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.transparent), o.precision, image.premultiplied), colorSpaceName(o.colorSpace));
986
974
  };
987
975
  /** @deprecated The same function as buildPalette, its name before 3.4.0. Removed in 4.0. */
988
976
  export const getPalette = buildPalette;
@@ -1047,7 +1035,9 @@ export const getSwatchesFromClustering = (clustering, k, ...extra) => cutSwatche
1047
1035
 
1048
1036
  // The same for an image: clusters it, then cuts, like getPalette.
1049
1037
  export const buildSwatches = async (image, k, options) => {
1038
+ image = imageCopy(image);
1050
1039
  // Arguments are checked in the order they are given (image, then k, then options), as in every other function.
1040
+ // `load` only validates here (buildClustering loads again); both see the copy, so the caller's fields are read once.
1051
1041
  load(image);
1052
1042
  k = check(k);
1053
1043
  return getSwatchesFromClustering(await buildClustering(image, options), k);
@@ -1103,6 +1093,7 @@ const readInfo = async (name, clustering, extra) => {
1103
1093
  };
1104
1094
  export const getClusteringInfo = (clustering, ...extra) => readInfo('getClusteringInfo', clustering, extra);
1105
1095
  export const quantize = async (image, k, options) => {
1096
+ image = imageCopy(image);
1106
1097
  const warn = warningFor(image);
1107
1098
  const wrap = getWrapper(image);
1108
1099
  image = load(image);
@@ -1121,9 +1112,10 @@ export const quantize = async (image, k, options) => {
1121
1112
  report(1);
1122
1113
  return mapped;
1123
1114
  }
1124
- 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));
1115
+ 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));
1125
1116
  };
1126
1117
  export const quantizeFromClustering = async (image, clustering, k, options) => {
1118
+ image = imageCopy(image);
1127
1119
  const warn = warningFor(image);
1128
1120
  const wrap = getWrapper(image);
1129
1121
  image = load(image);
@@ -1144,10 +1136,11 @@ export const quantizeFromClustering = async (image, clustering, k, options) => {
1144
1136
  report(1);
1145
1137
  return mapped;
1146
1138
  }
1147
- 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)));
1139
+ 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));
1148
1140
  return result;
1149
1141
  };
1150
1142
  export const quantizeWithPalette = async (image, palette, options) => {
1143
+ image = imageCopy(image);
1151
1144
  const warn = warningFor(image);
1152
1145
  const wrap = getWrapper(image);
1153
1146
  image = load(image);
@@ -1167,10 +1160,11 @@ export const quantizeWithPalette = async (image, palette, options) => {
1167
1160
  report(1);
1168
1161
  return mapped;
1169
1162
  }
1170
- 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)));
1163
+ 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));
1171
1164
  return result;
1172
1165
  };
1173
1166
  export const quantizeToIndices = async (image, k, options) => {
1167
+ image = imageCopy(image);
1174
1168
  const warn = warningFor(image);
1175
1169
  const original = image;
1176
1170
  image = load(image);
@@ -1189,9 +1183,10 @@ export const quantizeToIndices = async (image, k, options) => {
1189
1183
  report(1);
1190
1184
  return indexed;
1191
1185
  }
1192
- 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, colorSpaceName(o.colorSpace));
1186
+ 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, colorSpaceName(o.colorSpace));
1193
1187
  };
1194
1188
  export const quantizeToIndicesFromClustering = async (image, clustering, k, options) => {
1189
+ image = imageCopy(image);
1195
1190
  const warn = warningFor(image);
1196
1191
  const original = image;
1197
1192
  image = load(image);
@@ -1215,10 +1210,11 @@ export const quantizeToIndicesFromClustering = async (image, clustering, k, opti
1215
1210
  report(1);
1216
1211
  return indexed;
1217
1212
  }
1218
- 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, colorSpaceName(header.colorSpace));
1213
+ 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, colorSpaceName(header.colorSpace));
1219
1214
  return result;
1220
1215
  };
1221
1216
  export const quantizeToIndicesWithPalette = async (image, palette, options) => {
1217
+ image = imageCopy(image);
1222
1218
  const warn = warningFor(image);
1223
1219
  const original = image;
1224
1220
  image = load(image);
@@ -1239,7 +1235,7 @@ export const quantizeToIndicesWithPalette = async (image, palette, options) => {
1239
1235
  report(1);
1240
1236
  return indexed;
1241
1237
  }
1242
- 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);
1238
+ 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);
1243
1239
  return result;
1244
1240
  };
1245
1241
 
package/dist/shared.cjs CHANGED
@@ -6,14 +6,14 @@ Object.defineProperty(exports, "__esModule", {
6
6
  exports.Clustering = Clustering;
7
7
  exports.MARK = void 0;
8
8
  exports.Palette = Palette;
9
- exports.warnOnce = exports.version = exports.tooLarge = exports.sniffImageFormat = exports.snapshot = exports.sizeText = exports.silenceWarnings = exports.setEngine = exports.revive = exports.resetWarnings = exports.readHeader = exports.parseDither = exports.maxBytes = exports.markPalette = exports.markClustering = exports.mark = exports.looksLikeRgb = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isImageData = exports.isDetached = exports.isCodedError = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageFormats = exports.imageDataLike = exports.hasAlpha = exports.formatVersion = exports.formatNames = exports.fail = exports.errorCodes = exports.ditherSteps = exports.ditherMethods = exports.detachedError = exports.describe = exports.colorSpaces = exports.colorSpaceName = exports.colorSpaceCodes = exports.checkPalette = exports.checkImageDataPixels = exports.channels = exports.bareLayout = exports.bareImageWarning = exports.alphaModes = void 0;
9
+ exports.warnOnce = exports.version = exports.tooLarge = exports.sniffImageFormat = exports.snapshot = exports.sizeText = exports.silenceWarnings = exports.setEngine = exports.revive = exports.resetWarnings = exports.readHeader = exports.parseDither = exports.maxBytes = exports.markPalette = exports.markClustering = exports.mark = exports.looksLikeRgb = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isImageData = exports.isDetached = exports.isCodedError = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageFormats = exports.imageDataLike = exports.imageCopy = exports.hasAlpha = exports.formatVersion = exports.formatNames = exports.formatHint = exports.fail = exports.errorCodes = exports.ditherSteps = exports.ditherMethods = exports.detachedError = exports.describe = exports.colorSpaces = exports.colorSpaceName = exports.colorSpaceCodes = exports.checkSize = exports.checkPalette = exports.checkImageObject = exports.checkImageKeys = exports.checkImageDataPixels = exports.checkImageBody = exports.channels = exports.bareLayout = exports.bareImageWarning = exports.alphaModes = void 0;
10
10
  // Shared by both entries (index.js and worker.js) and the worker thread: errors, option snapshots, reading a clustering's
11
11
  // header, the Palette and Clustering types, and the markers that carry those types across the worker boundary. Imported as
12
12
  // './shared.js'; the build rewrites that to './shared.mjs' or './shared.cjs' (scripts/babel-import-extensions.cjs).
13
13
 
14
14
  // The library's version: package.json is the source, and scripts/sync-version.mjs keeps this line (and the copy the .wasm
15
15
  // is built from, src/version.hpp) in step with it. Do not edit it by hand.
16
- const version = exports.version = '3.8.0';
16
+ const version = exports.version = '4.0.0-beta.2';
17
17
  const colorSpaceCodes = exports.colorSpaceCodes = {
18
18
  'rgb': 0,
19
19
  'oklab': 1
@@ -184,10 +184,168 @@ const imageHint = image => {
184
184
  return '';
185
185
  };
186
186
 
187
+ // An image object has only these keys; any other own enumerable key (a decoder's result spread in) is an error, with a hint where
188
+ // the mistake is a common one. Inherited keys are not checked.
189
+ exports.imageHint = imageHint;
190
+ const imageKeys = ['data', 'format', 'width', 'height', 'premultiplied'];
191
+ const withinOne = (a, b) => {
192
+ if (a === b) {
193
+ return true;
194
+ }
195
+ if (Math.abs(a.length - b.length) > 1) {
196
+ return false;
197
+ }
198
+ let i = 0;
199
+ while (i < a.length && i < b.length && a[i] === b[i]) {
200
+ i++;
201
+ }
202
+ if (a.length === b.length) {
203
+ // One substitution, or two neighbouring letters swapped (widht).
204
+ return a.slice(i + 1) === b.slice(i + 1) || a[i] === b[i + 1] && a[i + 1] === b[i] && a.slice(i + 2) === b.slice(i + 2);
205
+ }
206
+ const [long, short] = a.length > b.length ? [a, b] : [b, a];
207
+ return long.slice(i + 1) === short.slice(i);
208
+ };
209
+ const checkImageKeys = image => {
210
+ for (const key of Object.keys(image)) {
211
+ if (imageKeys.includes(key)) {
212
+ continue;
213
+ }
214
+ let hint = '';
215
+ if (key === 'premultiply') {
216
+ hint = ' Did you mean premultiplied: true?';
217
+ } else if (key === 'channels' || key === 'size' || key === 'depth') {
218
+ hint = " Take only width and height from a decoder's result.";
219
+ } else {
220
+ const near = imageKeys.find(known => key.toLowerCase() === known || withinOne(key, known));
221
+ if (near) {
222
+ hint = ` Did you mean '${near}'?`;
223
+ }
224
+ }
225
+ throw fail('invalid-argument', `Invalid image: unknown key '${key}'. An image object has data, format, width, height and premultiplied: build it from those rather than spreading a decoder's result.${hint}`, 'image');
226
+ }
227
+ };
228
+
229
+ // 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
230
+ // supported layout.
231
+ exports.checkImageKeys = checkImageKeys;
232
+ const formatHint = format => {
233
+ if (typeof format !== 'string') {
234
+ return '';
235
+ }
236
+ const lower = format.toLowerCase();
237
+ if (lower !== format && imageFormats.includes(lower)) {
238
+ return ` Format names are lower case: '${lower}'.`;
239
+ }
240
+ if (lower === 'xrgb' || lower === 'rgb24') {
241
+ return " Cairo RGB24 (xRGB) is BGRX in memory on little-endian machines: pass 'bgrx'.";
242
+ }
243
+ if (lower === 'argb' || lower === 'argb32') {
244
+ return " Cairo and node-canvas ARGB32 is BGRA in memory on little-endian machines, and premultiplied: pass it as 'bgra' with premultiplied: true (see Input in the API docs).";
245
+ }
246
+ if (lower === 'bgr' || lower === 'bgr24') {
247
+ return " 24-bit BGR isn't supported: widen each pixel to 4 bytes and pass 'bgrx'.";
248
+ }
249
+ return '';
250
+ };
251
+ // width and height are copied to results and used for dithering, so each must make sense on its own: a whole number of
252
+ // pixels that divides the pixel count (and, when both are given, account for exactly the pixels in the data).
253
+ exports.formatHint = formatHint;
254
+ const checkSize = (pixels, size, name, argument) => {
255
+ if (size === undefined) {
256
+ return;
257
+ }
258
+ if (!Number.isInteger(size) || size < 0) {
259
+ throw fail('invalid-argument', `Invalid ${name}: must be a whole number of pixels.`, argument);
260
+ }
261
+ if (pixels > 0 && (size === 0 || pixels % size !== 0)) {
262
+ throw fail('invalid-argument', `Invalid ${name}: ${size} does not divide the image's ${pixels} pixels into whole rows.`, argument);
263
+ }
264
+ };
265
+
266
+ // `premultiplied` on an image object: true only for 'rgba' and 'bgra' (the formats with alpha); false is accepted on any format.
267
+ exports.checkSize = checkSize;
268
+ const checkPremultiplied = image => {
269
+ const value = image.premultiplied;
270
+ if (value === undefined || value === false) {
271
+ return false;
272
+ }
273
+ if (value !== true) {
274
+ throw fail('invalid-argument', `Invalid image: premultiplied must be true or false, got ${describe(value)}.`, 'image');
275
+ }
276
+ if (image.format !== 'rgba' && image.format !== 'bgra') {
277
+ throw fail('invalid-argument', `Invalid image: premultiplied is for 'rgba' and 'bgra'; '${image.format}' has no alpha, so remove it.`, 'image');
278
+ }
279
+ return true;
280
+ };
281
+
282
+ // Everything checked about an image object whose data is a Uint8Array or Uint8ClampedArray, in this order: format, data length,
283
+ // width and height, unknown keys, premultiplied. The main entry and the worker entry (before it posts) both run it, so their errors
284
+ // are identical. Returns the premultiplied flag.
285
+ const checkImageObject = image => {
286
+ if (!imageFormats.includes(image.format)) {
287
+ throw fail('invalid-argument', `Invalid format: got ${describe(image.format)}; it must be ${formatNames}.${formatHint(image.format)}`, 'image');
288
+ }
289
+ const stride = channels(image.format);
290
+ if (image.data.length % stride !== 0) {
291
+ throw fail('invalid-argument', `Invalid image data: length must be a multiple of ${stride} for '${image.format}'.`, 'image');
292
+ }
293
+ const pixels = image.data.length / stride;
294
+ checkSize(pixels, image.width, 'image width', 'image');
295
+ checkSize(pixels, image.height, 'image height', 'image');
296
+ if (image.width !== undefined && image.height !== undefined && image.width * image.height !== pixels) {
297
+ throw fail('invalid-argument', `Invalid image: width x height (${image.width} x ${image.height}) does not match its ${pixels} pixels.`, 'image');
298
+ }
299
+ checkImageKeys(image);
300
+ return checkPremultiplied(image);
301
+ };
302
+
303
+ // The image object's own fields, read once: `data`, `format`, `width`, `height` and `premultiplied` are taken from it here, and
304
+ // everything after (validation and use) reads the copy, so a getter that answers differently on a later read changes nothing.
305
+ // The copy also names the object's other own enumerable keys (with no value, never read), in order, for the unknown-key check.
306
+ // Anything that isn't an object with `data` and `format` is returned as it is (a bare array, ImageData, a function...), or, for
307
+ // an object without them, rejected here with the shape error the main entry gives.
308
+ exports.checkImageObject = checkImageObject;
309
+ const imageCopy = image => {
310
+ if (typeof image !== 'object' || image === null || ArrayBuffer.isView(image) || isImageData(image)) {
311
+ return image;
312
+ }
313
+ const data = image.data;
314
+ const format = image.format;
315
+ if (!data || !format) {
316
+ throw fail('invalid-argument', `Invalid image: expected object with \`data\` and \`format\`.${imageHint(image)}`, 'image');
317
+ }
318
+ const copy = Object.create(null);
319
+ copy.data = data;
320
+ copy.format = format;
321
+ copy.width = image.width;
322
+ copy.height = image.height;
323
+ copy.premultiplied = image.premultiplied;
324
+ for (const key of Object.keys(image)) {
325
+ if (!imageKeys.includes(key)) {
326
+ copy[key] = undefined;
327
+ }
328
+ }
329
+ return copy;
330
+ };
331
+
332
+ // What the main entry's `load` checks about an image object, from the copy imageCopy made, in its order: data's type, whether its
333
+ // buffer is detached, then checkImageObject. The worker entry runs the same before it posts an image. Returns the premultiplied flag.
334
+ exports.imageCopy = imageCopy;
335
+ const checkImageBody = image => {
336
+ if (!isUint8Array(image.data) && !isUint8ClampedArray(image.data)) {
337
+ throw fail('invalid-argument', "Invalid image data: must be Uint8Array or Uint8ClampedArray.", 'image');
338
+ }
339
+ if (isDetached(image.data)) {
340
+ throw detachedError('data');
341
+ }
342
+ return checkImageObject(image);
343
+ };
344
+
187
345
  // An options object is an ordinary object. A Map, Date, ArrayBuffer or typed array has no own keys and would pass as
188
346
  // `{}`, silently ignoring what the caller meant. Checked by tag rather than prototype so objects from another realm
189
347
  // (an iframe, a test sandbox) are fine.
190
- exports.imageHint = imageHint;
348
+ exports.checkImageBody = checkImageBody;
191
349
  const isOptionsObject = value => value !== null && typeof value === 'object' && Object.prototype.toString.call(value) === '[object Object]';
192
350
 
193
351
  // One plain copy of an options object, taken once: every enumerable property, own or inherited (so options layered with