agglomerative-clustering 3.0.0-beta.3 → 3.0.0-beta.4
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 +94 -11
- package/dist/clustering.cjs +3 -0
- package/dist/clustering.js +1 -1
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +37 -36
- package/dist/index.mjs +27 -33
- package/dist/shared.cjs +43 -5
- package/dist/shared.mjs +39 -3
- package/dist/worker-thread.mjs +37 -7
- package/dist/worker.d.ts +21 -2
- package/dist/worker.mjs +144 -38
- package/package.json +4 -2
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
[](LICENSE)
|
|
7
7
|

|
|
8
8
|
|
|
9
|
-

|
|
9
|
+

|
|
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
|
|
|
@@ -26,7 +26,7 @@ Most colour quantizers answer one question: *give me k colours*. Ask for a diffe
|
|
|
26
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)).
|
|
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](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/migrating.md)).
|
|
30
30
|
|
|
31
31
|
It runs on Node 20.19+ and 22.12+, and in browsers with WebAssembly SIMD (see [Where it runs](#where-it-runs)).
|
|
32
32
|
|
|
@@ -257,7 +257,33 @@ slider.oninput = async () => {
|
|
|
257
257
|
|
|
258
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
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
|
|
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).
|
|
261
|
+
|
|
262
|
+
### Fixed palettes: e-ink, thread, bricks
|
|
263
|
+
|
|
264
|
+
Hardware, craft and print often have a palette you didn't choose. `quantizeToIndicesWithPalette(image, palette, options?)` maps to it and gives indices in *your* palette's order (what firmware, thread charts and parts lists need):
|
|
265
|
+
|
|
266
|
+
```js
|
|
267
|
+
const eink = [0,0,0, 255,255,255, 0,255,0, 0,0,255, 255,0,0, 255,255,0, 255,128,0]; // black white green blue red yellow orange
|
|
268
|
+
const { indices } = await quantizeToIndicesWithPalette({ data, format: 'rgba', width }, eink, { dither: true });
|
|
269
|
+
// indices[i] is the entry of `eink` for pixel i: pack it to 4 bits per pixel for the panel
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
- **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
|
+
- **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): there is no function for it, but this works. Cluster the image, cut it to a few more than N colours, snap each cut colour to its nearest thread (pass the cut palette as a one-pixel-per-colour `rgb` image to `quantizeToIndicesWithPalette`), and raise the number you cut until N distinct threads appear. It beat "the N most used threads" by up to 6 dB PSNR in testing.
|
|
275
|
+
- **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
|
+
- A palette of more than 1024 colours is mapped about three times slower than one of 1024 or fewer.
|
|
277
|
+
|
|
278
|
+
### Swatches for many images (a build step)
|
|
279
|
+
|
|
280
|
+
For placeholders, theming or colour search over a site's images, one call each is fast enough, and most of the time goes to decoding:
|
|
281
|
+
|
|
282
|
+
- **Downscale first.** 512 px on the long side changes the palette by about 2% (256 px by 6%, 64 px by half) and is 3 to 8 times faster; with `precision: 6` a photo takes about 20 ms.
|
|
283
|
+
- **Use a few workers, not one per image.** The main entry runs one call at a time, so throughput comes from several `createWorker()`s (the pool in [Performance and limits](#performance-and-limits)). About four is the sweet spot; more mostly adds memory.
|
|
284
|
+
- **Cache palettes, not clusterings:** 1,500 palettes are about half a megabyte of JSON, and 1,500 clusterings are 0.2 to 1 GB. Key the cache by the image's content hash, plus the library's major version and your options; palettes are the same for every 3.x release (see [stability](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/stability.md)).
|
|
285
|
+
- "Dominant colour" is up to you: the heaviest swatch of `getSwatches(image, 5)` (sort by `shares`) is a good one. These colours are averages of regions, so they are muted: for vivid accents, a library built for them (node-vibrant, colorthief) suits better.
|
|
286
|
+
- A sharp `Buffer` from `.raw()` can be passed as it is, with `{ data, format: 'rgba', width }`.
|
|
261
287
|
|
|
262
288
|
### Using the output
|
|
263
289
|
|
|
@@ -312,7 +338,7 @@ ImageData // from a canvas: always RGBA, widt
|
|
|
312
338
|
|
|
313
339
|
> **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()`).
|
|
314
340
|
|
|
315
|
-
> **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](docs/ROADMAP.md).
|
|
341
|
+
> **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).
|
|
316
342
|
|
|
317
343
|
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.
|
|
318
344
|
|
|
@@ -427,7 +453,7 @@ const clustering = await getClustering(image, {
|
|
|
427
453
|
});
|
|
428
454
|
```
|
|
429
455
|
|
|
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.
|
|
456
|
+
- **Slices.** With either option, clustering runs in slices of about 10 ms (a large image has a few unsliced steps of up to 150 ms in between), so an abort takes effect within a slice and the page stays responsive. The result is the same; slicing costs about 5% more time.
|
|
431
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: check `error.name === 'AbortError'`. An already aborted signal does no work.
|
|
432
458
|
- **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`.
|
|
433
459
|
- **Progress** is approximate, never goes backwards, and ends at exactly 1.
|
|
@@ -466,6 +492,8 @@ Messages are for people and may change. The worker entry fails the same way as t
|
|
|
466
492
|
- **`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.
|
|
467
493
|
- **`terminate()`** stops the worker and rejects the calls still waiting.
|
|
468
494
|
|
|
495
|
+
`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
|
+
|
|
469
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. The entry is an ES module; `require()` works too on the supported Node versions.
|
|
470
498
|
|
|
471
499
|
### TypeScript
|
|
@@ -641,6 +669,59 @@ Checked with Next.js 16, under Turbopack and webpack, in production builds:
|
|
|
641
669
|
}
|
|
642
670
|
```
|
|
643
671
|
|
|
672
|
+
### Angular, esbuild, Rollup and other bundlers
|
|
673
|
+
|
|
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:
|
|
675
|
+
|
|
676
|
+
```js
|
|
677
|
+
import { createWorker } from 'agglomerative-clustering/worker';
|
|
678
|
+
const worker = createWorker({
|
|
679
|
+
script: '/assets/agglomerative-clustering/worker-thread.mjs', // relative URLs resolve against the page
|
|
680
|
+
wasm: '/assets/agglomerative-clustering/clustering.wasm',
|
|
681
|
+
});
|
|
682
|
+
```
|
|
683
|
+
|
|
684
|
+
- **Angular** (the default `application` builder): add the files to the app's `angular.json` assets, then use the code above.
|
|
685
|
+
|
|
686
|
+
```json
|
|
687
|
+
"assets": [{ "glob": "{worker-thread.mjs,shared.mjs,index.mjs,clustering.js,clustering.wasm}", "input": "node_modules/agglomerative-clustering/dist", "output": "assets/agglomerative-clustering" }]
|
|
688
|
+
```
|
|
689
|
+
- **esbuild and Rollup** do not recognise `new Worker(new URL(...))`, so copy the same files into the output and give `script`. Rollup users can also build `worker-thread.mjs` as a second entry.
|
|
690
|
+
- **Vite, webpack 5 and Parcel** find the script themselves.
|
|
691
|
+
- **The main entry** can also be told where the `.wasm` is with `init({ wasm })`.
|
|
692
|
+
|
|
693
|
+
### Electron
|
|
694
|
+
|
|
695
|
+
Everything works in dev and in an app packaged with `asar` (no `asarUnpack`), in the renderer, the main process and a `utilityProcess`, loaded from `file://`, a custom scheme or a dev server. For responsiveness, **decode in the renderer and use `agglomerative-clustering/worker`** there: the main entry in the main process blocks the whole app for the length of a clustering. Two traps:
|
|
696
|
+
|
|
697
|
+
- **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
|
+
- **`nodeIntegrationInWorker: true`** is supported: the worker script talks through `self` there.
|
|
699
|
+
|
|
700
|
+
Errors lose their `code` and `argument` crossing Electron's IPC (only the message survives), so send `error.code` yourself. `nativeImage` gives BGRA pixels: swap the channels to RGBA first.
|
|
701
|
+
|
|
702
|
+
### Browser extensions
|
|
703
|
+
|
|
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).
|
|
705
|
+
|
|
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'" }`. Content scripts need nothing.
|
|
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, and in a content script on a page whose CSP allows `worker-src blob:`.
|
|
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.
|
|
709
|
+
- 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
|
+
|
|
711
|
+
### Testing code that uses it
|
|
712
|
+
|
|
713
|
+
- **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` (the package falls back to a CommonJS build of its glue where `require()` of an ES module fails).
|
|
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`: each Jest test file otherwise leaves a worker thread, about 30 MB, in the process.
|
|
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' })`.
|
|
718
|
+
- **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
|
+
- Fake timers don't affect it. An unawaited call still running at the end holds Jest open until it finishes.
|
|
720
|
+
|
|
721
|
+
### Writing a package that wraps it
|
|
722
|
+
|
|
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.
|
|
724
|
+
|
|
644
725
|
### Performance and limits
|
|
645
726
|
|
|
646
727
|
**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:
|
|
@@ -669,7 +750,7 @@ const swatches = await run('getSwatches', image, 8, { precision: 6, signal: cont
|
|
|
669
750
|
- **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
751
|
- Running out of memory is a catchable `out-of-memory` error, and `terminate()` on each worker shuts the pool down.
|
|
671
752
|
|
|
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.
|
|
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 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.
|
|
673
754
|
|
|
674
755
|
### Troubleshooting
|
|
675
756
|
|
|
@@ -684,15 +765,17 @@ const swatches = await run('getSwatches', image, 8, { precision: 6, signal: cont
|
|
|
684
765
|
| 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
766
|
| `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. |
|
|
686
767
|
| `out-of-memory` | An image with very many distinct colours. | Use `precision: 6`, or a smaller image. |
|
|
687
|
-
| The worker doesn't start under a bundler | The bundler didn't
|
|
768
|
+
| 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`. |
|
|
688
771
|
| TypeScript says a `Uint8Array` isn't a `Clustering` | Stored bytes lost their type. | `new Clustering(bytes)` (see "Palette and Clustering"). |
|
|
689
772
|
|
|
690
773
|
## More
|
|
691
774
|
|
|
692
|
-
- **[Migrating](docs/migrating.md)** from 2.x (and 1.x) to the current version, and the [CHANGELOG](CHANGELOG.md) for every release.
|
|
693
|
-
- **[Stability and versioning](docs/stability.md)**: what won't change within a major version.
|
|
694
|
-
- **[How it works](docs/how-it-works.md)**: the algorithm, and the architecture notes for contributors in [CLAUDE.md](CLAUDE.md).
|
|
695
|
-
- **[Roadmap](docs/ROADMAP.md)**: what is planned and what was tried and dropped.
|
|
775
|
+
- **[Migrating](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/migrating.md)** from 2.x (and 1.x) to the current version, and the [CHANGELOG](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/CHANGELOG.md) for every release.
|
|
776
|
+
- **[Stability and versioning](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/stability.md)**: what won't change within a major version.
|
|
777
|
+
- **[How it works](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/how-it-works.md)**: the algorithm, and the architecture notes for contributors in [CLAUDE.md](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/CLAUDE.md).
|
|
778
|
+
- **[Roadmap](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/ROADMAP.md)**: what is planned and what was tried and dropped.
|
|
696
779
|
|
|
697
780
|
### Demo
|
|
698
781
|
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
"use strict";var __agglomerativeGlueUrl=typeof __filename=="string"&&typeof process!="undefined"&&typeof process.getBuiltinModule=="function"?process.getBuiltinModule("node:url").pathToFileURL(__filename).href:"";
|
|
2
|
+
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 __filename=="string"&&typeof process.getBuiltinModule=="function";if(ENVIRONMENT_IS_NODE){var require=(name)=>process.getBuiltinModule(name)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=__agglomerativeGlueUrl;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(globalThis.process.argv.length>1){thisProgram=globalThis.process.argv[1].replace(/\\/g,"/")}programArgs=globalThis.process.argv.slice(2);quit_=(status,toThrow)=>{globalThis.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",__agglomerativeGlueUrl).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();
|
|
3
|
+
;return Module}module.exports=createWasmModule;
|
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"&&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();
|
|
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(globalThis.process.argv.length>1){thisProgram=globalThis.process.argv[1].replace(/\\/g,"/")}programArgs=globalThis.process.argv.slice(2);quit_=(status,toThrow)=>{globalThis.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
|
package/dist/index.cjs
CHANGED
|
@@ -22,7 +22,14 @@ Object.defineProperty(exports, "version", {
|
|
|
22
22
|
return _shared.version;
|
|
23
23
|
}
|
|
24
24
|
});
|
|
25
|
-
var _clustering = _interopRequireDefault(
|
|
25
|
+
var _clustering = _interopRequireDefault((() => {
|
|
26
|
+
try {
|
|
27
|
+
return require("./clustering.js");
|
|
28
|
+
} catch (error) {
|
|
29
|
+
// A module system that can't require() an ES module (Jest): the CommonJS copy of the glue.
|
|
30
|
+
return require("./clustering.cjs");
|
|
31
|
+
}
|
|
32
|
+
})());
|
|
26
33
|
var _shared = require("./shared.cjs");
|
|
27
34
|
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
|
|
28
35
|
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } // The library's version, the stored-data format version, and the Palette and Clustering types (see shared.js).
|
|
@@ -108,21 +115,36 @@ const hasSimd = () => {
|
|
|
108
115
|
};
|
|
109
116
|
// Node itself (or Bun), not a runtime that imitates it: Cloudflare Workers with nodejs_compat and Deno also define
|
|
110
117
|
// process.versions.node, but their navigator.userAgent says what they are (Node 20 has no navigator at all).
|
|
111
|
-
const isNodeLike =
|
|
118
|
+
const isNodeLike = !!(globalThis.process && globalThis.process.versions && globalThis.process.versions.node) && (typeof navigator === 'undefined' || /^(Node\.js|Bun)\//.test(String(navigator.userAgent)));
|
|
119
|
+
// Emscripten appends advice about its own debug build, which doesn't apply to this package's users.
|
|
120
|
+
const assertionsAdvice = /\s*\(?Build with -sASSERTIONS for more info\.?\)?/;
|
|
112
121
|
const wasmLoadFailed = (cause, given) => {
|
|
113
122
|
const text = String(cause && cause.message !== undefined ? cause.message : cause).split('\n')[0];
|
|
114
|
-
// Emscripten
|
|
115
|
-
|
|
116
|
-
let reason = text.replace(/\s*\(?Build with -sASSERTIONS for more info\.?\)?/, '').trim().replace(/\.+$/, '');
|
|
123
|
+
// Emscripten wraps a failed compile in Aborted(...), which is how it stops itself, not part of the reason.
|
|
124
|
+
let reason = text.replace(assertionsAdvice, '').trim().replace(/\.+$/, '');
|
|
117
125
|
const aborted = /^Aborted\((.*)\)$/.exec(reason);
|
|
118
126
|
if (aborted) {
|
|
119
127
|
reason = aborted[1].replace(/\.+$/, '');
|
|
120
128
|
}
|
|
129
|
+
// The cause keeps Emscripten's own message, without that advice.
|
|
130
|
+
if (cause && typeof cause.message === 'string' && assertionsAdvice.test(cause.message)) {
|
|
131
|
+
try {
|
|
132
|
+
cause.message = cause.message.replace(assertionsAdvice, '');
|
|
133
|
+
} catch (error) {/* read-only: leave it */}
|
|
134
|
+
}
|
|
135
|
+
// Where an explicit init({ wasm }) URL or path pointed, to name in the message.
|
|
136
|
+
const where = typeof given === 'string' ? ` (${given})` : '';
|
|
121
137
|
let advice;
|
|
122
|
-
if (
|
|
138
|
+
if (/Content.Security.Policy|wasm-eval|unsafe-eval|CompileError: .*(disallowed|refused)/i.test(text)) {
|
|
139
|
+
// Chrome's message names 'wasm-eval', which Chrome rejects in an extension's manifest; 'wasm-unsafe-eval' is the one.
|
|
140
|
+
advice = "A Content-Security-Policy blocks compiling WebAssembly: add 'wasm-unsafe-eval' to its script-src (in a browser extension, to content_security_policy.extension_pages in the manifest).";
|
|
141
|
+
} else if (!hasSimd()) {
|
|
123
142
|
advice = "This engine has no WebAssembly SIMD, which the module needs (Chrome and Edge 91, Firefox 89, Safari 16.4, Node 16.4 or newer).";
|
|
143
|
+
} else if (/XMLHttpRequest is not defined|both async and sync fetching|failed to fetch|NetworkError|404|ENOENT/i.test(text)) {
|
|
144
|
+
reason = given ? `the .wasm file could not be fetched${where}` : 'the .wasm file could not be fetched (the package looks for clustering.wasm next to its script)';
|
|
145
|
+
advice = given ? "Check that URL or path: it must be this package's clustering.wasm, served (not a 404) with the application/wasm type." : "Check that clustering.wasm is served next to the script or emitted by your bundler, or say where it is with init({ wasm }).";
|
|
124
146
|
} else if (given) {
|
|
125
|
-
advice =
|
|
147
|
+
advice = `Check what init({ wasm }) was given${where}: it must be this package's clustering.wasm (its URL or path, its bytes, or the module compiled from it).`;
|
|
126
148
|
} else if (isNodeLike) {
|
|
127
149
|
advice = "If the package was bundled into a server build (Next.js and others), the bundler may have moved or renamed clustering.wasm: leave the package out of the bundle (in Next.js, serverExternalPackages: ['agglomerative-clustering']) or give the module with init({ wasm }).";
|
|
128
150
|
} else {
|
|
@@ -186,7 +208,7 @@ const packagedWasm = async () => {
|
|
|
186
208
|
const {
|
|
187
209
|
readFile
|
|
188
210
|
} = await (specifier => new Promise(r => r(`${specifier}`)).then(s => _interopRequireWildcard(require(s))))(/* webpackIgnore: true */ /* @vite-ignore */['node', 'fs/promises'].join(':'));
|
|
189
|
-
const file = createRequire(`${process.cwd()}/`).resolve('agglomerative-clustering/clustering.wasm');
|
|
211
|
+
const file = createRequire(`${globalThis.process.cwd()}/`).resolve('agglomerative-clustering/clustering.wasm');
|
|
190
212
|
return readFile(file);
|
|
191
213
|
};
|
|
192
214
|
|
|
@@ -225,7 +247,7 @@ const acquire = async options => {
|
|
|
225
247
|
// way Node resolves packages, from the working directory; if that fails too, the first error is reported.
|
|
226
248
|
const fallback = wasm === undefined && isNodeLike ? await packagedWasm().catch(() => null) : null;
|
|
227
249
|
if (!fallback) {
|
|
228
|
-
throw wasmLoadFailed(error, wasm !== undefined);
|
|
250
|
+
throw wasmLoadFailed(error, typeof wasm === 'string' ? wasm : isURL(wasm) ? wasm.href : wasm !== undefined);
|
|
229
251
|
}
|
|
230
252
|
instance = await instantiate(fallback).catch(() => {
|
|
231
253
|
throw wasmLoadFailed(error, false);
|
|
@@ -345,20 +367,6 @@ const sniffImageFormat = bytes => {
|
|
|
345
367
|
return null;
|
|
346
368
|
};
|
|
347
369
|
|
|
348
|
-
// A typed array whose buffer was transferred away (to a worker, say) is empty and can't be read or viewed.
|
|
349
|
-
const isDetached = view => {
|
|
350
|
-
const buffer = view.buffer;
|
|
351
|
-
if (typeof buffer.detached === 'boolean') {
|
|
352
|
-
return buffer.detached;
|
|
353
|
-
}
|
|
354
|
-
try {
|
|
355
|
-
new Uint8Array(buffer, 0, 0);
|
|
356
|
-
return false;
|
|
357
|
-
} catch (error) {
|
|
358
|
-
return true;
|
|
359
|
-
}
|
|
360
|
-
};
|
|
361
|
-
|
|
362
370
|
// The bytes a call works on are read when it is made, as with any function that takes an array: the caller may reuse
|
|
363
371
|
// or change the array as soon as the call returns. Once the module is loaded the bytes go into its memory before the
|
|
364
372
|
// call returns; until then (the first call) a copy is kept for when it has loaded.
|
|
@@ -383,7 +391,7 @@ const load = image => {
|
|
|
383
391
|
const fix = (0, _shared.isClustering)(image) ? 'To cut a palette from it, use getPaletteFromClustering (or quantizeFromClustering to map an image with it).' : 'To map an image to it, use quantizeWithPalette(image, palette).';
|
|
384
392
|
throw (0, _shared.fail)('invalid-argument', `Invalid image: this is ${what}, not pixels. ${fix}`, 'image');
|
|
385
393
|
}
|
|
386
|
-
if (ArrayBuffer.isView(image) && isDetached(image)) {
|
|
394
|
+
if (ArrayBuffer.isView(image) && (0, _shared.isDetached)(image)) {
|
|
387
395
|
throw (0, _shared.fail)('invalid-argument', "Invalid image: its buffer was transferred away (detached), for example to a worker created with transfer: true, so it has no pixels left. Pass a copy if you need to keep using it.", 'image');
|
|
388
396
|
}
|
|
389
397
|
if ((0, _shared.isUint8Array)(image)) {
|
|
@@ -400,7 +408,7 @@ const load = image => {
|
|
|
400
408
|
};
|
|
401
409
|
}
|
|
402
410
|
if (isImageData(image)) {
|
|
403
|
-
if (isDetached(image.data)) {
|
|
411
|
+
if ((0, _shared.isDetached)(image.data)) {
|
|
404
412
|
throw (0, _shared.fail)('invalid-argument', "Invalid image: the ImageData's pixels were transferred away (detached), for example to a worker created with transfer: true.", 'image');
|
|
405
413
|
}
|
|
406
414
|
return {
|
|
@@ -418,7 +426,7 @@ const load = image => {
|
|
|
418
426
|
if (!(0, _shared.isUint8Array)(image.data) && !(0, _shared.isUint8ClampedArray)(image.data)) {
|
|
419
427
|
throw (0, _shared.fail)('invalid-argument', "Invalid image data: must be Uint8Array or Uint8ClampedArray.", 'image');
|
|
420
428
|
}
|
|
421
|
-
if (isDetached(image.data)) {
|
|
429
|
+
if ((0, _shared.isDetached)(image.data)) {
|
|
422
430
|
throw (0, _shared.fail)('invalid-argument', "Invalid image data: its buffer was transferred away (detached), for example to a worker created with transfer: true, so it has no pixels left. Pass a copy if you need to keep using it.", 'image');
|
|
423
431
|
}
|
|
424
432
|
if (!Object.keys(codes).includes(image.format)) {
|
|
@@ -442,15 +450,8 @@ const load = image => {
|
|
|
442
450
|
};
|
|
443
451
|
const getWrapper = image => {
|
|
444
452
|
if (isImageData(image)) {
|
|
445
|
-
//
|
|
446
|
-
|
|
447
|
-
width,
|
|
448
|
-
height,
|
|
449
|
-
colorSpace
|
|
450
|
-
} = image;
|
|
451
|
-
return output => new ImageData(new Uint8ClampedArray(output.buffer), width, height, colorSpace ? {
|
|
452
|
-
colorSpace
|
|
453
|
-
} : undefined);
|
|
453
|
+
// In the input's own class and colour space (see imageDataLike).
|
|
454
|
+
return output => (0, _shared.imageDataLike)(image, new Uint8ClampedArray(output.buffer));
|
|
454
455
|
}
|
|
455
456
|
if (!(0, _shared.isUint8Array)(image) && typeof image === 'object' && image && image.data && image.format) {
|
|
456
457
|
const {
|
|
@@ -848,7 +849,7 @@ const getSwatchesFromClustering = async (clustering, k, ...extra) => {
|
|
|
848
849
|
k = check(k);
|
|
849
850
|
noOptions('getSwatchesFromClustering', extra);
|
|
850
851
|
if (header.version < 3) {
|
|
851
|
-
throw (0, _shared.fail)('unsupported-version', `
|
|
852
|
+
throw (0, _shared.fail)('unsupported-version', `Unsupported clustering: format version ${header.version} (agglomerative-clustering ${header.version}.x) has no weights. Cluster the image again.`, 'clustering');
|
|
852
853
|
}
|
|
853
854
|
clustering = held(clustering);
|
|
854
855
|
const wasm = Module || (await acquire());
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import createWasmModule from './clustering.js';
|
|
2
|
-
import { version, fail, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, imageHint, latestVersion, readHeader, checkPalette } from "./shared.mjs";
|
|
2
|
+
import { version, fail, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, imageHint, latestVersion, readHeader, checkPalette, isDetached, imageDataLike } from "./shared.mjs";
|
|
3
3
|
|
|
4
4
|
// The library's version, the stored-data format version, and the Palette and Clustering types (see shared.js).
|
|
5
5
|
export { version, Palette, Clustering } from "./shared.mjs";
|
|
@@ -85,21 +85,36 @@ const hasSimd = () => {
|
|
|
85
85
|
};
|
|
86
86
|
// Node itself (or Bun), not a runtime that imitates it: Cloudflare Workers with nodejs_compat and Deno also define
|
|
87
87
|
// process.versions.node, but their navigator.userAgent says what they are (Node 20 has no navigator at all).
|
|
88
|
-
const isNodeLike =
|
|
88
|
+
const isNodeLike = !!(globalThis.process && globalThis.process.versions && globalThis.process.versions.node) && (typeof navigator === 'undefined' || /^(Node\.js|Bun)\//.test(String(navigator.userAgent)));
|
|
89
|
+
// Emscripten appends advice about its own debug build, which doesn't apply to this package's users.
|
|
90
|
+
const assertionsAdvice = /\s*\(?Build with -sASSERTIONS for more info\.?\)?/;
|
|
89
91
|
const wasmLoadFailed = (cause, given) => {
|
|
90
92
|
const text = String(cause && cause.message !== undefined ? cause.message : cause).split('\n')[0];
|
|
91
|
-
// Emscripten
|
|
92
|
-
|
|
93
|
-
let reason = text.replace(/\s*\(?Build with -sASSERTIONS for more info\.?\)?/, '').trim().replace(/\.+$/, '');
|
|
93
|
+
// Emscripten wraps a failed compile in Aborted(...), which is how it stops itself, not part of the reason.
|
|
94
|
+
let reason = text.replace(assertionsAdvice, '').trim().replace(/\.+$/, '');
|
|
94
95
|
const aborted = /^Aborted\((.*)\)$/.exec(reason);
|
|
95
96
|
if (aborted) {
|
|
96
97
|
reason = aborted[1].replace(/\.+$/, '');
|
|
97
98
|
}
|
|
99
|
+
// The cause keeps Emscripten's own message, without that advice.
|
|
100
|
+
if (cause && typeof cause.message === 'string' && assertionsAdvice.test(cause.message)) {
|
|
101
|
+
try {
|
|
102
|
+
cause.message = cause.message.replace(assertionsAdvice, '');
|
|
103
|
+
} catch (error) {/* read-only: leave it */}
|
|
104
|
+
}
|
|
105
|
+
// Where an explicit init({ wasm }) URL or path pointed, to name in the message.
|
|
106
|
+
const where = typeof given === 'string' ? ` (${given})` : '';
|
|
98
107
|
let advice;
|
|
99
|
-
if (
|
|
108
|
+
if (/Content.Security.Policy|wasm-eval|unsafe-eval|CompileError: .*(disallowed|refused)/i.test(text)) {
|
|
109
|
+
// Chrome's message names 'wasm-eval', which Chrome rejects in an extension's manifest; 'wasm-unsafe-eval' is the one.
|
|
110
|
+
advice = "A Content-Security-Policy blocks compiling WebAssembly: add 'wasm-unsafe-eval' to its script-src (in a browser extension, to content_security_policy.extension_pages in the manifest).";
|
|
111
|
+
} else if (!hasSimd()) {
|
|
100
112
|
advice = "This engine has no WebAssembly SIMD, which the module needs (Chrome and Edge 91, Firefox 89, Safari 16.4, Node 16.4 or newer).";
|
|
113
|
+
} else if (/XMLHttpRequest is not defined|both async and sync fetching|failed to fetch|NetworkError|404|ENOENT/i.test(text)) {
|
|
114
|
+
reason = given ? `the .wasm file could not be fetched${where}` : 'the .wasm file could not be fetched (the package looks for clustering.wasm next to its script)';
|
|
115
|
+
advice = given ? "Check that URL or path: it must be this package's clustering.wasm, served (not a 404) with the application/wasm type." : "Check that clustering.wasm is served next to the script or emitted by your bundler, or say where it is with init({ wasm }).";
|
|
101
116
|
} else if (given) {
|
|
102
|
-
advice =
|
|
117
|
+
advice = `Check what init({ wasm }) was given${where}: it must be this package's clustering.wasm (its URL or path, its bytes, or the module compiled from it).`;
|
|
103
118
|
} else if (isNodeLike) {
|
|
104
119
|
advice = "If the package was bundled into a server build (Next.js and others), the bundler may have moved or renamed clustering.wasm: leave the package out of the bundle (in Next.js, serverExternalPackages: ['agglomerative-clustering']) or give the module with init({ wasm }).";
|
|
105
120
|
} else {
|
|
@@ -163,7 +178,7 @@ const packagedWasm = async () => {
|
|
|
163
178
|
const {
|
|
164
179
|
readFile
|
|
165
180
|
} = await import(/* webpackIgnore: true */ /* @vite-ignore */['node', 'fs/promises'].join(':'));
|
|
166
|
-
const file = createRequire(`${process.cwd()}/`).resolve('agglomerative-clustering/clustering.wasm');
|
|
181
|
+
const file = createRequire(`${globalThis.process.cwd()}/`).resolve('agglomerative-clustering/clustering.wasm');
|
|
167
182
|
return readFile(file);
|
|
168
183
|
};
|
|
169
184
|
|
|
@@ -202,7 +217,7 @@ const acquire = async options => {
|
|
|
202
217
|
// way Node resolves packages, from the working directory; if that fails too, the first error is reported.
|
|
203
218
|
const fallback = wasm === undefined && isNodeLike ? await packagedWasm().catch(() => null) : null;
|
|
204
219
|
if (!fallback) {
|
|
205
|
-
throw wasmLoadFailed(error, wasm !== undefined);
|
|
220
|
+
throw wasmLoadFailed(error, typeof wasm === 'string' ? wasm : isURL(wasm) ? wasm.href : wasm !== undefined);
|
|
206
221
|
}
|
|
207
222
|
instance = await instantiate(fallback).catch(() => {
|
|
208
223
|
throw wasmLoadFailed(error, false);
|
|
@@ -321,20 +336,6 @@ const sniffImageFormat = bytes => {
|
|
|
321
336
|
return null;
|
|
322
337
|
};
|
|
323
338
|
|
|
324
|
-
// A typed array whose buffer was transferred away (to a worker, say) is empty and can't be read or viewed.
|
|
325
|
-
const isDetached = view => {
|
|
326
|
-
const buffer = view.buffer;
|
|
327
|
-
if (typeof buffer.detached === 'boolean') {
|
|
328
|
-
return buffer.detached;
|
|
329
|
-
}
|
|
330
|
-
try {
|
|
331
|
-
new Uint8Array(buffer, 0, 0);
|
|
332
|
-
return false;
|
|
333
|
-
} catch (error) {
|
|
334
|
-
return true;
|
|
335
|
-
}
|
|
336
|
-
};
|
|
337
|
-
|
|
338
339
|
// The bytes a call works on are read when it is made, as with any function that takes an array: the caller may reuse
|
|
339
340
|
// or change the array as soon as the call returns. Once the module is loaded the bytes go into its memory before the
|
|
340
341
|
// call returns; until then (the first call) a copy is kept for when it has loaded.
|
|
@@ -418,15 +419,8 @@ const load = image => {
|
|
|
418
419
|
};
|
|
419
420
|
const getWrapper = image => {
|
|
420
421
|
if (isImageData(image)) {
|
|
421
|
-
//
|
|
422
|
-
|
|
423
|
-
width,
|
|
424
|
-
height,
|
|
425
|
-
colorSpace
|
|
426
|
-
} = image;
|
|
427
|
-
return output => new ImageData(new Uint8ClampedArray(output.buffer), width, height, colorSpace ? {
|
|
428
|
-
colorSpace
|
|
429
|
-
} : undefined);
|
|
422
|
+
// In the input's own class and colour space (see imageDataLike).
|
|
423
|
+
return output => imageDataLike(image, new Uint8ClampedArray(output.buffer));
|
|
430
424
|
}
|
|
431
425
|
if (!isUint8Array(image) && typeof image === 'object' && image && image.data && image.format) {
|
|
432
426
|
const {
|
|
@@ -821,7 +815,7 @@ export const getSwatchesFromClustering = async (clustering, k, ...extra) => {
|
|
|
821
815
|
k = check(k);
|
|
822
816
|
noOptions('getSwatchesFromClustering', extra);
|
|
823
817
|
if (header.version < 3) {
|
|
824
|
-
throw fail('unsupported-version', `
|
|
818
|
+
throw fail('unsupported-version', `Unsupported clustering: format version ${header.version} (agglomerative-clustering ${header.version}.x) has no weights. Cluster the image again.`, 'clustering');
|
|
825
819
|
}
|
|
826
820
|
clustering = held(clustering);
|
|
827
821
|
const wasm = Module || (await acquire());
|
package/dist/shared.cjs
CHANGED
|
@@ -6,14 +6,14 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
6
6
|
exports.Clustering = Clustering;
|
|
7
7
|
exports.MARK = void 0;
|
|
8
8
|
exports.Palette = Palette;
|
|
9
|
-
exports.version = exports.snapshot = exports.revive = exports.readHeader = exports.markPalette = exports.markClustering = exports.mark = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.formatVersion = exports.fail = exports.colorSpaces = exports.colorSpaceName = exports.checkPalette = void 0;
|
|
9
|
+
exports.version = exports.snapshot = exports.revive = exports.readHeader = exports.markPalette = exports.markClustering = exports.mark = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isDetached = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageDataLike = exports.formatVersion = exports.fail = exports.colorSpaces = exports.colorSpaceName = exports.checkPalette = void 0;
|
|
10
10
|
// Shared by both entries (index.js and worker.js) and the worker thread: errors, option snapshots, reading a clustering's
|
|
11
11
|
// header, the Palette and Clustering types, and the markers that carry those types across the worker boundary. Imported as
|
|
12
12
|
// './shared.js'; the build rewrites that to './shared.mjs' or './shared.cjs' (scripts/babel-import-extensions.cjs).
|
|
13
13
|
|
|
14
14
|
// The library's version: package.json is the source, and scripts/sync-version.mjs keeps this line (and the copy the .wasm
|
|
15
15
|
// is built from, src/version.hpp) in step with it. Do not edit it by hand.
|
|
16
|
-
const version = exports.version = '3.0.0-beta.
|
|
16
|
+
const version = exports.version = '3.0.0-beta.4';
|
|
17
17
|
const colorSpaces = exports.colorSpaces = {
|
|
18
18
|
'rgb': 0,
|
|
19
19
|
'oklab': 1
|
|
@@ -44,8 +44,43 @@ const isUint8ClampedArray = value => ArrayBuffer.isView(value) && tag(value) ===
|
|
|
44
44
|
exports.isUint8ClampedArray = isUint8ClampedArray;
|
|
45
45
|
const isArrayBufferLike = value => tag(value) === '[object ArrayBuffer]' || tag(value) === '[object SharedArrayBuffer]';
|
|
46
46
|
|
|
47
|
-
//
|
|
47
|
+
// A typed array whose buffer was transferred away (to a worker, say) is empty and can't be read or viewed.
|
|
48
48
|
exports.isArrayBufferLike = isArrayBufferLike;
|
|
49
|
+
const isDetached = view => {
|
|
50
|
+
const buffer = view.buffer;
|
|
51
|
+
if (typeof buffer.detached === 'boolean') {
|
|
52
|
+
return buffer.detached;
|
|
53
|
+
}
|
|
54
|
+
try {
|
|
55
|
+
new Uint8Array(buffer, 0, 0);
|
|
56
|
+
return false;
|
|
57
|
+
} catch (error) {
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
// An ImageData like `like`, with these pixels: made with `like`'s own class where it has one, so an ImageData from another
|
|
63
|
+
// implementation (node-canvas, in Node or under jsdom) comes back as one that implementation accepts, and where there is
|
|
64
|
+
// no global ImageData at all. The colour space is kept ('display-p3' canvases), since the pixels are still in it.
|
|
65
|
+
exports.isDetached = isDetached;
|
|
66
|
+
const imageDataLike = (like, pixels) => {
|
|
67
|
+
const {
|
|
68
|
+
width,
|
|
69
|
+
height,
|
|
70
|
+
colorSpace
|
|
71
|
+
} = like;
|
|
72
|
+
const own = like.constructor;
|
|
73
|
+
const make = typeof own === 'function' && own.name === 'ImageData' ? own : typeof ImageData === 'function' ? ImageData : null;
|
|
74
|
+
if (!make) {
|
|
75
|
+
throw fail('invalid-argument', "Invalid image: an ImageData whose class can't be used to make the result. Pass { data, format: 'rgba', width } instead.", 'image');
|
|
76
|
+
}
|
|
77
|
+
return colorSpace ? new make(pixels, width, height, {
|
|
78
|
+
colorSpace
|
|
79
|
+
}) : new make(pixels, width, height);
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
// What to say about something that isn't an image, when it is a common thing to pass by mistake: each has a one-line fix.
|
|
83
|
+
exports.imageDataLike = imageDataLike;
|
|
49
84
|
const imageHint = image => {
|
|
50
85
|
const decode = " Decode it to pixels first, then pass them.";
|
|
51
86
|
if (image === undefined || image === null) {
|
|
@@ -303,7 +338,7 @@ const readHeader = clustering => {
|
|
|
303
338
|
// A header field with a fixed set of meanings (colour space, weight unit) that holds a value this version
|
|
304
339
|
// doesn't know is how a later release would add one, so it asks for an upgrade rather than misreading it.
|
|
305
340
|
if (clustering[4] > 1 || clustering[6] > 1) {
|
|
306
|
-
throw fail('unsupported-version', "
|
|
341
|
+
throw fail('unsupported-version', "Unsupported clustering: it uses a colour space or weight unit that this version of agglomerative-clustering does not know. If it came from a newer version, upgrade the package; otherwise it is damaged.", 'clustering');
|
|
307
342
|
}
|
|
308
343
|
const merges = length < headerLength + 3 ? 0 : Math.floor((length - headerLength - 3) / recordLength);
|
|
309
344
|
const padding = length < headerLength + 3 ? length - headerLength : length - headerLength - 3 - merges * recordLength;
|
|
@@ -330,7 +365,7 @@ const readHeader = clustering => {
|
|
|
330
365
|
}
|
|
331
366
|
}
|
|
332
367
|
if (version > latestVersion) {
|
|
333
|
-
throw fail('unsupported-version', `
|
|
368
|
+
throw fail('unsupported-version', `Unsupported clustering: format version ${version} is newer than this version of agglomerative-clustering reads. Upgrade the package.`, 'clustering');
|
|
334
369
|
}
|
|
335
370
|
}
|
|
336
371
|
throw notAClustering(clustering);
|
|
@@ -346,6 +381,9 @@ const checkPalette = palette => {
|
|
|
346
381
|
if (!isUint8Array(palette) && !isUint8ClampedArray(palette) && !Array.isArray(palette)) {
|
|
347
382
|
throw fail('invalid-argument', "Invalid palette: must be a Uint8Array of RGB bytes.", 'palette');
|
|
348
383
|
}
|
|
384
|
+
if (Array.isArray(palette) && palette.some(value => Array.isArray(value) || ArrayBuffer.isView(value))) {
|
|
385
|
+
throw fail('invalid-argument', "Invalid palette: a plain array must be flat RGB bytes, integers from 0 to 255, not an array of [r, g, b] colours. Flatten it first: colours.flat().", 'palette');
|
|
386
|
+
}
|
|
349
387
|
if (palette.length % 3 !== 0) {
|
|
350
388
|
throw fail('invalid-argument', "Invalid palette: length must be a multiple of 3 (flat RGB bytes).", 'palette');
|
|
351
389
|
}
|
package/dist/shared.mjs
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
// The library's version: package.json is the source, and scripts/sync-version.mjs keeps this line (and the copy the .wasm
|
|
6
6
|
// is built from, src/version.hpp) in step with it. Do not edit it by hand.
|
|
7
|
-
export const version = '3.0.0-beta.
|
|
7
|
+
export const version = '3.0.0-beta.4';
|
|
8
8
|
export const colorSpaces = {
|
|
9
9
|
'rgb': 0,
|
|
10
10
|
'oklab': 1
|
|
@@ -31,6 +31,39 @@ export const isUint8Array = value => ArrayBuffer.isView(value) && tag(value) ===
|
|
|
31
31
|
export const isUint8ClampedArray = value => ArrayBuffer.isView(value) && tag(value) === '[object Uint8ClampedArray]';
|
|
32
32
|
export const isArrayBufferLike = value => tag(value) === '[object ArrayBuffer]' || tag(value) === '[object SharedArrayBuffer]';
|
|
33
33
|
|
|
34
|
+
// A typed array whose buffer was transferred away (to a worker, say) is empty and can't be read or viewed.
|
|
35
|
+
export const isDetached = view => {
|
|
36
|
+
const buffer = view.buffer;
|
|
37
|
+
if (typeof buffer.detached === 'boolean') {
|
|
38
|
+
return buffer.detached;
|
|
39
|
+
}
|
|
40
|
+
try {
|
|
41
|
+
new Uint8Array(buffer, 0, 0);
|
|
42
|
+
return false;
|
|
43
|
+
} catch (error) {
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
// An ImageData like `like`, with these pixels: made with `like`'s own class where it has one, so an ImageData from another
|
|
49
|
+
// implementation (node-canvas, in Node or under jsdom) comes back as one that implementation accepts, and where there is
|
|
50
|
+
// no global ImageData at all. The colour space is kept ('display-p3' canvases), since the pixels are still in it.
|
|
51
|
+
export const imageDataLike = (like, pixels) => {
|
|
52
|
+
const {
|
|
53
|
+
width,
|
|
54
|
+
height,
|
|
55
|
+
colorSpace
|
|
56
|
+
} = like;
|
|
57
|
+
const own = like.constructor;
|
|
58
|
+
const make = typeof own === 'function' && own.name === 'ImageData' ? own : typeof ImageData === 'function' ? ImageData : null;
|
|
59
|
+
if (!make) {
|
|
60
|
+
throw fail('invalid-argument', "Invalid image: an ImageData whose class can't be used to make the result. Pass { data, format: 'rgba', width } instead.", 'image');
|
|
61
|
+
}
|
|
62
|
+
return colorSpace ? new make(pixels, width, height, {
|
|
63
|
+
colorSpace
|
|
64
|
+
}) : new make(pixels, width, height);
|
|
65
|
+
};
|
|
66
|
+
|
|
34
67
|
// What to say about something that isn't an image, when it is a common thing to pass by mistake: each has a one-line fix.
|
|
35
68
|
export const imageHint = image => {
|
|
36
69
|
const decode = " Decode it to pixels first, then pass them.";
|
|
@@ -282,7 +315,7 @@ export const readHeader = clustering => {
|
|
|
282
315
|
// A header field with a fixed set of meanings (colour space, weight unit) that holds a value this version
|
|
283
316
|
// doesn't know is how a later release would add one, so it asks for an upgrade rather than misreading it.
|
|
284
317
|
if (clustering[4] > 1 || clustering[6] > 1) {
|
|
285
|
-
throw fail('unsupported-version', "
|
|
318
|
+
throw fail('unsupported-version', "Unsupported clustering: it uses a colour space or weight unit that this version of agglomerative-clustering does not know. If it came from a newer version, upgrade the package; otherwise it is damaged.", 'clustering');
|
|
286
319
|
}
|
|
287
320
|
const merges = length < headerLength + 3 ? 0 : Math.floor((length - headerLength - 3) / recordLength);
|
|
288
321
|
const padding = length < headerLength + 3 ? length - headerLength : length - headerLength - 3 - merges * recordLength;
|
|
@@ -309,7 +342,7 @@ export const readHeader = clustering => {
|
|
|
309
342
|
}
|
|
310
343
|
}
|
|
311
344
|
if (version > latestVersion) {
|
|
312
|
-
throw fail('unsupported-version', `
|
|
345
|
+
throw fail('unsupported-version', `Unsupported clustering: format version ${version} is newer than this version of agglomerative-clustering reads. Upgrade the package.`, 'clustering');
|
|
313
346
|
}
|
|
314
347
|
}
|
|
315
348
|
throw notAClustering(clustering);
|
|
@@ -324,6 +357,9 @@ export const checkPalette = palette => {
|
|
|
324
357
|
if (!isUint8Array(palette) && !isUint8ClampedArray(palette) && !Array.isArray(palette)) {
|
|
325
358
|
throw fail('invalid-argument', "Invalid palette: must be a Uint8Array of RGB bytes.", 'palette');
|
|
326
359
|
}
|
|
360
|
+
if (Array.isArray(palette) && palette.some(value => Array.isArray(value) || ArrayBuffer.isView(value))) {
|
|
361
|
+
throw fail('invalid-argument', "Invalid palette: a plain array must be flat RGB bytes, integers from 0 to 255, not an array of [r, g, b] colours. Flatten it first: colours.flat().", 'palette');
|
|
362
|
+
}
|
|
327
363
|
if (palette.length % 3 !== 0) {
|
|
328
364
|
throw fail('invalid-argument', "Invalid palette: length must be a multiple of 3 (flat RGB bytes).", 'palette');
|
|
329
365
|
}
|
package/dist/worker-thread.mjs
CHANGED
|
@@ -179,17 +179,47 @@ const onMessage = (data, post) => {
|
|
|
179
179
|
};
|
|
180
180
|
|
|
181
181
|
// No top-level await: bundlers build workers as classic scripts by default (Vite's 'iife'), which can't have it.
|
|
182
|
-
//
|
|
183
|
-
//
|
|
184
|
-
//
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
182
|
+
// Where Node's APIs exist (Node, Deno, Bun) the thread was usually started through worker_threads and talks through
|
|
183
|
+
// parentPort. Bun also defines the browser's `self.postMessage` inside such a thread, so `self` is not checked first. But a
|
|
184
|
+
// Web Worker can have Node's globals too (Electron with nodeIntegrationInWorker) and no worker_threads, or no parentPort:
|
|
185
|
+
// then it talks through `self`. Messages that arrive while that is decided are kept, since a Web Worker drops messages
|
|
186
|
+
// that find no listener. (`globalThis.process`, so bundlers don't take this for a use of Node's `process` to polyfill.)
|
|
187
|
+
const runtime = globalThis.process;
|
|
188
|
+
const isNode = !!(runtime && runtime.versions && runtime.versions.node);
|
|
189
|
+
const hasSelf = typeof self !== 'undefined' && typeof self.postMessage === 'function' && typeof self.addEventListener === 'function';
|
|
190
|
+
const viaSelf = (early = []) => {
|
|
191
|
+
const post = (message, transfer) => self.postMessage(message, transfer);
|
|
192
|
+
self.addEventListener('message', event => onMessage(event.data, post));
|
|
193
|
+
for (const data of early) {
|
|
194
|
+
onMessage(data, post);
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
if (!isNode && hasSelf) {
|
|
198
|
+
viaSelf();
|
|
188
199
|
} else {
|
|
200
|
+
const early = [];
|
|
201
|
+
const keep = event => early.push(event.data);
|
|
202
|
+
if (hasSelf) {
|
|
203
|
+
self.addEventListener('message', keep);
|
|
204
|
+
}
|
|
205
|
+
const fallback = () => {
|
|
206
|
+
if (!hasSelf) {
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
self.removeEventListener('message', keep);
|
|
210
|
+
viaSelf(early);
|
|
211
|
+
};
|
|
189
212
|
// Built at run time so no bundler tries to resolve it (see worker.js).
|
|
190
213
|
import(/* webpackIgnore: true */ /* @vite-ignore */['node', 'worker_threads'].join(':')).then(({
|
|
191
214
|
parentPort
|
|
192
215
|
}) => {
|
|
216
|
+
if (!parentPort) {
|
|
217
|
+
fallback();
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
if (hasSelf) {
|
|
221
|
+
self.removeEventListener('message', keep);
|
|
222
|
+
}
|
|
193
223
|
parentPort.on('message', data => onMessage(data, (message, transfer) => parentPort.postMessage(message, transfer)));
|
|
194
|
-
});
|
|
224
|
+
}, fallback);
|
|
195
225
|
}
|
package/dist/worker.d.ts
CHANGED
|
@@ -36,6 +36,22 @@ export interface WorkerOptions {
|
|
|
36
36
|
transfer?: boolean | undefined;
|
|
37
37
|
/** Where the worker gets its WebAssembly module; see `InitOptions`. It is sent as the worker's first call. */
|
|
38
38
|
wasm?: InitOptions['wasm'] | undefined;
|
|
39
|
+
/**
|
|
40
|
+
* The worker script to start, where the package's own isn't emitted or found: Angular's application builder, esbuild
|
|
41
|
+
* or Rollup without a worker plugin, a bundled Electron main process run from another directory. Point it at a copy
|
|
42
|
+
* of the package's `dist/worker-thread.mjs`, served or kept next to the rest of `dist/` (which it imports). A URL
|
|
43
|
+
* (relative URLs resolve against the page), or in Node a path (relative to the working directory) or `file:` URL.
|
|
44
|
+
*/
|
|
45
|
+
script?: string | URL | undefined;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Options for the worker entry's shared `init`: the main entry's, plus the shared worker's `script`. */
|
|
49
|
+
export interface SharedInitOptions extends InitOptions {
|
|
50
|
+
/**
|
|
51
|
+
* The shared worker's script (see `WorkerOptions.script`). Give it before any other call to the worker entry's
|
|
52
|
+
* functions: once the shared worker has started, a different script is rejected (call `terminate()` first).
|
|
53
|
+
*/
|
|
54
|
+
script?: string | URL | undefined;
|
|
39
55
|
}
|
|
40
56
|
|
|
41
57
|
/** An image and its clustering, kept in the worker so re-cutting and re-mapping them copies nothing across. */
|
|
@@ -89,8 +105,11 @@ export function createWorker(options?: WorkerOptions): AgglomerativeWorker;
|
|
|
89
105
|
export function terminate(): Promise<void>;
|
|
90
106
|
|
|
91
107
|
// The main entry's functions, run in one shared worker started on first use.
|
|
92
|
-
/**
|
|
93
|
-
|
|
108
|
+
/**
|
|
109
|
+
* The main entry's `init`, run in the shared worker (see `createWorker` for a worker of your own). It also takes the
|
|
110
|
+
* shared worker's `script`, before any other call.
|
|
111
|
+
*/
|
|
112
|
+
export function init(options?: SharedInitOptions): Promise<void>;
|
|
94
113
|
/** The main entry's `getClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
95
114
|
export const getClustering: AgglomerativeWorker['getClustering'];
|
|
96
115
|
/** The main entry's `getPalette`, run in the shared worker (see `createWorker` for a worker of your own). */
|
package/dist/worker.mjs
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// handle, so re-cutting and re-mapping it copies nothing across. The functions exported directly use one shared
|
|
5
5
|
// worker, started on first use.
|
|
6
6
|
|
|
7
|
-
import { fail, isOptionsObject, snapshot, mark, revive, latestVersion, imageHint } from "./shared.mjs";
|
|
7
|
+
import { fail, isOptionsObject, snapshot, mark, revive, latestVersion, imageHint, isDetached, imageDataLike } from "./shared.mjs";
|
|
8
8
|
|
|
9
9
|
// The same version, types and data-format version as the main entry (one implementation, in shared.js).
|
|
10
10
|
export { version, Palette, Clustering } from "./shared.mjs";
|
|
@@ -12,21 +12,42 @@ export const formatVersion = latestVersion;
|
|
|
12
12
|
|
|
13
13
|
// Node's worker_threads, where this script runs from a file in Node, Bun or Deno (from npm). A runtime that only imitates Node
|
|
14
14
|
// (Cloudflare Workers with nodejs_compat, a CDN copy in Deno) defines process.versions.node too, but isn't loaded from a file.
|
|
15
|
-
|
|
15
|
+
// A DOM in Node (jsdom or happy-dom, in tests) defines `window` but has no Worker, so it uses worker_threads too; a page with
|
|
16
|
+
// Node's globals and a real Worker (an Electron renderer with nodeIntegration) uses the Web Worker. `globalThis.process`, so
|
|
17
|
+
// bundlers don't take this for a use of Node's `process` and add a polyfill (Parcel installs one).
|
|
18
|
+
const runtime = globalThis.process;
|
|
19
|
+
const scriptUrl = typeof import.meta.url === 'string' ? import.meta.url : '';
|
|
20
|
+
const hasNode = !!(runtime && runtime.versions && runtime.versions.node) && (typeof window === 'undefined' || typeof Worker !== 'function');
|
|
21
|
+
const isNode = hasNode && scriptUrl.startsWith('file:');
|
|
22
|
+
// Node itself (or Bun) with this script bundled into CommonJS, where import.meta.url is gone: worker_threads still works, with
|
|
23
|
+
// the script given, or the package's own copy. Runtimes that imitate Node say what they are in navigator.userAgent.
|
|
24
|
+
const isBundledNode = hasNode && !scriptUrl && (typeof navigator === 'undefined' || /^(Node\.js|Bun)\//.test(String(navigator.userAgent)));
|
|
16
25
|
|
|
17
26
|
// The worker thread's script in Node: the one next to this file, which imports the main entry (index.mjs) next to it. A
|
|
18
27
|
// server bundle (Next.js with webpack or Turbopack) copies the script elsewhere without what it imports, and may hand
|
|
19
28
|
// over its URL as another realm's URL object, which Node's Worker rejects. Then the package's own copy is used, found the
|
|
20
29
|
// way Node resolves packages from the working directory. Built from strings so Node's own URL class makes it.
|
|
21
|
-
|
|
30
|
+
// `chosen` is the script given with createWorker({ script }): a URL, or a path (relative to the working directory).
|
|
31
|
+
const nodeWorkerScript = async chosen => {
|
|
22
32
|
const load = name => import(/* webpackIgnore: true */ /* @vite-ignore */['node', name].join(':'));
|
|
33
|
+
if (chosen) {
|
|
34
|
+
if (/^[a-z][a-z0-9+.-]+:/i.test(chosen) && !/^[a-z]:[\\/]/i.test(chosen)) {
|
|
35
|
+
return new URL(chosen);
|
|
36
|
+
}
|
|
37
|
+
const [{
|
|
38
|
+
resolve
|
|
39
|
+
}, {
|
|
40
|
+
pathToFileURL
|
|
41
|
+
}] = await Promise.all([load('path'), load('url')]);
|
|
42
|
+
return pathToFileURL(resolve(chosen));
|
|
43
|
+
}
|
|
23
44
|
// The base is a variable so bundlers don't take this Node-only URL for an asset to emit (Vite would copy the script a
|
|
24
45
|
// second time for it): they look for `new URL('…', import.meta.url)` written out, which the browser branch of `start` keeps.
|
|
25
|
-
const here =
|
|
46
|
+
const here = scriptUrl;
|
|
26
47
|
const file = './worker-thread.mjs';
|
|
27
48
|
let script = null;
|
|
28
49
|
try {
|
|
29
|
-
const made = new URL(file, here);
|
|
50
|
+
const made = new URL(file, here || undefined);
|
|
30
51
|
script = new URL(typeof made.href === 'string' ? made.href : String(made));
|
|
31
52
|
} catch (error) {/* a URL Node can't read: use the package's copy */}
|
|
32
53
|
try {
|
|
@@ -42,38 +63,74 @@ const nodeWorkerScript = async () => {
|
|
|
42
63
|
const {
|
|
43
64
|
createRequire
|
|
44
65
|
} = await load('module');
|
|
45
|
-
const packaged = new URL('./dist/worker-thread.mjs', pathToFileURL(createRequire(`${
|
|
66
|
+
const packaged = new URL('./dist/worker-thread.mjs', pathToFileURL(createRequire(`${runtime.cwd()}/`).resolve('agglomerative-clustering/package.json')));
|
|
46
67
|
if (existsSync(fileURLToPath(packaged))) {
|
|
47
68
|
return packaged;
|
|
48
69
|
}
|
|
49
70
|
} catch (error) {/* not found: start the script as it is, and report what happens */}
|
|
50
|
-
|
|
71
|
+
if (!script) {
|
|
72
|
+
throw fail('worker-failed', `Worker failed: ${noWorker()}`);
|
|
73
|
+
}
|
|
74
|
+
return script;
|
|
51
75
|
};
|
|
52
76
|
|
|
53
77
|
// Whether a worker script at `url` is on another origin than the page (or worker) starting it.
|
|
78
|
+
const webOrigins = ['http:', 'https:', 'chrome-extension:', 'moz-extension:', 'safari-web-extension:'];
|
|
54
79
|
const isCrossOrigin = url => {
|
|
55
80
|
try {
|
|
56
81
|
const here = typeof location !== 'undefined' && location.origin;
|
|
57
|
-
|
|
82
|
+
// http(s), and an extension's own scheme in a content script, which runs with the page's origin. (Not file:,
|
|
83
|
+
// which webpack gives import.meta.url at build time, nor blob: or data:.)
|
|
84
|
+
return Boolean(here) && here !== 'null' && webOrigins.includes(url.protocol) && url.origin !== here;
|
|
58
85
|
} catch (error) {
|
|
59
86
|
return false;
|
|
60
87
|
}
|
|
61
88
|
};
|
|
62
89
|
|
|
63
|
-
//
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
90
|
+
// The page's (or worker's) base URL, to resolve relative URLs given in options against: the page, as fetch would, not the
|
|
91
|
+
// worker script's folder, where the worker would otherwise resolve them.
|
|
92
|
+
const pageBase = () => {
|
|
93
|
+
try {
|
|
94
|
+
if (typeof document !== 'undefined' && typeof document.baseURI === 'string') {
|
|
95
|
+
return document.baseURI;
|
|
96
|
+
}
|
|
97
|
+
if (typeof location !== 'undefined' && typeof location.href === 'string') {
|
|
98
|
+
return location.href;
|
|
99
|
+
}
|
|
100
|
+
} catch (error) {/* no page */}
|
|
101
|
+
return undefined;
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
// Why the worker can't start where there is no Worker, by what the runtime is.
|
|
105
|
+
const noWorker = () => {
|
|
106
|
+
if (!scriptUrl) {
|
|
107
|
+
return "the worker entry can't find its worker script: import.meta.url is not available, so it was bundled into CommonJS or a classic script. Keep it an ES module, or say where the script is with createWorker({ script }) (a copy of the package's dist/worker-thread.mjs, served next to the rest of dist/).";
|
|
108
|
+
}
|
|
109
|
+
if (typeof ServiceWorkerGlobalScope !== 'undefined' && typeof self !== 'undefined' && self instanceof ServiceWorkerGlobalScope) {
|
|
110
|
+
return "this runtime has no Worker: a service worker (a browser extension's background script, for one) can't start threads. Use the main entry, 'agglomerative-clustering', there; it runs off the page's main thread already.";
|
|
111
|
+
}
|
|
112
|
+
return "this runtime has no Worker (a service worker, Cloudflare Workers or another edge runtime, or a test environment without worker support can't start threads). Use the main entry, 'agglomerative-clustering', instead.";
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
// Starts the worker and returns {post, terminate, ref, unref}, with messages delivered to `receive`. `chosen` is the
|
|
116
|
+
// script given with createWorker({ script }) (a URL, or in Node a path), or null for the package's own.
|
|
117
|
+
const start = async (receive, chosen) => {
|
|
118
|
+
if (!isNode && !isBundledNode) {
|
|
119
|
+
if (typeof Worker !== 'function' || !scriptUrl && !chosen) {
|
|
120
|
+
throw fail('worker-failed', `Worker failed: ${noWorker()}`);
|
|
68
121
|
}
|
|
69
122
|
// Where the script is when the package is used unbundled (from a CDN, say). The base is a variable so bundlers
|
|
70
123
|
// leave this one alone; they rewrite the literal `new Worker(new URL(...))` below, which must stay written out.
|
|
71
|
-
const here =
|
|
72
|
-
const script = new URL('./worker-thread.mjs', here);
|
|
124
|
+
const here = scriptUrl;
|
|
125
|
+
const script = chosen ? new URL(chosen, pageBase()) : new URL('./worker-thread.mjs', here);
|
|
73
126
|
const crossOrigin = isCrossOrigin(script);
|
|
74
127
|
let worker,
|
|
75
128
|
source = null;
|
|
76
|
-
if (crossOrigin) {
|
|
129
|
+
if (chosen && !crossOrigin) {
|
|
130
|
+
worker = new Worker(script, {
|
|
131
|
+
type: 'module'
|
|
132
|
+
});
|
|
133
|
+
} else if (crossOrigin) {
|
|
77
134
|
// A page can't start a worker from another origin's script, but a worker of its own can import one: a one-line
|
|
78
135
|
// module from a blob URL, which imports the script by its full URL (CDNs send the CORS headers that needs). A
|
|
79
136
|
// Content-Security-Policy then needs `worker-src blob:`.
|
|
@@ -106,7 +163,7 @@ const start = async receive => {
|
|
|
106
163
|
Worker: NodeWorker
|
|
107
164
|
} = await import(/* webpackIgnore: true */ /* @vite-ignore */['node', 'worker_threads'].join(':'));
|
|
108
165
|
// The worker script needs none of the parent's flags, and some (like --input-type) are invalid in a worker.
|
|
109
|
-
const worker = new NodeWorker(await nodeWorkerScript(), {
|
|
166
|
+
const worker = new NodeWorker(await nodeWorkerScript(chosen), {
|
|
110
167
|
execArgv: []
|
|
111
168
|
});
|
|
112
169
|
worker.on('message', receive);
|
|
@@ -169,6 +226,11 @@ const send = image => {
|
|
|
169
226
|
if (notPixels(image)) {
|
|
170
227
|
throw fail('invalid-argument', `Invalid image: expected object with \`data\` and \`format\`.${imageHint(image)}`, 'image');
|
|
171
228
|
}
|
|
229
|
+
// A detached buffer (transferred to a worker created with transfer: true, say) is reported as the main entry reports it.
|
|
230
|
+
const pixels = ArrayBuffer.isView(image) ? image : image && typeof image === 'object' && ArrayBuffer.isView(image.data) ? image.data : null;
|
|
231
|
+
if (pixels && isDetached(pixels)) {
|
|
232
|
+
throw fail('invalid-argument', "Invalid image: its pixels were transferred away (detached), for example to a worker created with transfer: true, so it has none left. Pass a copy if you need to keep using it.", 'image');
|
|
233
|
+
}
|
|
172
234
|
if (isImageData(image)) {
|
|
173
235
|
const data = image.data;
|
|
174
236
|
return {
|
|
@@ -198,14 +260,7 @@ const send = image => {
|
|
|
198
260
|
// RawImage, and a RawImage for ImageData, which is turned back into ImageData here.
|
|
199
261
|
const rebuild = image => {
|
|
200
262
|
if (isImageData(image)) {
|
|
201
|
-
|
|
202
|
-
width,
|
|
203
|
-
height,
|
|
204
|
-
colorSpace
|
|
205
|
-
} = image;
|
|
206
|
-
return result => new ImageData(new Uint8ClampedArray(result.data.buffer, result.data.byteOffset, result.data.byteLength), width, height, colorSpace ? {
|
|
207
|
-
colorSpace
|
|
208
|
-
} : undefined);
|
|
263
|
+
return result => imageDataLike(image, new Uint8ClampedArray(result.data.buffer, result.data.byteOffset, result.data.byteLength));
|
|
209
264
|
}
|
|
210
265
|
return result => result;
|
|
211
266
|
};
|
|
@@ -249,8 +304,17 @@ const remoteError = (info, origin) => {
|
|
|
249
304
|
// Checks the `wasm` option (see init in the main entry) and makes it fit for posting to the worker: a URL becomes its
|
|
250
305
|
// string, and bytes and compiled modules are cloned across.
|
|
251
306
|
const wasmOption = wasm => {
|
|
307
|
+
// A relative URL is resolved here, against the page, as fetch would; in the worker it would resolve against the worker
|
|
308
|
+
// script's folder. In Node it is a path, which the worker thread resolves against the same working directory.
|
|
252
309
|
if (typeof wasm === 'string') {
|
|
253
|
-
|
|
310
|
+
if (isNode || isBundledNode) {
|
|
311
|
+
return wasm;
|
|
312
|
+
}
|
|
313
|
+
try {
|
|
314
|
+
return new URL(wasm, pageBase()).href;
|
|
315
|
+
} catch (error) {
|
|
316
|
+
return wasm;
|
|
317
|
+
}
|
|
254
318
|
}
|
|
255
319
|
if (typeof wasm === 'object' && wasm !== null && (typeof URL !== 'undefined' && wasm instanceof URL || tagOf(wasm) === '[object URL]')) {
|
|
256
320
|
return wasm.href;
|
|
@@ -264,8 +328,22 @@ const wasmOption = wasm => {
|
|
|
264
328
|
throw fail('invalid-argument', "Invalid wasm: must be a URL or path string, a URL, an ArrayBuffer or typed array of the .wasm bytes, or a WebAssembly.Module.", 'options.wasm');
|
|
265
329
|
};
|
|
266
330
|
|
|
267
|
-
//
|
|
268
|
-
|
|
331
|
+
// The `script` option: the worker script to start, for setups where the package's own can't be found or bundled (Angular's
|
|
332
|
+
// application builder, esbuild or Rollup without a worker plugin, a bundled Electron main process): a copy of the package's
|
|
333
|
+
// dist/worker-thread.mjs, served or kept next to the rest of dist/, which it imports. A URL, or a string: in browsers
|
|
334
|
+
// resolved against the page, in Node a path relative to the working directory (or a file: URL).
|
|
335
|
+
const scriptOption = script => {
|
|
336
|
+
if (typeof script === 'string' && script.length > 0) {
|
|
337
|
+
return isNode || isBundledNode ? script : new URL(script, pageBase()).href;
|
|
338
|
+
}
|
|
339
|
+
if (typeof script === 'object' && script !== null && (typeof URL !== 'undefined' && script instanceof URL || tagOf(script) === '[object URL]')) {
|
|
340
|
+
return script.href;
|
|
341
|
+
}
|
|
342
|
+
throw fail('invalid-argument', "Invalid script: must be the URL (or in Node, the path) of a copy of the package's dist/worker-thread.mjs, as a string or a URL.", 'options.script');
|
|
343
|
+
};
|
|
344
|
+
|
|
345
|
+
// Options for init: `wasm`, and for the shared worker `script`, or none.
|
|
346
|
+
const initOptions = (options, allowScript) => {
|
|
269
347
|
if (options === undefined) {
|
|
270
348
|
return undefined;
|
|
271
349
|
}
|
|
@@ -274,13 +352,20 @@ const initOptions = options => {
|
|
|
274
352
|
}
|
|
275
353
|
options = snapshot(options);
|
|
276
354
|
for (const key of Object.keys(options)) {
|
|
277
|
-
if (key
|
|
278
|
-
throw fail('invalid-argument',
|
|
355
|
+
if (key === 'script' && !allowScript) {
|
|
356
|
+
throw fail('invalid-argument', "Invalid option 'script': a worker's script is chosen when it is created, with createWorker({ script }).", 'options.script');
|
|
357
|
+
}
|
|
358
|
+
if (key !== 'wasm' && key !== 'script') {
|
|
359
|
+
throw fail('invalid-argument', `Invalid option '${key}': expected ${allowScript ? 'script, wasm' : 'wasm'}.`, `options.${key}`);
|
|
279
360
|
}
|
|
280
361
|
}
|
|
281
|
-
|
|
362
|
+
const checked = options.wasm === undefined ? {} : {
|
|
282
363
|
wasm: wasmOption(options.wasm)
|
|
283
364
|
};
|
|
365
|
+
if (options.script !== undefined) {
|
|
366
|
+
checked.script = scriptOption(options.script);
|
|
367
|
+
}
|
|
368
|
+
return checked;
|
|
284
369
|
};
|
|
285
370
|
|
|
286
371
|
// A signal and a progress callback can't cross to the worker, so they stay on this side: the options are sent without
|
|
@@ -348,7 +433,9 @@ const mappedImageFunctions = ['quantize', 'quantizeFromClustering', 'quantizeWit
|
|
|
348
433
|
// These only map pixels, so they take a signal but no progress callback (see mapOptions in index.js).
|
|
349
434
|
const mappingOnlyFunctions = ['quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
|
|
350
435
|
const otherFunctions = ['getPaletteFromClustering', 'getSwatchesFromClustering', 'getClusteringInfo'];
|
|
351
|
-
|
|
436
|
+
|
|
437
|
+
// `allowScript`: whether init takes `script` (the shared worker's; createWorker takes it as an option instead).
|
|
438
|
+
const makeWorker = (options, allowScript) => {
|
|
352
439
|
if (options === undefined) {
|
|
353
440
|
options = {};
|
|
354
441
|
}
|
|
@@ -357,14 +444,16 @@ export const createWorker = options => {
|
|
|
357
444
|
}
|
|
358
445
|
options = snapshot(options);
|
|
359
446
|
for (const key of Object.keys(options)) {
|
|
360
|
-
if (key !== 'transfer' && key !== 'wasm') {
|
|
361
|
-
throw fail('invalid-argument', `Invalid option '${key}': expected transfer, wasm.`, `options.${key}`);
|
|
447
|
+
if (key !== 'transfer' && key !== 'wasm' && key !== 'script') {
|
|
448
|
+
throw fail('invalid-argument', `Invalid option '${key}': expected script, transfer, wasm.`, `options.${key}`);
|
|
362
449
|
}
|
|
363
450
|
}
|
|
364
451
|
if (options.transfer !== undefined && typeof options.transfer !== 'boolean') {
|
|
365
452
|
throw fail('invalid-argument', "Invalid transfer: must be a boolean.", 'options.transfer');
|
|
366
453
|
}
|
|
367
454
|
const transfer = options.transfer === true;
|
|
455
|
+
// The worker script to start instead of the package's own (see scriptOption); set by init({ script }) for the shared one.
|
|
456
|
+
let script = options.script === undefined ? null : scriptOption(options.script);
|
|
368
457
|
// Where the worker finds its .wasm: sent as the worker's first call, and repeated until it has succeeded.
|
|
369
458
|
const initialWasm = options.wasm === undefined ? undefined : wasmOption(options.wasm);
|
|
370
459
|
let initial = initialWasm === undefined ? null : {
|
|
@@ -490,10 +579,13 @@ export const createWorker = options => {
|
|
|
490
579
|
if (mine === generation) {
|
|
491
580
|
receive(message);
|
|
492
581
|
}
|
|
493
|
-
}).catch(error => {
|
|
582
|
+
}, script).catch(error => {
|
|
494
583
|
if (mine === generation) {
|
|
495
584
|
starting = null;
|
|
496
585
|
}
|
|
586
|
+
if (error && error.code === 'worker-failed') {
|
|
587
|
+
throw error;
|
|
588
|
+
}
|
|
497
589
|
throw Object.assign(fail('worker-failed', `Worker failed: ${error && error.message}`), {
|
|
498
590
|
cause: error
|
|
499
591
|
});
|
|
@@ -639,11 +731,24 @@ export const createWorker = options => {
|
|
|
639
731
|
const origin = new Error();
|
|
640
732
|
let checked;
|
|
641
733
|
try {
|
|
642
|
-
checked = initOptions(initArgs);
|
|
734
|
+
checked = initOptions(initArgs, allowScript);
|
|
735
|
+
if (checked !== undefined && checked.script !== undefined) {
|
|
736
|
+
// The script decides how the worker starts, so it can only be chosen before it has.
|
|
737
|
+
const chosen = checked.script;
|
|
738
|
+
if ((connection || starting) && chosen !== script) {
|
|
739
|
+
throw fail('invalid-argument', "Invalid script: the worker has already started. Call init({ script }) before any other call (or terminate() first).", 'options.script');
|
|
740
|
+
}
|
|
741
|
+
script = chosen;
|
|
742
|
+
const {
|
|
743
|
+
script: _script,
|
|
744
|
+
...rest
|
|
745
|
+
} = checked;
|
|
746
|
+
checked = rest;
|
|
747
|
+
}
|
|
643
748
|
} catch (error) {
|
|
644
749
|
return Promise.reject(error);
|
|
645
750
|
}
|
|
646
|
-
return invoke('init', checked === undefined ? [] : [checked], [], origin).then(() => undefined);
|
|
751
|
+
return invoke('init', checked === undefined || Object.keys(checked).length === 0 ? [] : [checked], [], origin).then(() => undefined);
|
|
647
752
|
};
|
|
648
753
|
|
|
649
754
|
// Clusters `image` and keeps it, with its clustering, in the worker.
|
|
@@ -760,8 +865,9 @@ export const createWorker = options => {
|
|
|
760
865
|
};
|
|
761
866
|
return instance;
|
|
762
867
|
};
|
|
868
|
+
export const createWorker = options => makeWorker(options, false);
|
|
763
869
|
let shared = null;
|
|
764
|
-
const sharedWorker = () => shared = shared ||
|
|
870
|
+
const sharedWorker = () => shared = shared || makeWorker({}, true);
|
|
765
871
|
|
|
766
872
|
// Stops the shared worker, rejecting calls still waiting. The next call starts a fresh one.
|
|
767
873
|
export const terminate = async () => {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agglomerative-clustering",
|
|
3
|
-
"version": "3.0.0-beta.
|
|
3
|
+
"version": "3.0.0-beta.4",
|
|
4
4
|
"description": "Colour palette extraction and image quantization with exact Ward clustering, in WebAssembly. Cluster an image once, then cut it to a palette of any size.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Rohan Fredriksson",
|
|
@@ -73,7 +73,7 @@
|
|
|
73
73
|
],
|
|
74
74
|
"scripts": {
|
|
75
75
|
"build:wasm": "mkdirp dist && em++ src/clustering.cpp -O3 -msimd128 -s WASM=1 -s MODULARIZE=1 -s EXPORT_ES6=1 -s EXPORT_NAME='createWasmModule' -s ALLOW_MEMORY_GROWTH=1 -s INITIAL_MEMORY=32MB -s MAXIMUM_MEMORY=2147483648 -s EXPORTED_FUNCTIONS=\"['_library_version','_get_clustering','_clustering_job_start','_clustering_job_step','_clustering_job_result','_clustering_job_free','_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','_malloc','_free']\" -s EXPORTED_RUNTIME_METHODS=\"['HEAPU8']\" -o dist/clustering.js && node scripts/patch-glue.mjs",
|
|
76
|
-
"build:cjs": "cross-env BABEL_ENV=cjs babel src --out-dir dist --extensions \".js\" --ignore \"src/worker.js\",\"src/worker-thread.js\" --out-file-extension .cjs",
|
|
76
|
+
"build:cjs": "cross-env BABEL_ENV=cjs babel src --out-dir dist --extensions \".js\" --ignore \"src/worker.js\",\"src/worker-thread.js\" --out-file-extension .cjs && node scripts/patch-cjs.mjs",
|
|
77
77
|
"build:esm": "cross-env BABEL_ENV=esm babel src --out-dir dist --extensions \".js\" --out-file-extension .mjs",
|
|
78
78
|
"build:types": "mkdirp dist && node -e \"const fs = require('fs'); for (const f of ['index.d.ts', 'worker.d.ts']) {fs.copyFileSync('src/' + f, 'dist/' + f);} fs.copyFileSync('src/index.d.ts', 'dist/index.d.cts');\"",
|
|
79
79
|
"build:js": "npm run build:types && npm run build:cjs && npm run build:esm",
|
|
@@ -101,6 +101,8 @@
|
|
|
101
101
|
"fast-png": "^8.0.0",
|
|
102
102
|
"gifenc": "^1.0.3",
|
|
103
103
|
"image-q": "^4.0.0",
|
|
104
|
+
"jest": "^30.5.2",
|
|
105
|
+
"jest-environment-jsdom": "^30.5.2",
|
|
104
106
|
"libimagequant-wasm": "^0.3.0",
|
|
105
107
|
"mkdirp": "^3.0.1",
|
|
106
108
|
"omggif": "^1.0.10",
|