agglomerative-clustering 3.7.2 → 3.8.0

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/dist/worker.d.cts CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  import type {
6
6
  ImageLike, RawImage, ClusteringOptions, MappingOptions, QuantizeOptions, QuantizeIndexOptions, MappingIndexOptions,
7
- IndexedImage, ClusteringInfo, InitOptions, ImageResult, PaletteLike, Swatches,
7
+ IndexedImage, ClusteringInfo, InitOptions, ImageResult, PaletteLike, Swatches, ChooseOptions, PaletteChoice,
8
8
  } from './index.cjs';
9
9
  import type { Palette, Clustering } from './index.cjs';
10
10
 
@@ -13,7 +13,7 @@ export { Palette } from './index.cjs';
13
13
 
14
14
  /**
15
15
  * The same class as the main entry's `Clustering`. Its methods run on the calling thread and need the main entry imported
16
- * there; off the thread, use this entry's `…FromClustering` functions or `cluster()`.
16
+ * there; off the thread, use `worker.load(clustering)` or `cluster()`.
17
17
  */
18
18
  export { Clustering } from './index.cjs';
19
19
 
@@ -34,7 +34,7 @@ export const formatVersion: number;
34
34
 
35
35
  export type {
36
36
  ImageFormat, RawImage, ImageLike, PaletteLike, PlatformImageData, ImageResult, WasmModule, ColorSpace, AlphaMode, DitherMethod, DitherOptions, DitherSteps, ClusteringOptions, MappingOptions, QuantizeOptions,
37
- ErrorCode, ErrorArgument, CodedError, InitOptions, ProgressOptions, CancelOptions, IndexOptions, QuantizeIndexOptions, MappingIndexOptions, IndexedImage, ClusteringInfo, Swatches,
37
+ ErrorCode, ErrorArgument, CodedError, InitOptions, ProgressOptions, CancelOptions, IndexOptions, QuantizeIndexOptions, MappingIndexOptions, IndexedImage, ClusteringInfo, Swatches, ChooseOptions, PaletteChoice,
38
38
  } from './index.cjs';
39
39
 
40
40
  /** Options for `createWorker`. */
@@ -69,9 +69,14 @@ export interface SharedInitOptions extends InitOptions {
69
69
  /** An image and its clustering, kept in the worker so re-cutting and re-mapping them copies nothing across. */
70
70
  export interface ClusteringHandle<Image extends ImageLike = ImageLike> {
71
71
  getClustering(): Promise<Clustering>;
72
+ /** The k-colour palette of the clustering. */
72
73
  getPalette(k: number): Promise<Palette>;
74
+ /** Palette, weights and shares of the k-colour cut. */
73
75
  getSwatches(k: number): Promise<Swatches>;
76
+ /** The error curve and totals of the clustering. */
74
77
  getClusteringInfo(): Promise<ClusteringInfo>;
78
+ /** The main entry's `clustering.chooseFrom`, run in the worker on the kept clustering: picks `k` entries of a fixed palette. Takes `colorSpace` and `signal`. */
79
+ chooseFrom(palette: PaletteLike, k: number, options?: ChooseOptions): Promise<PaletteChoice>;
75
80
  /** Maps the kept image to the k-colour palette. Returns the same type as the image given to `cluster`. */
76
81
  quantize(k: number, options?: MappingOptions): Promise<Image>;
77
82
  quantizeToIndices(k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
@@ -88,6 +93,34 @@ export interface ClusteringHandle<Image extends ImageLike = ImageLike> {
88
93
  [Symbol.asyncDispose](): Promise<void>;
89
94
  }
90
95
 
96
+ /**
97
+ * A stored clustering, kept in the worker (from `worker.load`): cut it and map images with it without sending it again.
98
+ * It holds no image, so the mapping methods take the image, then k (`cluster` keeps the image and maps it with `quantize(k)`).
99
+ * There is no `getClustering()`: you passed the clustering in and still have it.
100
+ */
101
+ export interface LoadedClusteringHandle {
102
+ /** The k-colour palette of the clustering. */
103
+ getPalette(k: number): Promise<Palette>;
104
+ /** Palette, weights and shares of the k-colour cut. */
105
+ getSwatches(k: number): Promise<Swatches>;
106
+ /** The error curve and totals of the clustering. */
107
+ getClusteringInfo(): Promise<ClusteringInfo>;
108
+ /** The main entry's `clustering.chooseFrom`, run in the worker on the kept clustering: picks `k` entries of a fixed palette. Takes `colorSpace` and `signal`. */
109
+ chooseFrom(palette: PaletteLike, k: number, options?: ChooseOptions): Promise<PaletteChoice>;
110
+ /** Maps `image` to the k-colour palette of the kept clustering. Returns the same type as the image given. */
111
+ quantize<Image extends ImageLike>(image: Image, k: number, options?: MappingOptions): Promise<ImageResult<Image>>;
112
+ /** Maps `image` to indices into the k-colour palette of the kept clustering. */
113
+ quantizeToIndices(image: ImageLike, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
114
+ /**
115
+ * Frees the clustering in the worker. Later calls on the handle fail. Call it when you are done, or declare the
116
+ * handle with `await using`, which does. A handle that is dropped without either is freed once it is garbage-collected,
117
+ * but when that happens is up to the JavaScript engine.
118
+ */
119
+ release(): Promise<void>;
120
+ /** The same as `release()`, for `await using`. Present where the runtime has `Symbol.asyncDispose`. */
121
+ [Symbol.asyncDispose](): Promise<void>;
122
+ }
123
+
91
124
  /** The main entry's functions, run in a worker, plus handles and `terminate`. */
92
125
  export interface AgglomerativeWorker {
93
126
  /** Loads the module in the worker. `wasm` is the only option, and `createWorker({ wasm })` does the same. */
@@ -100,21 +133,31 @@ export interface AgglomerativeWorker {
100
133
  buildPalette(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Palette>;
101
134
  /** @deprecated Renamed {@link AgglomerativeWorker.buildPalette} in 3.4.0 (the same function). Removed in 4.0. */
102
135
  getPalette(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Palette>;
136
+ /** @deprecated Use `clustering.getPalette(k)`; off the main thread, `(await worker.load(clustering)).getPalette(k)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time. */
103
137
  getPaletteFromClustering(clustering: Clustering, k: number): Promise<Palette>;
104
138
  /** The main entry's `buildSwatches`, run in this worker. */
105
139
  buildSwatches(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Swatches>;
106
140
  /** @deprecated Renamed {@link AgglomerativeWorker.buildSwatches} in 3.4.0 (the same function). Removed in 4.0. */
107
141
  getSwatches(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Swatches>;
142
+ /** @deprecated Use `clustering.getSwatches(k)`; off the main thread, `(await worker.load(clustering)).getSwatches(k)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time. */
108
143
  getSwatchesFromClustering(clustering: Clustering, k: number): Promise<Swatches>;
144
+ /** @deprecated Use `clustering.getClusteringInfo()`; off the main thread, `(await worker.load(clustering)).getClusteringInfo()` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time. */
109
145
  getClusteringInfo(clustering: Clustering): Promise<ClusteringInfo>;
110
146
  quantize<Image extends ImageLike>(image: Image, k: number, options?: QuantizeOptions): Promise<ImageResult<Image>>;
147
+ /** @deprecated Use `clustering.quantize(image, k, options)`; off the main thread, `(await worker.load(clustering)).quantize(image, k, options)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time. */
111
148
  quantizeFromClustering<Image extends ImageLike>(image: Image, clustering: Clustering, k: number, options?: MappingOptions): Promise<ImageResult<Image>>;
112
149
  quantizeWithPalette<Image extends ImageLike>(image: Image, palette: PaletteLike, options?: MappingOptions): Promise<ImageResult<Image>>;
113
150
  quantizeToIndices(image: ImageLike, k: number, options?: QuantizeIndexOptions): Promise<IndexedImage>;
151
+ /** @deprecated Use `clustering.quantizeToIndices(image, k, options)`; off the main thread, `(await worker.load(clustering)).quantizeToIndices(image, k, options)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time. */
114
152
  quantizeToIndicesFromClustering(image: ImageLike, clustering: Clustering, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
115
153
  quantizeToIndicesWithPalette(image: ImageLike, palette: PaletteLike, options?: MappingIndexOptions): Promise<IndexedImage>;
116
154
  /** Clusters `image` and keeps it, with its clustering, in the worker. */
117
155
  cluster<Image extends ImageLike>(image: Image, options?: ClusteringOptions): Promise<ClusteringHandle<ImageResult<Image>>>;
156
+ /**
157
+ * Keeps a stored clustering in the worker and gives a handle for cutting it and mapping images with it. The bytes are
158
+ * checked and taken at the call (copied, or moved with `transfer: true`), so you may change the array at once.
159
+ */
160
+ load(clustering: Clustering | Uint8Array): Promise<LoadedClusteringHandle>;
118
161
  /** Stops the worker. Calls still waiting are rejected, and later calls fail. */
119
162
  terminate(): Promise<void>;
120
163
  /** The same as `terminate()`, for `await using worker = createWorker()`. Present where the runtime has `Symbol.asyncDispose`. */
@@ -146,25 +189,25 @@ export const getClustering: AgglomerativeWorker['getClustering'];
146
189
  export const buildPalette: AgglomerativeWorker['buildPalette'];
147
190
  /** @deprecated Renamed {@link buildPalette} in 3.4.0 (the same function). Removed in 4.0. */
148
191
  export const getPalette: AgglomerativeWorker['getPalette'];
149
- /** The main entry's `getPaletteFromClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
192
+ /** @deprecated Use `clustering.getPalette(k)`; off the main thread, `(await worker.load(clustering)).getPalette(k)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time. */
150
193
  export const getPaletteFromClustering: AgglomerativeWorker['getPaletteFromClustering'];
151
194
  /** The main entry's `buildSwatches`, run in the shared worker (see `createWorker` for a worker of your own). */
152
195
  export const buildSwatches: AgglomerativeWorker['buildSwatches'];
153
196
  /** @deprecated Renamed {@link buildSwatches} in 3.4.0 (the same function). Removed in 4.0. */
154
197
  export const getSwatches: AgglomerativeWorker['getSwatches'];
155
- /** The main entry's `getSwatchesFromClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
198
+ /** @deprecated Use `clustering.getSwatches(k)`; off the main thread, `(await worker.load(clustering)).getSwatches(k)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time. */
156
199
  export const getSwatchesFromClustering: AgglomerativeWorker['getSwatchesFromClustering'];
157
- /** The main entry's `getClusteringInfo`, run in the shared worker (see `createWorker` for a worker of your own). */
200
+ /** @deprecated Use `clustering.getClusteringInfo()`; off the main thread, `(await worker.load(clustering)).getClusteringInfo()` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time. */
158
201
  export const getClusteringInfo: AgglomerativeWorker['getClusteringInfo'];
159
202
  /** The main entry's `quantize`, run in the shared worker (see `createWorker` for a worker of your own). */
160
203
  export const quantize: AgglomerativeWorker['quantize'];
161
- /** The main entry's `quantizeFromClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
204
+ /** @deprecated Use `clustering.quantize(image, k, options)`; off the main thread, `(await worker.load(clustering)).quantize(image, k, options)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time. */
162
205
  export const quantizeFromClustering: AgglomerativeWorker['quantizeFromClustering'];
163
206
  /** The main entry's `quantizeWithPalette`, run in the shared worker (see `createWorker` for a worker of your own). */
164
207
  export const quantizeWithPalette: AgglomerativeWorker['quantizeWithPalette'];
165
208
  /** The main entry's `quantizeToIndices`, run in the shared worker (see `createWorker` for a worker of your own). */
166
209
  export const quantizeToIndices: AgglomerativeWorker['quantizeToIndices'];
167
- /** The main entry's `quantizeToIndicesFromClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
210
+ /** @deprecated Use `clustering.quantizeToIndices(image, k, options)`; off the main thread, `(await worker.load(clustering)).quantizeToIndices(image, k, options)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time. */
168
211
  export const quantizeToIndicesFromClustering: AgglomerativeWorker['quantizeToIndicesFromClustering'];
169
212
  /** The main entry's `quantizeToIndicesWithPalette`, run in the shared worker (see `createWorker` for a worker of your own). */
170
213
  export const quantizeToIndicesWithPalette: AgglomerativeWorker['quantizeToIndicesWithPalette'];
package/dist/worker.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  import type {
6
6
  ImageLike, RawImage, ClusteringOptions, MappingOptions, QuantizeOptions, QuantizeIndexOptions, MappingIndexOptions,
7
- IndexedImage, ClusteringInfo, InitOptions, ImageResult, PaletteLike, Swatches,
7
+ IndexedImage, ClusteringInfo, InitOptions, ImageResult, PaletteLike, Swatches, ChooseOptions, PaletteChoice,
8
8
  } from './index.js';
9
9
  import type { Palette, Clustering } from './index.js';
10
10
 
@@ -13,7 +13,7 @@ export { Palette } from './index.js';
13
13
 
14
14
  /**
15
15
  * The same class as the main entry's `Clustering`. Its methods run on the calling thread and need the main entry imported
16
- * there; off the thread, use this entry's `…FromClustering` functions or `cluster()`.
16
+ * there; off the thread, use `worker.load(clustering)` or `cluster()`.
17
17
  */
18
18
  export { Clustering } from './index.js';
19
19
 
@@ -34,7 +34,7 @@ export const formatVersion: number;
34
34
 
35
35
  export type {
36
36
  ImageFormat, RawImage, ImageLike, PaletteLike, PlatformImageData, ImageResult, WasmModule, ColorSpace, AlphaMode, DitherMethod, DitherOptions, DitherSteps, ClusteringOptions, MappingOptions, QuantizeOptions,
37
- ErrorCode, ErrorArgument, CodedError, InitOptions, ProgressOptions, CancelOptions, IndexOptions, QuantizeIndexOptions, MappingIndexOptions, IndexedImage, ClusteringInfo, Swatches,
37
+ ErrorCode, ErrorArgument, CodedError, InitOptions, ProgressOptions, CancelOptions, IndexOptions, QuantizeIndexOptions, MappingIndexOptions, IndexedImage, ClusteringInfo, Swatches, ChooseOptions, PaletteChoice,
38
38
  } from './index.js';
39
39
 
40
40
  /** Options for `createWorker`. */
@@ -69,9 +69,14 @@ export interface SharedInitOptions extends InitOptions {
69
69
  /** An image and its clustering, kept in the worker so re-cutting and re-mapping them copies nothing across. */
70
70
  export interface ClusteringHandle<Image extends ImageLike = ImageLike> {
71
71
  getClustering(): Promise<Clustering>;
72
+ /** The k-colour palette of the clustering. */
72
73
  getPalette(k: number): Promise<Palette>;
74
+ /** Palette, weights and shares of the k-colour cut. */
73
75
  getSwatches(k: number): Promise<Swatches>;
76
+ /** The error curve and totals of the clustering. */
74
77
  getClusteringInfo(): Promise<ClusteringInfo>;
78
+ /** The main entry's `clustering.chooseFrom`, run in the worker on the kept clustering: picks `k` entries of a fixed palette. Takes `colorSpace` and `signal`. */
79
+ chooseFrom(palette: PaletteLike, k: number, options?: ChooseOptions): Promise<PaletteChoice>;
75
80
  /** Maps the kept image to the k-colour palette. Returns the same type as the image given to `cluster`. */
76
81
  quantize(k: number, options?: MappingOptions): Promise<Image>;
77
82
  quantizeToIndices(k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
@@ -88,6 +93,34 @@ export interface ClusteringHandle<Image extends ImageLike = ImageLike> {
88
93
  [Symbol.asyncDispose](): Promise<void>;
89
94
  }
90
95
 
96
+ /**
97
+ * A stored clustering, kept in the worker (from `worker.load`): cut it and map images with it without sending it again.
98
+ * It holds no image, so the mapping methods take the image, then k (`cluster` keeps the image and maps it with `quantize(k)`).
99
+ * There is no `getClustering()`: you passed the clustering in and still have it.
100
+ */
101
+ export interface LoadedClusteringHandle {
102
+ /** The k-colour palette of the clustering. */
103
+ getPalette(k: number): Promise<Palette>;
104
+ /** Palette, weights and shares of the k-colour cut. */
105
+ getSwatches(k: number): Promise<Swatches>;
106
+ /** The error curve and totals of the clustering. */
107
+ getClusteringInfo(): Promise<ClusteringInfo>;
108
+ /** The main entry's `clustering.chooseFrom`, run in the worker on the kept clustering: picks `k` entries of a fixed palette. Takes `colorSpace` and `signal`. */
109
+ chooseFrom(palette: PaletteLike, k: number, options?: ChooseOptions): Promise<PaletteChoice>;
110
+ /** Maps `image` to the k-colour palette of the kept clustering. Returns the same type as the image given. */
111
+ quantize<Image extends ImageLike>(image: Image, k: number, options?: MappingOptions): Promise<ImageResult<Image>>;
112
+ /** Maps `image` to indices into the k-colour palette of the kept clustering. */
113
+ quantizeToIndices(image: ImageLike, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
114
+ /**
115
+ * Frees the clustering in the worker. Later calls on the handle fail. Call it when you are done, or declare the
116
+ * handle with `await using`, which does. A handle that is dropped without either is freed once it is garbage-collected,
117
+ * but when that happens is up to the JavaScript engine.
118
+ */
119
+ release(): Promise<void>;
120
+ /** The same as `release()`, for `await using`. Present where the runtime has `Symbol.asyncDispose`. */
121
+ [Symbol.asyncDispose](): Promise<void>;
122
+ }
123
+
91
124
  /** The main entry's functions, run in a worker, plus handles and `terminate`. */
92
125
  export interface AgglomerativeWorker {
93
126
  /** Loads the module in the worker. `wasm` is the only option, and `createWorker({ wasm })` does the same. */
@@ -100,21 +133,31 @@ export interface AgglomerativeWorker {
100
133
  buildPalette(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Palette>;
101
134
  /** @deprecated Renamed {@link AgglomerativeWorker.buildPalette} in 3.4.0 (the same function). Removed in 4.0. */
102
135
  getPalette(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Palette>;
136
+ /** @deprecated Use `clustering.getPalette(k)`; off the main thread, `(await worker.load(clustering)).getPalette(k)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time. */
103
137
  getPaletteFromClustering(clustering: Clustering, k: number): Promise<Palette>;
104
138
  /** The main entry's `buildSwatches`, run in this worker. */
105
139
  buildSwatches(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Swatches>;
106
140
  /** @deprecated Renamed {@link AgglomerativeWorker.buildSwatches} in 3.4.0 (the same function). Removed in 4.0. */
107
141
  getSwatches(image: ImageLike, k: number, options?: ClusteringOptions): Promise<Swatches>;
142
+ /** @deprecated Use `clustering.getSwatches(k)`; off the main thread, `(await worker.load(clustering)).getSwatches(k)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time. */
108
143
  getSwatchesFromClustering(clustering: Clustering, k: number): Promise<Swatches>;
144
+ /** @deprecated Use `clustering.getClusteringInfo()`; off the main thread, `(await worker.load(clustering)).getClusteringInfo()` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time. */
109
145
  getClusteringInfo(clustering: Clustering): Promise<ClusteringInfo>;
110
146
  quantize<Image extends ImageLike>(image: Image, k: number, options?: QuantizeOptions): Promise<ImageResult<Image>>;
147
+ /** @deprecated Use `clustering.quantize(image, k, options)`; off the main thread, `(await worker.load(clustering)).quantize(image, k, options)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time. */
111
148
  quantizeFromClustering<Image extends ImageLike>(image: Image, clustering: Clustering, k: number, options?: MappingOptions): Promise<ImageResult<Image>>;
112
149
  quantizeWithPalette<Image extends ImageLike>(image: Image, palette: PaletteLike, options?: MappingOptions): Promise<ImageResult<Image>>;
113
150
  quantizeToIndices(image: ImageLike, k: number, options?: QuantizeIndexOptions): Promise<IndexedImage>;
151
+ /** @deprecated Use `clustering.quantizeToIndices(image, k, options)`; off the main thread, `(await worker.load(clustering)).quantizeToIndices(image, k, options)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time. */
114
152
  quantizeToIndicesFromClustering(image: ImageLike, clustering: Clustering, k: number, options?: MappingIndexOptions): Promise<IndexedImage>;
115
153
  quantizeToIndicesWithPalette(image: ImageLike, palette: PaletteLike, options?: MappingIndexOptions): Promise<IndexedImage>;
116
154
  /** Clusters `image` and keeps it, with its clustering, in the worker. */
117
155
  cluster<Image extends ImageLike>(image: Image, options?: ClusteringOptions): Promise<ClusteringHandle<ImageResult<Image>>>;
156
+ /**
157
+ * Keeps a stored clustering in the worker and gives a handle for cutting it and mapping images with it. The bytes are
158
+ * checked and taken at the call (copied, or moved with `transfer: true`), so you may change the array at once.
159
+ */
160
+ load(clustering: Clustering | Uint8Array): Promise<LoadedClusteringHandle>;
118
161
  /** Stops the worker. Calls still waiting are rejected, and later calls fail. */
119
162
  terminate(): Promise<void>;
120
163
  /** The same as `terminate()`, for `await using worker = createWorker()`. Present where the runtime has `Symbol.asyncDispose`. */
@@ -146,25 +189,25 @@ export const getClustering: AgglomerativeWorker['getClustering'];
146
189
  export const buildPalette: AgglomerativeWorker['buildPalette'];
147
190
  /** @deprecated Renamed {@link buildPalette} in 3.4.0 (the same function). Removed in 4.0. */
148
191
  export const getPalette: AgglomerativeWorker['getPalette'];
149
- /** The main entry's `getPaletteFromClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
192
+ /** @deprecated Use `clustering.getPalette(k)`; off the main thread, `(await worker.load(clustering)).getPalette(k)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time. */
150
193
  export const getPaletteFromClustering: AgglomerativeWorker['getPaletteFromClustering'];
151
194
  /** The main entry's `buildSwatches`, run in the shared worker (see `createWorker` for a worker of your own). */
152
195
  export const buildSwatches: AgglomerativeWorker['buildSwatches'];
153
196
  /** @deprecated Renamed {@link buildSwatches} in 3.4.0 (the same function). Removed in 4.0. */
154
197
  export const getSwatches: AgglomerativeWorker['getSwatches'];
155
- /** The main entry's `getSwatchesFromClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
198
+ /** @deprecated Use `clustering.getSwatches(k)`; off the main thread, `(await worker.load(clustering)).getSwatches(k)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time. */
156
199
  export const getSwatchesFromClustering: AgglomerativeWorker['getSwatchesFromClustering'];
157
- /** The main entry's `getClusteringInfo`, run in the shared worker (see `createWorker` for a worker of your own). */
200
+ /** @deprecated Use `clustering.getClusteringInfo()`; off the main thread, `(await worker.load(clustering)).getClusteringInfo()` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time. */
158
201
  export const getClusteringInfo: AgglomerativeWorker['getClusteringInfo'];
159
202
  /** The main entry's `quantize`, run in the shared worker (see `createWorker` for a worker of your own). */
160
203
  export const quantize: AgglomerativeWorker['quantize'];
161
- /** The main entry's `quantizeFromClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
204
+ /** @deprecated Use `clustering.quantize(image, k, options)`; off the main thread, `(await worker.load(clustering)).quantize(image, k, options)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time. */
162
205
  export const quantizeFromClustering: AgglomerativeWorker['quantizeFromClustering'];
163
206
  /** The main entry's `quantizeWithPalette`, run in the shared worker (see `createWorker` for a worker of your own). */
164
207
  export const quantizeWithPalette: AgglomerativeWorker['quantizeWithPalette'];
165
208
  /** The main entry's `quantizeToIndices`, run in the shared worker (see `createWorker` for a worker of your own). */
166
209
  export const quantizeToIndices: AgglomerativeWorker['quantizeToIndices'];
167
- /** The main entry's `quantizeToIndicesFromClustering`, run in the shared worker (see `createWorker` for a worker of your own). */
210
+ /** @deprecated Use `clustering.quantizeToIndices(image, k, options)`; off the main thread, `(await worker.load(clustering)).quantizeToIndices(image, k, options)` (`worker.load` is in the worker entry). Deprecated in 3.8, removed in 4.0; no warning at run time. */
168
211
  export const quantizeToIndicesFromClustering: AgglomerativeWorker['quantizeToIndicesFromClustering'];
169
212
  /** The main entry's `quantizeToIndicesWithPalette`, run in the shared worker (see `createWorker` for a worker of your own). */
170
213
  export const quantizeToIndicesWithPalette: AgglomerativeWorker['quantizeToIndicesWithPalette'];
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, isCodedError, detachedError, isOptionsObject, snapshot, parseDither, mark, revive, latestVersion, imageHint, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, tooLarge, bareImageWarning, warnOnce } from "./shared.mjs";
7
+ import { fail, isCodedError, detachedError, isOptionsObject, isUint8Array, isUint8ClampedArray, snapshot, parseDither, mark, revive, latestVersion, imageHint, isDetached, imageDataLike, isImageData, checkImageDataPixels, maxBytes, tooLarge, bareImageWarning, warnOnce, readHeader } 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, errorCodes, isCodedError, ditherMethods, ditherSteps, colorSpaces, imageFormats, alphaModes } from "./shared.mjs";
@@ -138,7 +138,7 @@ const start = async (receive, chosen) => {
138
138
  // A page with an opaque origin (a sandboxed iframe without allow-same-origin, as plugin hosts such as Figma use) can't
139
139
  // start a worker from any http(s) script, nor, in Chromium, from a blob: URL; a data: URL module can, and imports it.
140
140
  const opaque = !crossOrigin && isOpaqueOrigin() && webOrigins.includes(script.protocol);
141
- 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 }).";
141
+ const scriptHint = "Check that worker-thread.mjs is served (open its URL), with index.mjs, shared.mjs, choose.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 }).";
142
142
  let worker,
143
143
  source = null;
144
144
  try {
@@ -199,7 +199,7 @@ const start = async (receive, chosen) => {
199
199
  // Yarn Plug'n'Play keeps packages in zip archives, which Node reads ES modules from only through Yarn's loader.
200
200
  const inZip = error => /\.zip[\\/]/.test(String(error && error.message));
201
201
  worker.on('error', error => receive({
202
- failure: missing(error) ? inZip(error) ? `${String(error.message).split('\n')[0]}. Under Yarn Plug'n'Play the package sits in a zip archive, which a worker thread can load its ES modules from only through Yarn's loader: run the app with yarn node (or node --require ./.pnp.cjs --loader ./.pnp.loader.mjs), or unplug the package (yarn unplug agglomerative-clustering). Otherwise keep dist/ together and say where it is with createWorker({ script }).` : `${String(error.message).split('\n')[0]}. 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). In a serverless deployment (AWS Lambda, Vercel or Netlify functions), the file tracer may have left them out: include node_modules/agglomerative-clustering/dist in the function's files.` : error.message
202
+ failure: missing(error) ? inZip(error) ? `${String(error.message).split('\n')[0]}. Under Yarn Plug'n'Play the package sits in a zip archive, which a worker thread can load its ES modules from only through Yarn's loader: run the app with yarn node (or node --require ./.pnp.cjs --loader ./.pnp.loader.mjs), or unplug the package (yarn unplug agglomerative-clustering). Otherwise keep dist/ together and say where it is with createWorker({ script }).` : `${String(error.message).split('\n')[0]}. The worker script (worker-thread.mjs) needs index.mjs, shared.mjs, choose.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). In a serverless deployment (AWS Lambda, Vercel or Netlify functions), the file tracer may have left them out: include node_modules/agglomerative-clustering/dist in the function's files.` : error.message
203
203
  }));
204
204
  worker.on('exit', code => receive({
205
205
  failure: `The worker exited unexpectedly (code ${code}).`
@@ -891,6 +891,152 @@ const makeWorker = (options, allowScript) => {
891
891
  return invoke('init', checked === undefined || Object.keys(checked).length === 0 ? [] : [checked], [], origin).then(() => undefined);
892
892
  };
893
893
 
894
+ // Whether a value is an image where a palette size was expected (a pixel array, an ImageData or `{data, ...}`).
895
+ const looksLikeImage = value => value !== null && typeof value === 'object' && (isUint8Array(value) || isUint8ClampedArray(value) || isImageData(value) || 'data' in value);
896
+ // Builds the handle object for what the worker keeps under `id`: `kind` is 'image' (from `cluster`: an image and its
897
+ // clustering) or 'clustering' (from `load`: a clustering alone). `output` turns a mapped result back into the type of the image given.
898
+ const makeHandle = (id, kind, output) => {
899
+ let released = false;
900
+ // Every method goes through `use`, which refers to `handle`, so a method kept after the handle itself is dropped
901
+ // keeps it alive and it is not reclaimed while still in use.
902
+ const use = (method, args, controls) => {
903
+ if (released || !handle) {
904
+ return Promise.reject(fail('invalid-handle', "Invalid handle: it was released."));
905
+ }
906
+ return invoke(method, [id, ...args], [], new Error(), controls);
907
+ };
908
+ // Calls with mapping options, whose signal and progress callback stay on this side (see takeControls).
909
+ const withControls = (method, leading, mapOptions) => {
910
+ let taken;
911
+ try {
912
+ taken = takeControls(mapOptions);
913
+ } catch (error) {
914
+ return Promise.reject(error);
915
+ }
916
+ return use(method, [...leading, taken.options], {
917
+ signal: taken.signal,
918
+ onProgress: taken.onProgress
919
+ });
920
+ };
921
+ // The cuts take no options (the handle's clustering already says how it was made): one passed anyway is an error,
922
+ // as in the main entry, rather than silently ignored.
923
+ const plain = (method, name, args, extra) => extra.some(value => value !== undefined) ? Promise.reject(fail('invalid-argument', `Invalid arguments: handle.${name} takes no options. To map pixels with options, use handle.quantize.`, 'options')) : use(method, args);
924
+ // An image where k belongs is a mix-up between the two kinds of handle: say so, rather than "k must be an integer".
925
+ const imageAsK = (name, k) => looksLikeImage(k) ? Promise.reject(fail('invalid-argument', `Invalid k: this handle holds an image (from worker.cluster) and maps it with ${name}(k); pass k, not an image. To map other images with a stored clustering, use worker.load(clustering).`, 'k')) : null;
926
+ const handle = {
927
+ getPalette: (k, ...extra) => plain('handleGetPalette', 'getPalette', [k], extra),
928
+ getSwatches: (k, ...extra) => plain('handleGetSwatches', 'getSwatches', [k], extra),
929
+ getClusteringInfo: (...extra) => plain('handleGetClusteringInfo', 'getClusteringInfo', [], extra),
930
+ // Takes the signal only: the main entry's chooseFrom takes no progress callback, so one given crosses as null for
931
+ // the thread to reject with the main entry's own error.
932
+ // That relies on the thread injecting a progress poster only for calls that have one (see `optionsIndex` in
933
+ // worker-thread.js): the null is then the only onProgress it sees, so its own option check rejects it.
934
+ chooseFrom: (palette, k, chooseOptions) => {
935
+ let taken;
936
+ try {
937
+ taken = takeControls(chooseOptions, false);
938
+ } catch (error) {
939
+ return Promise.reject(error);
940
+ }
941
+ const sent = taken.onProgress !== undefined ? {
942
+ ...taken.options,
943
+ onProgress: null
944
+ } : taken.options;
945
+ return use('handleChooseFrom', [palette, k, sent], {
946
+ signal: taken.signal
947
+ });
948
+ },
949
+ release: async () => {
950
+ if (released) {
951
+ return;
952
+ }
953
+ released = true;
954
+ liveHandles--;
955
+ if (reclaim) {
956
+ reclaim.unregister(handle);
957
+ }
958
+ // If the worker has been terminated there is nothing left to free (so `await using` and
959
+ // terminate() can come in either order); any other failure is reported.
960
+ try {
961
+ await invoke('release', [id], [], new Error());
962
+ } catch (error) {
963
+ if (error.code !== 'worker-terminated') {
964
+ throw error;
965
+ }
966
+ }
967
+ stopIfAbandoned();
968
+ }
969
+ };
970
+ if (kind === 'image') {
971
+ Object.assign(handle, {
972
+ getClustering: (...extra) => plain('handleGetClustering', 'getClustering', [], extra),
973
+ quantize: (k, mapOptions) => imageAsK('quantize', k) || (async () => output(await withControls('handleQuantize', [k], mapOptions)))(),
974
+ quantizeToIndices: (k, mapOptions) => imageAsK('quantizeToIndices', k) || withControls('handleQuantizeToIndices', [k], mapOptions),
975
+ quantizeWithPalette: async (palette, mapOptions) => output(await withControls('handleQuantizeWithPalette', [palette], mapOptions)),
976
+ quantizeToIndicesWithPalette: (palette, mapOptions) => withControls('handleQuantizeToIndicesWithPalette', [palette], mapOptions)
977
+ });
978
+ }
979
+ if (kind === 'clustering') {
980
+ // The handle holds no image: each call maps the image it is given, and returns the type of that image.
981
+ const mapping = (name, method, mapped) => (image, k, mapOptions) => {
982
+ if (typeof image === 'number') {
983
+ return Promise.reject(fail('invalid-argument', "Invalid image: this handle holds a clustering, not an image (from worker.load); pass the image, then k.", 'image'));
984
+ }
985
+ const origin = new Error();
986
+ return (async () => {
987
+ if (released || !handle) {
988
+ throw fail('invalid-handle', "Invalid handle: it was released.");
989
+ }
990
+ const {
991
+ options,
992
+ signal,
993
+ onProgress
994
+ } = takeControls(mapOptions);
995
+ if (signal && signal.aborted) {
996
+ // As the functions on the worker do: a wrong argument is reported before the abort.
997
+ try {
998
+ await invoke(method, [id, own(send(image)), k, options], [], origin, {
999
+ check: true
1000
+ });
1001
+ } catch (error) {
1002
+ if (isCodedError(error) && error.argument !== undefined) {
1003
+ throw error;
1004
+ }
1005
+ }
1006
+ throw abortReason(signal);
1007
+ }
1008
+ const warning = bareImageWarning(image);
1009
+ const byteLength = warning ? image.byteLength : 0;
1010
+ let sent = send(image);
1011
+ const ahead = !ready();
1012
+ if (ahead) {
1013
+ sent = take(sent);
1014
+ }
1015
+ const result = await invoke(method, [id, sent, ahead ? own(k) : k, options], pixelBuffers(sent), origin, {
1016
+ signal,
1017
+ onProgress
1018
+ });
1019
+ if (warning) {
1020
+ warnOnce(warning, byteLength);
1021
+ }
1022
+ return mapped ? rebuild(image)(result) : result;
1023
+ })();
1024
+ };
1025
+ Object.assign(handle, {
1026
+ quantize: mapping('quantize', 'handleQuantizeImage', true),
1027
+ quantizeToIndices: mapping('quantizeToIndices', 'handleQuantizeToIndicesImage', false)
1028
+ });
1029
+ }
1030
+ // `await using handle = await worker.cluster(image)` releases it at the end of the block.
1031
+ if (typeof Symbol.asyncDispose === 'symbol') {
1032
+ handle[Symbol.asyncDispose] = handle.release;
1033
+ }
1034
+ if (reclaim) {
1035
+ reclaim.register(handle, id, handle);
1036
+ }
1037
+ return handle;
1038
+ };
1039
+
894
1040
  // Clusters `image` and keeps it, with its clustering, in the worker.
895
1041
  instance.cluster = (image, clusterOptions) => {
896
1042
  const origin = new Error();
@@ -928,70 +1074,33 @@ const makeWorker = (options, allowScript) => {
928
1074
  if (warning) {
929
1075
  warnOnce(warning, byteLength);
930
1076
  }
931
- const output = rebuild(image);
932
- let released = false;
933
- // Every method goes through `use`, which refers to `handle`, so a method kept after the handle itself is dropped
934
- // keeps it alive and it is not reclaimed while still in use.
935
- const use = (method, args, controls) => {
936
- if (released || !handle) {
937
- return Promise.reject(fail('invalid-handle', "Invalid handle: it was released."));
938
- }
939
- return invoke(method, [id, ...args], [], new Error(), controls);
940
- };
941
- // Calls with mapping options, whose signal and progress callback stay on this side (see takeControls).
942
- const withControls = (method, leading, mapOptions) => {
943
- let taken;
944
- try {
945
- taken = takeControls(mapOptions);
946
- } catch (error) {
947
- return Promise.reject(error);
948
- }
949
- return use(method, [...leading, taken.options], {
950
- signal: taken.signal,
951
- onProgress: taken.onProgress
952
- });
953
- };
954
- // The cuts take no options (the handle's clustering already says how it was made): one passed anyway is an error,
955
- // as in the main entry, rather than silently ignored.
956
- const plain = (method, name, args, extra) => extra.some(value => value !== undefined) ? Promise.reject(fail('invalid-argument', `Invalid arguments: handle.${name} takes no options. To map pixels with options, use handle.quantize.`, 'options')) : use(method, args);
957
- const handle = {
958
- getClustering: (...extra) => plain('handleGetClustering', 'getClustering', [], extra),
959
- getPalette: (k, ...extra) => plain('handleGetPalette', 'getPalette', [k], extra),
960
- getSwatches: (k, ...extra) => plain('handleGetSwatches', 'getSwatches', [k], extra),
961
- getClusteringInfo: (...extra) => plain('handleGetClusteringInfo', 'getClusteringInfo', [], extra),
962
- quantize: async (k, mapOptions) => output(await withControls('handleQuantize', [k], mapOptions)),
963
- quantizeToIndices: (k, mapOptions) => withControls('handleQuantizeToIndices', [k], mapOptions),
964
- quantizeWithPalette: async (palette, mapOptions) => output(await withControls('handleQuantizeWithPalette', [palette], mapOptions)),
965
- quantizeToIndicesWithPalette: (palette, mapOptions) => withControls('handleQuantizeToIndicesWithPalette', [palette], mapOptions),
966
- release: async () => {
967
- if (released) {
968
- return;
969
- }
970
- released = true;
971
- liveHandles--;
972
- if (reclaim) {
973
- reclaim.unregister(handle);
974
- }
975
- // If the worker has been terminated there is nothing left to free (so `await using` and
976
- // terminate() can come in either order); any other failure is reported.
977
- try {
978
- await invoke('release', [id], [], new Error());
979
- } catch (error) {
980
- if (error.code !== 'worker-terminated') {
981
- throw error;
982
- }
983
- }
984
- stopIfAbandoned();
985
- }
986
- };
987
- // `await using handle = await worker.cluster(image)` releases it at the end of the block.
988
- if (typeof Symbol.asyncDispose === 'symbol') {
989
- handle[Symbol.asyncDispose] = handle.release;
1077
+ return makeHandle(id, 'image', rebuild(image));
1078
+ })();
1079
+ };
1080
+
1081
+ // Keeps a stored clustering in the worker, for cutting it and mapping images with it without sending it again.
1082
+ instance.load = (clustering, ...extra) => {
1083
+ const origin = new Error();
1084
+ return (async () => {
1085
+ // Checked, and the bytes taken, before anything is awaited (see `own`): a damaged clustering, a palette or an
1086
+ // image is reported here, and nothing is posted.
1087
+ if (extra.length > 0) {
1088
+ throw fail('invalid-argument', "Invalid arguments: load takes the clustering only. Options go to the handle's methods.", 'options');
990
1089
  }
991
- if (reclaim) {
992
- reclaim.register(handle, id, handle);
1090
+ readHeader(clustering);
1091
+ const id = nextHandle++;
1092
+ const sent = ready() ? clustering : take(clustering);
1093
+ liveHandles++;
1094
+ try {
1095
+ await invoke('load', [id, sent], pixelBuffers(sent), origin);
1096
+ } catch (error) {
1097
+ liveHandles--;
1098
+ if (!terminated) {
1099
+ invoke('release', [id], [], new Error()).catch(() => {});
1100
+ }
1101
+ throw error;
993
1102
  }
994
- return handle;
1103
+ return makeHandle(id, 'clustering');
995
1104
  })();
996
1105
  };
997
1106
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agglomerative-clustering",
3
- "version": "3.7.2",
3
+ "version": "3.8.0",
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",