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

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.
@@ -0,0 +1,968 @@
1
+ "use strict";
2
+ var __agglomerativeWorkerUrl = typeof __filename == "string" && globalThis.process && typeof globalThis.process.getBuiltinModule == "function" ? globalThis.process.getBuiltinModule("node:url").pathToFileURL(__filename).href : "";
3
+
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ Object.defineProperty(exports, "Clustering", {
9
+ enumerable: true,
10
+ get: function () {
11
+ return _shared.Clustering;
12
+ }
13
+ });
14
+ Object.defineProperty(exports, "Palette", {
15
+ enumerable: true,
16
+ get: function () {
17
+ return _shared.Palette;
18
+ }
19
+ });
20
+ exports.createWorker = void 0;
21
+ Object.defineProperty(exports, "errorCodes", {
22
+ enumerable: true,
23
+ get: function () {
24
+ return _shared.errorCodes;
25
+ }
26
+ });
27
+ exports.init = exports.getSwatchesFromClustering = exports.getSwatches = exports.getPaletteFromClustering = exports.getPalette = exports.getClusteringInfo = exports.getClustering = exports.formatVersion = void 0;
28
+ Object.defineProperty(exports, "isCodedError", {
29
+ enumerable: true,
30
+ get: function () {
31
+ return _shared.isCodedError;
32
+ }
33
+ });
34
+ exports.terminate = exports.quantizeWithPalette = exports.quantizeToIndicesWithPalette = exports.quantizeToIndicesFromClustering = exports.quantizeToIndices = exports.quantizeFromClustering = exports.quantize = void 0;
35
+ Object.defineProperty(exports, "version", {
36
+ enumerable: true,
37
+ get: function () {
38
+ return _shared.version;
39
+ }
40
+ });
41
+ var _shared = require("./shared.cjs");
42
+ 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 `agglomerative-clustering/worker` entry: the same API, run in a Web Worker (browsers) or a worker thread
43
+ // (Node), so clustering doesn't block the calling thread. `createWorker()` starts a worker with every function of
44
+ // the main entry as a method, plus `cluster`, which keeps an image and its clustering in the worker behind a
45
+ // handle, so re-cutting and re-mapping it copies nothing across. The functions exported directly use one shared
46
+ // worker, started on first use.
47
+ // The same version, types and data-format version as the main entry (one implementation, in shared.js).
48
+ const formatVersion = exports.formatVersion = _shared.latestVersion;
49
+
50
+ // Node's worker_threads, where this script runs from a file in Node, Bun or Deno (from npm). A runtime that only imitates Node
51
+ // (Cloudflare Workers with nodejs_compat, a CDN copy in Deno) defines process.versions.node too, but isn't loaded from a file.
52
+ // 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
53
+ // Node's globals and a real Worker (an Electron renderer with nodeIntegration) uses the Web Worker. `globalThis.process`, so
54
+ // bundlers don't take this for a use of Node's `process` and add a polyfill (Parcel installs one).
55
+ const runtime = globalThis.process;
56
+ const scriptUrl = typeof __agglomerativeWorkerUrl === 'string' ? __agglomerativeWorkerUrl : '';
57
+ const hasNode = !!(runtime && runtime.versions && runtime.versions.node) && (typeof window === 'undefined' || typeof Worker !== 'function');
58
+ const isNode = hasNode && scriptUrl.startsWith('file:');
59
+ // Node itself (or Bun) with this script bundled into CommonJS, where __agglomerativeWorkerUrl is gone: worker_threads still works, with
60
+ // the script given, or the package's own copy. Runtimes that imitate Node say what they are in navigator.userAgent.
61
+ const isBundledNode = hasNode && !scriptUrl && (typeof navigator === 'undefined' || /^(Node\.js|Bun)\//.test(String(navigator.userAgent)));
62
+
63
+ // The worker thread's script in Node: the one next to this file, which imports the main entry (index.mjs) next to it. A
64
+ // server bundle (Next.js with webpack or Turbopack) copies the script elsewhere without what it imports, and may hand
65
+ // over its URL as another realm's URL object, which Node's Worker rejects. Then the package's own copy is used, found the
66
+ // way Node resolves packages from the working directory. Built from strings so Node's own URL class makes it.
67
+ // `chosen` is the script given with createWorker({ script }): a URL, or a path (relative to the working directory).
68
+ const nodeWorkerScript = async chosen => {
69
+ const load = name => (specifier => new Promise(r => r(`${specifier}`)).then(s => _interopRequireWildcard(require(s))))(/* webpackIgnore: true */ /* @vite-ignore */['node', name].join(':'));
70
+ if (chosen) {
71
+ if (/^[a-z][a-z0-9+.-]+:/i.test(chosen) && !/^[a-z]:[\\/]/i.test(chosen)) {
72
+ return new URL(chosen);
73
+ }
74
+ const [{
75
+ resolve
76
+ }, {
77
+ pathToFileURL
78
+ }] = await Promise.all([load('path'), load('url')]);
79
+ return pathToFileURL(resolve(chosen));
80
+ }
81
+ // 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
82
+ // second time for it): they look for `new URL('…', __agglomerativeWorkerUrl)` written out, which the browser branch of `start` keeps.
83
+ const here = scriptUrl;
84
+ const file = './worker-thread.mjs';
85
+ let script = null;
86
+ try {
87
+ const made = new URL(file, here || undefined);
88
+ script = new URL(typeof made.href === 'string' ? made.href : String(made));
89
+ } catch (error) {/* a URL Node can't read: use the package's copy */}
90
+ try {
91
+ const [{
92
+ existsSync
93
+ }, {
94
+ fileURLToPath,
95
+ pathToFileURL
96
+ }] = await Promise.all([load('fs'), load('url')]);
97
+ if (script && script.protocol === 'file:' && existsSync(fileURLToPath(script)) && existsSync(fileURLToPath(new URL('./index.mjs', script)))) {
98
+ return script;
99
+ }
100
+ const {
101
+ createRequire
102
+ } = await load('module');
103
+ const packaged = new URL('./dist/worker-thread.mjs', pathToFileURL(createRequire(`${runtime.cwd()}/`).resolve('agglomerative-clustering/package.json')));
104
+ if (existsSync(fileURLToPath(packaged))) {
105
+ return packaged;
106
+ }
107
+ } catch (error) {/* not found: start the script as it is, and report what happens */}
108
+ if (!script) {
109
+ throw (0, _shared.fail)('worker-failed', `Worker failed: ${noWorker()}`);
110
+ }
111
+ return script;
112
+ };
113
+
114
+ // Whether a worker script at `url` is on another origin than the page (or worker) starting it.
115
+ const webOrigins = ['http:', 'https:', 'chrome-extension:', 'moz-extension:', 'safari-web-extension:'];
116
+ const isCrossOrigin = url => {
117
+ try {
118
+ const here = typeof location !== 'undefined' && location.origin;
119
+ // http(s), and an extension's own scheme in a content script, which runs with the page's origin. (Not file:,
120
+ // which webpack gives __agglomerativeWorkerUrl at build time, nor blob: or data:.)
121
+ return Boolean(here) && here !== 'null' && webOrigins.includes(url.protocol) && url.origin !== here;
122
+ } catch (error) {
123
+ return false;
124
+ }
125
+ };
126
+
127
+ // Whether the page (or worker) has an opaque origin: a sandboxed iframe without allow-same-origin, or a data: page.
128
+ const isOpaqueOrigin = () => {
129
+ try {
130
+ return typeof location !== 'undefined' && location.origin === 'null';
131
+ } catch (error) {
132
+ return false;
133
+ }
134
+ };
135
+
136
+ // The page's (or worker's) base URL, to resolve relative URLs given in options against: the page, as fetch would, not the
137
+ // worker script's folder, where the worker would otherwise resolve them.
138
+ const pageBase = () => {
139
+ try {
140
+ if (typeof document !== 'undefined' && typeof document.baseURI === 'string') {
141
+ return document.baseURI;
142
+ }
143
+ if (typeof location !== 'undefined' && typeof location.href === 'string') {
144
+ return location.href;
145
+ }
146
+ } catch (error) {/* no page */}
147
+ return undefined;
148
+ };
149
+
150
+ // Why the worker can't start where there is no Worker, by what the runtime is.
151
+ const noWorker = () => {
152
+ if (!scriptUrl) {
153
+ return "the worker entry can't find its worker script: it doesn't know its own URL, so it was bundled into CommonJS or a classic script, or loaded with require() (which gives the CommonJS build, made for Node and Jest). Import it as 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/).";
154
+ }
155
+ if (typeof ServiceWorkerGlobalScope !== 'undefined' && typeof self !== 'undefined' && self instanceof ServiceWorkerGlobalScope) {
156
+ 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.";
157
+ }
158
+ 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.";
159
+ };
160
+
161
+ // Starts the worker and returns {post, terminate, ref, unref}, with messages delivered to `receive`. `chosen` is the
162
+ // script given with createWorker({ script }) (a URL, or in Node a path), or null for the package's own.
163
+ const start = async (receive, chosen) => {
164
+ if (!isNode && !isBundledNode) {
165
+ if (typeof Worker !== 'function' || !scriptUrl && !chosen) {
166
+ throw (0, _shared.fail)('worker-failed', `Worker failed: ${noWorker()}`);
167
+ }
168
+ // Where the script is when the package is used unbundled (from a CDN, say). The base is a variable so bundlers
169
+ // leave this one alone; they rewrite the literal `new Worker(new URL(...))` below, which must stay written out.
170
+ const here = scriptUrl;
171
+ const script = chosen ? new URL(chosen, pageBase()) : new URL('./worker-thread.mjs', here);
172
+ const crossOrigin = isCrossOrigin(script);
173
+ // A page with an opaque origin (a sandboxed iframe without allow-same-origin, as plugin hosts such as Figma use) can't
174
+ // start a worker from any http(s) script, nor, in Chromium, from a blob: URL; a data: URL module can, and imports it.
175
+ const opaque = !crossOrigin && isOpaqueOrigin() && webOrigins.includes(script.protocol);
176
+ const scriptHint = "Check that worker-thread.mjs is served (open its URL), with index.mjs, shared.mjs, clustering.js and clustering.wasm next to it, which it imports, or say where your copy of dist/ is with createWorker({ script }) or, for the shared worker, init({ script }).";
177
+ let worker,
178
+ source = null;
179
+ try {
180
+ if (opaque) {
181
+ worker = new Worker(`data:text/javascript,${encodeURIComponent(`import ${JSON.stringify(script.href)};`)}`, {
182
+ type: 'module'
183
+ });
184
+ } else if (chosen && !crossOrigin) {
185
+ worker = new Worker(script, {
186
+ type: 'module'
187
+ });
188
+ } else if (crossOrigin) {
189
+ // A page can't start a worker from another origin's script, but a worker of its own can import one: a one-line
190
+ // module from a blob URL, which imports the script by its full URL (CDNs send the CORS headers that needs). A
191
+ // Content-Security-Policy then needs `worker-src blob:` and the script's origin.
192
+ source = URL.createObjectURL(new Blob([`import ${JSON.stringify(script.href)};`], {
193
+ type: 'text/javascript'
194
+ }));
195
+ worker = new Worker(source, {
196
+ type: 'module'
197
+ });
198
+ setTimeout(() => URL.revokeObjectURL(source), 60000);
199
+ } else {
200
+ // Written out in full so bundlers (Vite, webpack 5, Parcel) find and bundle the worker script.
201
+ worker = new Worker(new URL('./worker-thread.mjs', __agglomerativeWorkerUrl), {
202
+ type: 'module'
203
+ });
204
+ }
205
+ } catch (error) {
206
+ throw Object.assign((0, _shared.fail)('worker-failed', `Worker failed: ${error && error.message} ${scriptHint}`), {
207
+ cause: error
208
+ });
209
+ }
210
+ worker.addEventListener('message', event => receive(event.data));
211
+ worker.addEventListener('error', event => receive({
212
+ failure: event.message ? `${event.message} ${scriptHint}` : crossOrigin ? `The worker failed to start: its script comes from another origin (${script.origin}), so it was started through a blob: URL, which also failed. Check that the server sends CORS headers, and that a Content-Security-Policy allows the worker: worker-src needs both blob: and ${script.origin} (the blob: worker imports the script from there). Or serve a copy of dist/ from this origin and say where with createWorker({ script }) or init({ script }).` : opaque ? `The worker failed to start from this page, whose origin is opaque (a sandboxed iframe): it was started from a data: URL importing ${script.href}, which needs CORS headers on that script and on what it imports. Or bundle worker-thread.mjs and its imports into one file, and pass it as a data: URL with createWorker({ script }).` : `The worker failed to start${chosen ? ` from ${script.href}` : ''}. ${scriptHint} A Content-Security-Policy must also allow it as a worker (worker-src).`
213
+ }));
214
+ return {
215
+ post: (message, transfer) => worker.postMessage(message, transfer),
216
+ terminate: () => worker.terminate(),
217
+ ref: () => {},
218
+ unref: () => {}
219
+ };
220
+ }
221
+ // The specifier is built at run time so no bundler tries to resolve it (esbuild ignores comment hints on a literal).
222
+ const {
223
+ Worker: NodeWorker
224
+ } = await (specifier => new Promise(r => r(`${specifier}`)).then(s => _interopRequireWildcard(require(s))))(/* webpackIgnore: true */ /* @vite-ignore */['node', 'worker_threads'].join(':'));
225
+ // The worker script needs none of the parent's flags, and some (like --input-type) are invalid in a worker.
226
+ const worker = new NodeWorker(await nodeWorkerScript(chosen), {
227
+ execArgv: []
228
+ });
229
+ worker.on('message', receive);
230
+ // A worker script that can't be found, or that can't find what it imports: a copy of dist/ split up or bundled away.
231
+ const missing = error => error && (error.code === 'ERR_MODULE_NOT_FOUND' || /Cannot find module|import\.meta' outside a module/.test(String(error.message)));
232
+ worker.on('error', error => receive({
233
+ failure: missing(error) ? `${error.message}. The worker script (worker-thread.mjs) needs index.mjs, shared.mjs, clustering.js and clustering.wasm next to it: keep dist/ together, and say where it is with createWorker({ script }) or, for the shared worker, init({ script }) (a path, or a file: URL).` : error.message
234
+ }));
235
+ worker.on('exit', code => receive({
236
+ failure: `The worker exited unexpectedly (code ${code}).`
237
+ }));
238
+ worker.unref();
239
+ return {
240
+ post: (message, transfer) => worker.postMessage(message, transfer),
241
+ terminate: () => worker.terminate(),
242
+ ref: () => worker.ref(),
243
+ unref: () => worker.unref()
244
+ };
245
+ };
246
+
247
+ // Checked by tag as well as `instanceof`, so a module compiled by a bundler's runtime is recognised (see index.js).
248
+ const tagOf = value => Object.prototype.toString.call(value);
249
+ const isWasmModule = value => typeof value === 'object' && value !== null && (typeof WebAssembly !== 'undefined' && value instanceof WebAssembly.Module || tagOf(value) === '[object WebAssembly.Module]');
250
+
251
+ // A copy of the bytes in an argument (a typed array, or an image's `data`), for a call made before the worker is ready to
252
+ // take it: the caller may change or reuse its arrays as soon as the call returns, as with the main entry. Once the worker
253
+ // is running, a call posts (and so copies or transfers) its arguments before it returns.
254
+ const own = value => {
255
+ if (ArrayBuffer.isView(value)) {
256
+ const copy = value.slice();
257
+ // A Palette or Clustering keeps its tags (slice gives a plain array).
258
+ for (const key of Object.getOwnPropertySymbols(value)) {
259
+ Object.defineProperty(copy, key, {
260
+ value: value[key]
261
+ });
262
+ }
263
+ if (Object.prototype.hasOwnProperty.call(value, 'colorSpace')) {
264
+ Object.defineProperty(copy, 'colorSpace', {
265
+ value: value.colorSpace
266
+ });
267
+ }
268
+ return copy;
269
+ }
270
+ if ((0, _shared.isOptionsObject)(value) && ArrayBuffer.isView(value.data)) {
271
+ return {
272
+ ...value,
273
+ data: value.data.slice()
274
+ };
275
+ }
276
+ return value;
277
+ };
278
+
279
+ // Images cross to the worker as plain {data, format, width?, height?} objects (ImageData can't cross into Node
280
+ // worker threads, and its clamped array needn't), and mapped images are rebuilt in the caller's type on return.
281
+ // Anything else is sent as it is, so the worker's validation gives the usual errors.
282
+ // Things that aren't pixels and can't be posted (a canvas, an image element, an ImageBitmap, a Blob) are reported here with
283
+ // the main entry's hint, rather than as the structured clone's own error, which says nothing about what to pass instead.
284
+ const notPixels = image => image !== null && typeof image === 'object' && !ArrayBuffer.isView(image) && !(0, _shared.isImageData)(image) && (typeof image.getContext === 'function' || typeof image.close === 'function' || typeof image.nodeName === 'string' || typeof image.arrayBuffer === 'function' && typeof image.type === 'string');
285
+ const send = image => {
286
+ if (notPixels(image)) {
287
+ throw (0, _shared.fail)('invalid-argument', `Invalid image: expected object with \`data\` and \`format\`.${(0, _shared.imageHint)(image)}`, 'image');
288
+ }
289
+ // A detached buffer (transferred to a worker created with transfer: true, say) is reported as the main entry reports it.
290
+ const pixels = ArrayBuffer.isView(image) ? image : image && typeof image === 'object' && ArrayBuffer.isView(image.data) ? image.data : null;
291
+ if (pixels && (0, _shared.isDetached)(pixels)) {
292
+ throw (0, _shared.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');
293
+ }
294
+ if ((0, _shared.isImageData)(image)) {
295
+ const data = image.data;
296
+ return {
297
+ data: new Uint8Array(data.buffer, data.byteOffset, data.byteLength),
298
+ format: 'rgba',
299
+ width: image.width,
300
+ height: image.height
301
+ };
302
+ }
303
+ if (image && typeof image === 'object' && !ArrayBuffer.isView(image) && ArrayBuffer.isView(image.data)) {
304
+ const sent = {
305
+ data: image.data,
306
+ format: image.format
307
+ };
308
+ if (image.width !== undefined) {
309
+ sent.width = image.width;
310
+ }
311
+ if (image.height !== undefined) {
312
+ sent.height = image.height;
313
+ }
314
+ return sent;
315
+ }
316
+ return image;
317
+ };
318
+
319
+ // The worker returns what the main entry gives for the image it was sent: the same type for a Uint8Array or a
320
+ // RawImage, and a RawImage for ImageData, which is turned back into ImageData here.
321
+ const rebuild = image => {
322
+ if ((0, _shared.isImageData)(image)) {
323
+ return result => (0, _shared.imageDataLike)(image, new Uint8ClampedArray(result.data.buffer, result.data.byteOffset, result.data.byteLength));
324
+ }
325
+ return result => result;
326
+ };
327
+
328
+ // The buffer behind an image's pixels, to transfer when the worker was created with `transfer: true`: only when the
329
+ // pixels are the whole of an ordinary ArrayBuffer. Transferring empties every view of the buffer, so a view into part
330
+ // of a larger one (a subarray, a small Node Buffer from Node's shared pool) is copied instead, as is shared memory.
331
+ const pixelBuffers = sent => {
332
+ const data = ArrayBuffer.isView(sent) ? sent : sent && ArrayBuffer.isView(sent.data) ? sent.data : null;
333
+ if (!data || !(data.buffer instanceof ArrayBuffer) || data.byteOffset !== 0 || data.byteLength !== data.buffer.byteLength) {
334
+ return [];
335
+ }
336
+ return [data.buffer];
337
+ };
338
+
339
+ // Rebuilds an error that happened in the worker: same name, message and code as the main entry gives for the same
340
+ // input, the stack of the call that failed (`origin`, made when the call was sent), and the worker's own stack as `cause`.
341
+ const remoteError = (info, origin) => {
342
+ const error = new Error(info.message);
343
+ if (info.name && info.name !== 'Error') {
344
+ error.name = info.name;
345
+ }
346
+ if (info.code !== undefined) {
347
+ error.code = info.code;
348
+ }
349
+ if (info.argument !== undefined) {
350
+ error.argument = info.argument;
351
+ }
352
+ if (origin.stack) {
353
+ error.stack = `${error.name}: ${error.message}${origin.stack.slice(origin.stack.indexOf('\n'))}`;
354
+ }
355
+ if (info.stack) {
356
+ const cause = new Error(info.message);
357
+ cause.name = error.name;
358
+ cause.stack = info.stack;
359
+ error.cause = cause;
360
+ }
361
+ return error;
362
+ };
363
+
364
+ // Checks the `wasm` option (see init in the main entry) and makes it fit for posting to the worker: a URL becomes its
365
+ // string, and bytes and compiled modules are cloned across.
366
+ const wasmOption = wasm => {
367
+ // A relative URL is resolved here, against the page, as fetch would; in the worker it would resolve against the worker
368
+ // script's folder. In Node it is a path, which the worker thread resolves against the same working directory.
369
+ if (typeof wasm === 'string') {
370
+ if (isNode || isBundledNode) {
371
+ return wasm;
372
+ }
373
+ try {
374
+ return new URL(wasm, pageBase()).href;
375
+ } catch (error) {
376
+ return wasm;
377
+ }
378
+ }
379
+ if (typeof wasm === 'object' && wasm !== null && (typeof URL !== 'undefined' && wasm instanceof URL || tagOf(wasm) === '[object URL]')) {
380
+ return wasm.href;
381
+ }
382
+ if (wasm instanceof ArrayBuffer || tagOf(wasm) === '[object ArrayBuffer]' || ArrayBuffer.isView(wasm)) {
383
+ return wasm;
384
+ }
385
+ if (isWasmModule(wasm)) {
386
+ return wasm;
387
+ }
388
+ throw (0, _shared.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');
389
+ };
390
+
391
+ // The `script` option: the worker script to start, for setups where the package's own can't be found or bundled (Angular's
392
+ // application builder, esbuild or Rollup without a worker plugin, a bundled Electron main process): a copy of the package's
393
+ // dist/worker-thread.mjs, served or kept next to the rest of dist/, which it imports. A URL, or a string: in browsers
394
+ // resolved against the page, in Node a path relative to the working directory (or a file: URL).
395
+ const scriptOption = script => {
396
+ if (typeof script === 'string' && script.length > 0) {
397
+ return isNode || isBundledNode ? script : new URL(script, pageBase()).href;
398
+ }
399
+ if (typeof script === 'object' && script !== null && (typeof URL !== 'undefined' && script instanceof URL || tagOf(script) === '[object URL]')) {
400
+ return script.href;
401
+ }
402
+ throw (0, _shared.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');
403
+ };
404
+
405
+ // Options for init: `wasm`, and for the shared worker `script`, or none.
406
+ const initOptions = (options, allowScript) => {
407
+ if (options === undefined) {
408
+ return undefined;
409
+ }
410
+ if (!(0, _shared.isOptionsObject)(options)) {
411
+ throw (0, _shared.fail)('invalid-argument', "Invalid options: expected an object.", 'options');
412
+ }
413
+ options = (0, _shared.snapshot)(options);
414
+ for (const key of Object.keys(options)) {
415
+ if (key === 'script' && !allowScript) {
416
+ throw (0, _shared.fail)('invalid-argument', "Invalid option 'script': a worker's script is chosen when it is created, with createWorker({ script }).", 'options.script');
417
+ }
418
+ if (key !== 'wasm' && key !== 'script') {
419
+ throw (0, _shared.fail)('invalid-argument', `Invalid option '${key}': expected ${allowScript ? 'script, wasm' : 'wasm'}.`, `options.${key}`);
420
+ }
421
+ }
422
+ const checked = options.wasm === undefined ? {} : {
423
+ wasm: wasmOption(options.wasm)
424
+ };
425
+ if (options.script !== undefined) {
426
+ checked.script = scriptOption(options.script);
427
+ }
428
+ return checked;
429
+ };
430
+
431
+ // A signal and a progress callback can't cross to the worker, so they stay on this side: the options are sent without
432
+ // them, a cancel message is sent when the signal aborts, and the worker's progress messages call the callback.
433
+ const takeControls = (options, progressAllowed = true) => {
434
+ // Anything but an ordinary object goes on as it is, for the worker's own validation to reject. An ordinary one is copied
435
+ // once first: structured cloning drops inherited properties, and the copy is what gets validated and sent.
436
+ if (!(0, _shared.isOptionsObject)(options)) {
437
+ return {
438
+ options,
439
+ signal: undefined,
440
+ onProgress: undefined
441
+ };
442
+ }
443
+ options = (0, _shared.snapshot)(options);
444
+ const {
445
+ signal,
446
+ onProgress
447
+ } = options;
448
+ if (!progressAllowed && onProgress !== undefined) {
449
+ throw (0, _shared.fail)('invalid-argument', "Invalid option 'onProgress': the functions that only map pixels take just `signal`.", 'options.onProgress');
450
+ }
451
+ if (signal === undefined && onProgress === undefined) {
452
+ return {
453
+ options,
454
+ signal,
455
+ onProgress
456
+ };
457
+ }
458
+ if (signal !== undefined && (signal === null || typeof signal !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function')) {
459
+ throw (0, _shared.fail)('invalid-argument', "Invalid signal: must be an AbortSignal.", 'options.signal');
460
+ }
461
+ if (onProgress !== undefined && typeof onProgress !== 'function') {
462
+ throw (0, _shared.fail)('invalid-argument', "Invalid onProgress: must be a function.", 'options.onProgress');
463
+ }
464
+ const {
465
+ signal: _signal,
466
+ onProgress: _onProgress,
467
+ ...rest
468
+ } = options;
469
+ return {
470
+ options: rest,
471
+ signal,
472
+ onProgress
473
+ };
474
+ };
475
+
476
+ // Where the options sit among a function's arguments after the image (see takeControls).
477
+ const optionsPosition = {
478
+ getClustering: 0,
479
+ getPalette: 1,
480
+ getSwatches: 1,
481
+ quantize: 1,
482
+ quantizeFromClustering: 2,
483
+ quantizeWithPalette: 1,
484
+ quantizeToIndices: 1,
485
+ quantizeToIndicesFromClustering: 2,
486
+ quantizeToIndicesWithPalette: 1
487
+ };
488
+
489
+ // Like fetch: an aborted call rejects with the signal's reason, an AbortError unless the caller gave another.
490
+ const abortReason = signal => signal.reason !== undefined ? signal.reason : new DOMException('This operation was aborted', 'AbortError');
491
+ const imageFunctions = ['getClustering', 'getPalette', 'getSwatches', 'quantize', 'quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndices', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
492
+ const mappedImageFunctions = ['quantize', 'quantizeFromClustering', 'quantizeWithPalette'];
493
+ // These only map pixels, so they take a signal but no progress callback (see mapOptions in index.js).
494
+ const mappingOnlyFunctions = ['quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
495
+ const otherFunctions = ['getPaletteFromClustering', 'getSwatchesFromClustering', 'getClusteringInfo'];
496
+
497
+ // `allowScript`: whether init takes `script` (the shared worker's; createWorker takes it as an option instead).
498
+ const makeWorker = (options, allowScript) => {
499
+ if (options === undefined) {
500
+ options = {};
501
+ }
502
+ if (!(0, _shared.isOptionsObject)(options)) {
503
+ throw (0, _shared.fail)('invalid-argument', "Invalid options: expected an object.", 'options');
504
+ }
505
+ options = (0, _shared.snapshot)(options);
506
+ for (const key of Object.keys(options)) {
507
+ if (key !== 'transfer' && key !== 'wasm' && key !== 'script') {
508
+ throw (0, _shared.fail)('invalid-argument', `Invalid option '${key}': expected script, transfer, wasm.`, `options.${key}`);
509
+ }
510
+ }
511
+ if (options.transfer !== undefined && typeof options.transfer !== 'boolean') {
512
+ throw (0, _shared.fail)('invalid-argument', "Invalid transfer: must be a boolean.", 'options.transfer');
513
+ }
514
+ const transfer = options.transfer === true;
515
+ // The worker script to start instead of the package's own (see scriptOption); set by init({ script }) for the shared one.
516
+ let script = options.script === undefined ? null : scriptOption(options.script);
517
+ // Where the worker finds its .wasm: sent as the worker's first call, and repeated until it has succeeded.
518
+ const initialWasm = options.wasm === undefined ? undefined : wasmOption(options.wasm);
519
+ let initial = initialWasm === undefined ? null : {
520
+ wasm: initialWasm
521
+ };
522
+ let initialising = null;
523
+ let connection = null;
524
+ let starting = null;
525
+ // Counts the workers this instance has started, so a late message or error from one it already dropped is ignored.
526
+ let generation = 0;
527
+ let startingGeneration = 0;
528
+ let terminated = false;
529
+ let nextId = 1;
530
+ let nextHandle = 1;
531
+ const pending = new Map();
532
+ // Whether a call made now is posted before it returns (see `own`).
533
+ const ready = () => connection !== null && !initial;
534
+ // The image of a call made before the worker is ready: with `transfer: true` its buffer is moved out of the caller's
535
+ // hands at once (a structured clone that transfers it, so the caller's array empties now, as it would on posting),
536
+ // otherwise copied.
537
+ const take = sent => {
538
+ const buffers = transfer ? pixelBuffers(sent) : [];
539
+ if (buffers.length > 0 && typeof structuredClone === 'function') {
540
+ try {
541
+ return structuredClone(sent, {
542
+ transfer: buffers
543
+ });
544
+ } catch (error) {/* untransferable: copy it */}
545
+ }
546
+ return own(sent);
547
+ };
548
+
549
+ // Safety net for handles dropped without release(): when a handle is garbage-collected, the worker frees what it
550
+ // kept for it. Best-effort, since collection time is up to the engine; release() or `await using` is the contract.
551
+ const reclaim = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(id => {
552
+ if (!terminated) {
553
+ invoke('release', [id], [], new Error()).catch(() => {});
554
+ }
555
+ }) : null;
556
+
557
+ // A worker that failed (could not start, crashed or exited) is dropped: the calls waiting on it get the failure, and
558
+ // the next call starts a new one, which either works or fails the same clear way. Without this, later calls would be
559
+ // posted to a thread that will never answer and hang forever. Handles kept in the dropped worker are gone with it.
560
+ const lose = reason => {
561
+ const lost = connection;
562
+ generation++;
563
+ connection = null;
564
+ starting = null;
565
+ initialising = null;
566
+ if (initialWasm !== undefined) {
567
+ initial = {
568
+ wasm: initialWasm
569
+ };
570
+ }
571
+ const calls = [...pending.values()];
572
+ pending.clear();
573
+ for (const call of calls) {
574
+ call.cleanup();
575
+ call.reject((0, _shared.fail)('worker-failed', reason));
576
+ }
577
+ if (lost) {
578
+ try {
579
+ Promise.resolve(lost.terminate()).catch(() => {});
580
+ } catch (ignored) {/* already gone */}
581
+ }
582
+ };
583
+ const receive = message => {
584
+ if (message.failure !== undefined) {
585
+ if (!terminated) {
586
+ lose(`Worker failed: ${message.failure}`);
587
+ }
588
+ return;
589
+ }
590
+ const call = pending.get(message.id);
591
+ if (!call) {
592
+ return;
593
+ }
594
+ if (message.progress !== undefined) {
595
+ // As on the main thread, a callback that throws fails the call (with its error) and stops the work.
596
+ if (call.onProgress) {
597
+ try {
598
+ call.onProgress(message.progress);
599
+ } catch (error) {
600
+ pending.delete(message.id);
601
+ call.cleanup();
602
+ if (pending.size === 0 && connection) {
603
+ connection.unref();
604
+ }
605
+ try {
606
+ connection.post({
607
+ cancel: message.id
608
+ }, []);
609
+ } catch (ignored) {/* the worker is gone anyway */}
610
+ call.reject(error);
611
+ }
612
+ }
613
+ return;
614
+ }
615
+ pending.delete(message.id);
616
+ call.cleanup();
617
+ if (pending.size === 0 && connection) {
618
+ connection.unref();
619
+ }
620
+ if (message.error !== undefined) {
621
+ call.reject(remoteError(message.error, call.origin));
622
+ } else {
623
+ call.resolve((0, _shared.revive)(message.result));
624
+ }
625
+ };
626
+
627
+ // `origin` is an Error made in the caller's own (non-async) function, for the stack of a failure: async helpers
628
+ // from transpiled code would otherwise fill the stack's frame limit before the caller shows up.
629
+ const invoke = async (method, args, transferable, origin, controls = {}) => {
630
+ if (terminated) {
631
+ throw (0, _shared.fail)('worker-terminated', "Worker terminated.");
632
+ }
633
+ if (!connection) {
634
+ if (!starting) {
635
+ const mine = ++generation;
636
+ startingGeneration = mine;
637
+ // A start that fails is not kept, so the next call tries again.
638
+ starting = start(message => {
639
+ if (mine === generation) {
640
+ receive(message);
641
+ }
642
+ }, script).catch(error => {
643
+ if (mine === generation) {
644
+ starting = null;
645
+ }
646
+ if (error && error.code === 'worker-failed') {
647
+ throw error;
648
+ }
649
+ throw Object.assign((0, _shared.fail)('worker-failed', `Worker failed: ${error && error.message}`), {
650
+ cause: error
651
+ });
652
+ });
653
+ }
654
+ const waitingFor = startingGeneration;
655
+ const started = await starting;
656
+ if (terminated) {
657
+ started.terminate();
658
+ throw (0, _shared.fail)('worker-terminated', "Worker terminated.");
659
+ }
660
+ // The worker may have failed in the instant between starting and being adopted; it has been dropped then.
661
+ if (waitingFor !== generation) {
662
+ throw (0, _shared.fail)('worker-failed', 'Worker failed while starting.');
663
+ }
664
+ connection = connection || started;
665
+ }
666
+ if (initial && !(method === 'init' && args.length > 0 && args[0].wasm !== undefined)) {
667
+ initialising = initialising || post('init', [initial], [], origin).then(() => {
668
+ initial = null;
669
+ }, error => {
670
+ initialising = null;
671
+ throw error;
672
+ });
673
+ await initialising;
674
+ }
675
+ return post(method, args, transferable, origin, controls);
676
+ };
677
+ const post = (method, args, transferable, origin, {
678
+ signal,
679
+ onProgress
680
+ } = {}) => {
681
+ if (terminated) {
682
+ return Promise.reject((0, _shared.fail)('worker-terminated', "Worker terminated."));
683
+ }
684
+ if (signal && signal.aborted) {
685
+ return Promise.reject(abortReason(signal));
686
+ }
687
+ const id = nextId++;
688
+ return new Promise((resolve, reject) => {
689
+ if (pending.size === 0) {
690
+ connection.ref();
691
+ }
692
+ const call = {
693
+ resolve,
694
+ reject,
695
+ origin,
696
+ onProgress,
697
+ cleanup: () => {}
698
+ };
699
+ if (signal) {
700
+ // Rejects at once; the worker is told to stop (it may still be working on an earlier call or this one,
701
+ // and drops whatever it produces). The thread no longer keeps a Node process alive for this call.
702
+ const abort = () => {
703
+ if (!pending.delete(id)) {
704
+ return;
705
+ }
706
+ if (pending.size === 0) {
707
+ connection.unref();
708
+ }
709
+ try {
710
+ connection.post({
711
+ cancel: id
712
+ }, []);
713
+ } catch (error) {/* the worker is gone anyway */}
714
+ reject(abortReason(signal));
715
+ };
716
+ signal.addEventListener('abort', abort, {
717
+ once: true
718
+ });
719
+ call.cleanup = () => signal.removeEventListener('abort', abort);
720
+ }
721
+ pending.set(id, call);
722
+ try {
723
+ const message = {
724
+ id,
725
+ method,
726
+ args: args.map(_shared.mark),
727
+ cancellable: signal !== undefined || onProgress !== undefined,
728
+ progress: onProgress !== undefined
729
+ };
730
+ try {
731
+ connection.post(message, transfer ? transferable : []);
732
+ } catch (error) {
733
+ // Some whole buffers still can't be transferred (Node marks some untransferable): copy them instead.
734
+ // A message that can't be copied either fails the same way again, and is reported below.
735
+ if (!(transfer && transferable.length > 0 && error && error.name === 'DataCloneError')) {
736
+ throw error;
737
+ }
738
+ connection.post(message, []);
739
+ }
740
+ } catch (error) {
741
+ pending.delete(id);
742
+ call.cleanup();
743
+ if (pending.size === 0) {
744
+ connection.unref();
745
+ }
746
+ // A value that can't be structured-cloned (a function, symbol or promise) is an invalid argument, as it
747
+ // would be if the main entry were called with it.
748
+ reject(error && error.name === 'DataCloneError' ? Object.assign((0, _shared.fail)('invalid-argument', `Invalid argument: it cannot be sent to the worker (${error.message})`), {
749
+ cause: error
750
+ }) : error);
751
+ }
752
+ });
753
+ };
754
+ const instance = {};
755
+ for (const name of imageFunctions) {
756
+ const mapped = mappedImageFunctions.includes(name);
757
+ instance[name] = (image, ...rest) => {
758
+ const origin = new Error();
759
+ return (async () => {
760
+ const position = optionsPosition[name];
761
+ const {
762
+ options,
763
+ signal,
764
+ onProgress
765
+ } = takeControls(rest[position], !mappingOnlyFunctions.includes(name));
766
+ // Checked before the image is copied or transferred away, so an aborted call leaves it with the caller.
767
+ if (signal && signal.aborted) {
768
+ throw abortReason(signal);
769
+ }
770
+ let args = rest.slice();
771
+ if (position < args.length) {
772
+ args[position] = options;
773
+ }
774
+ let sent = send(image);
775
+ if (!ready()) {
776
+ sent = take(sent);
777
+ args = args.map(own);
778
+ }
779
+ const result = await invoke(name, [sent, ...args], pixelBuffers(sent), origin, {
780
+ signal,
781
+ onProgress
782
+ });
783
+ return mapped ? rebuild(image)(result) : result;
784
+ })();
785
+ };
786
+ }
787
+ for (const name of otherFunctions) {
788
+ instance[name] = (...args) => invoke(name, ready() ? args : args.map(own), [], new Error());
789
+ }
790
+ instance.init = initArgs => {
791
+ const origin = new Error();
792
+ let checked;
793
+ try {
794
+ checked = initOptions(initArgs, allowScript);
795
+ if (checked !== undefined && checked.script !== undefined) {
796
+ // The script decides how the worker starts, so it can only be chosen before it has.
797
+ const chosen = checked.script;
798
+ if ((connection || starting) && chosen !== script) {
799
+ throw (0, _shared.fail)('invalid-argument', "Invalid script: the worker has already started. Call init({ script }) before any other call (or terminate() first).", 'options.script');
800
+ }
801
+ script = chosen;
802
+ const {
803
+ script: _script,
804
+ ...rest
805
+ } = checked;
806
+ checked = rest;
807
+ }
808
+ } catch (error) {
809
+ return Promise.reject(error);
810
+ }
811
+ return invoke('init', checked === undefined || Object.keys(checked).length === 0 ? [] : [checked], [], origin).then(() => undefined);
812
+ };
813
+
814
+ // Clusters `image` and keeps it, with its clustering, in the worker.
815
+ instance.cluster = (image, clusterOptions) => {
816
+ const origin = new Error();
817
+ return (async () => {
818
+ const {
819
+ options,
820
+ signal,
821
+ onProgress
822
+ } = takeControls(clusterOptions);
823
+ if (signal && signal.aborted) {
824
+ throw abortReason(signal);
825
+ }
826
+ const id = nextHandle++;
827
+ const sent = ready() ? send(image) : take(send(image));
828
+ try {
829
+ await invoke('cluster', [id, sent, options], pixelBuffers(sent), origin, {
830
+ signal,
831
+ onProgress
832
+ });
833
+ } catch (error) {
834
+ // A cancelled call is rejected at once, but the worker may have finished it just before it heard: it
835
+ // would then keep the image and clustering with nobody able to release them. Releasing an unknown handle
836
+ // is harmless, and this message follows the cluster call in the worker's queue.
837
+ if (!terminated) {
838
+ invoke('release', [id], [], new Error()).catch(() => {});
839
+ }
840
+ throw error;
841
+ }
842
+ const output = rebuild(image);
843
+ let released = false;
844
+ // Every method goes through `use`, which refers to `handle`, so a method kept after the handle itself is dropped
845
+ // keeps it alive and it is not reclaimed while still in use.
846
+ const use = (method, args, controls) => {
847
+ if (released || !handle) {
848
+ return Promise.reject((0, _shared.fail)('invalid-handle', "Invalid handle: it was released."));
849
+ }
850
+ return invoke(method, [id, ...args], [], new Error(), controls);
851
+ };
852
+ // Calls with mapping options, whose signal and progress callback stay on this side (see takeControls).
853
+ const withControls = (method, leading, mapOptions) => {
854
+ let taken;
855
+ try {
856
+ taken = takeControls(mapOptions, false);
857
+ } catch (error) {
858
+ return Promise.reject(error);
859
+ }
860
+ return use(method, [...leading, taken.options], {
861
+ signal: taken.signal,
862
+ onProgress: taken.onProgress
863
+ });
864
+ };
865
+ // The cuts take no options (the handle's clustering already says how it was made): one passed anyway is an error,
866
+ // as in the main entry, rather than silently ignored.
867
+ const plain = (method, name, args, extra) => extra.some(value => value !== undefined) ? Promise.reject((0, _shared.fail)('invalid-argument', `Invalid arguments: handle.${name} takes no options. To map pixels with options, use handle.quantize.`, 'options')) : use(method, args);
868
+ const handle = {
869
+ getClustering: (...extra) => plain('handleGetClustering', 'getClustering', [], extra),
870
+ getPalette: (k, ...extra) => plain('handleGetPalette', 'getPalette', [k], extra),
871
+ getSwatches: (k, ...extra) => plain('handleGetSwatches', 'getSwatches', [k], extra),
872
+ getClusteringInfo: (...extra) => plain('handleGetClusteringInfo', 'getClusteringInfo', [], extra),
873
+ quantize: async (k, mapOptions) => output(await withControls('handleQuantize', [k], mapOptions)),
874
+ quantizeToIndices: (k, mapOptions) => withControls('handleQuantizeToIndices', [k], mapOptions),
875
+ quantizeWithPalette: async (palette, mapOptions) => output(await withControls('handleQuantizeWithPalette', [palette], mapOptions)),
876
+ quantizeToIndicesWithPalette: (palette, mapOptions) => withControls('handleQuantizeToIndicesWithPalette', [palette], mapOptions),
877
+ release: async () => {
878
+ if (released) {
879
+ return;
880
+ }
881
+ released = true;
882
+ if (reclaim) {
883
+ reclaim.unregister(handle);
884
+ }
885
+ // If the worker has been terminated there is nothing left to free (so `await using` and
886
+ // terminate() can come in either order); any other failure is reported.
887
+ try {
888
+ await invoke('release', [id], [], new Error());
889
+ } catch (error) {
890
+ if (error.code !== 'worker-terminated') {
891
+ throw error;
892
+ }
893
+ }
894
+ }
895
+ };
896
+ // `await using handle = await worker.cluster(image)` releases it at the end of the block.
897
+ if (typeof Symbol.asyncDispose === 'symbol') {
898
+ handle[Symbol.asyncDispose] = handle.release;
899
+ }
900
+ if (reclaim) {
901
+ reclaim.register(handle, id, handle);
902
+ }
903
+ return handle;
904
+ })();
905
+ };
906
+
907
+ // Stops the worker. Calls still waiting are rejected, and later calls fail.
908
+ instance.terminate = async () => {
909
+ if (terminated) {
910
+ return;
911
+ }
912
+ terminated = true;
913
+ for (const call of pending.values()) {
914
+ call.cleanup();
915
+ call.reject((0, _shared.fail)('worker-terminated', "Worker terminated."));
916
+ }
917
+ pending.clear();
918
+ if (connection) {
919
+ await connection.terminate();
920
+ } else if (starting) {
921
+ try {
922
+ (await starting).terminate();
923
+ } catch (ignored) {/* it never started */}
924
+ }
925
+ };
926
+ return instance;
927
+ };
928
+ const createWorker = options => makeWorker(options, false);
929
+ exports.createWorker = createWorker;
930
+ let shared = null;
931
+ const sharedWorker = () => shared = shared || makeWorker({}, true);
932
+
933
+ // Stops the shared worker, rejecting calls still waiting. The next call starts a fresh one.
934
+ const terminate = async () => {
935
+ if (!shared) {
936
+ return;
937
+ }
938
+ const stopping = shared;
939
+ shared = null;
940
+ await stopping.terminate();
941
+ };
942
+ exports.terminate = terminate;
943
+ const init = (...args) => sharedWorker().init(...args);
944
+ exports.init = init;
945
+ const getClustering = (...args) => sharedWorker().getClustering(...args);
946
+ exports.getClustering = getClustering;
947
+ const getPalette = (...args) => sharedWorker().getPalette(...args);
948
+ exports.getPalette = getPalette;
949
+ const getPaletteFromClustering = (...args) => sharedWorker().getPaletteFromClustering(...args);
950
+ exports.getPaletteFromClustering = getPaletteFromClustering;
951
+ const getSwatches = (...args) => sharedWorker().getSwatches(...args);
952
+ exports.getSwatches = getSwatches;
953
+ const getSwatchesFromClustering = (...args) => sharedWorker().getSwatchesFromClustering(...args);
954
+ exports.getSwatchesFromClustering = getSwatchesFromClustering;
955
+ const getClusteringInfo = (...args) => sharedWorker().getClusteringInfo(...args);
956
+ exports.getClusteringInfo = getClusteringInfo;
957
+ const quantize = (...args) => sharedWorker().quantize(...args);
958
+ exports.quantize = quantize;
959
+ const quantizeFromClustering = (...args) => sharedWorker().quantizeFromClustering(...args);
960
+ exports.quantizeFromClustering = quantizeFromClustering;
961
+ const quantizeWithPalette = (...args) => sharedWorker().quantizeWithPalette(...args);
962
+ exports.quantizeWithPalette = quantizeWithPalette;
963
+ const quantizeToIndices = (...args) => sharedWorker().quantizeToIndices(...args);
964
+ exports.quantizeToIndices = quantizeToIndices;
965
+ const quantizeToIndicesFromClustering = (...args) => sharedWorker().quantizeToIndicesFromClustering(...args);
966
+ exports.quantizeToIndicesFromClustering = quantizeToIndicesFromClustering;
967
+ const quantizeToIndicesWithPalette = (...args) => sharedWorker().quantizeToIndicesWithPalette(...args);
968
+ exports.quantizeToIndicesWithPalette = quantizeToIndicesWithPalette;