agglomerative-clustering 3.0.0-beta.4 → 3.0.0-beta.6
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 +207 -40
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +111 -18
- package/dist/index.d.cts +12 -1
- package/dist/index.d.ts +12 -1
- package/dist/index.mjs +97 -17
- package/dist/shared.cjs +34 -6
- package/dist/shared.mjs +29 -4
- package/dist/worker.cjs +1032 -0
- package/dist/worker.d.cts +149 -0
- package/dist/worker.d.ts +14 -1
- package/dist/worker.mjs +111 -29
- package/package.json +15 -6
package/README.md
CHANGED
|
@@ -163,6 +163,8 @@ const { explained } = await getClusteringInfo(clustering); // null only for a
|
|
|
163
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
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`.
|
|
@@ -226,6 +228,56 @@ for (const frame of frames) {
|
|
|
226
228
|
|
|
227
229
|
Cutting the clustering keeps `k` counting the transparent entry, so the palette fits a GIF. (A palette passed to `quantizeToIndicesWithPalette` has the transparent entry added to it, so 256 colours become 257 entries: cut 255.) A frame with no transparent pixels has no transparent entry, so its palette can be one entry shorter than another frame's; a GIF with one global palette should reserve a slot for it. With the worker entry, a few `createWorker()`s map frames in parallel; on small frames (320×240) the cost of sending them across outweighs the gain.
|
|
228
230
|
|
|
231
|
+
### Live video and camera frames
|
|
232
|
+
|
|
233
|
+
For a palette that follows a video or a camera (ambient light, a live theme), take each frame small and **skip frames while the worker is busy**:
|
|
234
|
+
|
|
235
|
+
```js
|
|
236
|
+
import { createWorker } from 'agglomerative-clustering/worker';
|
|
237
|
+
|
|
238
|
+
const worker = createWorker({ transfer: true }); // each frame's pixels are fresh, so move them rather than copy
|
|
239
|
+
const canvas = new OffscreenCanvas(160, 90); // a small copy is plenty for a palette
|
|
240
|
+
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
|
241
|
+
let busy = false;
|
|
242
|
+
|
|
243
|
+
const onFrame = () => {
|
|
244
|
+
if (!busy) {
|
|
245
|
+
busy = true;
|
|
246
|
+
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
|
|
247
|
+
worker.getPalette(ctx.getImageData(0, 0, canvas.width, canvas.height), 6, { precision: 6 })
|
|
248
|
+
.then(show, console.error)
|
|
249
|
+
.finally(() => {busy = false;});
|
|
250
|
+
}
|
|
251
|
+
video.requestVideoFrameCallback(onFrame);
|
|
252
|
+
};
|
|
253
|
+
video.requestVideoFrameCallback(onFrame);
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
- **Don't abort the running call when a new frame arrives**, as the slider example does. A slider stops; frames keep coming, so when each palette takes longer than a frame, every call is aborted before it finishes and no palette ever arrives (none in 6 seconds at 640×360 and 30 frames a second, in testing). Each abort also costs the worker a little. Skip frames instead, or keep only the newest one waiting.
|
|
257
|
+
- **Size.** In a worker with `precision: 6` a palette took about 20 ms at 160×90, 50 ms at 320×180, 100 ms at 640×360 and 185 ms at 1280×720 (on a busy machine, so a ceiling); exact precision is 3 to 7 times slower. 160×90 keeps up with 30 frames a second.
|
|
258
|
+
- **Flicker.** Each frame is clustered on its own, so even a still scene with a little noise gives palettes whose colours shift, swap places or split differently from frame to frame. Follow the previous palette and smooth it; in testing this cut the flicker about fourfold, for a lag of two or three frames:
|
|
259
|
+
|
|
260
|
+
```js
|
|
261
|
+
// Match each colour of the previous (smoothed) palette to its nearest new colour, then move a quarter of the way there.
|
|
262
|
+
const follow = (previous, next, weight = 0.25) => {
|
|
263
|
+
if (!previous || previous.length !== next.length) {return Array.from(next);}
|
|
264
|
+
const free = new Set(Array.from({ length: next.length / 3 }, (_, i) => i));
|
|
265
|
+
const smoothed = [];
|
|
266
|
+
for (let i = 0; i < previous.length; i += 3) {
|
|
267
|
+
let best = 0, bestDistance = Infinity;
|
|
268
|
+
for (const j of free) {
|
|
269
|
+
const d = (previous[i] - next[3 * j]) ** 2 + (previous[i + 1] - next[3 * j + 1]) ** 2 + (previous[i + 2] - next[3 * j + 2]) ** 2;
|
|
270
|
+
if (d < bestDistance) {bestDistance = d; best = j;}
|
|
271
|
+
}
|
|
272
|
+
free.delete(best);
|
|
273
|
+
for (let c = 0; c < 3; c++) {smoothed.push(previous[i + c] + weight * (next[3 * best + c] - previous[i + c]));}
|
|
274
|
+
}
|
|
275
|
+
return smoothed; // fractional values: round them for display
|
|
276
|
+
};
|
|
277
|
+
```
|
|
278
|
+
- **One palette for a whole clip** (no flicker at all) is the animated-GIF recipe above: cluster a sample of frames once.
|
|
279
|
+
- **In Node**, pipe ffmpeg's raw output (`-f rawvideo -pix_fmt rgba`) and hand each frame to a few `createWorker()`s; memory stayed flat over thousands of frames in testing.
|
|
280
|
+
|
|
229
281
|
### Off the main thread
|
|
230
282
|
|
|
231
283
|
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):
|
|
@@ -246,18 +298,18 @@ const handle = await worker.cluster(imageData, { precision: 6 });
|
|
|
246
298
|
let controller = null;
|
|
247
299
|
slider.oninput = async () => {
|
|
248
300
|
controller?.abort(); // a size the slider has already moved past isn't worth finishing
|
|
249
|
-
controller = new AbortController();
|
|
301
|
+
const mine = (controller = new AbortController());
|
|
250
302
|
try {
|
|
251
|
-
ctx.putImageData(await handle.quantize(Number(slider.value), { dither: true, signal:
|
|
303
|
+
ctx.putImageData(await handle.quantize(Number(slider.value), { dither: true, signal: mine.signal }), 0, 0);
|
|
252
304
|
} catch (error) {
|
|
253
|
-
if (
|
|
305
|
+
if (!mine.signal.aborted) {throw error;} // an abort is expected; anything else is a real failure
|
|
254
306
|
}
|
|
255
307
|
};
|
|
256
308
|
```
|
|
257
309
|
|
|
258
|
-
Calls to one worker run in order, and re-mapping a large image takes a while (0.2 to 0.3 s at 12 megapixels, about 1 s dithered), 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.
|
|
310
|
+
Calls to one worker run in order, and re-mapping a large image takes a while (0.2 to 0.3 s at 12 megapixels, about 1 s dithered), 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. This suits a slider, which stops; for a stream that never does, such as video frames, see [Live video and camera frames](#live-video-and-camera-frames).
|
|
259
311
|
|
|
260
|
-
It starts the worker with `new Worker(new URL('./worker-thread.mjs', import.meta.url))`, the form bundlers look for: CI tests Vite and webpack 5, Parcel 2 works with its `packageExports` option on, and for Next.js see [Next.js](#nextjs). Bundlers that don't emit that script (Angular's `application` builder, plain esbuild or Rollup) need it given to them: see [Angular, esbuild, Rollup and other bundlers](#angular-esbuild-rollup-and-other-bundlers). Loaded from a CDN (another origin than the page), it starts the worker through a small `blob:` script, as browsers don't start workers from other origins' scripts. In TypeScript a handle keeps the image type it was made from: a variable that holds one is `ClusteringHandle<ImageData> | null`, not a bare `ClusteringHandle`, whose `quantize` returns the general image type. In Node an idle worker never keeps the process alive. See the [worker reference](#worker-entry).
|
|
312
|
+
It starts the worker with `new Worker(new URL('./worker-thread.mjs', import.meta.url))`, the form bundlers look for: CI tests Vite and webpack 5, Parcel 2 works with its `packageExports` option on (see [below](#angular-esbuild-rollup-and-other-bundlers)), and for Next.js see [Next.js](#nextjs). Bundlers that don't emit that script (Angular's `application` builder, plain esbuild or Rollup) need it given to them: see [Angular, esbuild, Rollup and other bundlers](#angular-esbuild-rollup-and-other-bundlers). Loaded from a CDN (another origin than the page), it starts the worker through a small `blob:` script, as browsers don't start workers from other origins' scripts. In TypeScript a handle keeps the image type it was made from: a variable that holds one is `ClusteringHandle<ImageData> | null`, not a bare `ClusteringHandle`, whose `quantize` returns the general image type. In Node an idle worker never keeps the process alive. See the [worker reference](#worker-entry).
|
|
261
313
|
|
|
262
314
|
### Fixed palettes: e-ink, thread, bricks
|
|
263
315
|
|
|
@@ -271,9 +323,28 @@ const { indices } = await quantizeToIndicesWithPalette({ data, format: 'rgba', w
|
|
|
271
323
|
|
|
272
324
|
- **Undithered, every pixel gets its nearest entry** (ties go to the smaller RGB value, and a repeated entry gets its first index). Dithering diffuses the error to the neighbours, and keeps working when the palette can't reach the image's colours: saturated cyan with the seven e-ink inks comes out as an even mix of white, green and blue, not solid blue.
|
|
273
325
|
- **Colour space is a choice here too, and the answer differs from clustering.** `'oklab'` keeps skin tones from going olive when mapping *without* dithering; with small palettes of widely spaced inks (e-ink, grey levels) `'rgb'` dithers better, and OKLab brightens black and white. Try both on your panel.
|
|
274
|
-
- **Choosing N colours from a fixed set** (the 12 threads that best represent a photo out of 400)
|
|
326
|
+
- **Choosing N colours from a fixed set** (the 12 threads that best represent a photo out of 400) has no function of its own, but a few lines do it: cut the clustering, snap each cut colour to its nearest thread, and cut finer until N distinct threads appear. In testing it beat "the N most used threads" by 3 to 8 dB PSNR for N up to 12; the gain shrinks as N grows (under 1 dB at 24).
|
|
327
|
+
|
|
328
|
+
```js
|
|
329
|
+
import { getClustering, getPaletteFromClustering, quantizeToIndicesWithPalette } from 'agglomerative-clustering';
|
|
330
|
+
|
|
331
|
+
// The indices (into `threads`, flat RGB) of the n threads that best represent `image`.
|
|
332
|
+
async function chooseThreads(image, threads, n) {
|
|
333
|
+
const clustering = await getClustering(image);
|
|
334
|
+
let chosen = [];
|
|
335
|
+
for (let k = n; k <= 4 * n && chosen.length < n; k++) {
|
|
336
|
+
const cut = await getPaletteFromClustering(clustering, k);
|
|
337
|
+
// The cut palette as an image of one pixel per colour, mapped to the threads.
|
|
338
|
+
const { indices } = await quantizeToIndicesWithPalette({ data: cut, format: 'rgb' }, threads);
|
|
339
|
+
// Split order puts the coarsest colours first, so when a cut gives more than n threads, the first n are kept.
|
|
340
|
+
chosen = [...new Set(indices)].slice(0, n);
|
|
341
|
+
}
|
|
342
|
+
return chosen; // can be fewer than n for an image with few colours
|
|
343
|
+
}
|
|
344
|
+
```
|
|
275
345
|
- **Transparent pixels** map to black unless you pass `transparent`, which appends an entry for them (so a 1- or 2-bit panel has no room for it): composite the image onto your background first.
|
|
276
|
-
-
|
|
346
|
+
- **Index width:** up to 256 entries give 8-bit indices; more give 16-bit ones (`indexBits` says which), so a 257-colour palette doesn't fit an 8-bit format.
|
|
347
|
+
- **Speed:** a palette of more than 1024 colours is mapped about three times slower than one of 1024 or fewer, and dithered about four to six times slower (at 12 megapixels, about 2 s with 1024 colours against 8 to 13 s with 1025 to 2000).
|
|
277
348
|
|
|
278
349
|
### Swatches for many images (a build step)
|
|
279
350
|
|
|
@@ -293,8 +364,9 @@ Palettes are flat RGB bytes, the compact form; each format an encoder or UI want
|
|
|
293
364
|
// [[r, g, b], …]: what gifenc, fast-png, color-thief and libimagequant use
|
|
294
365
|
const colors = Array.from({ length: palette.length / 3 }, (_, i) => [palette[3 * i], palette[3 * i + 1], palette[3 * i + 2]]);
|
|
295
366
|
|
|
296
|
-
// A CSS colour, and a 0xRRGGBB number
|
|
367
|
+
// A CSS colour, a '#rrggbb' string and a 0xRRGGBB number
|
|
297
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('');
|
|
298
370
|
const hex = (i) => (palette[3 * i] << 16) | (palette[3 * i + 1] << 8) | palette[3 * i + 2];
|
|
299
371
|
|
|
300
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)
|
|
@@ -321,6 +393,47 @@ const rankedIndices = indices.map((index) => rank[index]);
|
|
|
321
393
|
const rankedTransparentIndex = transparentIndex === null ? null : rank[transparentIndex];
|
|
322
394
|
```
|
|
323
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
|
+
|
|
420
|
+
### Coming from color-thief, node-vibrant, image-q or get-image-colors
|
|
421
|
+
|
|
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.
|
|
423
|
+
|
|
424
|
+
| You used | Use | Notes |
|
|
425
|
+
|---|---|---|
|
|
426
|
+
| color-thief `getColor(image)` | `getSwatches(image, 5, { precision: 6 })`, then the entry with the largest `shares` | The heaviest cluster's average colour. |
|
|
427
|
+
| color-thief `getPalette(image, n)` | `getPalette(image, n, { precision: 6 })` | Flat bytes; `[[r, g, b], …]` is one line ("Using the output"). |
|
|
428
|
+
| get-image-colors | `getSwatches(image, n)`, and hex strings from the palette | Sort by `shares` for most-used first. |
|
|
429
|
+
| node-vibrant's named swatches (Vibrant, Muted, …) | `getSwatches(image, 16)`, then choose by saturation and lightness yourself | There are no named roles: these colours are averages, more muted than node-vibrant's picks. |
|
|
430
|
+
| image-q `buildPalette` and `applyPalette` | `quantize(image, k, { dither })`, or `getPalette` then `quantizeWithPalette` | Same idea, one call; `quantizeToIndices` for indexed output. |
|
|
431
|
+
|
|
432
|
+
- **Expect different colours.** The palettes are the ones with the least error, not the most vivid or the most frequent, so they won't match what you had (a mean ΔE2000 of 12 to 14 between matched colours, against color-thief, get-image-colors and node-vibrant, in testing).
|
|
433
|
+
- **Speed.** color-thief and node-vibrant sample pixels, so they are quick on photos; the exact default here is several times slower at photo sizes. With `precision: 6` it was level with color-thief at 12 megapixels; downscaling helps both. Against image-q it was 4 to 6 times faster.
|
|
434
|
+
- **Quality.** Undithered, the error was lower than image-q's Wu (at 16 colours, MSE 71 against 84). `dither: true` diffuses the whole error, so per-pixel error is higher than with image-q's Floyd–Steinberg while the image looks closer from a distance; a strength such as `dither: 0.5` sits between.
|
|
435
|
+
- **Missing pieces** are a few lines each: hex strings and ranking by share in [Using the output](#using-the-output), and a dominant colour above.
|
|
436
|
+
|
|
324
437
|
## Reference
|
|
325
438
|
|
|
326
439
|
### Input and output
|
|
@@ -338,6 +451,8 @@ ImageData // from a canvas: always RGBA, widt
|
|
|
338
451
|
|
|
339
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()`).
|
|
340
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
|
+
|
|
341
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).
|
|
342
457
|
|
|
343
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.
|
|
@@ -412,12 +527,12 @@ Give one or the other: `transparent` replaces `alpha`, so naming both is an erro
|
|
|
412
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.
|
|
413
528
|
|
|
414
529
|
### Palette and Clustering
|
|
415
|
-
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
|
|
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:
|
|
416
531
|
|
|
417
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.
|
|
418
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.
|
|
419
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.
|
|
420
|
-
- **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.
|
|
421
536
|
|
|
422
537
|
```js
|
|
423
538
|
import { Clustering, Palette, getPaletteFromClustering } from 'agglomerative-clustering';
|
|
@@ -453,8 +568,8 @@ const clustering = await getClustering(image, {
|
|
|
453
568
|
});
|
|
454
569
|
```
|
|
455
570
|
|
|
456
|
-
- **Slices.** With either option, clustering runs in slices of about 10 ms (a large
|
|
457
|
-
- **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
|
|
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.
|
|
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.
|
|
458
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`.
|
|
459
574
|
- **Progress** is approximate, never goes backwards, and ends at exactly 1.
|
|
460
575
|
- **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.
|
|
@@ -470,34 +585,42 @@ When an error is about one argument, `error.argument` names it: `'image'`, `'k'`
|
|
|
470
585
|
| `invalid-argument` | A bad image, `k`, option or palette. |
|
|
471
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). |
|
|
472
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`). |
|
|
473
|
-
| `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). |
|
|
474
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. |
|
|
475
|
-
| `worker-terminated`, `worker-failed`, `invalid-handle` | Worker entry only: the worker was stopped or failed
|
|
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. |
|
|
476
591
|
|
|
477
592
|
```js
|
|
593
|
+
import { getPaletteFromClustering, isCodedError } from 'agglomerative-clustering';
|
|
594
|
+
|
|
478
595
|
try {
|
|
479
596
|
await getPaletteFromClustering(stored, 16);
|
|
480
597
|
} catch (error) {
|
|
481
|
-
|
|
482
|
-
if (code === 'unsupported-version' || code === 'invalid-clustering') { /* cluster the image again */ }
|
|
598
|
+
// isCodedError narrows the type in TypeScript, and is false for errors that aren't the library's (Node's ENOENT, an abort)
|
|
599
|
+
if (isCodedError(error) && (error.code === 'unsupported-version' || error.code === 'invalid-clustering')) { /* cluster the image again */ }
|
|
483
600
|
else { throw error; }
|
|
484
601
|
}
|
|
485
602
|
```
|
|
486
603
|
|
|
604
|
+
`errorCodes` lists every code, for code that forwards them (a wrapper package re-exporting them, a bridge between processes). `isCodedError` also accepts a plain object with a known `code` and a `message`, which is what an error becomes after Electron's IPC or a `postMessage`.
|
|
605
|
+
|
|
487
606
|
Messages are for people and may change. The worker entry fails the same way as the main entry, with your call's stack (the worker's is on `cause`). A failure that isn't the library's own, such as a WebAssembly trap, has no `code`.
|
|
488
607
|
|
|
489
608
|
### Worker entry
|
|
490
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:
|
|
491
610
|
|
|
492
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.
|
|
493
|
-
- **`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).
|
|
494
615
|
|
|
495
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.
|
|
496
617
|
|
|
497
|
-
Calls run one at a time, in order. Results are transferred back without copying. Images are copied in, unless you create the worker with `createWorker({ transfer: true })`, which is faster but leaves your buffer empty. Only pixels that are a whole buffer of their own are transferred; a view into part of a larger buffer, such as a `subarray` or a small Node `Buffer`, is copied.
|
|
618
|
+
Calls run one at a time, in order. Results are transferred back without copying. Images are copied in, unless you create the worker with `createWorker({ transfer: true })`, which is faster but leaves your buffer empty. Only pixels that are a whole buffer of their own are transferred; a view into part of a larger buffer, such as a `subarray` or a small Node `Buffer`, is copied.
|
|
619
|
+
|
|
620
|
+
The entry is an ES module, with a CommonJS build for `require()` in Node and in Jest. In a browser bundle, import it rather than `require()` it: bundlers find the worker script only from the ES module, so the CommonJS build there needs `createWorker({ script })`.
|
|
498
621
|
|
|
499
622
|
### TypeScript
|
|
500
|
-
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.
|
|
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.
|
|
501
624
|
|
|
502
625
|
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`.
|
|
503
626
|
|
|
@@ -587,6 +710,9 @@ Options: `colorSpace` (defaults to the palette's own), `dither`, `width`, `signa
|
|
|
587
710
|
### `init(options?): Promise<void>`
|
|
588
711
|
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).
|
|
589
712
|
|
|
713
|
+
### `errorCodes: readonly string[]` and `isCodedError(value): boolean`
|
|
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.
|
|
715
|
+
|
|
590
716
|
### `version: string` and `formatVersion: number`
|
|
591
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: 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`.
|
|
592
718
|
|
|
@@ -596,7 +722,7 @@ Loads the WebAssembly module. Every other function does this on first use, so ca
|
|
|
596
722
|
|
|
597
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.
|
|
598
724
|
|
|
599
|
-
CI also loads `dist/` from another origin, as a page using a CDN does, in the same browsers. Checked by hand, not in CI: Deno 2.9, Bun 1.4, Cloudflare Workers (Wrangler, workerd), Vercel's edge runtime,
|
|
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).
|
|
600
726
|
|
|
601
727
|
### From a CDN, without a build step
|
|
602
728
|
|
|
@@ -607,7 +733,7 @@ CI also loads `dist/` from another origin, as a page using a CDN does, in the sa
|
|
|
607
733
|
</script>
|
|
608
734
|
```
|
|
609
735
|
|
|
610
|
-
Import `dist/index.mjs` and `dist/worker.mjs` by their paths (jsDelivr and unpkg don't follow the package's `exports` for subpaths such as `/worker`); `https://esm.sh/agglomerative-clustering@next` works too. The `.wasm` is found next to the script, so `init` needs no `wasm` option, and the worker entry starts its worker through a `blob:` script (browsers don't start workers from another origin's script). A Content-Security-Policy needs the CDN in `script-src` and `connect-src` (the `.wasm` is fetched)
|
|
736
|
+
Import `dist/index.mjs` and `dist/worker.mjs` by their paths (jsDelivr and unpkg don't follow the package's `exports` for subpaths such as `/worker`); `https://esm.sh/agglomerative-clustering@next` works too. The `.wasm` is found next to the script, so `init` needs no `wasm` option, and the worker entry starts its worker through a `blob:` script (browsers don't start workers from another origin's script). A Content-Security-Policy needs the CDN in `script-src` and `connect-src` (the `.wasm` is fetched) and `'wasm-unsafe-eval'` in `script-src`. The worker entry also needs `worker-src blob:` *and* the CDN, since the `blob:` worker imports its script from there: `worker-src blob: https://cdn.jsdelivr.net`. Pin an exact version in production, as `@3.0.0` rather than `@next`.
|
|
611
737
|
|
|
612
738
|
### Deno, Bun and Cloudflare Workers
|
|
613
739
|
|
|
@@ -637,12 +763,27 @@ await init({ wasm: await (await fetch(url)).arrayBuffer() }); // the by
|
|
|
637
763
|
await init({ wasm: wasmModule }); // a compiled WebAssembly.Module
|
|
638
764
|
```
|
|
639
765
|
|
|
640
|
-
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.
|
|
766
|
+
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`. In Node a path or `file:` URL is read from disk, also when the package is bundled into CommonJS. A strict Content-Security-Policy needs `'wasm-unsafe-eval'` in `script-src`. `createWorker({ wasm })` passes the same option to a worker.
|
|
641
767
|
|
|
642
768
|
### SvelteKit, Nuxt and other frameworks
|
|
643
769
|
|
|
644
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.
|
|
645
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
|
+
|
|
646
787
|
### Next.js
|
|
647
788
|
|
|
648
789
|
Checked with Next.js 16, under Turbopack and webpack, in production builds:
|
|
@@ -671,7 +812,7 @@ Checked with Next.js 16, under Turbopack and webpack, in production builds:
|
|
|
671
812
|
|
|
672
813
|
### Angular, esbuild, Rollup and other bundlers
|
|
673
814
|
|
|
674
|
-
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 `dist/` files out as static assets and say where they are:
|
|
675
816
|
|
|
676
817
|
```js
|
|
677
818
|
import { createWorker } from 'agglomerative-clustering/worker';
|
|
@@ -681,14 +822,20 @@ const worker = createWorker({
|
|
|
681
822
|
});
|
|
682
823
|
```
|
|
683
824
|
|
|
684
|
-
- **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.
|
|
685
826
|
|
|
686
827
|
```json
|
|
687
828
|
"assets": [{ "glob": "{worker-thread.mjs,shared.mjs,index.mjs,clustering.js,clustering.wasm}", "input": "node_modules/agglomerative-clustering/dist", "output": "assets/agglomerative-clustering" }]
|
|
688
829
|
```
|
|
689
|
-
- **esbuild and
|
|
690
|
-
- **Vite, webpack 5 and
|
|
830
|
+
- **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.
|
|
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`):
|
|
832
|
+
|
|
833
|
+
```json
|
|
834
|
+
"@parcel/resolver-default": { "packageExports": true }
|
|
835
|
+
```
|
|
836
|
+
in your `package.json`.
|
|
691
837
|
- **The main entry** can also be told where the `.wasm` is with `init({ wasm })`.
|
|
838
|
+
- **A server bundle** (esbuild or Rollup with a Node target, CommonJS or ES module): leave the package external if you ship `node_modules`. Bundled, it finds its files from the working directory, if at all: pass `init({ wasm: path })` and `createWorker({ script: path })`, with paths to copies of `dist/` that you ship.
|
|
692
839
|
|
|
693
840
|
### Electron
|
|
694
841
|
|
|
@@ -697,30 +844,41 @@ Everything works in dev and in an app packaged with `asar` (no `asarUnpack`), in
|
|
|
697
844
|
- **Keep the package external in a bundled main process** (electron-vite does by default; with webpack or esbuild mark it external). A bundle that inlines it finds the `.wasm` and worker script only when the app starts from the project directory, which a packaged app doesn't. If you must bundle it, pass `init({ wasm })` for the main entry and `createWorker({ script })` for the worker.
|
|
698
845
|
- **`nodeIntegrationInWorker: true`** is supported: the worker script talks through `self` there.
|
|
699
846
|
|
|
700
|
-
Errors lose their `code` and `argument` crossing Electron's IPC (only the message survives), so send `
|
|
847
|
+
Errors lose their `code` and `argument` crossing Electron's IPC (only the message survives), so send `{ message, code, argument }` yourself; `isCodedError` accepts that object on the other side. `nativeImage` gives BGRA pixels: swap the channels to RGBA first.
|
|
701
848
|
|
|
702
849
|
### Browser extensions
|
|
703
850
|
|
|
704
|
-
The main entry runs in every extension context: a Manifest V3 service worker, an offscreen document, extension pages and content scripts (a page's own Content-Security-Policy does not apply to a content script).
|
|
851
|
+
The main entry runs in every extension context: a Manifest V3 service worker, an offscreen document, extension pages and content scripts (a page's own Content-Security-Policy does not apply to the main entry in a content script). Tested in Chrome and in Firefox's extension pages and background.
|
|
705
852
|
|
|
706
|
-
- **Manifest CSP.** Compiling WebAssembly in the service worker, an offscreen document or an extension page needs `'wasm-unsafe-eval'` (not `'wasm-eval'`, which Chrome refuses in a manifest): `"content_security_policy": { "extension_pages": "script-src 'self' 'wasm-unsafe-eval'; object-src 'self'" }`.
|
|
707
|
-
- **A service worker has no `Worker`**, so use the main entry there, which already keeps the page's thread free. The worker entry works in an offscreen document or an extension page
|
|
708
|
-
- **Files.** With Vite and CRXJS the `.wasm` and worker script are emitted and made web-accessible for you. Without a bundler, copy `dist/*.mjs`, `clustering.js` and `clustering.wasm` into the extension and list them under `web_accessible_resources` if a content script loads them.
|
|
853
|
+
- **Manifest CSP.** Compiling WebAssembly in the service worker, an offscreen document or an extension page needs `'wasm-unsafe-eval'` (not `'wasm-eval'`, which Chrome refuses in a manifest): `"content_security_policy": { "extension_pages": "script-src 'self' 'wasm-unsafe-eval'; object-src 'self'" }`. The main entry in a content script needs nothing.
|
|
854
|
+
- **A service worker has no `Worker`**, so use the main entry there, which already keeps the page's thread free. The worker entry works in an offscreen document or an extension page. In a content script it starts its worker through a `blob:` URL, and that worker follows the *page's* policy, so it works only on pages whose CSP allows `worker-src blob:` and `'wasm-unsafe-eval'` (or has no CSP); on other pages, use the main entry in the content script, or hand the pixels to an offscreen document.
|
|
855
|
+
- **Files.** With Vite and CRXJS the `.wasm` and worker script are emitted and made web-accessible for you. Without a bundler, copy `dist/*.mjs`, `clustering.js` and `clustering.wasm` into the extension and list them under `web_accessible_resources` if a content script loads them (all of them: a `.wasm` left out fails as "could not be fetched", and only the browser's console names the key).
|
|
709
856
|
- A service worker can fetch cross-origin images with host permissions (a content script gets a tainted canvas), so cluster there. Typed arrays become plain objects through `chrome.runtime.sendMessage`: convert with `Array.from(palette)` and back with `new Uint8Array(...)`.
|
|
710
857
|
|
|
858
|
+
### Plugins and single-file hosts: Figma, VS Code, Obsidian
|
|
859
|
+
|
|
860
|
+
Some hosts load a plugin as one file, or a few fixed ones, so the package's `.wasm` and worker script can't sit next to it. Embed them, and say where everything is: in these hosts the package can't find its own files. (Tested against stand-ins for these hosts: a sandboxed iframe, a Node host process, an Electron renderer. Not inside the apps themselves.)
|
|
861
|
+
|
|
862
|
+
- **The `.wasm` as bytes.** Import it with your bundler's binary loader (esbuild: `--loader:.wasm=binary`, importing `agglomerative-clustering/clustering.wasm`) and pass the bytes: `init({ wasm: bytes })` for the main entry, `createWorker({ wasm: bytes })` for a worker. Set esbuild's `target` (such as `es2022`), or the decoder it emits may use `Uint8Array.fromBase64`, which not every runtime has. The file is about 92 KB, 122 KB as base64, and 54 KB gzipped then base64 (decompress it with `DecompressionStream` before passing it).
|
|
863
|
+
- **The worker script as a `data:` URL.** Bundle `node_modules/agglomerative-clustering/dist/worker-thread.mjs` into one ES module (esbuild `--bundle --format=esm`) and pass it as `createWorker({ script: 'data:text/javascript;base64,…', wasm: bytes })`. In a sandboxed iframe (Figma's UI) a `blob:` worker fails in Chromium; a `data:` one works. The main entry alone is often enough for a plugin's images, and needs only the bytes.
|
|
864
|
+
- **VS Code.** The extension host is Node: bundle your extension with the package external and ship it in `node_modules`, or bundle it and pass a path to a `.wasm` you ship (`init({ wasm: path.join(context.extensionPath, 'dist', 'clustering.wasm') })`); a bundled extension otherwise looks for the package from the working directory, which is not your extension's. A webview's CSP needs `'wasm-unsafe-eval'` in `script-src`, and `worker-src` for the worker entry.
|
|
865
|
+
- **Obsidian** ships `main.js`, `manifest.json` and `styles.css` only, so embed the `.wasm` bytes. Its renderer has Node's globals and a real `Worker`, so both entries work once given the bytes (and, for workers, the `data:` script).
|
|
866
|
+
- **Copying `dist/` files instead**, keep their `.mjs` names: they are ES modules by their extension. Renamed to `.js`, they need a `package.json` with `"type": "module"` next to them.
|
|
867
|
+
- **Get it wrong** and the error says so: a bundled main entry without its `.wasm` fails with `wasm-load-failed` asking for `init({ wasm })`, and a worker without its script with `worker-failed` naming `createWorker({ script })`.
|
|
868
|
+
|
|
711
869
|
### Testing code that uses it
|
|
712
870
|
|
|
713
871
|
- **Vitest** needs no configuration, in node, jsdom, happy-dom and browser mode. **Storybook** (Vite builder) works as it is.
|
|
714
|
-
- **Jest** works in its default CommonJS mode, in the node and jsdom environments, without transforms or `--experimental-vm-modules` (
|
|
715
|
-
- **jsdom and happy-dom** have no `ImageData` (install `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.
|
|
716
|
-
- **Leaks.** Call `terminate()` (from `agglomerative-clustering/worker`, or on a `createWorker()`) in `afterAll
|
|
717
|
-
- **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' })
|
|
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.
|
|
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.
|
|
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).
|
|
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).
|
|
718
876
|
- **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.
|
|
719
877
|
- Fake timers don't affect it. An unawaited call still running at the end holds Jest open until it finishes.
|
|
720
878
|
|
|
721
879
|
### Writing a package that wraps it
|
|
722
880
|
|
|
723
|
-
Make `agglomerative-clustering` a **`peerDependency`** and keep it **external** in your build (tsup `external`, Rollup `external`): the app's bundler then finds the worker script and `.wasm` once, with one copy in the output. Bundling it into your package leaves `./worker-thread.mjs` unresolved. Re-export the types you need (`CodedError`, `ErrorCode`, `ClusteringOptions`, …), check `version` against your supported range at run time, and let your users pass `wasm` and `script` through. Importing it on the server (SSR) doesn't run anything: only calls load the module.
|
|
881
|
+
Make `agglomerative-clustering` a **`peerDependency`** and keep it **external** in your build (tsup `external`, Rollup `external`): the app's bundler then finds the worker script and `.wasm` once, with one copy in the output. Bundling it into your package leaves `./worker-thread.mjs` unresolved. Re-export `errorCodes`, `isCodedError` and the types you need (`CodedError`, `ErrorCode`, `ClusteringOptions`, …), check `version` against your supported range at run time, and let your users pass `wasm` and `script` through. Importing it on the server (SSR) doesn't run anything: only calls load the module.
|
|
724
882
|
|
|
725
883
|
### Performance and limits
|
|
726
884
|
|
|
@@ -746,11 +904,14 @@ const swatches = await run('getSwatches', image, 8, { precision: 6, signal: cont
|
|
|
746
904
|
```
|
|
747
905
|
|
|
748
906
|
- **Small images wait behind large ones** in a shared pool. If you serve both, give large uploads a pool of their own.
|
|
749
|
-
- **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.
|
|
750
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).
|
|
751
910
|
- Running out of memory is a catchable `out-of-memory` error, and `terminate()` on each worker shuts the pool down.
|
|
752
911
|
|
|
753
|
-
**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
|
|
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.
|
|
754
915
|
|
|
755
916
|
### Troubleshooting
|
|
756
917
|
|
|
@@ -766,8 +927,14 @@ const swatches = await run('getSwatches', image, 8, { precision: 6, signal: cont
|
|
|
766
927
|
| `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. |
|
|
767
928
|
| `out-of-memory` | An image with very many distinct colours. | Use `precision: 6`, or a smaller image. |
|
|
768
929
|
| The worker doesn't start under a bundler (`worker-failed`, or a 404 for `worker-thread.mjs`) | The bundler didn't emit the worker script (Angular, esbuild, Rollup). | Copy the package's `dist/` files and pass `createWorker({ script })`: see [Angular, esbuild, Rollup and other bundlers](#angular-esbuild-rollup-and-other-bundlers). |
|
|
769
|
-
| Jest: "Must use import to load ES Module" | An older package version; this one loads in Jest's CommonJS mode. | Upgrade to the latest `3.0.0-beta`. |
|
|
770
|
-
| `wasm-load-failed` mentioning a Content-Security-Policy | The page or extension forbids compiling WebAssembly. | Add `'wasm-unsafe-eval'` to `script-src
|
|
930
|
+
| Jest: "Must use import to load ES Module" (or "Cannot use import statement" for `/worker`) | An older package version; this one loads in Jest's CommonJS mode, both entries. | Upgrade to the latest `3.0.0-beta`. |
|
|
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. |
|
|
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 })`. |
|
|
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. |
|
|
771
938
|
| TypeScript says a `Uint8Array` isn't a `Clustering` | Stored bytes lost their type. | `new Clustering(bytes)` (see "Palette and Clustering"). |
|
|
772
939
|
|
|
773
940
|
## More
|
package/dist/clustering.wasm
CHANGED
|
Binary file
|