agglomerative-clustering 3.0.0-beta.1 → 3.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/README.md CHANGED
@@ -10,7 +10,7 @@
10
10
 
11
11
  Most colour quantizers answer one question: *give me k colours*. Ask for a different k and they start over. This library clusters an image's colours once, into a complete tree, and every palette size is then a cheap cut of that tree. A colour-count slider, or a set of 8, 16, 32 and 64 colour versions, costs one clustering instead of one per size.
12
12
 
13
- - **Every palette size from one pass.** Clustering a photo takes about 100 ms. After that, a palette of any size takes about 0.4 ms.
13
+ - **Every palette size from one pass.** Clustering a photo takes about 70 ms. After that, a palette of any size takes about 0.4 ms.
14
14
  - **Palettes nest, in a stable order.** The 16-colour palette is the 32-colour one with pairs merged, so swatches don't jump around as the count changes.
15
15
  - **It knows each colour's share of the image,** so you can show swatches with percentages, or pick the smallest palette that meets an error target.
16
16
  - **Transparency-aware.** A logo's transparent background never ends up in its palette. GIF and palette PNG output are built in.
@@ -23,9 +23,11 @@ Most colour quantizers answer one question: *give me k colours*. Ask for a diffe
23
23
  ## Install
24
24
 
25
25
  ```sh
26
- npm install agglomerative-clustering
26
+ npm install agglomerative-clustering@next
27
27
  ```
28
28
 
29
+ **3.0 is in beta.** This page describes 3.0, which is published under the `next` tag until its release; a plain `npm install agglomerative-clustering` still gives 2.0 (see [its README](https://www.npmjs.com/package/agglomerative-clustering/v/2.0.0) and [what changed](docs/migrating.md)).
30
+
29
31
  It runs on Node 20.19+ and 22.12+, and in browsers with WebAssembly SIMD (see [Where it runs](#where-it-runs)).
30
32
 
31
33
  ## Quick start
@@ -73,7 +75,7 @@ Those three are all you need to get started. The rest of this page is organised
73
75
 
74
76
  ```
75
77
  image ──▶ getClustering ──▶ a clustering ──▶ cut to k colours ──▶ a palette ──▶ map the pixels ──▶ reduced image
76
- once, ~100 ms bytes you can under 1 ms, flat RGB a few ms,
78
+ once, ~70 ms bytes you can under 1 ms, flat RGB a few ms,
77
79
  store any k bytes any palette
78
80
  ```
79
81
 
@@ -110,19 +112,19 @@ Five words are used throughout:
110
112
 
111
113
  ### How it compares
112
114
 
113
- The 24 Kodak photos (768×512) at 64 colours. "Error vs ours" is mean squared error relative to this library, so 1.08× means 8% more error. Every palette is mapped to pixels the same way, so palettes are compared like for like. Times are medians per image, in WASM on Node 22.
115
+ The 24 Kodak photos (768×512) at 64 colours. "Error vs ours" is mean squared error relative to this library, so 1.08× means 8% more error. Every palette is mapped to pixels the same way, so palettes are compared like for like. Times are medians per image, in WASM on Node 24 on a laptop (Intel Core i7-1185G7).
114
116
 
115
117
  | Library | PSNR | Error vs ours | One palette | Palettes at 16/64/128/256 |
116
118
  |---|---|---|---|---|
117
- | **agglomerative-clustering** | **35.72 dB** | **1.00×** | 97 ms | **99 ms** |
118
- | agglomerative-clustering, `precision: 6` | 35.70 dB | 1.00× | 31 ms | 31 ms |
119
- | libimagequant (pngquant's engine) | 35.39 dB | 1.08× | 134 ms | 552 ms |
120
- | image-q Wu | 35.51 dB | 1.05× | 740 ms | 3387 ms |
121
- | image-q NeuQuant | 34.41 dB | 1.35× | 609 ms | 3461 ms |
122
- | MMCQ (color-thief's algorithm) | 32.53 dB | 2.08× | 24 ms | 120 ms |
123
- | image-q RgbQuant | 31.95 dB | 2.38× | 385 ms | 1535 ms |
119
+ | **agglomerative-clustering** | **35.72 dB** | **1.00×** | 70 ms | **69 ms** |
120
+ | agglomerative-clustering, `precision: 6` | 35.70 dB | 1.00× | 24 ms | 23 ms |
121
+ | libimagequant (pngquant's engine) | 35.39 dB | 1.08× | 79 ms | 323 ms |
122
+ | image-q Wu | 35.51 dB | 1.05× | 532 ms | 2404 ms |
123
+ | image-q NeuQuant | 34.41 dB | 1.35× | 428 ms | 2562 ms |
124
+ | MMCQ (color-thief's algorithm) | 32.53 dB | 2.08× | 19 ms | 98 ms |
125
+ | image-q RgbQuant | 31.95 dB | 2.38× | 242 ms | 1006 ms |
124
126
 
125
- The `precision: 6` row comes from a separate run on the same machine. Full results at every palette size, on synthetic images too, with ΔE2000 and the method, are in [bench/COMPARISON.md](bench/COMPARISON.md); reproduce them with `node bench/run.js`. These numbers are a snapshot, so expect them to move with the hardware and the versions.
127
+ All rows are from one run. Full results at every palette size, on synthetic images too, with ΔE2000 and the method, are in [bench/COMPARISON.md](bench/COMPARISON.md); reproduce them with `node bench/run.js`. These numbers are a snapshot, so expect them to move with the hardware and the versions.
126
128
 
127
129
  ## Guides
128
130
 
@@ -181,14 +183,18 @@ gif.finish();
181
183
  const bytes = gif.bytes();
182
184
  ```
183
185
 
184
- **A palette PNG** with [fast-png](https://github.com/image-js/fast-png): the same call, then give the transparent entry alpha 0:
186
+ **A palette PNG** with [fast-png](https://github.com/image-js/fast-png): the same call, then move the transparent entry to the front and give it alpha 0. A PNG lists alpha for the first palette entries, in order, and fast-png writes only the alphas below 255, so the transparent entry has to come first or the alpha lands on the wrong colour:
185
187
 
186
188
  ```js
187
189
  import { encode } from 'fast-png';
188
190
 
191
+ // Swap the transparent entry with entry 0 (when there is one), in the palette and in the indices.
192
+ const t = transparentIndex ?? 0;
193
+ const swap = (i) => (i === t ? 0 : i === 0 ? t : i);
189
194
  const png = encode({
190
- width: image.width, height: image.height, data: indices, depth: 8, channels: 1,
191
- palette: colors.map((color, i) => [...color, i === transparentIndex ? 0 : 255]),
195
+ width: image.width, height: image.height, depth: 8, channels: 1,
196
+ data: indices.map(swap),
197
+ palette: colors.map((_, i) => [...colors[swap(i)], i === 0 && transparentIndex !== null ? 0 : 255]),
192
198
  });
193
199
  ```
194
200
 
@@ -196,7 +202,7 @@ With at most 256 entries, `indices` is a `Uint8Array`, as these formats need (`i
196
202
 
197
203
  ### Off the main thread
198
204
 
199
- Clustering a photo takes about 100 ms, too long to run on a page's main thread while someone drags a slider. The worker entry has the same functions, run in a Web Worker (or a worker thread in Node):
205
+ Clustering a photo takes about 70 ms, too long to run on a page's main thread while someone drags a slider. The worker entry has the same functions, run in a Web Worker (or a worker thread in Node):
200
206
 
201
207
  ```js
202
208
  import { quantize } from 'agglomerative-clustering/worker'; // same API, one shared worker
@@ -211,12 +217,21 @@ import { createWorker } from 'agglomerative-clustering/worker';
211
217
  const worker = createWorker();
212
218
  const handle = await worker.cluster(imageData, { precision: 6 });
213
219
 
220
+ let controller = null;
214
221
  slider.oninput = async () => {
215
- ctx.putImageData(await handle.quantize(Number(slider.value), { dither: true }), 0, 0);
222
+ controller?.abort(); // a size the slider has already moved past isn't worth finishing
223
+ controller = new AbortController();
224
+ try {
225
+ ctx.putImageData(await handle.quantize(Number(slider.value), { dither: true, signal: controller.signal }), 0, 0);
226
+ } catch (error) {
227
+ if (error.name !== 'AbortError') {throw error;}
228
+ }
216
229
  };
217
230
  ```
218
231
 
219
- It starts the worker with `new Worker(new URL('./worker-thread.mjs', import.meta.url))`, the form bundlers look for: CI tests Vite, webpack 5 (as Next.js uses it) and esbuild, and Parcel 2 works with its `packageExports` option on. In Node an idle worker never keeps the process alive. See the [worker reference](#worker-entry).
232
+ Calls to one worker run in order, and re-mapping a large image takes a while (about 0.3 s at 10 megapixels), so without the `signal` a fast drag queues up every size it passed through and the picture keeps changing after the slider stops. Aborting the previous call drops it from the queue. Re-cutting alone (`handle.getPalette(k)`, `handle.getSwatches(k)`) takes well under a millisecond and needs none of this.
233
+
234
+ It starts the worker with `new Worker(new URL('./worker-thread.mjs', import.meta.url))`, the form bundlers look for: CI tests Vite, webpack 5 and esbuild, Parcel 2 works with its `packageExports` option on, and for Next.js see [Next.js](#nextjs). In Node an idle worker never keeps the process alive. See the [worker reference](#worker-entry).
220
235
 
221
236
  ### Using the output
222
237
 
@@ -318,17 +333,17 @@ const out = await quantize(rgbaBytes, 32, { dither: 0.8, width: 640 });
318
333
  | Smooth gradients and skies, not dithered | 8–64 | `'oklab'` | Mean ΔE 11.0 against 13.4 at 8 colours on the synthetic gradients (two images, so a hint). |
319
334
  | Noisy or very varied images | any | `'oklab'` | Mean ΔE 7.0 against 7.9 at 64 colours (one synthetic image). |
320
335
 
321
- `'oklab'` also takes 10–30% longer. Pixel values are treated as sRGB whatever the canvas colour space; a wide-gamut `ImageData` (`display-p3`) comes back in its own colour space, unshifted, but `'oklab'` is then approximate.
336
+ `'oklab'` also takes 10–25% longer. Pixel values are treated as sRGB whatever the canvas colour space; a wide-gamut `ImageData` (`display-p3`) comes back in its own colour space, unshifted, but `'oklab'` is then approximate.
322
337
 
323
338
  How the options trade speed and quality, measured on the Kodak photos:
324
339
 
325
340
  | Setting | 16 colours ΔE2000 | 256 colours ΔE2000 | One 64-colour palette |
326
341
  |---|---|---|---|
327
- | default (`rgb`, exact) | **4.31** | 1.67 | 102 ms |
328
- | `precision: 6` | **4.29** | 1.68 | 31 ms |
329
- | `colorSpace: 'oklab'` | 4.46 | **1.60** | 104 ms |
330
- | `colorSpace: 'oklab', precision: 6` | 4.44 | 1.61 | 39 ms |
331
- | libimagequant, for reference | 4.38 | 1.61 | 147 ms |
342
+ | default (`rgb`, exact) | **4.31** | 1.67 | 70 ms |
343
+ | `precision: 6` | **4.29** | 1.68 | 24 ms |
344
+ | `colorSpace: 'oklab'` | 4.46 | **1.60** | 78 ms |
345
+ | `colorSpace: 'oklab', precision: 6` | 4.44 | 1.61 | 30 ms |
346
+ | libimagequant, for reference | 4.38 | 1.61 | 79 ms |
332
347
 
333
348
  #### Transparency
334
349
 
@@ -337,17 +352,20 @@ Three things in this library are about alpha, and they act at different stages:
337
352
  | | What it is | Stage | Effect |
338
353
  |---|---|---|---|
339
354
  | `'rgba'` input | The format of the pixels (bare `Uint8Array` and `ImageData` are RGBA; `{ data, format: 'rgb' }` has none) | input | RGB images have no alpha, so nothing below applies to them. |
340
- | `alpha` | clustering | `'weight'` (default), `'ignore'` | `'weight'` counts each RGBA pixel in proportion to its opacity, so transparent pixels don't count (exact pixel counting for opaque images). `'ignore'` counts every pixel fully, as 1.x did. Each pixel keeps its own alpha in the output. |
341
- | `transparent` | clustering; indexed output | `false` (default), `true`, or an alpha cutoff `1`–`255` | Pixels with alpha below the cutoff (128 for `true`) are left out of clustering and the rest count whole; indexed output gives them a transparent entry, counted in `k`. For GIFs and palette PNGs; see "Transparency". |
355
+ | `alpha` | An option: `'weight'` (default) or `'ignore'` | clustering | `'weight'` counts each RGBA pixel in proportion to its opacity, so transparent pixels don't count; `'ignore'` counts every pixel fully, as 1.x did. Each pixel keeps its own alpha in the output. |
356
+ | `transparent` | An option: `false` (default), `true`, or an alpha cutoff `1`–`255` | clustering; indexed output | Pixels with alpha below the cutoff (128 for `true`) are left out of clustering and the rest count whole; indexed output gives them one transparent entry, counted in `k`. |
342
357
 
343
358
  Give one or the other: `transparent` replaces `alpha`, so naming both is an error. Use `alpha` (the default) for swatches and for images that keep each pixel's alpha, and `transparent` when the destination has one transparent colour, as GIF and palette PNG do, in the clustering step too, so the palette you cut is the one you map with. Translucent palette colours are not supported.
344
359
 
360
+ 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.
361
+
345
362
  ### Palette and Clustering
346
363
  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:
347
364
 
348
365
  - **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.
349
366
  - **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.
350
367
  - **`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.
368
+ - **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.
351
369
 
352
370
  ```js
353
371
  import { Clustering, Palette, getPaletteFromClustering } from 'agglomerative-clustering';
@@ -362,6 +380,16 @@ palette.slice(0, 3) instanceof Palette; // false: slic
362
380
 
363
381
  `slice`, `subarray`, `structuredClone`, `postMessage` and storage give plain, untagged `Uint8Array`s (the worker entry carries the tags across for you). In Node, `console.log` shows the tag: `Palette(oklab) Uint8Array(6) [ … ]`.
364
382
 
383
+ **Storing a palette.** Storage keeps a palette's bytes but not its colour space, and plain bytes are matched in RGB. So an OKLab palette that you store and read back maps differently from the one you stored, without an error. Store the colour space with it and give it back:
384
+
385
+ ```js
386
+ await db.put('palette', { bytes: Array.from(palette), colorSpace: palette.colorSpace });
387
+ const { bytes, colorSpace } = await db.get('palette');
388
+ const restored = new Palette(bytes, colorSpace); // maps exactly as the palette you stored
389
+ ```
390
+
391
+ A clustering needs none of this: its colour space is in its bytes.
392
+
365
393
  ### Cancelling and progress
366
394
  Every function that takes an image accepts `signal`; the ones that cluster (`getClustering`, `getPalette`, `getSwatches`, `quantize`, `quantizeToIndices`) also accept `onProgress`:
367
395
 
@@ -374,10 +402,10 @@ const clustering = await getClustering(image, {
374
402
  ```
375
403
 
376
404
  - **Slices.** With either option, clustering runs in slices of about 10 ms, so an abort takes effect within a slice and the page stays responsive. The result is the same; slicing costs about 5% more time.
377
- - **Aborting** rejects with the signal's `reason` (an `AbortError` by default), like `fetch`. It is the one error without a `code`: check `error.name === 'AbortError'`. An already aborted signal does no work.
405
+ - **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: check `error.name === 'AbortError'`. An already aborted signal does no work.
378
406
  - **Mapping can't be interrupted** (it takes a few milliseconds). The functions that only map check the signal before they start, and don't take `onProgress`.
379
407
  - **Progress** is approximate, never goes backwards, and ends at exactly 1.
380
- - **In a worker** the worker itself stops, and a call still queued is removed without running.
408
+ - **In a worker** the work in the worker stops too, and a call still queued is removed without running. The worker keeps running for later calls.
381
409
 
382
410
  ### Errors
383
411
 
@@ -388,17 +416,18 @@ When an error is about one argument, `error.argument` names it: `'image'`, `'k'`
388
416
  | `code` | When |
389
417
  | --- | --- |
390
418
  | `invalid-argument` | A bad image, `k`, option or palette. |
391
- | `invalid-clustering` | Bytes that aren't a clustering this version can read. |
419
+ | `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). |
392
420
  | `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`). |
393
421
  | `out-of-memory` | The WebAssembly module couldn't allocate. |
394
- | `wasm-load-failed` | The WebAssembly module couldn't be loaded or compiled: a missing or blocked `.wasm` file, 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 says what to check, and `cause` is the engine's own error. |
422
+ | `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. |
395
423
  | `worker-terminated`, `worker-failed`, `invalid-handle` | Worker entry only: the worker was stopped or failed to start, or a handle was released. |
396
424
 
397
425
  ```js
398
426
  try {
399
427
  await getPaletteFromClustering(stored, 16);
400
428
  } catch (error) {
401
- if (error.code === 'unsupported-version' || error.code === 'invalid-clustering') { /* cluster the image again */ }
429
+ const code = error instanceof Error && 'code' in error ? error.code : undefined; // also compiles in strict TypeScript
430
+ if (code === 'unsupported-version' || code === 'invalid-clustering') { /* cluster the image again */ }
402
431
  else { throw error; }
403
432
  }
404
433
  ```
@@ -418,6 +447,8 @@ Both entries ship declarations, checked in CI under strict mode with `nodenext`
418
447
 
419
448
  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`.
420
449
 
450
+ 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`.
451
+
421
452
  ## API
422
453
 
423
454
  ### `getClustering(image, options?): Promise<Clustering>`
@@ -503,13 +534,13 @@ Options: `colorSpace` (defaults to the palette's own), `dither`, `width`, `signa
503
534
  Loads the WebAssembly module. Every other function does this on first use, so calling it is optional, for example to warm up before a batch. Concurrent calls share one load, and a failed load can be retried. To say where the module is, see [Loading the WebAssembly module](#loading-the-webassembly-module).
504
535
 
505
536
  ### `version: string` and `formatVersion: number`
506
- `version` is the library's version (`'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`.
537
+ `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`.
507
538
 
508
539
  ## Running it
509
540
 
510
541
  ### Where it runs
511
542
 
512
- Node 20.19+ and 22.12+ (CI tests Node 20, 22 and 24), 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.
543
+ 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.
513
544
 
514
545
  Checked by hand, not in CI: Deno 2.9, Bun 1.4 (both including the worker entry), Cloudflare Workers (a Worker bundled with esbuild, run in Miniflare) and Parcel 2.
515
546
 
@@ -524,6 +555,32 @@ await init({ wasm: wasmModule }); // a comp
524
555
 
525
556
  The package exports the file as `agglomerative-clustering/clustering.wasm`, so a bundler that imports `.wasm` files as compiled modules (Wrangler, for Cloudflare Workers) can give you `wasmModule`. A strict Content-Security-Policy needs `'wasm-unsafe-eval'` in `script-src`. `createWorker({ wasm })` passes the same option to a worker.
526
557
 
558
+ ### Next.js
559
+
560
+ Checked with Next.js 16, under Turbopack and webpack, in production builds:
561
+
562
+ - **Client components** need nothing: the main entry and the worker entry both work as they are.
563
+ - **Route handlers and Server Components** (the Node runtime) work as they are too. A server bundle moves the package's files away from each other, so the library then loads `clustering.wasm` and the worker script from the package in `node_modules`, found from the directory the server runs in. If your deployment doesn't ship `node_modules` with the server (a `standalone` output copied elsewhere, say), leave the package out of the bundle instead, which keeps its files together:
564
+
565
+ ```js
566
+ // next.config.js
567
+ export default { serverExternalPackages: ['agglomerative-clustering'] };
568
+ ```
569
+ - **The Edge runtime** can't fetch or compile a `.wasm` file itself, so import the module and pass it to `init`. The import has to be a relative path to the file (the bundler drops the `?module` query from a package path):
570
+
571
+ ```ts
572
+ import { init, getSwatches } from 'agglomerative-clustering';
573
+ // @ts-expect-error -- `?module` gives a compiled WebAssembly.Module
574
+ import wasm from '../../../node_modules/agglomerative-clustering/dist/clustering.wasm?module';
575
+
576
+ export const runtime = 'edge';
577
+
578
+ export async function POST(request: Request) {
579
+ await init({ wasm }); // loads once; later calls return at once
580
+ // … decode the upload to pixels, then getSwatches(pixels, 8)
581
+ }
582
+ ```
583
+
527
584
  ### Performance and limits
528
585
 
529
586
  **Servers.** Cap the pixel count of uploads, use `precision: 6` (it bounds the memory an image with very many colours needs), and use the worker entry so a clustering doesn't block the event loop. One worker runs one call at a time, so create a few with `createWorker()` for concurrency. Running out of memory is a catchable `out-of-memory` error.
@@ -534,12 +591,14 @@ The package exports the file as `agglomerative-clustering/clustering.wasm`, so a
534
591
 
535
592
  | What you see | Why | What to do |
536
593
  |---|---|---|
537
- | `wasm-load-failed` | The `.wasm` is missing, blocked, served from another version, or the browser has no WebAssembly SIMD. | Check the file is served and the Content-Security-Policy allows `'wasm-unsafe-eval'`; say where it is with `init({ wasm })`. |
594
+ | `wasm-load-failed` | The `.wasm` is missing, blocked, served from another version, moved by a server bundle, or the browser has no WebAssembly SIMD. | Check the file is served and the Content-Security-Policy allows `'wasm-unsafe-eval'`; say where it is with `init({ wasm })`. In Next.js, see "Next.js". |
538
595
  | `invalid-argument` naming a PNG, JPEG, … | You passed an image file's bytes, not pixels. | Decode it first (canvas or `createImageBitmap` in a browser, sharp in Node). |
539
596
  | A palette of nonsense, no error | RGB bytes were passed bare, so they were read as RGBA. | Pass `{ data, format: 'rgb', width }`, or add an alpha channel (`sharp(...).ensureAlpha()`). |
540
597
  | `invalid-argument` for a canvas, `Blob` or `ImageBitmap` | Those aren't pixels. | Draw to a canvas and pass `getImageData()`. |
541
598
  | The palette isn't sorted by how much of the image each colour covers | Palettes come in split order, so they nest. | Sort by `shares` (see "Using the output"), or accept the order. |
542
599
  | `quantizeWithPalette` maps differently from a plain-bytes palette | A `Palette` is matched in the space it was made in, unless you name one. | Pass `colorSpace` explicitly if you want a specific space. |
600
+ | A stored OKLab palette maps differently from when it was made | Storage dropped its colour space, so it is matched in RGB. | Store `palette.colorSpace` too and restore it with `new Palette(bytes, colorSpace)` (see "Palette and Clustering"). |
601
+ | `invalid-clustering` for a clustering you stored | Its bytes changed in storage (truncated, re-encoded, mixed up). | Cluster the image again, and check how it is stored: as a binary blob, or base64 that is decoded in full. |
543
602
  | `out-of-memory` | An image with very many distinct colours. | Use `precision: 6`, or a smaller image. |
544
603
  | The worker doesn't start under a bundler | The bundler didn't see the `new Worker(new URL(...))` form. | See "Off the main thread" for the bundlers that are tested. |
545
604
  | TypeScript says a `Uint8Array` isn't a `Clustering` | Stored bytes lost their type. | `new Clustering(bytes)` (see "Palette and Clustering"). |
Binary file