agglomerative-clustering 3.0.0-beta.6 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Binary file
package/dist/index.cjs CHANGED
@@ -153,7 +153,7 @@ const wasmLoadFailed = (cause, given) => {
153
153
  let advice;
154
154
  if (/disallowed by embedder|code generation disallowed/i.test(text) && !isNodeLike && !isBrowserLike()) {
155
155
  // Edge runtimes (Cloudflare Workers, Vercel's edge runtime) compile WebAssembly only at build time, from an import.
156
- advice = "This runtime doesn't compile WebAssembly while it runs, from bytes or from a URL (edge runtimes such as Cloudflare Workers and Vercel's): import clustering.wasm as a module, which the bundler compiles when it builds (in Wrangler a plain import of 'agglomerative-clustering/clustering.wasm'; in Next.js a relative path with ?module), and pass it to init({ wasm }) before the first call, as the README shows for Cloudflare Workers and Next.js.";
156
+ advice = "This runtime doesn't compile WebAssembly while it runs, from bytes or from a URL (edge runtimes such as Cloudflare Workers and Vercel's): import clustering.wasm as a module, which the bundler compiles when it builds (in Wrangler a plain import of 'agglomerative-clustering/clustering.wasm'; in Next.js a relative path with ?module), and pass it to init({ wasm }) before the first call, as the docs show for Cloudflare Workers and Next.js (https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/environments.md).";
157
157
  } else if (/(memory|allocate)/i.test(text) && /(could not|cannot|can't|failed to|out of) (allocate|memory|reserve)/i.test(text)) {
158
158
  // A 64-bit engine reserves the module's whole address range up front (about 10 GB of virtual memory per instance),
159
159
  // though it only uses what it needs; an address-space limit refuses that reservation.
@@ -174,6 +174,10 @@ const wasmLoadFailed = (cause, given) => {
174
174
  reason = `the file loaded as clustering.wasm${where} is not WebAssembly (${reason}): most likely an error page (a 404) or a fallback HTML page served in its place`;
175
175
  advice = given ? "Check that URL or path: it must be this package's clustering.wasm, served with the application/wasm type." : "Check that clustering.wasm is served next to the script or emitted by your bundler (open its URL in the browser), or say where it is with init({ wasm }).";
176
176
  }
177
+ } else if (isNodeLike && typeof given === 'string' && /^https?:/i.test(given)) {
178
+ // Node fetches an http(s) URL itself (see nodeWasmFile), so the server or the network failed, not a path.
179
+ reason = `the .wasm file could not be fetched${where}: ${reason}`;
180
+ advice = "Check that this machine can reach that URL and that it serves this package's clustering.wasm. On a server, a path to the package's own copy (or its bytes) avoids the request.";
177
181
  } else if (/XMLHttpRequest is not defined|both async and sync fetching|failed to fetch|NetworkError|404|ENOENT/i.test(text) && isNodeLike) {
178
182
  // In Node the file is read from disk, so the browser's reasons (a CSP, an extension's resources) don't apply.
179
183
  reason = given ? `the .wasm file could not be read${where}` : 'the .wasm file could not be read (the package looks for clustering.wasm next to its script)';
@@ -195,7 +199,7 @@ const wasmLoadFailed = (cause, given) => {
195
199
  if (/Invalid URL/i.test(reason)) {
196
200
  reason = "the package can't tell where clustering.wasm is in this runtime";
197
201
  }
198
- advice = "Give the module to init({ wasm }) before the first call: in an edge runtime (Cloudflare Workers, Vercel's), import clustering.wasm as a compiled module (the README shows how for Cloudflare Workers and Next.js); elsewhere its bytes or URL.";
202
+ advice = "Give the module to init({ wasm }) before the first call: in an edge runtime (Cloudflare Workers, Vercel's), import clustering.wasm as a compiled module (the docs show how for Cloudflare Workers and Next.js: https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/environments.md); elsewhere its bytes or URL.";
199
203
  } else {
200
204
  advice = "Check that clustering.wasm is served next to the script (not a 404, and with the application/wasm type) and allowed by the page's Content-Security-Policy, or say where it is with init({ wasm }).";
201
205
  }
@@ -275,6 +279,14 @@ const nodeWasmFile = async wasm => {
275
279
  }
276
280
  const isFileUrl = /^file:/i.test(text);
277
281
  // A string with a scheme (http:, data:, blob:) is a URL; a Windows drive letter (C:\) is a path.
282
+ // An http(s) URL is fetched here: the glue would read it as a file path in Node.
283
+ if (/^https?:/i.test(text)) {
284
+ const response = await fetch(text);
285
+ if (!response.ok) {
286
+ throw new Error(`HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ''}`);
287
+ }
288
+ return new Uint8Array(await response.arrayBuffer());
289
+ }
278
290
  if (!isFileUrl && /^[a-z][a-z0-9+.-]+:/i.test(text) && !/^[a-z]:[\\/]/i.test(text)) {
279
291
  return null;
280
292
  }
@@ -371,7 +383,23 @@ const retireIfLarge = instance => {
371
383
  discard(instance);
372
384
  }
373
385
  };
374
- const outOfMemory = () => (0, _shared.fail)('out-of-memory', "The WebAssembly module ran out of memory (it can use up to 2 GB for one image). Try `precision: 6`, which bounds the memory an image with very many colours needs, or a smaller image.");
386
+ // What to try depends on the call: a large input has to shrink whatever else changes, and `precision: 6` helps only a
387
+ // clustering (`precision` given) that isn't already at 6 or below.
388
+ const outOfMemory = (bytes, precision) => {
389
+ const large = bytes >= 2 ** 28;
390
+ const tries = [];
391
+ if (large) {
392
+ tries.push(`scale the image down (its pixels alone are ${(0, _shared.sizeText)(bytes)}; a few megapixels give as good a palette)`);
393
+ }
394
+ if (precision > 6) {
395
+ tries.push('try `precision: 6`, which bounds the memory an image with very many colours needs');
396
+ }
397
+ if (!large) {
398
+ tries.push('use a smaller image');
399
+ }
400
+ const text = tries.join(', or ');
401
+ return (0, _shared.fail)('out-of-memory', `The WebAssembly module ran out of memory (it can use up to 2 GB for one image). ${text[0].toUpperCase()}${text.slice(1)}.`);
402
+ };
375
403
  const unpack = (wasm, pointer) => {
376
404
  const lengthBuffer = new Uint8Array(wasm.HEAPU8.subarray(pointer, pointer + 4));
377
405
  const length = lengthBuffer[0] | lengthBuffer[1] << 8 | lengthBuffer[2] << 16 | lengthBuffer[3] << 24;
@@ -722,28 +750,21 @@ const checkNotEmpty = (palette, image, cutoff) => {
722
750
  // The space to match pixels to a palette in: the one the caller names, else the one a Palette was made in, else RGB.
723
751
  const matchingSpace = (o, palette) => o.colorSpaceGiven ? o.colorSpace : _shared.colorSpaces[(0, _shared.isPalette)(palette) ? palette.colorSpace : 'rgb'];
724
752
 
725
- // The module's memory is at most 2 GB (MAXIMUM_MEMORY in build:wasm) and its allocator takes a 32-bit signed size, so a
726
- // buffer of 2 GB or more can never be copied in: _malloc would read its length as negative, or (from 4 GB) wrap it to a
727
- // small number and hand back a block too short for the copy. Such buffers are rejected before any allocation.
728
- const maxBytes = 2 ** 31;
729
- const sizeText = bytes => bytes >= 2 ** 30 ? `${(bytes / 2 ** 30).toFixed(2)} GB` : `${Math.round(bytes / 2 ** 20)} MB`;
730
- const tooLarge = bytes => (0, _shared.fail)('out-of-memory', `The input is ${sizeText(bytes)}, more than the WebAssembly module can hold: it has at most 2 GB in all, for the pixels and the work on them, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels of RGBA). Scale the image down for its palette (a few megapixels give as good a one), and map a full-size image in strips with quantizeWithPalette.`);
731
-
732
753
  // Allocates `length` bytes in the WASM heap, or throws a coded out-of-memory error.
733
754
  const allocate = (wasm, length) => {
734
- if (length >= maxBytes) {
735
- throw tooLarge(length);
755
+ if (length >= _shared.maxBytes) {
756
+ throw (0, _shared.tooLarge)(length);
736
757
  }
737
758
  const pointer = wasm._malloc(length);
738
759
  if (!pointer) {
739
- throw (0, _shared.fail)('out-of-memory', length >= 2 ** 28 ? `Failed to allocate ${sizeText(length)} of WASM memory for the input: the module has at most 2 GB in all, so an image this size leaves too little room for the work on it. Scale the image down first.` : "Failed to allocate WASM memory.");
760
+ throw (0, _shared.fail)('out-of-memory', length >= 2 ** 28 ? `Failed to allocate ${(0, _shared.sizeText)(length)} of WASM memory for the input: the module has at most 2 GB in all, so an image this size leaves too little room for the work on it. Scale the image down first.` : "Failed to allocate WASM memory.");
740
761
  }
741
762
  return pointer;
742
763
  };
743
764
 
744
765
  // Copies each buffer into the WASM heap, calls `fn` with their pointers, and returns the unpacked output,
745
- // freeing everything afterwards.
746
- const call = (wasm, buffers, fn) => {
766
+ // freeing everything afterwards. `precision` is given for a clustering, for the out-of-memory advice.
767
+ const call = (wasm, buffers, fn, precision) => {
747
768
  const pointers = [];
748
769
  let outputPointer = 0;
749
770
  let aborted = false;
@@ -766,7 +787,7 @@ const call = (wasm, buffers, fn) => {
766
787
  }
767
788
  aborted = true;
768
789
  discard(wasm);
769
- throw outOfMemory();
790
+ throw outOfMemory(buffers[0].length, precision);
770
791
  } finally {
771
792
  // After an abort the instance is being thrown away, and its allocator can't be trusted.
772
793
  if (!aborted) {
@@ -862,7 +883,7 @@ const clusterInSlices = async (wasm, image, o, report, share) => {
862
883
  }
863
884
  aborted = true;
864
885
  discard(wasm);
865
- throw outOfMemory();
886
+ throw outOfMemory(image.data.length, o.precision);
866
887
  } finally {
867
888
  if (!aborted) {
868
889
  if (job) {
@@ -896,7 +917,7 @@ const getClustering = async (image, options) => {
896
917
  report(1);
897
918
  return (0, _shared.markClustering)(clustering);
898
919
  }
899
- 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)));
920
+ 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));
900
921
  };
901
922
  exports.getClustering = getClustering;
902
923
  const getPalette = async (image, k, options) => {
@@ -912,7 +933,7 @@ const getPalette = async (image, k, options) => {
912
933
  report(1);
913
934
  return (0, _shared.markPalette)(palette, (0, _shared.colorSpaceName)(o.colorSpace));
914
935
  }
915
- 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)), (0, _shared.colorSpaceName)(o.colorSpace));
936
+ 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));
916
937
  };
917
938
  exports.getPalette = getPalette;
918
939
  const getPaletteFromClustering = async (clustering, k, ...extra) => {
@@ -934,6 +955,14 @@ const weightsOf = (wasm, clustering, header, k) => {
934
955
  return new Float64Array(bytes.buffer, bytes.byteOffset, bytes.length / 8);
935
956
  };
936
957
 
958
+ // The functions that report weights (swatches, the error curve) need a clustering from 3.x: 2.x recorded none. The others
959
+ // (palettes and mapping) still read 2.x clusterings.
960
+ const needsWeights = header => {
961
+ if (header.version < 3) {
962
+ throw (0, _shared.fail)('unsupported-version', `Unsupported clustering: format version ${header.version} (agglomerative-clustering ${header.version}.x) has no weights. Cluster the image again.`, 'clustering');
963
+ }
964
+ };
965
+
937
966
  // A palette with the weight and share of the image of each of its colours, from one cut of one clustering, so the three
938
967
  // arrays line up by construction. Weights are pixels: fully transparent pixels count 0 and partly transparent ones in
939
968
  // proportion to their opacity, as in clustering. Shares are the weights divided by their total, so they sum to 1.
@@ -941,9 +970,7 @@ const getSwatchesFromClustering = async (clustering, k, ...extra) => {
941
970
  const header = (0, _shared.readHeader)(clustering);
942
971
  k = check(k);
943
972
  noOptions('getSwatchesFromClustering', extra);
944
- if (header.version < 3) {
945
- throw (0, _shared.fail)('unsupported-version', `Unsupported clustering: format version ${header.version} (agglomerative-clustering ${header.version}.x) has no weights. Cluster the image again.`, 'clustering');
946
- }
973
+ needsWeights(header);
947
974
  clustering = held(clustering);
948
975
  const wasm = Module || (await acquire());
949
976
  const palette = (0, _shared.markPalette)(call(wasm, [clustering], clusteringPointer => wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k)), (0, _shared.colorSpaceName)(header.colorSpace));
@@ -981,6 +1008,7 @@ exports.getSwatches = getSwatches;
981
1008
  const getClusteringInfo = async (clustering, ...extra) => {
982
1009
  const header = (0, _shared.readHeader)(clustering);
983
1010
  noOptions('getClusteringInfo', extra);
1011
+ needsWeights(header);
984
1012
  const colors = header.merges + (clustering.length >= header.headerLength + 3 ? 1 : 0);
985
1013
  const info = {
986
1014
  formatVersion: header.version,
@@ -988,13 +1016,10 @@ const getClusteringInfo = async (clustering, ...extra) => {
988
1016
  precision: header.precision,
989
1017
  transparent: header.transparent === 0 ? false : header.transparent,
990
1018
  maxColors: colors,
991
- totalWeight: null,
1019
+ totalWeight: 0,
992
1020
  mse: null,
993
1021
  explained: null
994
1022
  };
995
- if (header.version < 3) {
996
- return info;
997
- }
998
1023
  const view = new DataView(clustering.buffer, clustering.byteOffset, clustering.byteLength);
999
1024
  const pixels = 2 ** clustering[7] / (clustering[6] === 1 ? 255 : 1);
1000
1025
  const total = view.getUint32(8, true);
@@ -1038,7 +1063,7 @@ const quantize = async (image, k, options) => {
1038
1063
  report(1);
1039
1064
  return mapped;
1040
1065
  }
1041
- 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.width, o.transparent)));
1066
+ 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.width, o.transparent), o.precision));
1042
1067
  };
1043
1068
  exports.quantize = quantize;
1044
1069
  const quantizeFromClustering = async (image, clustering, k, options) => {
@@ -1083,7 +1108,7 @@ const quantizeToIndices = async (image, k, options) => {
1083
1108
  report(1);
1084
1109
  return indexed;
1085
1110
  }
1086
- 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.width, o.transparent)), original, (0, _shared.colorSpaceName)(o.colorSpace));
1111
+ 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.width, o.transparent), o.precision), original, (0, _shared.colorSpaceName)(o.colorSpace));
1087
1112
  };
1088
1113
  exports.quantizeToIndices = quantizeToIndices;
1089
1114
  const quantizeToIndicesFromClustering = async (image, clustering, k, options) => {
package/dist/index.d.cts CHANGED
@@ -131,7 +131,7 @@ export type ColorSpace = 'rgb' | 'oklab';
131
131
  /** How pixel opacity affects clustering. */
132
132
  export type AlphaMode = 'weight' | 'ignore';
133
133
 
134
- /** Cancelling a call. Every function that takes an image has it; see `RunOptions.signal`. */
134
+ /** Cancelling a call. Every function that takes an image has it. */
135
135
  export interface CancelOptions {
136
136
  /**
137
137
  * Cancels the call. A call given a `signal` clusters (where it clusters) in slices of about 10 ms and checks the
@@ -146,8 +146,8 @@ export interface CancelOptions {
146
146
  signal?: AbortSignal | undefined;
147
147
  }
148
148
 
149
- /** Cancelling a long call and watching it, for the functions that cluster. Both are optional and can be used apart. */
150
- export interface RunOptions extends CancelOptions {
149
+ /** Cancelling a long call and watching its progress, for the functions that cluster. Both are optional and can be used apart. */
150
+ export interface ProgressOptions extends CancelOptions {
151
151
  /**
152
152
  * Called with the fraction done, from 0 to 1, as the call runs: a few times per slice at most, never going
153
153
  * backwards, ending with 1. It is approximate and not linear in time. Giving it also makes the call run in
@@ -157,10 +157,10 @@ export interface RunOptions extends CancelOptions {
157
157
  }
158
158
 
159
159
  /** Options for building the colour hierarchy: `getClustering`, `getPalette`, and the clustering half of `quantize` and `quantizeToIndices`. */
160
- export interface ClusteringOptions extends RunOptions {
160
+ export interface ClusteringOptions extends ProgressOptions {
161
161
  /**
162
162
  * `'rgb'` (default) minimises squared sRGB error, which is what MSE/PSNR measure.
163
- * `'oklab'` clusters in OKLab. Neither is better everywhere: see "Choosing a colour space" in the README.
163
+ * `'oklab'` clusters in OKLab. Neither is better everywhere: see "Choosing a colour space" in docs/api.md.
164
164
  */
165
165
  colorSpace?: ColorSpace | undefined;
166
166
  /**
@@ -250,9 +250,9 @@ interface IndexedImageFields {
250
250
  /** The index of the entry for fully transparent pixels, or `null` if there is none. */
251
251
  transparentIndex: number | null;
252
252
  /** Copied from the input, when it is `ImageData` or a `RawImage` with `width`. */
253
- width?: number;
253
+ width?: number | undefined;
254
254
  /** Copied from the input, when it is `ImageData` or a `RawImage` with `height`. */
255
- height?: number;
255
+ height?: number | undefined;
256
256
  }
257
257
 
258
258
  /**
@@ -282,10 +282,10 @@ export const version: string;
282
282
  /**
283
283
  * The version of the data this library stores: the format of the clusterings `getClustering` writes (`getClusteringInfo`
284
284
  * reports a clustering's own as its `formatVersion`). One integer for the library's stored data, unrelated to `version`: it
285
- * changes only when the stored format does, so a new release that keeps the format keeps this number. This build reads
286
- * this format and the one before it (2).
285
+ * changes only when the stored format does, so a new release that keeps the format keeps this number, and a minor release
286
+ * may raise it. Every earlier format from 2 on stays readable (see `getClusteringInfo` for what 2.x clusterings lack).
287
287
  */
288
- export const formatVersion: 3;
288
+ export const formatVersion: number;
289
289
 
290
290
  /**
291
291
  * Loads the WebAssembly module. Every other function does it on first use, so calling `init` is optional, except to
@@ -356,7 +356,13 @@ export function getSwatches(image: ImageLike, k: number, options?: ClusteringOpt
356
356
  */
357
357
  export function getSwatchesFromClustering(clustering: Clustering, k: number): Promise<Swatches>;
358
358
 
359
- interface ClusteringInfoFields {
359
+ /** What a clustering holds (`getClusteringInfo`). */
360
+ export interface ClusteringInfo {
361
+ /**
362
+ * The format of the clustering's bytes: the data version (compare it with the exported `formatVersion`, the one this
363
+ * build writes), not the library's `version`. 3 for a clustering from 3.x; a later minor release may write a higher one.
364
+ */
365
+ formatVersion: number;
360
366
  colorSpace: ColorSpace;
361
367
  /** Bits per channel it was clustered with. */
362
368
  precision: number;
@@ -367,12 +373,6 @@ interface ClusteringInfoFields {
367
373
  transparent: false | number;
368
374
  /** The largest palette it can be cut to: its number of distinct clustered colours (fewer than the image's own when `precision` is below 8). */
369
375
  maxColors: number;
370
- }
371
-
372
- /** What a 3.x clustering holds. A clustering you just made with `getClustering` is this one: check `formatVersion === 3` to narrow to it. */
373
- export interface ClusteringInfoV3 extends ClusteringInfoFields {
374
- /** The format of the clustering's bytes: the data version (see `formatVersion`, the one this build writes), not the library's `version`. */
375
- formatVersion: 3;
376
376
  /** Total weight in pixels (opacity-weighted). */
377
377
  totalWeight: number;
378
378
  /**
@@ -392,19 +392,11 @@ export interface ClusteringInfoV3 extends ClusteringInfoFields {
392
392
  explained: Float64Array;
393
393
  }
394
394
 
395
- /** What a 2.x clustering holds: no weights, so no error curve. */
396
- export interface ClusteringInfoV2 extends ClusteringInfoFields {
397
- /** The format of the clustering's bytes (see `ClusteringInfoV3.formatVersion`). */
398
- formatVersion: 2;
399
- totalWeight: null;
400
- mse: null;
401
- explained: null;
402
- }
403
-
404
- /** What `getClusteringInfo` returns: check `formatVersion` to narrow to the 3.x or 2.x shape. */
405
- export type ClusteringInfo = ClusteringInfoV3 | ClusteringInfoV2;
406
-
407
- /** Reads what a clustering holds, including its error curve for choosing a palette size. */
395
+ /**
396
+ * Reads what a clustering holds, including its error curve for choosing a palette size. Needs a clustering from 3.x: a 2.x
397
+ * clustering recorded no weights, so it is rejected with `unsupported-version` (as `getSwatchesFromClustering` rejects it);
398
+ * the palette and mapping functions still read it.
399
+ */
408
400
  export function getClusteringInfo(clustering: Clustering): Promise<ClusteringInfo>;
409
401
 
410
402
  /**
@@ -442,6 +434,7 @@ export function quantizeWithPalette<I extends ImageLike>(image: I, palette: Pale
442
434
  *
443
435
  * @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
444
436
  * 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.
437
+ * A colour is always kept besides the transparent entry, so with `transparent`, `k = 1` can give 2 entries.
445
438
  */
446
439
  export function quantizeToIndices(image: ImageLike, k: number, options?: QuantizeIndexOptions): Promise<IndexedImage>;
447
440
 
@@ -450,6 +443,7 @@ export function quantizeToIndices(image: ImageLike, k: number, options?: Quantiz
450
443
  *
451
444
  * @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
452
445
  * 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.
446
+ * A colour is always kept besides the transparent entry, so with `transparent`, `k = 1` can give 2 entries.
453
447
  */
454
448
  export function quantizeToIndicesFromClustering(image: ImageLike, clustering: Clustering, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
455
449
 
package/dist/index.d.ts CHANGED
@@ -131,7 +131,7 @@ export type ColorSpace = 'rgb' | 'oklab';
131
131
  /** How pixel opacity affects clustering. */
132
132
  export type AlphaMode = 'weight' | 'ignore';
133
133
 
134
- /** Cancelling a call. Every function that takes an image has it; see `RunOptions.signal`. */
134
+ /** Cancelling a call. Every function that takes an image has it. */
135
135
  export interface CancelOptions {
136
136
  /**
137
137
  * Cancels the call. A call given a `signal` clusters (where it clusters) in slices of about 10 ms and checks the
@@ -146,8 +146,8 @@ export interface CancelOptions {
146
146
  signal?: AbortSignal | undefined;
147
147
  }
148
148
 
149
- /** Cancelling a long call and watching it, for the functions that cluster. Both are optional and can be used apart. */
150
- export interface RunOptions extends CancelOptions {
149
+ /** Cancelling a long call and watching its progress, for the functions that cluster. Both are optional and can be used apart. */
150
+ export interface ProgressOptions extends CancelOptions {
151
151
  /**
152
152
  * Called with the fraction done, from 0 to 1, as the call runs: a few times per slice at most, never going
153
153
  * backwards, ending with 1. It is approximate and not linear in time. Giving it also makes the call run in
@@ -157,10 +157,10 @@ export interface RunOptions extends CancelOptions {
157
157
  }
158
158
 
159
159
  /** Options for building the colour hierarchy: `getClustering`, `getPalette`, and the clustering half of `quantize` and `quantizeToIndices`. */
160
- export interface ClusteringOptions extends RunOptions {
160
+ export interface ClusteringOptions extends ProgressOptions {
161
161
  /**
162
162
  * `'rgb'` (default) minimises squared sRGB error, which is what MSE/PSNR measure.
163
- * `'oklab'` clusters in OKLab. Neither is better everywhere: see "Choosing a colour space" in the README.
163
+ * `'oklab'` clusters in OKLab. Neither is better everywhere: see "Choosing a colour space" in docs/api.md.
164
164
  */
165
165
  colorSpace?: ColorSpace | undefined;
166
166
  /**
@@ -250,9 +250,9 @@ interface IndexedImageFields {
250
250
  /** The index of the entry for fully transparent pixels, or `null` if there is none. */
251
251
  transparentIndex: number | null;
252
252
  /** Copied from the input, when it is `ImageData` or a `RawImage` with `width`. */
253
- width?: number;
253
+ width?: number | undefined;
254
254
  /** Copied from the input, when it is `ImageData` or a `RawImage` with `height`. */
255
- height?: number;
255
+ height?: number | undefined;
256
256
  }
257
257
 
258
258
  /**
@@ -282,10 +282,10 @@ export const version: string;
282
282
  /**
283
283
  * The version of the data this library stores: the format of the clusterings `getClustering` writes (`getClusteringInfo`
284
284
  * reports a clustering's own as its `formatVersion`). One integer for the library's stored data, unrelated to `version`: it
285
- * changes only when the stored format does, so a new release that keeps the format keeps this number. This build reads
286
- * this format and the one before it (2).
285
+ * changes only when the stored format does, so a new release that keeps the format keeps this number, and a minor release
286
+ * may raise it. Every earlier format from 2 on stays readable (see `getClusteringInfo` for what 2.x clusterings lack).
287
287
  */
288
- export const formatVersion: 3;
288
+ export const formatVersion: number;
289
289
 
290
290
  /**
291
291
  * Loads the WebAssembly module. Every other function does it on first use, so calling `init` is optional, except to
@@ -356,7 +356,13 @@ export function getSwatches(image: ImageLike, k: number, options?: ClusteringOpt
356
356
  */
357
357
  export function getSwatchesFromClustering(clustering: Clustering, k: number): Promise<Swatches>;
358
358
 
359
- interface ClusteringInfoFields {
359
+ /** What a clustering holds (`getClusteringInfo`). */
360
+ export interface ClusteringInfo {
361
+ /**
362
+ * The format of the clustering's bytes: the data version (compare it with the exported `formatVersion`, the one this
363
+ * build writes), not the library's `version`. 3 for a clustering from 3.x; a later minor release may write a higher one.
364
+ */
365
+ formatVersion: number;
360
366
  colorSpace: ColorSpace;
361
367
  /** Bits per channel it was clustered with. */
362
368
  precision: number;
@@ -367,12 +373,6 @@ interface ClusteringInfoFields {
367
373
  transparent: false | number;
368
374
  /** The largest palette it can be cut to: its number of distinct clustered colours (fewer than the image's own when `precision` is below 8). */
369
375
  maxColors: number;
370
- }
371
-
372
- /** What a 3.x clustering holds. A clustering you just made with `getClustering` is this one: check `formatVersion === 3` to narrow to it. */
373
- export interface ClusteringInfoV3 extends ClusteringInfoFields {
374
- /** The format of the clustering's bytes: the data version (see `formatVersion`, the one this build writes), not the library's `version`. */
375
- formatVersion: 3;
376
376
  /** Total weight in pixels (opacity-weighted). */
377
377
  totalWeight: number;
378
378
  /**
@@ -392,19 +392,11 @@ export interface ClusteringInfoV3 extends ClusteringInfoFields {
392
392
  explained: Float64Array;
393
393
  }
394
394
 
395
- /** What a 2.x clustering holds: no weights, so no error curve. */
396
- export interface ClusteringInfoV2 extends ClusteringInfoFields {
397
- /** The format of the clustering's bytes (see `ClusteringInfoV3.formatVersion`). */
398
- formatVersion: 2;
399
- totalWeight: null;
400
- mse: null;
401
- explained: null;
402
- }
403
-
404
- /** What `getClusteringInfo` returns: check `formatVersion` to narrow to the 3.x or 2.x shape. */
405
- export type ClusteringInfo = ClusteringInfoV3 | ClusteringInfoV2;
406
-
407
- /** Reads what a clustering holds, including its error curve for choosing a palette size. */
395
+ /**
396
+ * Reads what a clustering holds, including its error curve for choosing a palette size. Needs a clustering from 3.x: a 2.x
397
+ * clustering recorded no weights, so it is rejected with `unsupported-version` (as `getSwatchesFromClustering` rejects it);
398
+ * the palette and mapping functions still read it.
399
+ */
408
400
  export function getClusteringInfo(clustering: Clustering): Promise<ClusteringInfo>;
409
401
 
410
402
  /**
@@ -442,6 +434,7 @@ export function quantizeWithPalette<I extends ImageLike>(image: I, palette: Pale
442
434
  *
443
435
  * @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
444
436
  * 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.
437
+ * A colour is always kept besides the transparent entry, so with `transparent`, `k = 1` can give 2 entries.
445
438
  */
446
439
  export function quantizeToIndices(image: ImageLike, k: number, options?: QuantizeIndexOptions): Promise<IndexedImage>;
447
440
 
@@ -450,6 +443,7 @@ export function quantizeToIndices(image: ImageLike, k: number, options?: Quantiz
450
443
  *
451
444
  * @param k The most palette entries in the result (`k` means this in every function), counting the transparent entry
452
445
  * 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.
446
+ * A colour is always kept besides the transparent entry, so with `transparent`, `k = 1` can give 2 entries.
453
447
  */
454
448
  export function quantizeToIndicesFromClustering(image: ImageLike, clustering: Clustering, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
455
449