agglomerative-clustering 3.0.0-beta.3 → 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.
- package/README.md +221 -24
- package/dist/clustering.cjs +3 -0
- package/dist/clustering.js +1 -1
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +101 -43
- package/dist/index.d.cts +12 -1
- package/dist/index.d.ts +12 -1
- package/dist/index.mjs +76 -38
- package/dist/shared.cjs +57 -5
- package/dist/shared.mjs +51 -3
- package/dist/worker-thread.mjs +37 -7
- package/dist/worker.cjs +968 -0
- package/dist/worker.d.cts +142 -0
- package/dist/worker.d.ts +27 -2
- package/dist/worker.mjs +187 -58
- package/package.json +17 -6
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// `[Symbol.asyncDispose]` on handles needs TypeScript's `esnext.disposable` lib (TypeScript 5.2 and newer); this
|
|
2
|
+
// directive pulls it in. Older TypeScript versions report it unless `skipLibCheck` is on, as it is in most setups.
|
|
3
|
+
/// <reference lib="esnext.disposable" />
|
|
4
|
+
|
|
5
|
+
import type {
|
|
6
|
+
ImageLike, RawImage, ClusteringOptions, MappingOptions, QuantizeOptions, QuantizeIndexOptions, MappingIndexOptions,
|
|
7
|
+
IndexedImage, ClusteringInfo, InitOptions, ImageResult, PaletteLike, Swatches,
|
|
8
|
+
} from './index.cjs';
|
|
9
|
+
import type { Palette, Clustering } from './index.cjs';
|
|
10
|
+
|
|
11
|
+
/** The same class as the main entry's `Palette`: flat RGB bytes that know their colour space. */
|
|
12
|
+
export { Palette } from './index.cjs';
|
|
13
|
+
|
|
14
|
+
/** The same class as the main entry's `Clustering`: the typed bytes of a clustering. */
|
|
15
|
+
export { Clustering } from './index.cjs';
|
|
16
|
+
|
|
17
|
+
/** The same list as the main entry's `errorCodes`: the worker entry's errors have the same codes. */
|
|
18
|
+
export { errorCodes } from './index.cjs';
|
|
19
|
+
|
|
20
|
+
/** The main entry's `isCodedError`: true for this library's errors, from either entry. */
|
|
21
|
+
export { isCodedError } from './index.cjs';
|
|
22
|
+
|
|
23
|
+
/** The version of this library, as in its `package.json`: the same value as the main entry's `version`. */
|
|
24
|
+
export const version: string;
|
|
25
|
+
|
|
26
|
+
/** The version of the data this library stores (clusterings): the same value as the main entry's `formatVersion`. */
|
|
27
|
+
export const formatVersion: 3;
|
|
28
|
+
|
|
29
|
+
export type {
|
|
30
|
+
ImageFormat, RawImage, ImageLike, PaletteLike, PlatformImageData, ImageResult, WasmModule, ColorSpace, AlphaMode, ClusteringOptions, MappingOptions, QuantizeOptions,
|
|
31
|
+
ErrorCode, ErrorArgument, CodedError, InitOptions, RunOptions, CancelOptions, IndexOptions, QuantizeIndexOptions, MappingIndexOptions, IndexedImage, ClusteringInfo, ClusteringInfoV2, ClusteringInfoV3, Swatches,
|
|
32
|
+
} from './index.cjs';
|
|
33
|
+
|
|
34
|
+
/** Options for `createWorker`. */
|
|
35
|
+
export interface WorkerOptions {
|
|
36
|
+
/**
|
|
37
|
+
* `false` (default): images are copied to the worker. `true`: their pixel buffers are transferred instead,
|
|
38
|
+
* which is faster for large images but leaves the caller's buffer detached (empty) afterwards. Only pixels that
|
|
39
|
+
* are a whole buffer of their own are transferred: a view into part of a larger buffer (a subarray, a small Node
|
|
40
|
+
* Buffer) is copied, so the caller's other data in that buffer is never detached.
|
|
41
|
+
*/
|
|
42
|
+
transfer?: boolean | undefined;
|
|
43
|
+
/** Where the worker gets its WebAssembly module; see `InitOptions`. It is sent as the worker's first call. */
|
|
44
|
+
wasm?: InitOptions['wasm'] | undefined;
|
|
45
|
+
/**
|
|
46
|
+
* The worker script to start, where the package's own isn't emitted or found: Angular's application builder, esbuild
|
|
47
|
+
* or Rollup without a worker plugin, a bundled Electron main process run from another directory. Point it at a copy
|
|
48
|
+
* of the package's `dist/worker-thread.mjs`, served or kept next to the rest of `dist/` (which it imports). A URL
|
|
49
|
+
* (relative URLs resolve against the page), or in Node a path (relative to the working directory) or `file:` URL.
|
|
50
|
+
*/
|
|
51
|
+
script?: string | URL | undefined;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Options for the worker entry's shared `init`: the main entry's, plus the shared worker's `script`. */
|
|
55
|
+
export interface SharedInitOptions extends InitOptions {
|
|
56
|
+
/**
|
|
57
|
+
* The shared worker's script (see `WorkerOptions.script`). Give it before any other call to the worker entry's
|
|
58
|
+
* functions: once the shared worker has started, a different script is rejected (call `terminate()` first).
|
|
59
|
+
*/
|
|
60
|
+
script?: string | URL | undefined;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** An image and its clustering, kept in the worker so re-cutting and re-mapping them copies nothing across. */
|
|
64
|
+
export interface ClusteringHandle<Image extends ImageLike = ImageLike> {
|
|
65
|
+
getClustering(): Promise<Clustering>;
|
|
66
|
+
getPalette(k: number): Promise<Palette>;
|
|
67
|
+
getSwatches(k: number): Promise<Swatches>;
|
|
68
|
+
getClusteringInfo(): Promise<ClusteringInfo>;
|
|
69
|
+
/** Maps the kept image to the k-colour palette. Returns the same type as the image given to `cluster`. */
|
|
70
|
+
quantize(k: number, options?: MappingOptions): Promise<Image>;
|
|
71
|
+
quantizeToIndices(k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
|
|
72
|
+
/** Maps the kept image to a palette of your own (an edited swatch, a brand palette) without sending the pixels again. */
|
|
73
|
+
quantizeWithPalette(palette: PaletteLike, options?: MappingOptions): Promise<Image>;
|
|
74
|
+
quantizeToIndicesWithPalette(palette: PaletteLike, options?: MappingIndexOptions): Promise<IndexedImage>;
|
|
75
|
+
/**
|
|
76
|
+
* Frees the image and clustering in the worker. Later calls on the handle fail. Call it when you are done, or
|
|
77
|
+
* declare the handle with `await using`, which does. A handle that is dropped without either is freed once it is
|
|
78
|
+
* garbage-collected, but when that happens is up to the JavaScript engine.
|
|
79
|
+
*/
|
|
80
|
+
release(): Promise<void>;
|
|
81
|
+
/** The same as `release()`, for `await using`. Present where the runtime has `Symbol.asyncDispose`. */
|
|
82
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The main entry's functions, run in a worker, plus handles and `terminate`. */
|
|
86
|
+
export interface AgglomerativeWorker {
|
|
87
|
+
/** Loads the module in the worker. `wasm` is the only option, and `createWorker({ wasm })` does the same. */
|
|
88
|
+
init(options?: InitOptions): Promise<void>;
|
|
89
|
+
getClustering(image: ImageLike, options?: ClusteringOptions): Promise<Clustering>;
|
|
90
|
+
getPalette(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Palette>;
|
|
91
|
+
getPaletteFromClustering(clustering: Clustering, k: number): Promise<Palette>;
|
|
92
|
+
getSwatches(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Swatches>;
|
|
93
|
+
getSwatchesFromClustering(clustering: Clustering, k: number): Promise<Swatches>;
|
|
94
|
+
getClusteringInfo(clustering: Clustering): Promise<ClusteringInfo>;
|
|
95
|
+
quantize<Image extends ImageLike>(image: Image, k: number, options?: QuantizeOptions): Promise<ImageResult<Image>>;
|
|
96
|
+
quantizeFromClustering<Image extends ImageLike>(image: Image, clustering: Clustering, k: number, options?: MappingOptions): Promise<ImageResult<Image>>;
|
|
97
|
+
quantizeWithPalette<Image extends ImageLike>(image: Image, palette: PaletteLike, options?: MappingOptions): Promise<ImageResult<Image>>;
|
|
98
|
+
quantizeToIndices(image: ImageLike, k: number, options?: QuantizeIndexOptions): Promise<IndexedImage>;
|
|
99
|
+
quantizeToIndicesFromClustering(image: ImageLike, clustering: Clustering, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
|
|
100
|
+
quantizeToIndicesWithPalette(image: ImageLike, palette: PaletteLike, options?: MappingIndexOptions): Promise<IndexedImage>;
|
|
101
|
+
/** Clusters `image` and keeps it, with its clustering, in the worker. */
|
|
102
|
+
cluster<Image extends ImageLike>(image: Image, options?: ClusteringOptions): Promise<ClusteringHandle<ImageResult<Image>>>;
|
|
103
|
+
/** Stops the worker. Calls still waiting are rejected, and later calls fail. */
|
|
104
|
+
terminate(): Promise<void>;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Starts a worker: a Web Worker in browsers, a worker thread in Node. It never keeps a Node process alive while idle. */
|
|
108
|
+
export function createWorker(options?: WorkerOptions): AgglomerativeWorker;
|
|
109
|
+
|
|
110
|
+
/** Stops the shared worker used by the exports below, rejecting calls still waiting. The next call starts a new one. */
|
|
111
|
+
export function terminate(): Promise<void>;
|
|
112
|
+
|
|
113
|
+
// The main entry's functions, run in one shared worker started on first use.
|
|
114
|
+
/**
|
|
115
|
+
* The main entry's `init`, run in the shared worker (see `createWorker` for a worker of your own). It also takes the
|
|
116
|
+
* shared worker's `script`, before any other call.
|
|
117
|
+
*/
|
|
118
|
+
export function init(options?: SharedInitOptions): Promise<void>;
|
|
119
|
+
/** The main entry's `getClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
120
|
+
export const getClustering: AgglomerativeWorker['getClustering'];
|
|
121
|
+
/** The main entry's `getPalette`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
122
|
+
export const getPalette: AgglomerativeWorker['getPalette'];
|
|
123
|
+
/** The main entry's `getPaletteFromClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
124
|
+
export const getPaletteFromClustering: AgglomerativeWorker['getPaletteFromClustering'];
|
|
125
|
+
/** The main entry's `getSwatches`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
126
|
+
export const getSwatches: AgglomerativeWorker['getSwatches'];
|
|
127
|
+
/** The main entry's `getSwatchesFromClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
128
|
+
export const getSwatchesFromClustering: AgglomerativeWorker['getSwatchesFromClustering'];
|
|
129
|
+
/** The main entry's `getClusteringInfo`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
130
|
+
export const getClusteringInfo: AgglomerativeWorker['getClusteringInfo'];
|
|
131
|
+
/** The main entry's `quantize`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
132
|
+
export const quantize: AgglomerativeWorker['quantize'];
|
|
133
|
+
/** The main entry's `quantizeFromClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
134
|
+
export const quantizeFromClustering: AgglomerativeWorker['quantizeFromClustering'];
|
|
135
|
+
/** The main entry's `quantizeWithPalette`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
136
|
+
export const quantizeWithPalette: AgglomerativeWorker['quantizeWithPalette'];
|
|
137
|
+
/** The main entry's `quantizeToIndices`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
138
|
+
export const quantizeToIndices: AgglomerativeWorker['quantizeToIndices'];
|
|
139
|
+
/** The main entry's `quantizeToIndicesFromClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
140
|
+
export const quantizeToIndicesFromClustering: AgglomerativeWorker['quantizeToIndicesFromClustering'];
|
|
141
|
+
/** The main entry's `quantizeToIndicesWithPalette`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
142
|
+
export const quantizeToIndicesWithPalette: AgglomerativeWorker['quantizeToIndicesWithPalette'];
|
package/dist/worker.d.ts
CHANGED
|
@@ -14,6 +14,12 @@ export { Palette } from './index.js';
|
|
|
14
14
|
/** The same class as the main entry's `Clustering`: the typed bytes of a clustering. */
|
|
15
15
|
export { Clustering } from './index.js';
|
|
16
16
|
|
|
17
|
+
/** The same list as the main entry's `errorCodes`: the worker entry's errors have the same codes. */
|
|
18
|
+
export { errorCodes } from './index.js';
|
|
19
|
+
|
|
20
|
+
/** The main entry's `isCodedError`: true for this library's errors, from either entry. */
|
|
21
|
+
export { isCodedError } from './index.js';
|
|
22
|
+
|
|
17
23
|
/** The version of this library, as in its `package.json`: the same value as the main entry's `version`. */
|
|
18
24
|
export const version: string;
|
|
19
25
|
|
|
@@ -36,6 +42,22 @@ export interface WorkerOptions {
|
|
|
36
42
|
transfer?: boolean | undefined;
|
|
37
43
|
/** Where the worker gets its WebAssembly module; see `InitOptions`. It is sent as the worker's first call. */
|
|
38
44
|
wasm?: InitOptions['wasm'] | undefined;
|
|
45
|
+
/**
|
|
46
|
+
* The worker script to start, where the package's own isn't emitted or found: Angular's application builder, esbuild
|
|
47
|
+
* or Rollup without a worker plugin, a bundled Electron main process run from another directory. Point it at a copy
|
|
48
|
+
* of the package's `dist/worker-thread.mjs`, served or kept next to the rest of `dist/` (which it imports). A URL
|
|
49
|
+
* (relative URLs resolve against the page), or in Node a path (relative to the working directory) or `file:` URL.
|
|
50
|
+
*/
|
|
51
|
+
script?: string | URL | undefined;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Options for the worker entry's shared `init`: the main entry's, plus the shared worker's `script`. */
|
|
55
|
+
export interface SharedInitOptions extends InitOptions {
|
|
56
|
+
/**
|
|
57
|
+
* The shared worker's script (see `WorkerOptions.script`). Give it before any other call to the worker entry's
|
|
58
|
+
* functions: once the shared worker has started, a different script is rejected (call `terminate()` first).
|
|
59
|
+
*/
|
|
60
|
+
script?: string | URL | undefined;
|
|
39
61
|
}
|
|
40
62
|
|
|
41
63
|
/** An image and its clustering, kept in the worker so re-cutting and re-mapping them copies nothing across. */
|
|
@@ -89,8 +111,11 @@ export function createWorker(options?: WorkerOptions): AgglomerativeWorker;
|
|
|
89
111
|
export function terminate(): Promise<void>;
|
|
90
112
|
|
|
91
113
|
// The main entry's functions, run in one shared worker started on first use.
|
|
92
|
-
/**
|
|
93
|
-
|
|
114
|
+
/**
|
|
115
|
+
* The main entry's `init`, run in the shared worker (see `createWorker` for a worker of your own). It also takes the
|
|
116
|
+
* shared worker's `script`, before any other call.
|
|
117
|
+
*/
|
|
118
|
+
export function init(options?: SharedInitOptions): Promise<void>;
|
|
94
119
|
/** The main entry's `getClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
|
|
95
120
|
export const getClustering: AgglomerativeWorker['getClustering'];
|
|
96
121
|
/** The main entry's `getPalette`, run in the shared worker (see `createWorker` for a worker of your own). */
|
package/dist/worker.mjs
CHANGED
|
@@ -4,29 +4,50 @@
|
|
|
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, isImageData } 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
|
-
export { version, Palette, Clustering } from "./shared.mjs";
|
|
10
|
+
export { version, Palette, Clustering, errorCodes, isCodedError } from "./shared.mjs";
|
|
11
11
|
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,57 +63,116 @@ 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;
|
|
85
|
+
} catch (error) {
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
// Whether the page (or worker) has an opaque origin: a sandboxed iframe without allow-same-origin, or a data: page.
|
|
91
|
+
const isOpaqueOrigin = () => {
|
|
92
|
+
try {
|
|
93
|
+
return typeof location !== 'undefined' && location.origin === 'null';
|
|
58
94
|
} catch (error) {
|
|
59
95
|
return false;
|
|
60
96
|
}
|
|
61
97
|
};
|
|
62
98
|
|
|
63
|
-
//
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
99
|
+
// The page's (or worker's) base URL, to resolve relative URLs given in options against: the page, as fetch would, not the
|
|
100
|
+
// worker script's folder, where the worker would otherwise resolve them.
|
|
101
|
+
const pageBase = () => {
|
|
102
|
+
try {
|
|
103
|
+
if (typeof document !== 'undefined' && typeof document.baseURI === 'string') {
|
|
104
|
+
return document.baseURI;
|
|
105
|
+
}
|
|
106
|
+
if (typeof location !== 'undefined' && typeof location.href === 'string') {
|
|
107
|
+
return location.href;
|
|
108
|
+
}
|
|
109
|
+
} catch (error) {/* no page */}
|
|
110
|
+
return undefined;
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
// Why the worker can't start where there is no Worker, by what the runtime is.
|
|
114
|
+
const noWorker = () => {
|
|
115
|
+
if (!scriptUrl) {
|
|
116
|
+
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/).";
|
|
117
|
+
}
|
|
118
|
+
if (typeof ServiceWorkerGlobalScope !== 'undefined' && typeof self !== 'undefined' && self instanceof ServiceWorkerGlobalScope) {
|
|
119
|
+
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.";
|
|
120
|
+
}
|
|
121
|
+
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.";
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
// Starts the worker and returns {post, terminate, ref, unref}, with messages delivered to `receive`. `chosen` is the
|
|
125
|
+
// script given with createWorker({ script }) (a URL, or in Node a path), or null for the package's own.
|
|
126
|
+
const start = async (receive, chosen) => {
|
|
127
|
+
if (!isNode && !isBundledNode) {
|
|
128
|
+
if (typeof Worker !== 'function' || !scriptUrl && !chosen) {
|
|
129
|
+
throw fail('worker-failed', `Worker failed: ${noWorker()}`);
|
|
68
130
|
}
|
|
69
131
|
// Where the script is when the package is used unbundled (from a CDN, say). The base is a variable so bundlers
|
|
70
132
|
// 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);
|
|
133
|
+
const here = scriptUrl;
|
|
134
|
+
const script = chosen ? new URL(chosen, pageBase()) : new URL('./worker-thread.mjs', here);
|
|
73
135
|
const crossOrigin = isCrossOrigin(script);
|
|
136
|
+
// A page with an opaque origin (a sandboxed iframe without allow-same-origin, as plugin hosts such as Figma use) can't
|
|
137
|
+
// start a worker from any http(s) script, nor, in Chromium, from a blob: URL; a data: URL module can, and imports it.
|
|
138
|
+
const opaque = !crossOrigin && isOpaqueOrigin() && webOrigins.includes(script.protocol);
|
|
139
|
+
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 }).";
|
|
74
140
|
let worker,
|
|
75
141
|
source = null;
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
})
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
142
|
+
try {
|
|
143
|
+
if (opaque) {
|
|
144
|
+
worker = new Worker(`data:text/javascript,${encodeURIComponent(`import ${JSON.stringify(script.href)};`)}`, {
|
|
145
|
+
type: 'module'
|
|
146
|
+
});
|
|
147
|
+
} else if (chosen && !crossOrigin) {
|
|
148
|
+
worker = new Worker(script, {
|
|
149
|
+
type: 'module'
|
|
150
|
+
});
|
|
151
|
+
} else if (crossOrigin) {
|
|
152
|
+
// A page can't start a worker from another origin's script, but a worker of its own can import one: a one-line
|
|
153
|
+
// module from a blob URL, which imports the script by its full URL (CDNs send the CORS headers that needs). A
|
|
154
|
+
// Content-Security-Policy then needs `worker-src blob:` and the script's origin.
|
|
155
|
+
source = URL.createObjectURL(new Blob([`import ${JSON.stringify(script.href)};`], {
|
|
156
|
+
type: 'text/javascript'
|
|
157
|
+
}));
|
|
158
|
+
worker = new Worker(source, {
|
|
159
|
+
type: 'module'
|
|
160
|
+
});
|
|
161
|
+
setTimeout(() => URL.revokeObjectURL(source), 60000);
|
|
162
|
+
} else {
|
|
163
|
+
// Written out in full so bundlers (Vite, webpack 5, Parcel) find and bundle the worker script.
|
|
164
|
+
worker = new Worker(new URL('./worker-thread.mjs', import.meta.url), {
|
|
165
|
+
type: 'module'
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
} catch (error) {
|
|
169
|
+
throw Object.assign(fail('worker-failed', `Worker failed: ${error && error.message} ${scriptHint}`), {
|
|
170
|
+
cause: error
|
|
91
171
|
});
|
|
92
172
|
}
|
|
93
173
|
worker.addEventListener('message', event => receive(event.data));
|
|
94
174
|
worker.addEventListener('error', event => receive({
|
|
95
|
-
failure: event.message
|
|
175
|
+
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).`
|
|
96
176
|
}));
|
|
97
177
|
return {
|
|
98
178
|
post: (message, transfer) => worker.postMessage(message, transfer),
|
|
@@ -106,12 +186,14 @@ const start = async receive => {
|
|
|
106
186
|
Worker: NodeWorker
|
|
107
187
|
} = await import(/* webpackIgnore: true */ /* @vite-ignore */['node', 'worker_threads'].join(':'));
|
|
108
188
|
// 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(), {
|
|
189
|
+
const worker = new NodeWorker(await nodeWorkerScript(chosen), {
|
|
110
190
|
execArgv: []
|
|
111
191
|
});
|
|
112
192
|
worker.on('message', receive);
|
|
193
|
+
// 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.
|
|
194
|
+
const missing = error => error && (error.code === 'ERR_MODULE_NOT_FOUND' || /Cannot find module|import\.meta' outside a module/.test(String(error.message)));
|
|
113
195
|
worker.on('error', error => receive({
|
|
114
|
-
failure: error.message
|
|
196
|
+
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
|
|
115
197
|
}));
|
|
116
198
|
worker.on('exit', code => receive({
|
|
117
199
|
failure: `The worker exited unexpectedly (code ${code}).`
|
|
@@ -125,10 +207,8 @@ const start = async receive => {
|
|
|
125
207
|
};
|
|
126
208
|
};
|
|
127
209
|
|
|
128
|
-
// Checked by tag as well as `instanceof`, so
|
|
129
|
-
// bundler's runtime is recognised (see index.js).
|
|
210
|
+
// Checked by tag as well as `instanceof`, so a module compiled by a bundler's runtime is recognised (see index.js).
|
|
130
211
|
const tagOf = value => Object.prototype.toString.call(value);
|
|
131
|
-
const isImageData = value => typeof value === 'object' && value !== null && (typeof ImageData !== 'undefined' && value instanceof ImageData || tagOf(value) === '[object ImageData]');
|
|
132
212
|
const isWasmModule = value => typeof value === 'object' && value !== null && (typeof WebAssembly !== 'undefined' && value instanceof WebAssembly.Module || tagOf(value) === '[object WebAssembly.Module]');
|
|
133
213
|
|
|
134
214
|
// 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
|
|
@@ -169,6 +249,11 @@ const send = image => {
|
|
|
169
249
|
if (notPixels(image)) {
|
|
170
250
|
throw fail('invalid-argument', `Invalid image: expected object with \`data\` and \`format\`.${imageHint(image)}`, 'image');
|
|
171
251
|
}
|
|
252
|
+
// A detached buffer (transferred to a worker created with transfer: true, say) is reported as the main entry reports it.
|
|
253
|
+
const pixels = ArrayBuffer.isView(image) ? image : image && typeof image === 'object' && ArrayBuffer.isView(image.data) ? image.data : null;
|
|
254
|
+
if (pixels && isDetached(pixels)) {
|
|
255
|
+
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');
|
|
256
|
+
}
|
|
172
257
|
if (isImageData(image)) {
|
|
173
258
|
const data = image.data;
|
|
174
259
|
return {
|
|
@@ -198,14 +283,7 @@ const send = image => {
|
|
|
198
283
|
// RawImage, and a RawImage for ImageData, which is turned back into ImageData here.
|
|
199
284
|
const rebuild = image => {
|
|
200
285
|
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);
|
|
286
|
+
return result => imageDataLike(image, new Uint8ClampedArray(result.data.buffer, result.data.byteOffset, result.data.byteLength));
|
|
209
287
|
}
|
|
210
288
|
return result => result;
|
|
211
289
|
};
|
|
@@ -249,8 +327,17 @@ const remoteError = (info, origin) => {
|
|
|
249
327
|
// Checks the `wasm` option (see init in the main entry) and makes it fit for posting to the worker: a URL becomes its
|
|
250
328
|
// string, and bytes and compiled modules are cloned across.
|
|
251
329
|
const wasmOption = wasm => {
|
|
330
|
+
// A relative URL is resolved here, against the page, as fetch would; in the worker it would resolve against the worker
|
|
331
|
+
// script's folder. In Node it is a path, which the worker thread resolves against the same working directory.
|
|
252
332
|
if (typeof wasm === 'string') {
|
|
253
|
-
|
|
333
|
+
if (isNode || isBundledNode) {
|
|
334
|
+
return wasm;
|
|
335
|
+
}
|
|
336
|
+
try {
|
|
337
|
+
return new URL(wasm, pageBase()).href;
|
|
338
|
+
} catch (error) {
|
|
339
|
+
return wasm;
|
|
340
|
+
}
|
|
254
341
|
}
|
|
255
342
|
if (typeof wasm === 'object' && wasm !== null && (typeof URL !== 'undefined' && wasm instanceof URL || tagOf(wasm) === '[object URL]')) {
|
|
256
343
|
return wasm.href;
|
|
@@ -264,8 +351,22 @@ const wasmOption = wasm => {
|
|
|
264
351
|
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
352
|
};
|
|
266
353
|
|
|
267
|
-
//
|
|
268
|
-
|
|
354
|
+
// The `script` option: the worker script to start, for setups where the package's own can't be found or bundled (Angular's
|
|
355
|
+
// application builder, esbuild or Rollup without a worker plugin, a bundled Electron main process): a copy of the package's
|
|
356
|
+
// dist/worker-thread.mjs, served or kept next to the rest of dist/, which it imports. A URL, or a string: in browsers
|
|
357
|
+
// resolved against the page, in Node a path relative to the working directory (or a file: URL).
|
|
358
|
+
const scriptOption = script => {
|
|
359
|
+
if (typeof script === 'string' && script.length > 0) {
|
|
360
|
+
return isNode || isBundledNode ? script : new URL(script, pageBase()).href;
|
|
361
|
+
}
|
|
362
|
+
if (typeof script === 'object' && script !== null && (typeof URL !== 'undefined' && script instanceof URL || tagOf(script) === '[object URL]')) {
|
|
363
|
+
return script.href;
|
|
364
|
+
}
|
|
365
|
+
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');
|
|
366
|
+
};
|
|
367
|
+
|
|
368
|
+
// Options for init: `wasm`, and for the shared worker `script`, or none.
|
|
369
|
+
const initOptions = (options, allowScript) => {
|
|
269
370
|
if (options === undefined) {
|
|
270
371
|
return undefined;
|
|
271
372
|
}
|
|
@@ -274,13 +375,20 @@ const initOptions = options => {
|
|
|
274
375
|
}
|
|
275
376
|
options = snapshot(options);
|
|
276
377
|
for (const key of Object.keys(options)) {
|
|
277
|
-
if (key
|
|
278
|
-
throw fail('invalid-argument',
|
|
378
|
+
if (key === 'script' && !allowScript) {
|
|
379
|
+
throw fail('invalid-argument', "Invalid option 'script': a worker's script is chosen when it is created, with createWorker({ script }).", 'options.script');
|
|
380
|
+
}
|
|
381
|
+
if (key !== 'wasm' && key !== 'script') {
|
|
382
|
+
throw fail('invalid-argument', `Invalid option '${key}': expected ${allowScript ? 'script, wasm' : 'wasm'}.`, `options.${key}`);
|
|
279
383
|
}
|
|
280
384
|
}
|
|
281
|
-
|
|
385
|
+
const checked = options.wasm === undefined ? {} : {
|
|
282
386
|
wasm: wasmOption(options.wasm)
|
|
283
387
|
};
|
|
388
|
+
if (options.script !== undefined) {
|
|
389
|
+
checked.script = scriptOption(options.script);
|
|
390
|
+
}
|
|
391
|
+
return checked;
|
|
284
392
|
};
|
|
285
393
|
|
|
286
394
|
// 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 +456,9 @@ const mappedImageFunctions = ['quantize', 'quantizeFromClustering', 'quantizeWit
|
|
|
348
456
|
// These only map pixels, so they take a signal but no progress callback (see mapOptions in index.js).
|
|
349
457
|
const mappingOnlyFunctions = ['quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
|
|
350
458
|
const otherFunctions = ['getPaletteFromClustering', 'getSwatchesFromClustering', 'getClusteringInfo'];
|
|
351
|
-
|
|
459
|
+
|
|
460
|
+
// `allowScript`: whether init takes `script` (the shared worker's; createWorker takes it as an option instead).
|
|
461
|
+
const makeWorker = (options, allowScript) => {
|
|
352
462
|
if (options === undefined) {
|
|
353
463
|
options = {};
|
|
354
464
|
}
|
|
@@ -357,14 +467,16 @@ export const createWorker = options => {
|
|
|
357
467
|
}
|
|
358
468
|
options = snapshot(options);
|
|
359
469
|
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}`);
|
|
470
|
+
if (key !== 'transfer' && key !== 'wasm' && key !== 'script') {
|
|
471
|
+
throw fail('invalid-argument', `Invalid option '${key}': expected script, transfer, wasm.`, `options.${key}`);
|
|
362
472
|
}
|
|
363
473
|
}
|
|
364
474
|
if (options.transfer !== undefined && typeof options.transfer !== 'boolean') {
|
|
365
475
|
throw fail('invalid-argument', "Invalid transfer: must be a boolean.", 'options.transfer');
|
|
366
476
|
}
|
|
367
477
|
const transfer = options.transfer === true;
|
|
478
|
+
// The worker script to start instead of the package's own (see scriptOption); set by init({ script }) for the shared one.
|
|
479
|
+
let script = options.script === undefined ? null : scriptOption(options.script);
|
|
368
480
|
// Where the worker finds its .wasm: sent as the worker's first call, and repeated until it has succeeded.
|
|
369
481
|
const initialWasm = options.wasm === undefined ? undefined : wasmOption(options.wasm);
|
|
370
482
|
let initial = initialWasm === undefined ? null : {
|
|
@@ -490,10 +602,13 @@ export const createWorker = options => {
|
|
|
490
602
|
if (mine === generation) {
|
|
491
603
|
receive(message);
|
|
492
604
|
}
|
|
493
|
-
}).catch(error => {
|
|
605
|
+
}, script).catch(error => {
|
|
494
606
|
if (mine === generation) {
|
|
495
607
|
starting = null;
|
|
496
608
|
}
|
|
609
|
+
if (error && error.code === 'worker-failed') {
|
|
610
|
+
throw error;
|
|
611
|
+
}
|
|
497
612
|
throw Object.assign(fail('worker-failed', `Worker failed: ${error && error.message}`), {
|
|
498
613
|
cause: error
|
|
499
614
|
});
|
|
@@ -639,11 +754,24 @@ export const createWorker = options => {
|
|
|
639
754
|
const origin = new Error();
|
|
640
755
|
let checked;
|
|
641
756
|
try {
|
|
642
|
-
checked = initOptions(initArgs);
|
|
757
|
+
checked = initOptions(initArgs, allowScript);
|
|
758
|
+
if (checked !== undefined && checked.script !== undefined) {
|
|
759
|
+
// The script decides how the worker starts, so it can only be chosen before it has.
|
|
760
|
+
const chosen = checked.script;
|
|
761
|
+
if ((connection || starting) && chosen !== script) {
|
|
762
|
+
throw fail('invalid-argument', "Invalid script: the worker has already started. Call init({ script }) before any other call (or terminate() first).", 'options.script');
|
|
763
|
+
}
|
|
764
|
+
script = chosen;
|
|
765
|
+
const {
|
|
766
|
+
script: _script,
|
|
767
|
+
...rest
|
|
768
|
+
} = checked;
|
|
769
|
+
checked = rest;
|
|
770
|
+
}
|
|
643
771
|
} catch (error) {
|
|
644
772
|
return Promise.reject(error);
|
|
645
773
|
}
|
|
646
|
-
return invoke('init', checked === undefined ? [] : [checked], [], origin).then(() => undefined);
|
|
774
|
+
return invoke('init', checked === undefined || Object.keys(checked).length === 0 ? [] : [checked], [], origin).then(() => undefined);
|
|
647
775
|
};
|
|
648
776
|
|
|
649
777
|
// Clusters `image` and keeps it, with its clustering, in the worker.
|
|
@@ -760,8 +888,9 @@ export const createWorker = options => {
|
|
|
760
888
|
};
|
|
761
889
|
return instance;
|
|
762
890
|
};
|
|
891
|
+
export const createWorker = options => makeWorker(options, false);
|
|
763
892
|
let shared = null;
|
|
764
|
-
const sharedWorker = () => shared = shared ||
|
|
893
|
+
const sharedWorker = () => shared = shared || makeWorker({}, true);
|
|
765
894
|
|
|
766
895
|
// Stops the shared worker, rejecting calls still waiting. The next call starts a fresh one.
|
|
767
896
|
export const terminate = async () => {
|