agglomerative-clustering 3.0.0-beta.1 → 3.0.0-beta.3
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 +192 -49
- package/dist/clustering.js +1 -1
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +649 -830
- package/dist/index.d.cts +16 -15
- package/dist/index.d.ts +16 -15
- package/dist/index.mjs +633 -828
- package/dist/shared.cjs +202 -132
- package/dist/shared.mjs +184 -130
- package/dist/worker-thread.mjs +115 -349
- package/dist/worker.d.ts +2 -2
- package/dist/worker.mjs +480 -646
- package/package.json +4 -1
package/README.md
CHANGED
|
@@ -10,22 +10,24 @@
|
|
|
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
|
|
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.
|
|
17
17
|
- **Off the main thread.** `agglomerative-clustering/worker` runs the same API in a Web Worker or Node worker thread.
|
|
18
18
|
- **Accurate and fast.** The lowest average error of the six JavaScript quantizers we benchmarked, at about the speed of libimagequant ([numbers](#how-it-compares)).
|
|
19
|
-
- **Small and portable.**
|
|
19
|
+
- **Small and portable.** 91 KB of WebAssembly, Node and browsers, TypeScript types, no runtime dependencies, deterministic output.
|
|
20
20
|
|
|
21
21
|
[Install](#install) · [Quick start](#quick-start) · [The idea](#the-idea-in-one-minute) · [Guides](#guides) · [Reference](#reference) · [API](#api) · [Troubleshooting](#troubleshooting)
|
|
22
22
|
|
|
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, ~
|
|
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
|
|
|
@@ -92,7 +94,7 @@ Five words are used throughout:
|
|
|
92
94
|
|
|
93
95
|
- **clustering**: the tree of an image's colours. It is opaque bytes (a `Clustering`) that you can store next to the image.
|
|
94
96
|
- **palette**: flat RGB bytes, `[r, g, b, r, g, b, …]`. A `Palette` knows the colour space it was made in.
|
|
95
|
-
- **k**: the most palette entries in what you get back, in every function. A flat palette has no transparent entry, so its entries are all colours; in indexed output with `transparent`, the transparent entry is one of the `k`, so `256` is the most a GIF holds. Fewer come back when the image has fewer distinct colours.
|
|
97
|
+
- **k**: the most palette entries in what you get back, in every function. A flat palette has no transparent entry, so its entries are all colours; in indexed output with `transparent`, the transparent entry is one of the `k`, so `256` is the most a GIF holds. Fewer come back when the image has fewer distinct colours. The one exception: indexed output always keeps a colour for the visible pixels, so `k = 1` with a transparent entry gives 2.
|
|
96
98
|
- **split order**: palettes come out so that the palette for `k + 1` is the one for `k` with one colour split in two. Entries keep their place as `k` grows, but the palette is not sorted by share.
|
|
97
99
|
- **precision**: an option that groups similar colours before clustering, about 3× faster at practically the same quality.
|
|
98
100
|
|
|
@@ -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
|
|
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×** |
|
|
118
|
-
| agglomerative-clustering, `precision: 6` | 35.70 dB | 1.00× |
|
|
119
|
-
| libimagequant (pngquant's engine) | 35.39 dB | 1.08× |
|
|
120
|
-
| image-q Wu | 35.51 dB | 1.05× |
|
|
121
|
-
| image-q NeuQuant | 34.41 dB | 1.35× |
|
|
122
|
-
| MMCQ (color-thief's algorithm) | 32.53 dB | 2.08× |
|
|
123
|
-
| image-q RgbQuant | 31.95 dB | 2.38× |
|
|
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
|
-
|
|
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
|
|
|
@@ -141,7 +143,7 @@ slider.oninput = async () => {
|
|
|
141
143
|
};
|
|
142
144
|
```
|
|
143
145
|
|
|
144
|
-
A clustering is
|
|
146
|
+
A clustering of a 768×512 photo is 0.3 to 1.5 MB, typically 0.7 MB (0.2 MB with `precision: 6`). Store it next to the image if you like: its format is versioned, and `new Clustering(bytes)` gives stored bytes their type back (see [Palette and Clustering](#palette-and-clustering)).
|
|
145
147
|
|
|
146
148
|
### Swatches, and choosing a palette size
|
|
147
149
|
|
|
@@ -157,8 +159,8 @@ const clustering = await getClustering(image);
|
|
|
157
159
|
const eight = await getSwatchesFromClustering(clustering, 8);
|
|
158
160
|
|
|
159
161
|
// The smallest palette that keeps 99% of the image's colour variance (works the same in 'rgb' and 'oklab')
|
|
160
|
-
const { explained } = await getClusteringInfo(clustering);
|
|
161
|
-
const k = explained.findIndex((share) => share >= 0.99) + 1;
|
|
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
164
|
```
|
|
163
165
|
|
|
164
166
|
### GIFs and palette PNGs
|
|
@@ -168,11 +170,14 @@ const k = explained.findIndex((share) => share >= 0.99) + 1;
|
|
|
168
170
|
**A GIF** with [gifenc](https://github.com/mattdesl/gifenc), keeping a transparent background:
|
|
169
171
|
|
|
170
172
|
```js
|
|
171
|
-
import
|
|
173
|
+
import * as gifenc from 'gifenc';
|
|
174
|
+
// Bundlers read gifenc's ES module, which has the named export; plain Node reads its CommonJS build, which has it on the default.
|
|
175
|
+
const GIFEncoder = gifenc.GIFEncoder ?? gifenc.default.GIFEncoder;
|
|
172
176
|
import { quantizeToIndices } from 'agglomerative-clustering';
|
|
173
177
|
|
|
174
178
|
// k counts the transparent entry, so 256 is the most a GIF holds. `image` is { data, format: 'rgba', width, height }.
|
|
175
|
-
const { palette, indices, transparentIndex } = await quantizeToIndices(image, 256, { transparent: true });
|
|
179
|
+
const { palette, indices, indexBits, transparentIndex } = await quantizeToIndices(image, 256, { transparent: true });
|
|
180
|
+
if (indexBits !== 8) {throw new Error('unreachable: 256 entries or fewer have 8-bit indices');} // tells TypeScript `indices` is a Uint8Array
|
|
176
181
|
const colors = Array.from({ length: palette.length / 3 }, (_, i) => [palette[3 * i], palette[3 * i + 1], palette[3 * i + 2]]);
|
|
177
182
|
|
|
178
183
|
const gif = GIFEncoder();
|
|
@@ -181,22 +186,49 @@ gif.finish();
|
|
|
181
186
|
const bytes = gif.bytes();
|
|
182
187
|
```
|
|
183
188
|
|
|
184
|
-
**A palette PNG** with [fast-png](https://github.com/image-js/fast-png): the same call, then give the transparent entry alpha
|
|
189
|
+
**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
190
|
|
|
186
191
|
```js
|
|
187
192
|
import { encode } from 'fast-png';
|
|
188
193
|
|
|
194
|
+
// Swap the transparent entry with entry 0 (when there is one), in the palette and in the indices.
|
|
195
|
+
const t = transparentIndex ?? 0;
|
|
196
|
+
const swap = (i) => (i === t ? 0 : i === 0 ? t : i);
|
|
189
197
|
const png = encode({
|
|
190
|
-
width: image.width, height: image.height,
|
|
191
|
-
|
|
198
|
+
width: image.width, height: image.height, depth: 8, channels: 1,
|
|
199
|
+
data: indices.map(swap),
|
|
200
|
+
palette: colors.map((_, i) => [...colors[swap(i)], i === 0 && transparentIndex !== null ? 0 : 255]),
|
|
192
201
|
});
|
|
193
202
|
```
|
|
194
203
|
|
|
195
|
-
With at most 256 entries, `indices` is a `Uint8Array`, as these formats need (`indexBits` says so).
|
|
204
|
+
With at most 256 entries, `indices` is a `Uint8Array`, as these formats need (`indexBits` says so).
|
|
205
|
+
|
|
206
|
+
### Animated GIFs and sets of images
|
|
207
|
+
|
|
208
|
+
One palette for a whole animation (or a set of images that should share colours) keeps colours from flickering between frames. Cluster a sample of the frames as one image, by putting their pixels end to end, then map every frame with that clustering:
|
|
209
|
+
|
|
210
|
+
```js
|
|
211
|
+
import { getClustering, quantizeToIndicesFromClustering } from 'agglomerative-clustering';
|
|
212
|
+
|
|
213
|
+
// `frames` are { data, format: 'rgba', width, height }. Every 5th one, end to end, is one image to cluster.
|
|
214
|
+
const sample = frames.filter((_, i) => i % 5 === 0);
|
|
215
|
+
const pixels = new Uint8Array(sample.reduce((n, frame) => n + frame.data.length, 0));
|
|
216
|
+
let offset = 0;
|
|
217
|
+
for (const frame of sample) {pixels.set(frame.data, offset); offset += frame.data.length;}
|
|
218
|
+
const clustering = await getClustering({ data: pixels, format: 'rgba' }, { precision: 6, transparent: true });
|
|
219
|
+
|
|
220
|
+
for (const frame of frames) {
|
|
221
|
+
// The same 256 entries for every frame (transparent one included), dithered lightly to limit shimmer between frames.
|
|
222
|
+
const { palette, indices, transparentIndex } = await quantizeToIndicesFromClustering(frame, clustering, 256, { dither: 0.5 });
|
|
223
|
+
// … gif.writeFrame(indices, width, height, { palette: …, transparent: transparentIndex !== null, transparentIndex: transparentIndex ?? 0 })
|
|
224
|
+
}
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
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.
|
|
196
228
|
|
|
197
229
|
### Off the main thread
|
|
198
230
|
|
|
199
|
-
Clustering a photo takes about
|
|
231
|
+
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
232
|
|
|
201
233
|
```js
|
|
202
234
|
import { quantize } from 'agglomerative-clustering/worker'; // same API, one shared worker
|
|
@@ -211,12 +243,21 @@ import { createWorker } from 'agglomerative-clustering/worker';
|
|
|
211
243
|
const worker = createWorker();
|
|
212
244
|
const handle = await worker.cluster(imageData, { precision: 6 });
|
|
213
245
|
|
|
246
|
+
let controller = null;
|
|
214
247
|
slider.oninput = async () => {
|
|
215
|
-
|
|
248
|
+
controller?.abort(); // a size the slider has already moved past isn't worth finishing
|
|
249
|
+
controller = new AbortController();
|
|
250
|
+
try {
|
|
251
|
+
ctx.putImageData(await handle.quantize(Number(slider.value), { dither: true, signal: controller.signal }), 0, 0);
|
|
252
|
+
} catch (error) {
|
|
253
|
+
if (error.name !== 'AbortError') {throw error;}
|
|
254
|
+
}
|
|
216
255
|
};
|
|
217
256
|
```
|
|
218
257
|
|
|
219
|
-
|
|
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.
|
|
259
|
+
|
|
260
|
+
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). 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).
|
|
220
261
|
|
|
221
262
|
### Using the output
|
|
222
263
|
|
|
@@ -292,7 +333,7 @@ Every function that takes an image also takes an optional last argument of optio
|
|
|
292
333
|
|
|
293
334
|
"Clustering" means any function that builds a clustering (`getClustering`, `getPalette`, `getSwatches`, `quantize` and `quantizeToIndices`), and "mapping" means any that maps pixels to a palette (`quantize`, `quantizeFromClustering`, `quantizeWithPalette` and the indexed versions). A function that does both takes both sets of options.
|
|
294
335
|
|
|
295
|
-
Pass an ordinary object. It is copied once before use (its enumerable properties, inherited ones included, so `Object.create(defaults)` works), and an unknown key is an error.
|
|
336
|
+
Pass an ordinary object. It is copied once before use (its enumerable properties, inherited ones included, so `Object.create(defaults)` works), and an unknown key is an error, including one that another function takes: an object with both `precision` and `dither` passed to `getClustering` throws on `dither`. TypeScript doesn't catch that when the object is a variable typed `QuantizeOptions` (extra properties of a variable are allowed), so give each call the options it takes, or keep one object per stage.
|
|
296
337
|
|
|
297
338
|
```js
|
|
298
339
|
// Perceptual palettes for a photo, quickly
|
|
@@ -318,17 +359,17 @@ const out = await quantize(rgbaBytes, 32, { dither: 0.8, width: 640 });
|
|
|
318
359
|
| 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
360
|
| Noisy or very varied images | any | `'oklab'` | Mean ΔE 7.0 against 7.9 at 64 colours (one synthetic image). |
|
|
320
361
|
|
|
321
|
-
`'oklab'` also takes 10–
|
|
362
|
+
`'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
363
|
|
|
323
364
|
How the options trade speed and quality, measured on the Kodak photos:
|
|
324
365
|
|
|
325
366
|
| Setting | 16 colours ΔE2000 | 256 colours ΔE2000 | One 64-colour palette |
|
|
326
367
|
|---|---|---|---|
|
|
327
|
-
| default (`rgb`, exact) | **4.31** | 1.67 |
|
|
328
|
-
| `precision: 6` | **4.29** | 1.68 |
|
|
329
|
-
| `colorSpace: 'oklab'` | 4.46 | **1.60** |
|
|
330
|
-
| `colorSpace: 'oklab', precision: 6` | 4.44 | 1.61 |
|
|
331
|
-
| libimagequant, for reference | 4.38 | 1.61 |
|
|
368
|
+
| default (`rgb`, exact) | **4.31** | 1.67 | 70 ms |
|
|
369
|
+
| `precision: 6` | **4.29** | 1.68 | 24 ms |
|
|
370
|
+
| `colorSpace: 'oklab'` | 4.46 | **1.60** | 78 ms |
|
|
371
|
+
| `colorSpace: 'oklab', precision: 6` | 4.44 | 1.61 | 30 ms |
|
|
372
|
+
| libimagequant, for reference | 4.38 | 1.61 | 79 ms |
|
|
332
373
|
|
|
333
374
|
#### Transparency
|
|
334
375
|
|
|
@@ -337,17 +378,20 @@ Three things in this library are about alpha, and they act at different stages:
|
|
|
337
378
|
| | What it is | Stage | Effect |
|
|
338
379
|
|---|---|---|---|
|
|
339
380
|
| `'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` |
|
|
341
|
-
| `transparent` |
|
|
381
|
+
| `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. |
|
|
382
|
+
| `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
383
|
|
|
343
384
|
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
385
|
|
|
386
|
+
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.
|
|
387
|
+
|
|
345
388
|
### Palette and Clustering
|
|
346
389
|
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
390
|
|
|
348
391
|
- **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
392
|
- **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
393
|
- **`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.
|
|
394
|
+
- **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
395
|
|
|
352
396
|
```js
|
|
353
397
|
import { Clustering, Palette, getPaletteFromClustering } from 'agglomerative-clustering';
|
|
@@ -362,6 +406,16 @@ palette.slice(0, 3) instanceof Palette; // false: slic
|
|
|
362
406
|
|
|
363
407
|
`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
408
|
|
|
409
|
+
**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:
|
|
410
|
+
|
|
411
|
+
```js
|
|
412
|
+
await db.put('palette', { bytes: Array.from(palette), colorSpace: palette.colorSpace });
|
|
413
|
+
const { bytes, colorSpace } = await db.get('palette');
|
|
414
|
+
const restored = new Palette(bytes, colorSpace); // maps exactly as the palette you stored
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
A clustering needs none of this: its colour space is in its bytes.
|
|
418
|
+
|
|
365
419
|
### Cancelling and progress
|
|
366
420
|
Every function that takes an image accepts `signal`; the ones that cluster (`getClustering`, `getPalette`, `getSwatches`, `quantize`, `quantizeToIndices`) also accept `onProgress`:
|
|
367
421
|
|
|
@@ -374,31 +428,32 @@ const clustering = await getClustering(image, {
|
|
|
374
428
|
```
|
|
375
429
|
|
|
376
430
|
- **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
|
|
378
|
-
- **Mapping can't be interrupted** (it takes
|
|
431
|
+
- **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.
|
|
432
|
+
- **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`.
|
|
379
433
|
- **Progress** is approximate, never goes backwards, and ends at exactly 1.
|
|
380
|
-
- **In a worker** the worker
|
|
434
|
+
- **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
435
|
|
|
382
436
|
### Errors
|
|
383
437
|
|
|
384
438
|
Every error the library throws is an `Error` with a `code`, so you don't have to match on message text (except an abort, which rejects with the signal's own `reason`).
|
|
385
439
|
|
|
386
|
-
When an error is about one argument, `error.argument` names it: `'image'`, `'k'`, `'clustering'`, `'palette'`, `'options'`, or `'options.<name>'` (for example `'options.colorSpace'`), so a form can point at the right field. Arguments are checked in the order you pass them, so the error is about the first that is wrong.
|
|
440
|
+
When an error is about one argument, `error.argument` names it: `'image'`, `'k'`, `'clustering'`, `'palette'`, `'options'`, `'colorSpace'` (from `new Palette`), or `'options.<name>'` (for example `'options.colorSpace'`), so a form can point at the right field. Arguments are checked in the order you pass them, so the error is about the first that is wrong.
|
|
387
441
|
|
|
388
442
|
| `code` | When |
|
|
389
443
|
| --- | --- |
|
|
390
444
|
| `invalid-argument` | A bad image, `k`, option or palette. |
|
|
391
|
-
| `invalid-clustering` | Bytes that aren't a clustering this version can read. |
|
|
445
|
+
| `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
446
|
| `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
447
|
| `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. |
|
|
448
|
+
| `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
449
|
| `worker-terminated`, `worker-failed`, `invalid-handle` | Worker entry only: the worker was stopped or failed to start, or a handle was released. |
|
|
396
450
|
|
|
397
451
|
```js
|
|
398
452
|
try {
|
|
399
453
|
await getPaletteFromClustering(stored, 16);
|
|
400
454
|
} catch (error) {
|
|
401
|
-
|
|
455
|
+
const code = error instanceof Error && 'code' in error ? error.code : undefined; // also compiles in strict TypeScript
|
|
456
|
+
if (code === 'unsupported-version' || code === 'invalid-clustering') { /* cluster the image again */ }
|
|
402
457
|
else { throw error; }
|
|
403
458
|
}
|
|
404
459
|
```
|
|
@@ -418,6 +473,8 @@ Both entries ship declarations, checked in CI under strict mode with `nodenext`
|
|
|
418
473
|
|
|
419
474
|
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
475
|
|
|
476
|
+
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`.
|
|
477
|
+
|
|
421
478
|
## API
|
|
422
479
|
|
|
423
480
|
### `getClustering(image, options?): Promise<Clustering>`
|
|
@@ -483,7 +540,7 @@ The result is `{ palette, colors, indices, indexBits, transparentIndex }`, plus
|
|
|
483
540
|
- `indices`: one per pixel, a `Uint8Array` for up to 256 entries, `Uint16Array` up to 65536, else `Uint32Array`; `indexBits` (8, 16 or 32) says which.
|
|
484
541
|
- `transparentIndex`: the transparent entry's index, or `null`.
|
|
485
542
|
|
|
486
|
-
With `transparent`, RGBA pixels below the cutoff get the transparent entry (appended after the colours, and counted in `k`) and every other pixel is shown fully opaque, which is all a GIF can express, so anti-aliased edges snap to one side. The colours are chosen from the visible pixels, the same as `getPalette(image, k - 1, { transparent: true })
|
|
543
|
+
With `transparent`, RGBA pixels below the cutoff get the transparent entry (appended after the colours, and counted in `k`) and every other pixel is shown fully opaque, which is all a GIF can express, so anti-aliased edges snap to one side. The colours are chosen from the visible pixels, the same as `getPalette(image, k - 1, { transparent: true })` when the image has pixels below the cutoff; when it has none there is no transparent entry, and all `k` entries are colours. At least one colour is always kept. See [Transparency](#transparency).
|
|
487
544
|
|
|
488
545
|
```js
|
|
489
546
|
const { palette, colors, indices, transparentIndex } = await quantizeToIndices(imageData, 256, { transparent: true });
|
|
@@ -503,15 +560,45 @@ Options: `colorSpace` (defaults to the palette's own), `dither`, `width`, `signa
|
|
|
503
560
|
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
561
|
|
|
505
562
|
### `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`.
|
|
563
|
+
`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
564
|
|
|
508
565
|
## Running it
|
|
509
566
|
|
|
510
567
|
### Where it runs
|
|
511
568
|
|
|
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.
|
|
569
|
+
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.
|
|
570
|
+
|
|
571
|
+
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, SvelteKit and Nuxt, Next.js and Parcel 2 (see below).
|
|
572
|
+
|
|
573
|
+
### From a CDN, without a build step
|
|
574
|
+
|
|
575
|
+
```html
|
|
576
|
+
<script type="module">
|
|
577
|
+
import { getSwatches } from 'https://cdn.jsdelivr.net/npm/agglomerative-clustering@next/dist/index.mjs';
|
|
578
|
+
import { createWorker } from 'https://cdn.jsdelivr.net/npm/agglomerative-clustering@next/dist/worker.mjs';
|
|
579
|
+
</script>
|
|
580
|
+
```
|
|
581
|
+
|
|
582
|
+
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), `'wasm-unsafe-eval'`, and `worker-src blob:` for the worker. Pin an exact version in production, as `@3.0.0` rather than `@next`.
|
|
583
|
+
|
|
584
|
+
### Deno, Bun and Cloudflare Workers
|
|
585
|
+
|
|
586
|
+
- **Bun** needs nothing: `bun add agglomerative-clustering`, then both entries work as in Node.
|
|
587
|
+
- **Deno**: `import { getPalette } from 'npm:agglomerative-clustering@next'`, run with `--allow-read` (the `.wasm` is read from the package). Importing from a CDN URL works too, without it. The worker entry runs on Deno's `worker_threads`, which is about 3 times slower per call than the main entry; for a few calls, use the main entry. Deno doesn't install npm versions less than a day old by default, so on the day of a release it may quietly install the previous one (`"minimumDependencyAge": 0` in `deno.json` turns that off; the exported `version` says what you got).
|
|
588
|
+
- **Cloudflare Workers**: Wrangler imports a `.wasm` file as a compiled module, so give it to `init` before the first call. There are no threads, so use the main entry.
|
|
513
589
|
|
|
514
|
-
|
|
590
|
+
```js
|
|
591
|
+
import { init, getSwatches } from 'agglomerative-clustering';
|
|
592
|
+
import wasm from 'agglomerative-clustering/clustering.wasm';
|
|
593
|
+
|
|
594
|
+
const ready = init({ wasm });
|
|
595
|
+
export default {
|
|
596
|
+
async fetch(request) {
|
|
597
|
+
await ready;
|
|
598
|
+
// … decode the upload to pixels (fast-png works here), then getSwatches(pixels, 8)
|
|
599
|
+
},
|
|
600
|
+
};
|
|
601
|
+
```
|
|
515
602
|
|
|
516
603
|
### Loading the WebAssembly module
|
|
517
604
|
By default the module is found next to the package's script, which Node and bundlers such as Vite handle. Otherwise, say where it is before any other call (the first load that succeeds wins):
|
|
@@ -524,22 +611,78 @@ await init({ wasm: wasmModule }); // a comp
|
|
|
524
611
|
|
|
525
612
|
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
613
|
|
|
614
|
+
### SvelteKit, Nuxt and other frameworks
|
|
615
|
+
|
|
616
|
+
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.
|
|
617
|
+
|
|
618
|
+
### Next.js
|
|
619
|
+
|
|
620
|
+
Checked with Next.js 16, under Turbopack and webpack, in production builds:
|
|
621
|
+
|
|
622
|
+
- **Client components** need nothing: the main entry and the worker entry both work as they are.
|
|
623
|
+
- **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:
|
|
624
|
+
|
|
625
|
+
```js
|
|
626
|
+
// next.config.js
|
|
627
|
+
export default { serverExternalPackages: ['agglomerative-clustering'] };
|
|
628
|
+
```
|
|
629
|
+
- **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):
|
|
630
|
+
|
|
631
|
+
```ts
|
|
632
|
+
import { init, getSwatches } from 'agglomerative-clustering';
|
|
633
|
+
// @ts-expect-error -- `?module` gives a compiled WebAssembly.Module
|
|
634
|
+
import wasm from '../../../node_modules/agglomerative-clustering/dist/clustering.wasm?module';
|
|
635
|
+
|
|
636
|
+
export const runtime = 'edge';
|
|
637
|
+
|
|
638
|
+
export async function POST(request: Request) {
|
|
639
|
+
await init({ wasm }); // loads once; later calls return at once
|
|
640
|
+
// … decode the upload to pixels, then getSwatches(pixels, 8)
|
|
641
|
+
}
|
|
642
|
+
```
|
|
643
|
+
|
|
527
644
|
### Performance and limits
|
|
528
645
|
|
|
529
|
-
**Servers.** Cap the pixel count of uploads, use `precision: 6` (it bounds the memory an image with very many colours needs), and
|
|
646
|
+
**Servers.** Cap the pixel count of uploads (check the header's dimensions before decoding, as sharp's `limitInputPixels` does), use `precision: 6` (it bounds the memory an image with very many colours needs), and run the work in workers so a clustering doesn't block the event loop. One worker runs one call at a time, so create a few:
|
|
647
|
+
|
|
648
|
+
```js
|
|
649
|
+
import { createWorker } from 'agglomerative-clustering/worker';
|
|
650
|
+
|
|
651
|
+
// Four workers; each call goes to the one with the least work waiting.
|
|
652
|
+
const pool = Array.from({ length: 4 }, () => ({ worker: createWorker(), waiting: 0 }));
|
|
653
|
+
const run = async (method, ...args) => {
|
|
654
|
+
const slot = pool.reduce((best, next) => (next.waiting < best.waiting ? next : best));
|
|
655
|
+
slot.waiting++;
|
|
656
|
+
const call = slot.worker[method];
|
|
657
|
+
try {return await call(...args);} finally {slot.waiting--;}
|
|
658
|
+
};
|
|
659
|
+
|
|
660
|
+
// In a request handler (Fastify shown): stop the work if the client goes away. In Node, listen on the response's
|
|
661
|
+
// 'close' (reply.raw, or res in Express), not the request's.
|
|
662
|
+
const controller = new AbortController();
|
|
663
|
+
reply.raw.on('close', () => {if (!reply.raw.writableFinished) {controller.abort();}});
|
|
664
|
+
const swatches = await run('getSwatches', image, 8, { precision: 6, signal: controller.signal });
|
|
665
|
+
```
|
|
666
|
+
|
|
667
|
+
- **Small images wait behind large ones** in a shared pool. If you serve both, give large uploads a pool of their own.
|
|
668
|
+
- **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).
|
|
669
|
+
- **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).
|
|
670
|
+
- Running out of memory is a catchable `out-of-memory` error, and `terminate()` on each worker shuts the pool down.
|
|
530
671
|
|
|
531
|
-
**Large images.** Time and memory grow with the number of *distinct colours*, not just pixels: a 12-megapixel photo takes
|
|
672
|
+
**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`. 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.
|
|
532
673
|
|
|
533
674
|
### Troubleshooting
|
|
534
675
|
|
|
535
676
|
| What you see | Why | What to do |
|
|
536
677
|
|---|---|---|
|
|
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 })`. |
|
|
678
|
+
| `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
679
|
| `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
680
|
| 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
681
|
| `invalid-argument` for a canvas, `Blob` or `ImageBitmap` | Those aren't pixels. | Draw to a canvas and pass `getImageData()`. |
|
|
541
682
|
| 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
683
|
| `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. |
|
|
684
|
+
| 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"). |
|
|
685
|
+
| `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
686
|
| `out-of-memory` | An image with very many distinct colours. | Use `precision: 6`, or a smaller image. |
|
|
544
687
|
| 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
688
|
| TypeScript says a `Uint8Array` isn't a `Clustering` | Stored bytes lost their type. | `new Clustering(bytes)` (see "Palette and Clustering"). |
|
package/dist/clustering.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
async function createWasmModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";if(ENVIRONMENT_IS_NODE){const{createRequire}=await(import(/* webpackIgnore: true */ /* @vite-ignore */ ["node", "module"].join(":")));var require=createRequire(import.meta.url)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}programArgs=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU32=new Uint32Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["f"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun=="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",import.meta.url).href}function getBinarySync(file){if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm){return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var onPreRuns=[];var noExitRuntime=true;var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var __Unwind_RaiseException=ex=>{abort()};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;__Unwind_RaiseException(ptr)};var __abort_js=()=>abort("");var _emscripten_get_now=()=>performance.now();var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var HEAPU8;var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit=="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0){preInit.shift()()}}}var _malloc,_library_version,_clustering_job_start,_clustering_job_step,_clustering_job_result,_clustering_job_free,_get_clustering,_get_palette,_get_palette_from_clustering,_get_palette_weights,_quantize,_quantize_with_clustering,_quantize_with_palette,_quantize_indices,_quantize_indices_with_clustering,_quantize_indices_with_palette,_free,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["g"];_library_version=Module["_library_version"]=wasmExports["h"];_clustering_job_start=Module["_clustering_job_start"]=wasmExports["i"];_clustering_job_step=Module["_clustering_job_step"]=wasmExports["j"];_clustering_job_result=Module["_clustering_job_result"]=wasmExports["k"];_clustering_job_free=Module["_clustering_job_free"]=wasmExports["l"];_get_clustering=Module["_get_clustering"]=wasmExports["m"];_get_palette=Module["_get_palette"]=wasmExports["n"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["o"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["p"];_quantize=Module["_quantize"]=wasmExports["q"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["r"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["s"];_quantize_indices=Module["_quantize_indices"]=wasmExports["t"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["u"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["v"];_free=Module["_free"]=wasmExports["w"];memory=wasmMemory=wasmExports["e"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={b:___cxa_throw,c:__abort_js,a:_emscripten_get_now,d:_emscripten_resize_heap};async function run(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;wasmExports=await createWasm();await run();
|
|
1
|
+
async function createWasmModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer"&&typeof import.meta.url=="string"&&import.meta.url.startsWith("file:");if(ENVIRONMENT_IS_NODE){const{createRequire}=await(import(/* webpackIgnore: true */ /* @vite-ignore */ ["node", "module"].join(":")));var require=createRequire(import.meta.url)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}programArgs=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU32=new Uint32Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["f"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun=="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",import.meta.url).href}function getBinarySync(file){if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm){return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var onPreRuns=[];var noExitRuntime=true;var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var __Unwind_RaiseException=ex=>{abort()};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;__Unwind_RaiseException(ptr)};var __abort_js=()=>abort("");var _emscripten_get_now=()=>performance.now();var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var HEAPU8;var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit=="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0){preInit.shift()()}}}var _malloc,_library_version,_clustering_job_start,_clustering_job_step,_clustering_job_result,_clustering_job_free,_get_clustering,_get_palette,_get_palette_from_clustering,_get_palette_weights,_quantize,_quantize_with_clustering,_quantize_with_palette,_quantize_indices,_quantize_indices_with_clustering,_quantize_indices_with_palette,_free,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["g"];_library_version=Module["_library_version"]=wasmExports["h"];_clustering_job_start=Module["_clustering_job_start"]=wasmExports["i"];_clustering_job_step=Module["_clustering_job_step"]=wasmExports["j"];_clustering_job_result=Module["_clustering_job_result"]=wasmExports["k"];_clustering_job_free=Module["_clustering_job_free"]=wasmExports["l"];_get_clustering=Module["_get_clustering"]=wasmExports["m"];_get_palette=Module["_get_palette"]=wasmExports["n"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["o"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["p"];_quantize=Module["_quantize"]=wasmExports["q"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["r"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["s"];_quantize_indices=Module["_quantize_indices"]=wasmExports["t"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["u"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["v"];_free=Module["_free"]=wasmExports["w"];memory=wasmMemory=wasmExports["e"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={b:___cxa_throw,c:__abort_js,a:_emscripten_get_now,d:_emscripten_resize_heap};async function run(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;wasmExports=await createWasm();await run();
|
|
2
2
|
;return Module}export default createWasmModule;
|
package/dist/clustering.wasm
CHANGED
|
Binary file
|