agglomerative-clustering 3.0.0-beta.5 → 3.0.0-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -39,7 +39,7 @@ import sharp from 'sharp';
39
39
  import { getPalette, quantize } from 'agglomerative-clustering';
40
40
 
41
41
  const { data, info } = await sharp('photo.jpg').ensureAlpha().raw().toBuffer({ resolveWithObject: true });
42
- const image = { data: new Uint8Array(data.buffer, data.byteOffset, data.length), format: 'rgba', width: info.width };
42
+ const image = { data, format: 'rgba', width: info.width }; // in TypeScript: format: 'rgba' as const
43
43
 
44
44
  const palette = await getPalette(image, 8); // flat bytes: [r, g, b, r, g, b, ...]
45
45
  const reduced = await quantize(image, 16, { dither: true }); // the image, in 16 colours
@@ -159,13 +159,15 @@ const clustering = await getClustering(image);
159
159
  const eight = await getSwatchesFromClustering(clustering, 8);
160
160
 
161
161
  // The smallest palette that keeps 99% of the image's colour variance (works the same in 'rgb' and 'oklab')
162
- const { explained } = await getClusteringInfo(clustering); // null only for a clustering from 2.x
163
- const k = (explained ?? []).findIndex((share) => share >= 0.99) + 1;
162
+ const { explained } = await getClusteringInfo(clustering);
163
+ const k = explained.findIndex((share) => share >= 0.99) + 1;
164
164
  ```
165
165
 
166
+ How many to ask for: 5 to 8 for a set of swatches to show. To *pick* from them (an accent colour, a theme), ask for more, 12 to 16: a small vivid area, such as a red sign in a street scene, only gets a colour of its own once the bigger areas have been split. Each colour is the average of its cluster, so it is a little less saturated than the image's most vivid pixels, and a white background comes back as a near-white such as `[254, 254, 254]` rather than exactly `#ffffff`. On a smooth single-hue photo no colour has a large share (the shares fall as `k` grows), so judge the heaviest swatch against the others, not by a fixed share. See [Picking colours from swatches](#picking-colours-from-swatches).
167
+
166
168
  ### GIFs and palette PNGs
167
169
 
168
- `quantizeToIndices` returns a palette and one index per pixel, which is what these formats store. With `transparent`, pixels below an alpha cutoff share one transparent entry, which counts in `k`.
170
+ `quantizeToIndices` returns a palette and one index per pixel, which is what these formats store. With `transparent`, pixels below an alpha cutoff share one transparent entry, which counts in `k`; a colour is always kept besides it, so `k = 1` can give 2 entries.
169
171
 
170
172
  **A GIF** with [gifenc](https://github.com/mattdesl/gifenc), keeping a transparent background:
171
173
 
@@ -362,8 +364,9 @@ Palettes are flat RGB bytes, the compact form; each format an encoder or UI want
362
364
  // [[r, g, b], …]: what gifenc, fast-png, color-thief and libimagequant use
363
365
  const colors = Array.from({ length: palette.length / 3 }, (_, i) => [palette[3 * i], palette[3 * i + 1], palette[3 * i + 2]]);
364
366
 
365
- // A CSS colour, and a 0xRRGGBB number
367
+ // A CSS colour, a '#rrggbb' string and a 0xRRGGBB number
366
368
  const css = (i) => `rgb(${palette[3 * i]} ${palette[3 * i + 1]} ${palette[3 * i + 2]})`;
369
+ const hexString = (i) => '#' + Array.from(palette.subarray(3 * i, 3 * i + 3), (v) => v.toString(16).padStart(2, '0')).join('');
367
370
  const hex = (i) => (palette[3 * i] << 16) | (palette[3 * i + 1] << 8) | palette[3 * i + 2];
368
371
 
369
372
  // Swatches with their share of the image (the palette is in split order, not sorted by share: sort `swatches` by `share` to put the biggest first)
@@ -390,6 +393,30 @@ const rankedIndices = indices.map((index) => rank[index]);
390
393
  const rankedTransparentIndex = transparentIndex === null ? null : rank[transparentIndex];
391
394
  ```
392
395
 
396
+ #### Picking colours from swatches
397
+
398
+ The library answers which colours an image has and how much of each; choosing among them (a vivid accent, text that contrasts with a background) is colour arithmetic that a colour library already does well. With [culori](https://culorijs.org/):
399
+
400
+ ```js
401
+ import { getSwatches } from 'agglomerative-clustering';
402
+ import { converter, wcagContrast, formatHex } from 'culori';
403
+
404
+ const oklch = converter('oklch');
405
+ const { palette, shares } = await getSwatches(image, 12);
406
+ const swatches = Array.from(shares, (share, i) => {
407
+ const color = { mode: 'rgb', r: palette[3 * i] / 255, g: palette[3 * i + 1] / 255, b: palette[3 * i + 2] / 255 };
408
+ return { hex: formatHex(color), share, ...oklch(color) }; // l (0-1), c (chroma), h (hue)
409
+ }).sort((a, b) => b.share - a.share); // heaviest first
410
+
411
+ const background = swatches[0];
412
+ // The most colourful swatch that covers at least 2% of the image, as an accent
413
+ const accent = swatches.filter((s) => s.share >= 0.02 && s !== background).sort((a, b) => b.c - a.c)[0];
414
+ // Text: black or white, whichever contrasts more with the background
415
+ const text = wcagContrast(background.hex, '#000') > wcagContrast(background.hex, '#fff') ? '#000' : '#fff';
416
+ ```
417
+
418
+ The colours come back as sRGB bytes whatever `colorSpace` they were clustered in; that option only changes how pixels are grouped. For picks by lightness, chroma or hue, convert them as above (OKLCH is the perceptual form of OKLab). Choose the colour space you cluster in as in [Choosing a colour space](#choosing-a-colour-space): the picks can differ between the two, since each gives different averages.
419
+
393
420
  ### Coming from color-thief, node-vibrant, image-q or get-image-colors
394
421
 
395
422
  This library takes **decoded pixels**, not files, URLs or image elements: decode first (sharp or pngjs in Node, a canvas or `createImageBitmap` in a browser). Pixels without alpha go in as `{ data, format: 'rgb' }`; passed bare they are read as RGBA, so sharp's `.raw()` without `.ensureAlpha()` gives a palette that is quietly wrong.
@@ -424,6 +451,8 @@ ImageData // from a canvas: always RGBA, widt
424
451
 
425
452
  > **A bare `Uint8Array` is read as RGBA**, like `ImageData`. RGB bytes passed bare are misread, with no error when their length happens to be a multiple of 4. Pass them as `{ data, format: 'rgb', width }`, or add an alpha channel (sharp's `.ensureAlpha()`).
426
453
 
454
+ > **Pixels are 8-bit sRGB with straight alpha**, as `getImageData()` gives them. Convert anything else first: premultiplied pixels (from some native and WebGL APIs) back to straight alpha, 16-bit or floating-point pixels (16-bit PNGs, HDR) to 8 bits (sharp: `.toColourspace('srgb').raw({ depth: 'uchar' })`; pngjs: `inputHasAlpha` and its 8-bit output), and gray or gray-and-alpha pixels to RGBA (sharp's `.toColourspace('srgb').ensureAlpha()`). A gray buffer passed as it is gets misread, with no error when its length is a multiple of 4. Apply a photo's EXIF orientation (sharp's `.rotate()`) and colour profile when decoding; the library doesn't read either. An `ImageData` in another pixel format (Chromium's `pixelFormat: 'rgba-float16'`) is rejected with `invalid-argument`: ask for `getImageData(x, y, w, h, { pixelFormat: 'rgba-unorm8' })`.
455
+
427
456
  > **Image files are not pixels.** A bare `Uint8Array` that starts like a PNG, JPEG, GIF, WebP, BMP, TIFF, AVIF or HEIC file (from `fs.readFile` or `fetch`) is rejected with `invalid-argument` naming the format. Decode it first: a canvas or `createImageBitmap` in a browser, sharp or pngjs in Node. Only bare arrays are checked, so if raw pixels really do begin like a file header, pass `{ data, format: 'rgba' }`. Decoding is [planned](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/ROADMAP.md).
428
457
 
429
458
  The functions that return an image give back the type they were given: a `Uint8Array`, `ImageData`, or an object with the same `format` (and `width` and `height`). In TypeScript the result type follows the input (`ImageResult<I>`). Palettes come back as a `Palette`, clusterings as a `Clustering`, and the other results are `Swatches`, `IndexedImage` and `ClusteringInfo` objects.
@@ -498,12 +527,12 @@ Give one or the other: `transparent` replaces `alpha`, so naming both is an erro
498
527
  The cutoff decides which side a half-transparent pixel falls on. With the default (128), a soft drop shadow under 50% opacity disappears, and the darker part of it becomes solid; raise the cutoff (`transparent: 200`) to drop more of it, or lower it to keep more.
499
528
 
500
529
  ### Palette and Clustering
501
- The palettes and clusterings this library returns are ordinary `Uint8Array`s with a hidden tag: what they are and, for a palette, the colour space it was made in. Anything that takes bytes takes them, and their `constructor` is `Uint8Array`, so `expect(palette).toEqual(new Uint8Array([...]))` passes in your tests. The tags buy three things:
530
+ The palettes and clusterings this library returns are ordinary `Uint8Array`s with a hidden tag: what they are and, for a palette, the colour space it was made in. Anything that takes bytes takes them, and their `constructor` is `Uint8Array`, so `expect(palette).toEqual(new Uint8Array([...]))` passes in your tests. The tags buy four things:
502
531
 
503
532
  - **A palette maps in the space it was made in.** `quantizeWithPalette(image, palette)` matches an OKLab palette in OKLab without being told; name a `colorSpace` to override it. Plain bytes are matched in RGB.
504
533
  - **A clustering can't be passed as a palette**, or the other way round. TypeScript rejects it, and at run time it throws (`invalid-argument` or `invalid-clustering`), with no guessing about bytes.
505
534
  - **`new Palette(bytes, colorSpace)` and `new Clustering(bytes)` give bytes their type back**, and check them: `new Palette([300, 0, 0])` throws rather than wrapping 300 to 44, and `new Clustering(bytes)` throws `invalid-clustering` unless they are one. The functions still accept a clustering as plain bytes, so stored clusterings keep working in JavaScript; TypeScript wants the constructor.
506
- - **A clustering is checked before it is used.** Clusterings carry a checksum, so stored bytes that came back damaged (truncated, a changed byte, a lossy base64 round trip) are reported as `invalid-clustering` rather than cut into a wrong palette.
535
+ - **A clustering is checked before it is used.** Clusterings carry a checksum, so stored bytes that came back damaged (truncated, a changed byte, a lossy base64 round trip) are reported as `invalid-clustering` rather than cut into a wrong palette. It is checked the first time an array is used, so bytes changed in place after that aren't caught. Clusterings from 2.x have no checksum. It catches accidents, not tampering (anyone can recompute it): a clustering or palette from an untrusted user can't crash the library or make it hang, but it can describe any palette it likes.
507
536
 
508
537
  ```js
509
538
  import { Clustering, Palette, getPaletteFromClustering } from 'agglomerative-clustering';
@@ -539,7 +568,7 @@ const clustering = await getClustering(image, {
539
568
  });
540
569
  ```
541
570
 
542
- - **Slices.** With either option, clustering runs in slices of about 10 ms (a large image has a few unsliced steps of up to 150 ms in between), so an abort takes effect within a slice and the page stays responsive. The result is the same; slicing costs about 5% more time.
571
+ - **Slices.** With either option, clustering runs in slices of about 10 ms (a large photo has a few unsliced steps of up to 150 ms in between; an image with millions of distinct colours, longer: see [Performance and limits](#performance-and-limits)), so an abort takes effect within a slice and the page stays responsive. The result is the same; slicing costs about 5% more time.
543
572
  - **Aborting** rejects with the signal's `reason` (an `AbortError` by default), like `fetch`. It is not one of this library's errors, and has none of their codes (a `DOMException`'s `code` is a number). To tell an abort from a failure, check your signal (`signal.aborted`), not the error: a reason you gave (`controller.abort(new Error('superseded'))`) keeps its own name. An already aborted signal does no work.
544
573
  - **Mapping can't be interrupted** (it takes milliseconds: 6 ms at 768×512, 27 ms dithered). The functions that only map check the signal before they start, and don't take `onProgress`.
545
574
  - **Progress** is approximate, never goes backwards, and ends at exactly 1.
@@ -556,7 +585,7 @@ When an error is about one argument, `error.argument` names it: `'image'`, `'k'`
556
585
  | `invalid-argument` | A bad image, `k`, option or palette. |
557
586
  | `invalid-clustering` | Bytes that aren't a clustering this version can read, or a stored clustering that came back damaged (its checksum or its records don't fit). |
558
587
  | `unsupported-version` | A clustering from a newer format, or using a colour space it doesn't know (upgrade the package), or an older one without what you asked for (cluster again, e.g. for `getSwatchesFromClustering`). |
559
- | `out-of-memory` | The WebAssembly module couldn't allocate. |
588
+ | `out-of-memory` | The WebAssembly module couldn't allocate: an image with very many colours, or pixel data over its 2 GB (the message gives the size). |
560
589
  | `wasm-load-failed` | The WebAssembly module couldn't be loaded or compiled: a missing or blocked `.wasm` file, a server bundle that moved it, a browser without SIMD, or a `.wasm` from a different version of the library than the script (a stale cache or CDN copy; the message names both versions). The message leads with the engine's reason and says what to check, and `cause` is the engine's own error. |
561
590
  | `worker-terminated`, `worker-failed`, `invalid-handle` | Worker entry only: the worker was stopped, failed, or a handle was released. `worker-terminated` is for calls running or waiting when `terminate()` was called, and every later call on that `createWorker()` worker, so retrying on it can't help (the shared worker starts again on the next call). After `worker-failed` (it couldn't start, crashed or exited), the next call starts a new worker. |
562
591
 
@@ -580,7 +609,9 @@ Messages are for people and may change. The worker entry fails the same way as t
580
609
  `agglomerative-clustering/worker` exports every function above, run in one shared worker started on first use, plus `terminate()`, which stops it (the next call starts a new one), and `createWorker(options?)`, which starts a worker of your own. A worker has every function as a method, plus:
581
610
 
582
611
  - **`cluster(image, options?)`** keeps the image and its clustering in the worker, behind a handle with `getClustering()`, `getPalette(k)`, `getSwatches(k)`, `getClusteringInfo()`, `quantize(k, options?)`, `quantizeToIndices(k, options?)`, `quantizeWithPalette(palette, options?)` and `quantizeToIndicesWithPalette(palette, options?)`. A palette of plain bytes is matched in the handle's colour space, and `quantizeToIndices` uses the cutoff it was clustered with. Free it with `release()`, or declare it with `await using handle = await worker.cluster(image)`; a dropped handle is freed only when the garbage collector gets to it.
583
- - **`terminate()`** stops the worker and rejects the calls still waiting.
612
+ - **`terminate()`** stops the worker and rejects the calls still waiting. `await using worker = createWorker()` calls it at the end of the block.
613
+
614
+ **Terminate the workers you create.** A worker's thread, and the memory its last images needed, stay until `terminate()`: a running worker is never garbage-collected, so a server or page that creates a worker per request and drops it gathers threads. Keep a few workers and reuse them (see [Performance and limits](#performance-and-limits)), or use the shared worker, which the exported functions use. As a safety net, a worker you dropped is stopped some time after the garbage collector has collected it, once no call is running on it and no handle from it is left, but when that happens is up to the engine (it may be never, in a process with little memory pressure).
584
615
 
585
616
  `createWorker` takes `transfer`, `wasm` (see [Loading the WebAssembly module](#loading-the-webassembly-module)) and `script`: the URL (or in Node, the path) of a copy of the package's `dist/worker-thread.mjs`, for setups whose bundler doesn't emit the package's own. For the shared worker, `init({ script })` does the same, before any other call.
586
617
 
@@ -591,7 +622,7 @@ The entry is an ES module, with a CommonJS build for `require()` in Node and in
591
622
  ### TypeScript
592
623
  Both entries ship declarations, checked in CI under strict mode with `nodenext` (ES module and CommonJS importers), `bundler`, and a Node-only project without the DOM lib. The worker entry's declarations use `await using` for handles, so they need **TypeScript 5.2 or newer** (or `skipLibCheck: true`); the main entry works on older versions. Both entries have CommonJS declarations too, so a `.cts` file or a CommonJS project imports either.
593
624
 
594
- Results narrow: checking `result.indexBits === 8` makes `indices` a `Uint8Array`, and checking `info.formatVersion === 3` makes `mse`, `explained` and `totalWeight` present. Palette parameters take a `PaletteLike` (a `Palette`, plain bytes or a `number[]`, not a `Clustering`), and errors are `CodedError`s with `code` and `argument`.
625
+ Results narrow: checking `result.indexBits === 8` makes `indices` a `Uint8Array`. Palette parameters take a `PaletteLike` (a `Palette`, plain bytes or a `number[]`, not a `Clustering`), and errors are `CodedError`s with `code` and `argument`.
595
626
 
596
627
  An image object assigned to a variable before it is passed widens `format: 'rgba'` to `string`, which no longer matches `RawImage`: write `format: 'rgba' as const`, or declare the variable as `RawImage`.
597
628
 
@@ -632,7 +663,7 @@ What a clustering holds: `{ formatVersion, colorSpace, precision, transparent, m
632
663
  - `mse[k - 1]`: the mean squared error per channel of the `k`-colour clustering, in 8-bit RGB values (OKLab units for an OKLab clustering). `mse[0]` is the image's variance, and `mse[maxColors - 1]` is 0 at the default `precision: 8` (below 8, it is the error that grouping colours discarded). It is an estimate from merge costs; mapping pixels to the palette usually lowers it by another 10–15%.
633
664
  - `explained[k - 1]`: `1 - mse[k - 1] / mse[0]`, the share of the image's variance the `k`-colour palette keeps, from 0 to 1. It has no units, so a target such as `0.99` means the same in both colour spaces.
634
665
 
635
- For a 2.x clustering, `formatVersion` is 2 and `totalWeight`, `mse` and `explained` are `null`; in TypeScript, checking `info.formatVersion === 3` narrows them to present.
666
+ It needs a clustering from 3.x, like `getSwatchesFromClustering`: a 2.x clustering recorded no weights, so it is rejected with `unsupported-version` (the palette and mapping functions still read it).
636
667
 
637
668
  ### `quantize(image, k, options?): Promise<the type of image>`
638
669
  Reduces the image to at most `k` colours.
@@ -683,7 +714,7 @@ Loads the WebAssembly module. Every other function does this on first use, so ca
683
714
  `errorCodes` is a frozen array of every `code` the library's errors have (see [Errors](#errors)). `isCodedError(value)` is true when `value` has a string `message` and one of those codes; in TypeScript it narrows to `CodedError`. Both entries export both.
684
715
 
685
716
  ### `version: string` and `formatVersion: number`
686
- `version` is the library's version (such as `'3.0.0'`), for bug reports and runtime checks. `formatVersion` is the version of the data it stores (the clustering format), which changes only when that format does: if a stored clustering's `getClusteringInfo(stored).formatVersion` differs, cluster the image again (2.x clusterings still load, but have no weights). Both entries export both, and a `.wasm` from another version fails to load with `wasm-load-failed`.
717
+ `version` is the library's version (such as `'3.0.0'`), for bug reports and runtime checks. `formatVersion` is the version of the data it stores (the clustering format), which changes only when that format does: a minor release may raise it, and every earlier format from 2 on stays readable. To keep stored clusterings current, cluster the image again when `getClusteringInfo(stored).formatVersion` is below it, or when `getClusteringInfo` rejects the clustering with `unsupported-version` (a 2.x clustering, which has no weights, or one from a newer version than this one). Both entries export both, and a `.wasm` from another version fails to load with `wasm-load-failed`.
687
718
 
688
719
  ## Running it
689
720
 
@@ -691,7 +722,7 @@ Loads the WebAssembly module. Every other function does this on first use, so ca
691
722
 
692
723
  Node 20.19+ and 22.12+ (CI tests Node 20, 22 and 24, on Linux and Windows), and browsers with WebAssembly SIMD: Chrome and Edge 91, Firefox 89, Safari 16.4 or newer ([support table](https://caniuse.com/wasm-simd)). CI bundles a test page with Vite and webpack 5 and runs it in Chromium, Firefox and WebKit on Linux and in Safari on macOS. In a browser without SIMD, or where the `.wasm` is blocked or missing, `init` and every other call reject with a `wasm-load-failed` error.
693
724
 
694
- CI also loads `dist/` from another origin, as a page using a CDN does, and the worker entry from a sandboxed iframe, in the same browsers, and runs both entries under Jest. Checked by hand, not in CI: Deno 2.9, Bun 1.4, Cloudflare Workers (Wrangler, workerd), Vercel's edge runtime, SvelteKit and Nuxt, Next.js and Parcel 2 (see below).
725
+ CI also loads `dist/` from another origin, as a page using a CDN does, and the worker entry from a sandboxed iframe, in the same browsers, and runs both entries under Jest. Checked by hand, not in CI: Deno 2.9, Bun 1.4, Cloudflare Workers (Wrangler, workerd), Vercel's edge runtime, the AWS Lambda Node image, pnpm and Yarn Plug'n'Play, SvelteKit, Nuxt, Astro, React Router, Angular, Next.js and Parcel 2 (see below).
695
726
 
696
727
  ### From a CDN, without a build step
697
728
 
@@ -738,6 +769,21 @@ The package exports the file as `agglomerative-clustering/clustering.wasm`, so a
738
769
 
739
770
  SvelteKit (adapter-node) and Nuxt (Nitro's node-server) need no configuration, in development and production builds: the worker entry for pages, the main entry in server routes. Importing either entry during server rendering is safe, and `createWorker()` starts no thread until its first call. On Nitro's Cloudflare preset, turn on `nitro: { experimental: { wasm: true } }` and pass the module from `import wasm from 'agglomerative-clustering/clustering.wasm?module'` to `init`, as for the Edge runtime below.
740
771
 
772
+ ### Serverless functions: AWS Lambda, Vercel, Netlify
773
+
774
+ Both entries run in Node functions (checked in the AWS Lambda Node 20 image, with a read-only code directory, and with the file tracers Vercel and Netlify use). Unbundled, with `node_modules` in the package or a layer, nothing is needed. Bundled:
775
+
776
+ - **An ES module bundle** finds `clustering.wasm` next to itself: copy `node_modules/agglomerative-clustering/dist/clustering.wasm` beside the bundle. **A CommonJS bundle** has lost the package's own location: pass `init({ wasm: path })`, with a path to the copy you ship.
777
+ - **The worker entry** needs `worker-thread.mjs` and the files it imports (`index.mjs`, `shared.mjs`, `clustering.js`, `clustering.wasm`): leave the package external, or ship a copy of `dist/` and pass `createWorker({ script: path })`. Netlify's esbuild bundler moves them apart, so list the package in `external_node_modules`.
778
+ - **Size and cold starts:** the files a function needs are about 180 KB (235 KB with the worker). Loading the module takes 10 to 70 ms, and a first palette of a 1-megapixel image at `precision: 6` came 0.3 to 0.5 s after a cold start; calling `init()` early doesn't make the first palette faster.
779
+ - **Edge functions** (Vercel's edge runtime, Cloudflare) can't compile WebAssembly while they run: import the module as described for [Next.js](#nextjs) and [Cloudflare Workers](#deno-bun-and-cloudflare-workers).
780
+
781
+ ### pnpm, Yarn Plug'n'Play and monorepos
782
+
783
+ pnpm (isolated or hoisted) and Yarn Plug'n'Play need nothing for the main entry. Under Plug'n'Play the package stays in its zip archive, and the worker entry's thread loads its ES modules from there only through Yarn's loader: run with `yarn node` (or `node --require ./.pnp.cjs --loader ./.pnp.loader.mjs`), or `yarn unplug agglomerative-clustering`. Yarn 4 holds back versions published in the last day by default, so to try a release on its first day set `npmMinimalAgeGate: 0` in `.yarnrc.yml`.
784
+
785
+ Two versions in one process (a monorepo whose packages depend on different releases) each load their own module and don't share state; clusterings and palettes pass between them, and `isCodedError` recognises either one's errors.
786
+
741
787
  ### Next.js
742
788
 
743
789
  Checked with Next.js 16, under Turbopack and webpack, in production builds:
@@ -766,7 +812,7 @@ Checked with Next.js 16, under Turbopack and webpack, in production builds:
766
812
 
767
813
  ### Angular, esbuild, Rollup and other bundlers
768
814
 
769
- The main entry works in all of them. The worker entry needs its script (`worker-thread.mjs`, which imports the package's other files) next to the rest of `dist/`, and some bundlers emit neither it nor `clustering.wasm`. Then a worker call fails at run time with `worker-failed` or `wasm-load-failed`, often only after deploying, because a dev server serves `node_modules` as it is. Copy the package's `dist/` files out as static assets and say where they are:
815
+ The main entry works in all of them, except that an Angular production build needs `init({ wasm })` (below). The worker entry needs its script (`worker-thread.mjs`, which imports the package's other files) next to the rest of `dist/`, and some bundlers emit neither it nor `clustering.wasm`. Then a worker call fails at run time with `worker-failed` or `wasm-load-failed`, often only after deploying, because a dev server serves `node_modules` as it is. Copy the package's whole `dist/` folder out as static assets and say where it is (copy all of it, not a list of files: which files the worker script imports isn't part of the API, and a minor release may change it):
770
816
 
771
817
  ```js
772
818
  import { createWorker } from 'agglomerative-clustering/worker';
@@ -776,12 +822,12 @@ const worker = createWorker({
776
822
  });
777
823
  ```
778
824
 
779
- - **Angular** (the default `application` builder): add the files to the app's `angular.json` assets, then use the code above.
825
+ - **Angular** (the default `application` builder): add the files to the app's `angular.json` assets, then use the code above. Production builds don't emit `clustering.wasm` for the main entry either, so in the browser call `init({ wasm: '/assets/agglomerative-clustering/clustering.wasm' })` before the first call (the dev server works without it). With SSR, the server bundle finds the package's files from the directory the server starts in: start it from the project directory, or give the server its own `init({ wasm: path })`. zone.js needs nothing.
780
826
 
781
827
  ```json
782
- "assets": [{ "glob": "{worker-thread.mjs,shared.mjs,index.mjs,clustering.js,clustering.wasm}", "input": "node_modules/agglomerative-clustering/dist", "output": "assets/agglomerative-clustering" }]
828
+ "assets": [{ "glob": "**/*", "input": "node_modules/agglomerative-clustering/dist", "output": "assets/agglomerative-clustering" }]
783
829
  ```
784
- - **esbuild, Rollup and `bun build`** do not recognise `new Worker(new URL(...))`, so copy the same files into the output and give `script` (and `wasm`). Rollup users can also build `worker-thread.mjs` as a second entry.
830
+ - **esbuild, Rollup and `bun build`** do not recognise `new Worker(new URL(...))`, so copy the whole `dist/` folder into the output and give `script` (and `wasm`). Rollup users can also build `worker-thread.mjs` as a second entry.
785
831
  - **Vite, webpack 5 and Rsbuild** find the script themselves. So does **Parcel 2**, once it reads package `exports` (without this it can't resolve `agglomerative-clustering/worker`):
786
832
 
787
833
  ```json
@@ -825,9 +871,9 @@ Some hosts load a plugin as one file, or a few fixed ones, so the package's `.wa
825
871
  - **Vitest** needs no configuration, in node, jsdom, happy-dom and browser mode. **Storybook** (Vite builder) works as it is.
826
872
  - **Jest** works in its default CommonJS mode, in the node and jsdom environments, with both entries, without transforms or `--experimental-vm-modules` (both have CommonJS builds). Mocha and `node:test` work too.
827
873
  - **jsdom and happy-dom** have no `ImageData` (install `canvas`, `@napi-rs/canvas` or `skia-canvas`, or pass `{ data, format: 'rgba', width }`) and no `Worker`: the worker entry then uses a Node worker thread, which is fine for tests. Results come back in the class of the `ImageData` you passed.
828
- - **Leaks.** Call `terminate()` (from `agglomerative-clustering/worker`, or on a `createWorker()`) in `afterAll`. It doesn't stop Jest from exiting, but each test file otherwise leaves a worker thread, 15 to 30 MB, in the process until the run ends.
874
+ - **Leaks.** Call `terminate()` (from `agglomerative-clustering/worker`, or on a `createWorker()`) in `afterAll`. It doesn't stop Jest from exiting, but each test file otherwise leaves a worker thread, 15 to 30 MB, in the process until the run ends (or until the garbage collector gets to a dropped `createWorker()`, which may not happen in a test run).
829
875
  - **Mocking.** Mock the module with a factory (`vi.mock('agglomerative-clustering', () => ({ getPalette: vi.fn(...) }))`), or in Vitest keep the real `Palette` with `importOriginal`. Build fake palettes with `new Palette(bytes, colorSpace)`, and fake errors as `Object.assign(new Error(message), { code: 'invalid-argument' })` (`isCodedError` accepts them).
830
- - **Snapshots.** Palettes (and swatches, indices, mapped pixels) are identical across platforms, Node versions and browsers, and stay the same within a major version: snapshot them. Clustering bytes are not promised to stay the same, so don't hash them. `toEqual` doesn't see a palette's `colorSpace`: compare it explicitly.
876
+ - **Snapshots.** Palettes (and swatches, indices, mapped pixels) are identical across platforms, Node versions and browsers, and within a major version change only for a bug fix that the changelog names: snapshot them, and expect to update a snapshot when such a fix lands. Clustering bytes are not promised to stay the same, so don't hash them. `toEqual` doesn't see a palette's `colorSpace`: compare it explicitly.
831
877
  - Fake timers don't affect it. An unawaited call still running at the end holds Jest open until it finishes.
832
878
 
833
879
  ### Writing a package that wraps it
@@ -858,11 +904,14 @@ const swatches = await run('getSwatches', image, 8, { precision: 6, signal: cont
858
904
  ```
859
905
 
860
906
  - **Small images wait behind large ones** in a shared pool. If you serve both, give large uploads a pool of their own.
861
- - **Memory:** one image can need up to 2 GB in a worker, so a pool of four can peak near 8 GB on hostile input; a pixel cap and `precision: 6` keep it to a fraction of that. Memory comes back after a large image (below).
907
+ - **Memory:** one image can need up to 2 GB in a worker, so a pool of four can peak near 8 GB on hostile input; a pixel cap and `precision: 6` keep it to a fraction of that. Memory comes back after a large image, but not at once (below).
908
+ - **Address space:** each WebAssembly instance (the main entry's, and one per worker) reserves about 10 GB of *virtual* memory up front on 64-bit engines, of which it uses only what it needs. A virtual-memory limit (`ulimit -v`) refuses that reservation, which shows as `wasm-load-failed`; limit resident memory instead. A container's memory limit (a cgroup's `memory.max`, Docker's `--memory`) applies to what is used, but when it is reached the kernel kills the process: there is no `out-of-memory` error to catch, so cap the image size below it.
862
909
  - **Stored clusterings:** make them with `precision: 6`. An exact clustering of a noisy 4-megapixel image is 78 MB, against 5.5 MB at `precision: 6`. Read back, wrap the bytes once with `new Clustering(bytes)` and keep that object while you use it: its checksum is checked the first time an object is used (2 to 3 ms for a photo's clustering).
863
910
  - Running out of memory is a catchable `out-of-memory` error, and `terminate()` on each worker shuts the pool down.
864
911
 
865
- **Large images.** Time and memory grow with the number of *distinct colours*, not just pixels: a 12-megapixel photo takes 2 to 8 s exact (0.2 to 0.9 million distinct colours) and 0.1 to 0.4 s with `precision: 6`, and 36 megapixels of random noise (the worst case) about 6 s with `precision: 6`. (Times are from an idle machine; a busy or throttled one, a laptop on battery or a CI runner can be several times slower.) One WebAssembly instance can use up to 2 GB; an image that needs more is rejected with `out-of-memory`, and later calls work normally. WebAssembly memory only grows, so after a call that leaves it above 256 MB the library replaces the instance (the next call loads a fresh one, in milliseconds): a server's memory comes back down after a huge image instead of staying at its peak.
912
+ **Large images.** Time and memory grow with the number of *distinct colours*, not just pixels: a 12-megapixel photo takes 2 to 8 s exact (0.2 to 0.9 million distinct colours) and 0.1 to 0.4 s with `precision: 6`, and 36 megapixels of random noise (the worst case) about 6 s with `precision: 6`. (Times are from an idle machine; a busy or throttled one, a laptop on battery or a CI runner can be several times slower.) One WebAssembly instance can use up to 2 GB, so an image's pixel data must stay under about 1.9 GB (about 480 megapixels of RGBA: 22000 × 22000 works); an image that needs more is rejected with `out-of-memory`, and later calls work normally. WebAssembly memory only grows, so after a call that leaves it above 256 MB the library drops the instance (the next call loads a fresh one, in milliseconds). The engine frees the old instance's memory at its next garbage collection, which in an idle process or worker can be much later: a worker that clustered 12 megapixels of noise held about 1 GB until it had served about a hundred more calls. `terminate()` frees a worker's memory at once.
913
+
914
+ The unsliced steps between slices (see [Cancelling and progress](#cancelling-and-progress)) take up to about 150 ms on a 12-megapixel photo, but grow with the number of distinct colours: on 12 megapixels of noise at full precision one takes over a second, and progress moves unevenly. `precision: 6` keeps them short.
866
915
 
867
916
  ### Troubleshooting
868
917
 
@@ -882,6 +931,10 @@ const swatches = await run('getSwatches', image, 8, { precision: 6, signal: cont
882
931
  | `wasm-load-failed` mentioning a Content-Security-Policy | The page or extension forbids compiling WebAssembly. | Add `'wasm-unsafe-eval'` to `script-src`: the page's for the worker entry's worker, also from a content script. |
883
932
  | `wasm-load-failed`: "is not WebAssembly" | An error page (a 404, or a server's fallback page) was served in place of `clustering.wasm`. | Open the `.wasm` URL in the browser; copy the file where it is expected, or say where it is with `init({ wasm })`. |
884
933
  | `worker-failed` with the worker entry from a CDN, under a CSP | `worker-src` allows `blob:` but not the CDN the worker imports from. | `worker-src blob: <the CDN's origin>`. |
934
+ | `worker-failed` in a serverless function, "Cannot find module … worker-thread.mjs" | The bundler or file tracer left the worker's files out. | Leave the package external, or ship `dist/` and pass `createWorker({ script })`: see [Serverless functions](#serverless-functions-aws-lambda-vercel-netlify). |
935
+ | `worker-failed` under Yarn Plug'n'Play, a path inside a `.zip` | Node can't load the worker's ES modules from the zip without Yarn's loader. | Run with `yarn node`, or `yarn unplug agglomerative-clustering`. |
936
+ | `wasm-load-failed` under `ulimit -v` | Each instance reserves about 10 GB of address space. | Limit resident memory instead (see [Performance and limits](#performance-and-limits)). |
937
+ | Threads and memory grow in a long-running process | `createWorker()` workers that were dropped without `terminate()`. | Reuse a few workers, or terminate each one. |
885
938
  | TypeScript says a `Uint8Array` isn't a `Clustering` | Stored bytes lost their type. | `new Clustering(bytes)` (see "Palette and Clustering"). |
886
939
 
887
940
  ## More
Binary file
package/dist/index.cjs CHANGED
@@ -127,6 +127,11 @@ const hasSimd = () => {
127
127
  // Node itself (or Bun), not a runtime that imitates it: Cloudflare Workers with nodejs_compat and Deno also define
128
128
  // process.versions.node, but their navigator.userAgent says what they are (Node 20 has no navigator at all).
129
129
  const isNodeLike = !!(globalThis.process && globalThis.process.versions && globalThis.process.versions.node) && (typeof navigator === 'undefined' || /^(Node\.js|Bun)\//.test(String(navigator.userAgent)));
130
+ // A browser page or worker, as opposed to a server-side runtime that isn't Node (Cloudflare Workers, Vercel's edge runtime,
131
+ // Deno Deploy): only those have a document, a worker scope or a browser's user agent.
132
+ const isBrowserLike = () => typeof document !== 'undefined' || typeof WorkerGlobalScope !== 'undefined' || typeof navigator !== 'undefined' && /Mozilla\//.test(String(navigator.userAgent));
133
+ // Where the advice for a server runtime ends: a deployment that left the .wasm behind.
134
+ const deployAdvice = "In a serverless deployment (AWS Lambda, Vercel or Netlify functions), the bundler or file tracer may have left the package's dist/ files out: include node_modules/agglomerative-clustering/dist in the function's files, or leave the package unbundled (external).";
130
135
  // Emscripten appends advice about its own debug build, which doesn't apply to this package's users.
131
136
  const assertionsAdvice = /\s*\(?Build with -sASSERTIONS for more info\.?\)?/;
132
137
  const wasmLoadFailed = (cause, given) => {
@@ -146,7 +151,14 @@ const wasmLoadFailed = (cause, given) => {
146
151
  // Where an explicit init({ wasm }) URL or path pointed, to name in the message.
147
152
  const where = typeof given === 'string' ? ` (${given})` : '';
148
153
  let advice;
149
- if (/Content.Security.Policy|blocked by CSP|wasm-eval|unsafe-eval|CompileError: .*(disallowed|refused)/i.test(text)) {
154
+ if (/disallowed by embedder|code generation disallowed/i.test(text) && !isNodeLike && !isBrowserLike()) {
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.";
157
+ } else if (/(memory|allocate)/i.test(text) && /(could not|cannot|can't|failed to|out of) (allocate|memory|reserve)/i.test(text)) {
158
+ // A 64-bit engine reserves the module's whole address range up front (about 10 GB of virtual memory per instance),
159
+ // though it only uses what it needs; an address-space limit refuses that reservation.
160
+ advice = "The engine couldn't reserve memory for the module. Each instance reserves a large range of address space up front (about 10 GB of virtual memory on 64-bit engines, of which it uses only what it needs), so a limit on virtual memory (ulimit -v, or a container's address-space limit) refuses it: lift that limit, or run fewer instances (each worker has its own).";
161
+ } else if (/Content.Security.Policy|blocked by CSP|wasm-eval|unsafe-eval|CompileError: .*(disallowed|refused)/i.test(text)) {
150
162
  // Chrome's message names 'wasm-eval', which Chrome rejects in an extension's manifest; 'wasm-unsafe-eval' is the one.
151
163
  // Which policy applies depends on where the module is compiled: a worker started from a blob: URL (the worker entry
152
164
  // does that for a script from another origin, a content script's included) follows the page's.
@@ -162,6 +174,14 @@ const wasmLoadFailed = (cause, given) => {
162
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`;
163
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 }).";
164
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.";
181
+ } else if (/XMLHttpRequest is not defined|both async and sync fetching|failed to fetch|NetworkError|404|ENOENT/i.test(text) && isNodeLike) {
182
+ // In Node the file is read from disk, so the browser's reasons (a CSP, an extension's resources) don't apply.
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)';
184
+ advice = given ? `Check that path: it must be this package's clustering.wasm (relative paths are read from the working directory, ${globalThis.process.cwd()}). ${deployAdvice}` : `Keep the package's dist/ files together, or say where clustering.wasm is with init({ wasm: path }). ${deployAdvice}`;
165
185
  } else if (/XMLHttpRequest is not defined|both async and sync fetching|failed to fetch|NetworkError|404|ENOENT/i.test(text)) {
166
186
  reason = given ? `the .wasm file could not be fetched${where}` : 'the .wasm file could not be fetched (the package looks for clustering.wasm next to its script)';
167
187
  const blocked = " If it is there, something may block the request: a Content-Security-Policy's connect-src, or, in a browser extension's content script, a clustering.wasm not listed in web_accessible_resources (the browser's console names the URL).";
@@ -173,7 +193,13 @@ const wasmLoadFailed = (cause, given) => {
173
193
  if (/Invalid URL/i.test(reason)) {
174
194
  reason = "the package doesn't know where clustering.wasm is (bundled into CommonJS, it has lost its own URL)";
175
195
  }
176
- advice = "If the package was bundled (a server build, a CommonJS bundle from esbuild or Rollup, a plugin's single file), the bundler moved clustering.wasm or dropped what tells the package where it is, and the package's own copy wasn't found from the working directory either: leave the package out of the bundle (mark it external; in Next.js, serverExternalPackages: ['agglomerative-clustering']), or say where the file is with init({ wasm: path }) or give its bytes.";
196
+ advice = `If the package was bundled (a server build, a CommonJS bundle from esbuild or Rollup, a plugin's single file), the bundler moved clustering.wasm or dropped what tells the package where it is, and the package's own copy wasn't found from the working directory either: leave the package out of the bundle (mark it external; in Next.js, serverExternalPackages: ['agglomerative-clustering']), or say where the file is with init({ wasm: path }) or give its bytes. ${deployAdvice}`;
197
+ } else if (!isBrowserLike()) {
198
+ // A server runtime that isn't Node (an edge runtime, Deno Deploy): it has no page, so a CSP or a 404 page are unlikely.
199
+ if (/Invalid URL/i.test(reason)) {
200
+ reason = "the package can't tell where clustering.wasm is in this runtime";
201
+ }
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 README shows how for Cloudflare Workers and Next.js); elsewhere its bytes or URL.";
177
203
  } else {
178
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 }).";
179
205
  }
@@ -253,6 +279,14 @@ const nodeWasmFile = async wasm => {
253
279
  }
254
280
  const isFileUrl = /^file:/i.test(text);
255
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
+ }
256
290
  if (!isFileUrl && /^[a-z][a-z0-9+.-]+:/i.test(text) && !/^[a-z]:[\\/]/i.test(text)) {
257
291
  return null;
258
292
  }
@@ -349,7 +383,23 @@ const retireIfLarge = instance => {
349
383
  discard(instance);
350
384
  }
351
385
  };
352
- 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
+ };
353
403
  const unpack = (wasm, pointer) => {
354
404
  const lengthBuffer = new Uint8Array(wasm.HEAPU8.subarray(pointer, pointer + 4));
355
405
  const length = lengthBuffer[0] | lengthBuffer[1] << 8 | lengthBuffer[2] << 16 | lengthBuffer[3] << 24;
@@ -468,6 +518,7 @@ const load = image => {
468
518
  if ((0, _shared.isDetached)(image.data)) {
469
519
  throw (0, _shared.fail)('invalid-argument', "Invalid image: the ImageData's pixels were transferred away (detached), for example to a worker created with transfer: true.", 'image');
470
520
  }
521
+ (0, _shared.checkImageDataPixels)(image);
471
522
  return {
472
523
  data: held(bytes(image.data)),
473
524
  format: 'rgba',
@@ -699,18 +750,27 @@ const checkNotEmpty = (palette, image, cutoff) => {
699
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.
700
751
  const matchingSpace = (o, palette) => o.colorSpaceGiven ? o.colorSpace : _shared.colorSpaces[(0, _shared.isPalette)(palette) ? palette.colorSpace : 'rgb'];
701
752
 
753
+ // Allocates `length` bytes in the WASM heap, or throws a coded out-of-memory error.
754
+ const allocate = (wasm, length) => {
755
+ if (length >= _shared.maxBytes) {
756
+ throw (0, _shared.tooLarge)(length);
757
+ }
758
+ const pointer = wasm._malloc(length);
759
+ if (!pointer) {
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.");
761
+ }
762
+ return pointer;
763
+ };
764
+
702
765
  // Copies each buffer into the WASM heap, calls `fn` with their pointers, and returns the unpacked output,
703
- // freeing everything afterwards.
704
- 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) => {
705
768
  const pointers = [];
706
769
  let outputPointer = 0;
707
770
  let aborted = false;
708
771
  try {
709
772
  for (const buffer of buffers) {
710
- const pointer = wasm._malloc(buffer.length);
711
- if (!pointer) {
712
- throw (0, _shared.fail)('out-of-memory', "Failed to allocate WASM memory.");
713
- }
773
+ const pointer = allocate(wasm, buffer.length);
714
774
  pointers.push(pointer);
715
775
  wasm.HEAPU8.set(buffer, pointer);
716
776
  }
@@ -727,7 +787,7 @@ const call = (wasm, buffers, fn) => {
727
787
  }
728
788
  aborted = true;
729
789
  discard(wasm);
730
- throw outOfMemory();
790
+ throw outOfMemory(buffers[0].length, precision);
731
791
  } finally {
732
792
  // After an abort the instance is being thrown away, and its allocator can't be trusted.
733
793
  if (!aborted) {
@@ -795,10 +855,7 @@ const isControlled = o => o.signal !== undefined || o.onProgress !== undefined;
795
855
  // Clusters in slices and returns the clustering. `share` is the part of the whole call's progress this takes.
796
856
  const clusterInSlices = async (wasm, image, o, report, share) => {
797
857
  checkAborted(o.signal);
798
- const imagePointer = wasm._malloc(image.data.length);
799
- if (!imagePointer) {
800
- throw (0, _shared.fail)('out-of-memory', "Failed to allocate WASM memory.");
801
- }
858
+ const imagePointer = allocate(wasm, image.data.length);
802
859
  let job = 0;
803
860
  let aborted = false;
804
861
  try {
@@ -826,7 +883,7 @@ const clusterInSlices = async (wasm, image, o, report, share) => {
826
883
  }
827
884
  aborted = true;
828
885
  discard(wasm);
829
- throw outOfMemory();
886
+ throw outOfMemory(image.data.length, o.precision);
830
887
  } finally {
831
888
  if (!aborted) {
832
889
  if (job) {
@@ -860,7 +917,7 @@ const getClustering = async (image, options) => {
860
917
  report(1);
861
918
  return (0, _shared.markClustering)(clustering);
862
919
  }
863
- 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));
864
921
  };
865
922
  exports.getClustering = getClustering;
866
923
  const getPalette = async (image, k, options) => {
@@ -876,7 +933,7 @@ const getPalette = async (image, k, options) => {
876
933
  report(1);
877
934
  return (0, _shared.markPalette)(palette, (0, _shared.colorSpaceName)(o.colorSpace));
878
935
  }
879
- 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));
880
937
  };
881
938
  exports.getPalette = getPalette;
882
939
  const getPaletteFromClustering = async (clustering, k, ...extra) => {
@@ -898,6 +955,14 @@ const weightsOf = (wasm, clustering, header, k) => {
898
955
  return new Float64Array(bytes.buffer, bytes.byteOffset, bytes.length / 8);
899
956
  };
900
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
+
901
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
902
967
  // arrays line up by construction. Weights are pixels: fully transparent pixels count 0 and partly transparent ones in
903
968
  // proportion to their opacity, as in clustering. Shares are the weights divided by their total, so they sum to 1.
@@ -905,9 +970,7 @@ const getSwatchesFromClustering = async (clustering, k, ...extra) => {
905
970
  const header = (0, _shared.readHeader)(clustering);
906
971
  k = check(k);
907
972
  noOptions('getSwatchesFromClustering', extra);
908
- if (header.version < 3) {
909
- 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');
910
- }
973
+ needsWeights(header);
911
974
  clustering = held(clustering);
912
975
  const wasm = Module || (await acquire());
913
976
  const palette = (0, _shared.markPalette)(call(wasm, [clustering], clusteringPointer => wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k)), (0, _shared.colorSpaceName)(header.colorSpace));
@@ -945,6 +1008,7 @@ exports.getSwatches = getSwatches;
945
1008
  const getClusteringInfo = async (clustering, ...extra) => {
946
1009
  const header = (0, _shared.readHeader)(clustering);
947
1010
  noOptions('getClusteringInfo', extra);
1011
+ needsWeights(header);
948
1012
  const colors = header.merges + (clustering.length >= header.headerLength + 3 ? 1 : 0);
949
1013
  const info = {
950
1014
  formatVersion: header.version,
@@ -952,13 +1016,10 @@ const getClusteringInfo = async (clustering, ...extra) => {
952
1016
  precision: header.precision,
953
1017
  transparent: header.transparent === 0 ? false : header.transparent,
954
1018
  maxColors: colors,
955
- totalWeight: null,
1019
+ totalWeight: 0,
956
1020
  mse: null,
957
1021
  explained: null
958
1022
  };
959
- if (header.version < 3) {
960
- return info;
961
- }
962
1023
  const view = new DataView(clustering.buffer, clustering.byteOffset, clustering.byteLength);
963
1024
  const pixels = 2 ** clustering[7] / (clustering[6] === 1 ? 255 : 1);
964
1025
  const total = view.getUint32(8, true);
@@ -1002,7 +1063,7 @@ const quantize = async (image, k, options) => {
1002
1063
  report(1);
1003
1064
  return mapped;
1004
1065
  }
1005
- 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));
1006
1067
  };
1007
1068
  exports.quantize = quantize;
1008
1069
  const quantizeFromClustering = async (image, clustering, k, options) => {
@@ -1047,7 +1108,7 @@ const quantizeToIndices = async (image, k, options) => {
1047
1108
  report(1);
1048
1109
  return indexed;
1049
1110
  }
1050
- 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));
1051
1112
  };
1052
1113
  exports.quantizeToIndices = quantizeToIndices;
1053
1114
  const quantizeToIndicesFromClustering = async (image, clustering, k, options) => {