agglomerative-clustering 3.0.0-beta.1 → 3.0.0-beta.2

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/index.mjs CHANGED
@@ -1,5 +1,4 @@
1
1
  function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
2
- function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
3
2
  function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (c = i[4] || 3, u = i[5] === e ? i[3] : i[5], i[4] = 3, i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
4
3
  function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { if (r) i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n;else { var o = function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); }; o("next", 0), o("throw", 1), o("return", 2); } }, _regeneratorDefine2(e, r, n, t); }
5
4
  function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
@@ -10,14 +9,32 @@ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r)
10
9
  function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
11
10
  function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
12
11
  function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
12
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
13
13
  import createWasmModule from './clustering.js';
14
- import { version, fail, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, markPalette, markClustering, latestVersion, readHeader, checkPalette } from "./shared.mjs";
14
+ import { version, fail, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, latestVersion, readHeader, checkPalette } from "./shared.mjs";
15
15
 
16
16
  // The library's version, the stored-data format version, and the Palette and Clustering types (see shared.js).
17
17
  export { version, Palette, Clustering } from "./shared.mjs";
18
18
  // The version of stored data (clusterings) this build writes. It reads this one and format 2 (see readHeader). Unlike
19
19
  // `version`, it changes only when the stored format does, so a 3.x release that keeps the format keeps this number.
20
20
  export var formatVersion = latestVersion;
21
+
22
+ // Checked by tag rather than `instanceof`, so values from another realm are recognised: an ImageData from an iframe's
23
+ // canvas, a WebAssembly.Module compiled by a bundler's runtime (Next.js Edge's `import wasm from '…wasm?module'`), a URL
24
+ // from a vm context. A tag can be faked, but only on purpose, and the value is then used as what it claims to be.
25
+ var tagOf = function tagOf(value) {
26
+ return Object.prototype.toString.call(value);
27
+ };
28
+ // (`instanceof` is kept too, for implementations without the tag, such as node-canvas's ImageData.)
29
+ var isImageData = function isImageData(value) {
30
+ return _typeof(value) === 'object' && value !== null && (typeof ImageData !== 'undefined' && value instanceof ImageData || tagOf(value) === '[object ImageData]');
31
+ };
32
+ var isWasmModule = function isWasmModule(value) {
33
+ return _typeof(value) === 'object' && value !== null && (typeof WebAssembly !== 'undefined' && value instanceof WebAssembly.Module || tagOf(value) === '[object WebAssembly.Module]');
34
+ };
35
+ var isURL = function isURL(value) {
36
+ return _typeof(value) === 'object' && value !== null && (typeof URL !== 'undefined' && value instanceof URL || tagOf(value) === '[object URL]');
37
+ };
21
38
  var codes = {
22
39
  'rgba': 0,
23
40
  'rgb': 1
@@ -36,7 +53,7 @@ var wasmSettings = function wasmSettings(wasm, onError) {
36
53
  if (wasm === undefined) {
37
54
  return {};
38
55
  }
39
- if (typeof wasm === 'string' || wasm instanceof URL) {
56
+ if (typeof wasm === 'string' || isURL(wasm)) {
40
57
  var location = String(wasm);
41
58
  return {
42
59
  locateFile: function locateFile(path, directory) {
@@ -44,22 +61,35 @@ var wasmSettings = function wasmSettings(wasm, onError) {
44
61
  }
45
62
  };
46
63
  }
47
- // Bytes and compiled modules go through `instantiateWasm`: this build of the glue reads no `wasmBinary` setting.
64
+ // Bytes and compiled modules go through `instantiateWasm`: this build of the glue reads no `wasmBinary` setting. The glue
65
+ // sets itself up on the instance inside `receive`, which throws for a module that isn't this one (it has other exports);
66
+ // that is reported as a failed load rather than left to escape, which would leave the load waiting forever.
67
+ var accept = function accept(receive) {
68
+ return function (instance) {
69
+ try {
70
+ receive(instance);
71
+ } catch (error) {
72
+ onError(Object.assign(new Error("it is not agglomerative-clustering's module (it lacks the memory and functions this script uses)"), {
73
+ cause: error
74
+ }));
75
+ }
76
+ };
77
+ };
48
78
  if (isArrayBufferLike(wasm) || ArrayBuffer.isView(wasm)) {
49
79
  var source = isArrayBufferLike(wasm) ? wasm : new Uint8Array(wasm.buffer, wasm.byteOffset, wasm.byteLength);
50
80
  return {
51
81
  instantiateWasm: function instantiateWasm(imports, receive) {
52
82
  WebAssembly.instantiate(source, imports).then(function (_ref) {
53
83
  var instance = _ref.instance;
54
- return receive(instance);
84
+ return accept(receive)(instance);
55
85
  }, onError);
56
86
  }
57
87
  };
58
88
  }
59
- if (typeof WebAssembly !== 'undefined' && wasm instanceof WebAssembly.Module) {
89
+ if (isWasmModule(wasm)) {
60
90
  return {
61
91
  instantiateWasm: function instantiateWasm(imports, receive) {
62
- WebAssembly.instantiate(wasm, imports).then(receive, onError);
92
+ WebAssembly.instantiate(wasm, imports).then(accept(receive), onError);
63
93
  }
64
94
  };
65
95
  }
@@ -67,9 +97,38 @@ var wasmSettings = function wasmSettings(wasm, onError) {
67
97
  };
68
98
 
69
99
  // A module that cannot be loaded is the commonest first-run failure: a 404, a Content-Security-Policy that blocks it, a
70
- // browser without WebAssembly SIMD. The engine's own error (a CompileError, a failed fetch) says little about which.
71
- var wasmLoadFailed = function wasmLoadFailed(cause) {
72
- return Object.assign(fail('wasm-load-failed', "Could not load the WebAssembly module (".concat(String(cause && cause.message !== undefined ? cause.message : cause).split('\n')[0].slice(0, 140), "). It needs WebAssembly with SIMD (Chrome and Edge 91, Firefox 89, Safari 16.4 or newer). If the file is missing or blocked, check that the .wasm is served and allowed by the page's Content-Security-Policy, or say where it is with init({ wasm }).")), {
100
+ // bundler that moved the file, an engine without WebAssembly SIMD. The engine's own error (a CompileError, a failed fetch)
101
+ // says little about which, so the message leads with what happened and then gives the likely fix for where it ran.
102
+ // The smallest module that uses a SIMD instruction (from wasm-feature-detect), to tell an old engine from a missing file.
103
+ var simdProbe = [0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 10, 1, 8, 0, 65, 0, 253, 15, 253, 98, 11];
104
+ var hasSimd = function hasSimd() {
105
+ try {
106
+ return (typeof WebAssembly === "undefined" ? "undefined" : _typeof(WebAssembly)) === 'object' && WebAssembly.validate(new Uint8Array(simdProbe));
107
+ } catch (error) {
108
+ return false;
109
+ }
110
+ };
111
+ var isNodeLike = typeof process !== 'undefined' && !!(process.versions && process.versions.node);
112
+ var wasmLoadFailed = function wasmLoadFailed(cause, given) {
113
+ var text = String(cause && cause.message !== undefined ? cause.message : cause).split('\n')[0];
114
+ // Emscripten appends advice about its own debug build, which doesn't apply to this package's users.
115
+ // and wraps a failed compile in Aborted(...), which is how it stops itself, not part of the reason.
116
+ var reason = text.replace(/\s*\(?Build with -sASSERTIONS for more info\.?\)?/, '').trim().replace(/\.+$/, '');
117
+ var aborted = /^Aborted\((.*)\)$/.exec(reason);
118
+ if (aborted) {
119
+ reason = aborted[1].replace(/\.+$/, '');
120
+ }
121
+ var advice;
122
+ if (!hasSimd()) {
123
+ advice = "This engine has no WebAssembly SIMD, which the module needs (Chrome and Edge 91, Firefox 89, Safari 16.4, Node 16.4 or newer).";
124
+ } else if (given) {
125
+ advice = "Check what init({ wasm }) was given: it must be this package's clustering.wasm (its URL or path, its bytes, or the module compiled from it).";
126
+ } else if (isNodeLike) {
127
+ advice = "If the package was bundled into a server build (Next.js and others), the bundler may have moved or renamed clustering.wasm: leave the package out of the bundle (in Next.js, serverExternalPackages: ['agglomerative-clustering']) or give the module with init({ wasm }).";
128
+ } else {
129
+ advice = "Check that clustering.wasm is served next to the script (not a 404, and with the application/wasm type) and allowed by the page's Content-Security-Policy, or say where it is with init({ wasm }).";
130
+ }
131
+ return Object.assign(fail('wasm-load-failed', "Could not load the WebAssembly module: ".concat(reason || 'unknown error', ". ").concat(advice)), {
73
132
  cause: cause
74
133
  });
75
134
  };
@@ -79,38 +138,81 @@ var wasmLoadFailed = function wasmLoadFailed(cause) {
79
138
  // pointing at the wrong one) would misbehave in ways nothing explains, so the module says which version it is and a
80
139
  // mismatch is reported when it loads.
81
140
  var checkWasmVersion = function checkWasmVersion(instance) {
82
- var found = 'an unknown version (from before 3.0)';
83
- if (typeof instance._library_version === 'function') {
141
+ // A module from before 3.0 has no version export (the glue's wrapper then throws or returns nothing), and one that isn't
142
+ // this library's at all may have none either: both are reported as a version mismatch, never as a stray TypeError.
143
+ var found = '';
144
+ try {
145
+ var pointer = instance._library_version();
84
146
  var heap = instance.HEAPU8;
85
- var end = instance._library_version();
86
- var start = end;
87
- while (heap[end] !== 0 && end - start < 64) {
88
- end++;
147
+ if (typeof pointer === 'number' && pointer > 0 && heap) {
148
+ var end = pointer;
149
+ while (heap[end] !== 0 && end - pointer < 64) {
150
+ end++;
151
+ }
152
+ found = String.fromCharCode.apply(String, _toConsumableArray(heap.subarray(pointer, end)));
89
153
  }
90
- found = String.fromCharCode.apply(String, _toConsumableArray(heap.subarray(start, end)));
91
- }
154
+ } catch (error) {/* no version export */}
92
155
  var expected = "agglomerative-clustering@".concat(version);
93
156
  if (found !== expected) {
94
- throw fail('wasm-load-failed', "The WebAssembly module is ".concat(found, ", but this script is ").concat(expected, ": a stale or mixed-up clustering.wasm (a cache or CDN serving another version, or init({ wasm }) pointing at one). Serve the .wasm that came with this version of the package."));
157
+ var what = found ? found : 'from another version (one from before 3.0, which does not say which, or not this library\'s module at all)';
158
+ throw fail('wasm-load-failed', "The WebAssembly module is ".concat(what, ", but this script is ").concat(expected, ": a stale or mixed-up clustering.wasm (a cache or CDN serving another version, or init({ wasm }) pointing at one). Serve the .wasm that came with this version of the package."));
95
159
  }
96
160
  };
97
161
 
162
+ // Instantiates the module from init's `wasm` option (undefined: the glue finds the .wasm next to itself).
163
+ var instantiate = function instantiate(wasm) {
164
+ var reject;
165
+ var failed = new Promise(function (_, r) {
166
+ reject = r;
167
+ });
168
+ failed["catch"](function () {});
169
+ return Promise.race([createWasmModule(wasmSettings(wasm, reject)), failed]);
170
+ };
171
+
172
+ // The bytes of this package's clustering.wasm as Node resolves it from the working directory, for when the copy next to
173
+ // the script is missing (see acquire). The specifiers are built at run time so bundlers leave them alone (see worker.js).
174
+ var packagedWasm = /*#__PURE__*/function () {
175
+ var _ref2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
176
+ var _yield$import, createRequire, _yield$import2, readFile, file;
177
+ return _regenerator().w(function (_context) {
178
+ while (1) switch (_context.n) {
179
+ case 0:
180
+ _context.n = 1;
181
+ return import(/* webpackIgnore: true */ /* @vite-ignore */['node', 'module'].join(':'));
182
+ case 1:
183
+ _yield$import = _context.v;
184
+ createRequire = _yield$import.createRequire;
185
+ _context.n = 2;
186
+ return import(/* webpackIgnore: true */ /* @vite-ignore */['node', 'fs/promises'].join(':'));
187
+ case 2:
188
+ _yield$import2 = _context.v;
189
+ readFile = _yield$import2.readFile;
190
+ file = createRequire("".concat(process.cwd(), "/")).resolve('agglomerative-clustering/clustering.wasm');
191
+ return _context.a(2, readFile(file));
192
+ }
193
+ }, _callee);
194
+ }));
195
+ return function packagedWasm() {
196
+ return _ref2.apply(this, arguments);
197
+ };
198
+ }();
199
+
98
200
  // The module loads once: concurrent calls share one load, and a load that fails is forgotten, so it can be retried.
99
201
  var loading = null;
100
202
 
101
203
  // Calls get the instance they run on from `acquire` and keep using it, so replacing the current instance (see `discard`)
102
204
  // never changes the module under a call already in flight.
103
205
  var acquire = /*#__PURE__*/function () {
104
- var _ref2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(options) {
105
- var _i, _Object$keys, key, reject, failed, settings;
106
- return _regenerator().w(function (_context2) {
107
- while (1) switch (_context2.n) {
206
+ var _ref3 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(options) {
207
+ var _i, _Object$keys, key, wasm;
208
+ return _regenerator().w(function (_context3) {
209
+ while (1) switch (_context3.n) {
108
210
  case 0:
109
211
  if (options === undefined) {
110
212
  options = {};
111
213
  }
112
214
  if (isOptionsObject(options)) {
113
- _context2.n = 1;
215
+ _context3.n = 1;
114
216
  break;
115
217
  }
116
218
  throw fail('invalid-argument', "Invalid options: expected an object.", 'options');
@@ -119,59 +221,90 @@ var acquire = /*#__PURE__*/function () {
119
221
  _i = 0, _Object$keys = Object.keys(options);
120
222
  case 2:
121
223
  if (!(_i < _Object$keys.length)) {
122
- _context2.n = 4;
224
+ _context3.n = 4;
123
225
  break;
124
226
  }
125
227
  key = _Object$keys[_i];
126
228
  if (!(key !== 'wasm')) {
127
- _context2.n = 3;
229
+ _context3.n = 3;
128
230
  break;
129
231
  }
130
232
  throw fail('invalid-argument', "Invalid option '".concat(key, "': expected wasm."), "options.".concat(key));
131
233
  case 3:
132
234
  _i++;
133
- _context2.n = 2;
235
+ _context3.n = 2;
134
236
  break;
135
237
  case 4:
136
- failed = new Promise(function (_, r) {
137
- reject = r;
138
- });
139
- failed["catch"](function () {});
140
- settings = wasmSettings(options.wasm, reject);
238
+ // Checked on every call, so a bad value is reported even when the module is already loaded.
239
+ wasmSettings(options.wasm, function () {});
141
240
  if (!Module) {
142
- _context2.n = 5;
241
+ _context3.n = 5;
143
242
  break;
144
243
  }
145
- return _context2.a(2, Module);
244
+ return _context3.a(2, Module);
146
245
  case 5:
147
246
  if (!loading) {
148
- loading = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
149
- var instance;
150
- return _regenerator().w(function (_context) {
151
- while (1) switch (_context.n) {
247
+ wasm = options.wasm;
248
+ loading = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2() {
249
+ var instance, fallback, _t, _t2;
250
+ return _regenerator().w(function (_context2) {
251
+ while (1) switch (_context2.n) {
152
252
  case 0:
153
- _context.n = 1;
154
- return Promise.race([createWasmModule(settings), failed])["catch"](function (error) {
155
- throw wasmLoadFailed(error);
156
- });
253
+ _context2.p = 0;
254
+ _context2.n = 1;
255
+ return instantiate(wasm);
157
256
  case 1:
158
- instance = _context.v;
257
+ instance = _context2.v;
258
+ _context2.n = 8;
259
+ break;
260
+ case 2:
261
+ _context2.p = 2;
262
+ _t = _context2.v;
263
+ if (!(wasm === undefined && isNodeLike)) {
264
+ _context2.n = 4;
265
+ break;
266
+ }
267
+ _context2.n = 3;
268
+ return packagedWasm()["catch"](function () {
269
+ return null;
270
+ });
271
+ case 3:
272
+ _t2 = _context2.v;
273
+ _context2.n = 5;
274
+ break;
275
+ case 4:
276
+ _t2 = null;
277
+ case 5:
278
+ fallback = _t2;
279
+ if (fallback) {
280
+ _context2.n = 6;
281
+ break;
282
+ }
283
+ throw wasmLoadFailed(_t, wasm !== undefined);
284
+ case 6:
285
+ _context2.n = 7;
286
+ return instantiate(fallback)["catch"](function () {
287
+ throw wasmLoadFailed(_t, false);
288
+ });
289
+ case 7:
290
+ instance = _context2.v;
291
+ case 8:
159
292
  checkWasmVersion(instance);
160
293
  Module = instance;
161
- return _context.a(2, instance);
294
+ return _context2.a(2, instance);
162
295
  }
163
- }, _callee);
296
+ }, _callee2, null, [[0, 2]]);
164
297
  }))()["catch"](function (error) {
165
298
  loading = null;
166
299
  throw error;
167
300
  });
168
301
  }
169
- return _context2.a(2, loading);
302
+ return _context3.a(2, loading);
170
303
  }
171
- }, _callee2);
304
+ }, _callee3);
172
305
  }));
173
306
  return function acquire(_x) {
174
- return _ref2.apply(this, arguments);
307
+ return _ref3.apply(this, arguments);
175
308
  };
176
309
  }();
177
310
 
@@ -179,19 +312,19 @@ var acquire = /*#__PURE__*/function () {
179
312
  // say where the .wasm file is (`wasm`), which must come before anything else. The first load that succeeds wins:
180
313
  // later calls, with or without options, get the same module.
181
314
  export var init = /*#__PURE__*/function () {
182
- var _ref4 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(options) {
183
- return _regenerator().w(function (_context3) {
184
- while (1) switch (_context3.n) {
315
+ var _ref5 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(options) {
316
+ return _regenerator().w(function (_context4) {
317
+ while (1) switch (_context4.n) {
185
318
  case 0:
186
- _context3.n = 1;
319
+ _context4.n = 1;
187
320
  return acquire(options);
188
321
  case 1:
189
- return _context3.a(2);
322
+ return _context4.a(2);
190
323
  }
191
- }, _callee3);
324
+ }, _callee4);
192
325
  }));
193
326
  return function init(_x2) {
194
- return _ref4.apply(this, arguments);
327
+ return _ref5.apply(this, arguments);
195
328
  };
196
329
  }();
197
330
 
@@ -322,7 +455,50 @@ var imageHint = function imageHint(image) {
322
455
  }
323
456
  return '';
324
457
  };
458
+
459
+ // A typed array whose buffer was transferred away (to a worker, say) is empty and can't be read or viewed.
460
+ var isDetached = function isDetached(view) {
461
+ var buffer = view.buffer;
462
+ if (typeof buffer.detached === 'boolean') {
463
+ return buffer.detached;
464
+ }
465
+ try {
466
+ new Uint8Array(buffer, 0, 0);
467
+ return false;
468
+ } catch (error) {
469
+ return true;
470
+ }
471
+ };
472
+
473
+ // The bytes a call works on are read when it is made, as with any function that takes an array: the caller may reuse
474
+ // or change the array as soon as the call returns. Once the module is loaded the bytes go into its memory before the
475
+ // call returns; until then (the first call) a copy is kept for when it has loaded.
476
+ var held = function held(data) {
477
+ return Module ? data : data.slice();
478
+ };
479
+
480
+ // width and height are copied to results and used for dithering, so each must make sense on its own: a whole number of
481
+ // pixels that divides the pixel count (and, when both are given, account for exactly the pixels in the data).
482
+ var checkSize = function checkSize(pixels, size, name, argument) {
483
+ if (size === undefined) {
484
+ return;
485
+ }
486
+ if (!Number.isInteger(size) || size < 0) {
487
+ throw fail('invalid-argument', "Invalid ".concat(name, ": must be a whole number of pixels."), argument);
488
+ }
489
+ if (pixels > 0 && (size === 0 || pixels % size !== 0)) {
490
+ throw fail('invalid-argument', "Invalid ".concat(name, ": ").concat(size, " does not divide the image's ").concat(pixels, " pixels into whole rows."), argument);
491
+ }
492
+ };
325
493
  var load = function load(image) {
494
+ if (isClustering(image) || isPalette(image)) {
495
+ var what = isClustering(image) ? 'a clustering (from getClustering)' : 'a palette';
496
+ var fix = isClustering(image) ? 'To cut a palette from it, use getPaletteFromClustering (or quantizeFromClustering to map an image with it).' : 'To map an image to it, use quantizeWithPalette(image, palette).';
497
+ throw fail('invalid-argument', "Invalid image: this is ".concat(what, ", not pixels. ").concat(fix), 'image');
498
+ }
499
+ if (ArrayBuffer.isView(image) && isDetached(image)) {
500
+ throw fail('invalid-argument', "Invalid image: its buffer was transferred away (detached), for example to a worker created with transfer: true, so it has no pixels left. Pass a copy if you need to keep using it.", 'image');
501
+ }
326
502
  if (isUint8Array(image)) {
327
503
  var encoded = sniffImageFormat(image);
328
504
  if (encoded) {
@@ -332,13 +508,16 @@ var load = function load(image) {
332
508
  throw fail('invalid-argument', "Invalid image data: length must be a multiple of 4 for 'rgba'.", 'image');
333
509
  }
334
510
  return {
335
- data: image,
511
+ data: held(image),
336
512
  format: 'rgba'
337
513
  };
338
514
  }
339
- if (typeof ImageData !== 'undefined' && image instanceof ImageData) {
515
+ if (isImageData(image)) {
516
+ if (isDetached(image.data)) {
517
+ throw fail('invalid-argument', "Invalid image: the ImageData's pixels were transferred away (detached), for example to a worker created with transfer: true.", 'image');
518
+ }
340
519
  return {
341
- data: bytes(image.data),
520
+ data: held(bytes(image.data)),
342
521
  format: 'rgba',
343
522
  width: image.width
344
523
  };
@@ -352,6 +531,9 @@ var load = function load(image) {
352
531
  if (!isUint8Array(image.data) && !isUint8ClampedArray(image.data)) {
353
532
  throw fail('invalid-argument', "Invalid image data: must be Uint8Array or Uint8ClampedArray.", 'image');
354
533
  }
534
+ if (isDetached(image.data)) {
535
+ throw fail('invalid-argument', "Invalid image data: its buffer was transferred away (detached), for example to a worker created with transfer: true, so it has no pixels left. Pass a copy if you need to keep using it.", 'image');
536
+ }
355
537
  if (!Object.keys(codes).includes(image.format)) {
356
538
  throw fail('invalid-argument', "Invalid format: must be 'rgb' or 'rgba'.", 'image');
357
539
  }
@@ -359,27 +541,20 @@ var load = function load(image) {
359
541
  if (image.data.length % channels !== 0) {
360
542
  throw fail('invalid-argument', "Invalid image data: length must be a multiple of ".concat(channels, " for '").concat(image.format, "'."), 'image');
361
543
  }
362
-
363
- // width and height are copied to results and used for dithering, so they must make sense: whole numbers that, when
364
- // both are given, account for exactly the pixels in the data.
365
- for (var _i2 = 0, _arr = ['width', 'height']; _i2 < _arr.length; _i2++) {
366
- var key = _arr[_i2];
367
- var value = image[key];
368
- if (value !== undefined && (!Number.isInteger(value) || value < 0)) {
369
- throw fail('invalid-argument', "Invalid image ".concat(key, ": must be a whole number of pixels."), 'image');
370
- }
371
- }
372
- if (image.width !== undefined && image.height !== undefined && image.width * image.height !== image.data.length / channels) {
373
- throw fail('invalid-argument', "Invalid image: width x height (".concat(image.width, " x ").concat(image.height, ") does not match its ").concat(image.data.length / channels, " pixels."), 'image');
544
+ var pixels = image.data.length / channels;
545
+ checkSize(pixels, image.width, 'image width', 'image');
546
+ checkSize(pixels, image.height, 'image height', 'image');
547
+ if (image.width !== undefined && image.height !== undefined && image.width * image.height !== pixels) {
548
+ throw fail('invalid-argument', "Invalid image: width x height (".concat(image.width, " x ").concat(image.height, ") does not match its ").concat(pixels, " pixels."), 'image');
374
549
  }
375
550
  return {
376
- data: bytes(image.data),
551
+ data: held(bytes(image.data)),
377
552
  format: image.format,
378
553
  width: image.width
379
554
  };
380
555
  };
381
556
  var getWrapper = function getWrapper(image) {
382
- if (typeof ImageData !== 'undefined' && image instanceof ImageData) {
557
+ if (isImageData(image)) {
383
558
  // The pixels stay in the colour space they came in ('display-p3' canvases), so the result must say so.
384
559
  var width = image.width,
385
560
  height = image.height,
@@ -475,8 +650,8 @@ var parseOptions = function parseOptions(options, allowed, image) {
475
650
  throw fail('invalid-argument', "Invalid options: expected an object.", 'options');
476
651
  }
477
652
  options = snapshot(options);
478
- for (var _i3 = 0, _Object$keys2 = Object.keys(options); _i3 < _Object$keys2.length; _i3++) {
479
- var key = _Object$keys2[_i3];
653
+ for (var _i2 = 0, _Object$keys2 = Object.keys(options); _i2 < _Object$keys2.length; _i2++) {
654
+ var key = _Object$keys2[_i2];
480
655
  if (!allowed.includes(key)) {
481
656
  throw fail('invalid-argument', "Invalid option '".concat(key, "': expected one of ").concat(allowed.join(', '), "."), "options.".concat(key));
482
657
  }
@@ -503,6 +678,9 @@ var parseOptions = function parseOptions(options, allowed, image) {
503
678
  if (options.width !== undefined && image && image.width !== undefined && options.width !== image.width) {
504
679
  throw fail('invalid-argument', "Invalid width: options.width (".concat(options.width, ") does not match the image's width (").concat(image.width, ")."), 'options.width');
505
680
  }
681
+ if (options.width !== undefined && image) {
682
+ checkSize(image.data.length / (image.format === 'rgb' ? 3 : 4), options.width, 'width', 'options.width');
683
+ }
506
684
  var width = options.width !== undefined ? options.width : image ? image.width : undefined;
507
685
  if (dither > 0) {
508
686
  var channels = image.format === 'rgb' ? 3 : 4;
@@ -555,6 +733,23 @@ var mapOptions = ['colorSpace', 'dither', 'width', 'signal'];
555
733
  var quantizeIndexOptions = quantizeOptions;
556
734
  var mapIndexOptions = [].concat(mapOptions, ['transparent']);
557
735
 
736
+ // An empty palette is what getPalette gives for an image with no visible pixels, and mapping such an image with it is
737
+ // fine. Mapping visible pixels to it has no answer (they would all come out black), so that is an error. `cutoff` is the
738
+ // alpha from which an RGBA pixel needs a colour.
739
+ var checkNotEmpty = function checkNotEmpty(palette, image, cutoff) {
740
+ if (palette.length > 0) {
741
+ return;
742
+ }
743
+ var data = image.data;
744
+ var visible = image.format === 'rgb' ? data.length > 0 : false;
745
+ for (var i = 3; !visible && i < data.length; i += 4) {
746
+ visible = data[i] >= cutoff;
747
+ }
748
+ if (visible) {
749
+ throw fail('invalid-argument', "Invalid palette: it is empty, but the image has visible pixels to map to it.", 'palette');
750
+ }
751
+ };
752
+
558
753
  // The space to match pixels to a palette in: the one the caller names, else the one a Palette was made in, else RGB.
559
754
  var matchingSpace = function matchingSpace(o, palette) {
560
755
  return o.colorSpaceGiven ? o.colorSpace : colorSpaces[isPalette(palette) ? palette.colorSpace : 'rgb'];
@@ -585,6 +780,11 @@ var call = function call(wasm, buffers, fn) {
585
780
  _iterator.f();
586
781
  }
587
782
  outputPointer = fn.apply(void 0, pointers);
783
+ // Only the functions that read a clustering return nothing: when its records don't fit together (see
784
+ // _get_palette_from_clustering), which a clustering whose checksum matches never does.
785
+ if (!outputPointer) {
786
+ throw fail('invalid-clustering', "Invalid clustering: its records don't fit together, so it is damaged or isn't a clustering. Cluster the image again.", 'clustering');
787
+ }
588
788
  return unpack(wasm, outputPointer);
589
789
  } catch (error) {
590
790
  if (!isAbort(error)) {
@@ -672,178 +872,205 @@ var isControlled = function isControlled(o) {
672
872
 
673
873
  // Clusters in slices and returns the clustering. `share` is the part of the whole call's progress this takes.
674
874
  var clusterInSlices = /*#__PURE__*/function () {
675
- var _ref5 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(wasm, image, o, report, share) {
676
- var imagePointer, job, aborted, progress, pointer, _t;
677
- return _regenerator().w(function (_context4) {
678
- while (1) switch (_context4.n) {
875
+ var _ref6 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(wasm, image, o, report, share) {
876
+ var imagePointer, job, aborted, progress, pointer, _t3;
877
+ return _regenerator().w(function (_context5) {
878
+ while (1) switch (_context5.n) {
679
879
  case 0:
680
880
  checkAborted(o.signal);
681
881
  imagePointer = wasm._malloc(image.data.length);
682
882
  if (imagePointer) {
683
- _context4.n = 1;
883
+ _context5.n = 1;
684
884
  break;
685
885
  }
686
886
  throw fail('out-of-memory', "Failed to allocate WASM memory.");
687
887
  case 1:
688
888
  job = 0;
689
889
  aborted = false;
690
- _context4.p = 2;
890
+ _context5.p = 2;
691
891
  wasm.HEAPU8.set(image.data, imagePointer);
692
892
  job = wasm._clustering_job_start(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent);
693
893
  report(0);
694
894
  case 3:
695
895
  if (!true) {
696
- _context4.n = 6;
896
+ _context5.n = 6;
697
897
  break;
698
898
  }
699
899
  progress = wasm._clustering_job_step(job, sliceMs);
700
900
  if (!(progress >= 1000)) {
701
- _context4.n = 4;
901
+ _context5.n = 4;
702
902
  break;
703
903
  }
704
- return _context4.a(3, 6);
904
+ return _context5.a(3, 6);
705
905
  case 4:
706
906
  report(share * progress / 1000);
707
- _context4.n = 5;
907
+ _context5.n = 5;
708
908
  return yieldNow();
709
909
  case 5:
710
910
  checkAborted(o.signal);
711
- _context4.n = 3;
911
+ _context5.n = 3;
712
912
  break;
713
913
  case 6:
714
914
  pointer = wasm._clustering_job_result(job);
715
- _context4.p = 7;
716
- return _context4.a(2, unpack(wasm, pointer));
915
+ _context5.p = 7;
916
+ return _context5.a(2, unpack(wasm, pointer));
717
917
  case 8:
718
- _context4.p = 8;
918
+ _context5.p = 8;
719
919
  wasm._free(pointer);
720
- return _context4.f(8);
920
+ return _context5.f(8);
721
921
  case 9:
722
- _context4.n = 12;
922
+ _context5.n = 12;
723
923
  break;
724
924
  case 10:
725
- _context4.p = 10;
726
- _t = _context4.v;
727
- if (isAbort(_t)) {
728
- _context4.n = 11;
925
+ _context5.p = 10;
926
+ _t3 = _context5.v;
927
+ if (isAbort(_t3)) {
928
+ _context5.n = 11;
729
929
  break;
730
930
  }
731
- throw _t;
931
+ throw _t3;
732
932
  case 11:
733
933
  aborted = true;
734
934
  discard(wasm);
735
935
  throw outOfMemory();
736
936
  case 12:
737
- _context4.p = 12;
937
+ _context5.p = 12;
738
938
  if (!aborted) {
739
939
  if (job) {
740
940
  wasm._clustering_job_free(job);
741
941
  }
742
942
  wasm._free(imagePointer);
743
943
  }
744
- return _context4.f(12);
944
+ return _context5.f(12);
745
945
  case 13:
746
- return _context4.a(2);
946
+ return _context5.a(2);
747
947
  }
748
- }, _callee4, null, [[7,, 8, 9], [2, 10, 12, 13]]);
948
+ }, _callee5, null, [[7,, 8, 9], [2, 10, 12, 13]]);
749
949
  }));
750
950
  return function clusterInSlices(_x3, _x4, _x5, _x6, _x7) {
751
- return _ref5.apply(this, arguments);
951
+ return _ref6.apply(this, arguments);
752
952
  };
753
953
  }();
954
+
955
+ // Every function checks its arguments and takes its bytes (see `held`) before it waits for anything: when the module is
956
+ // already loaded, `Module || await acquire()` doesn't wait, and the work up to the first slice of a long clustering
957
+ // happens before the call returns.
958
+
754
959
  export var getClustering = /*#__PURE__*/function () {
755
- var _ref6 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(image, options) {
756
- var wasm, o, report, clustering;
757
- return _regenerator().w(function (_context5) {
758
- while (1) switch (_context5.n) {
960
+ var _ref7 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6(image, options) {
961
+ var o, wasm, report, clustering, _t4;
962
+ return _regenerator().w(function (_context6) {
963
+ while (1) switch (_context6.n) {
759
964
  case 0:
760
- _context5.n = 1;
761
- return acquire();
762
- case 1:
763
- wasm = _context5.v;
764
965
  image = load(image);
765
966
  o = parseOptions(options, clusterOptions, image);
967
+ _t4 = Module;
968
+ if (_t4) {
969
+ _context6.n = 2;
970
+ break;
971
+ }
972
+ _context6.n = 1;
973
+ return acquire();
974
+ case 1:
975
+ _t4 = _context6.v;
976
+ case 2:
977
+ wasm = _t4;
766
978
  if (!isControlled(o)) {
767
- _context5.n = 3;
979
+ _context6.n = 4;
768
980
  break;
769
981
  }
770
982
  report = reporter(o);
771
- _context5.n = 2;
983
+ _context6.n = 3;
772
984
  return clusterInSlices(wasm, image, o, report, 1);
773
- case 2:
774
- clustering = _context5.v;
775
- report(1);
776
- return _context5.a(2, markClustering(clustering));
777
985
  case 3:
778
- return _context5.a(2, markClustering(call(wasm, [image.data], function (imagePointer) {
986
+ clustering = _context6.v;
987
+ report(1);
988
+ return _context6.a(2, markClustering(clustering));
989
+ case 4:
990
+ return _context6.a(2, markClustering(call(wasm, [image.data], function (imagePointer) {
779
991
  return wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent);
780
992
  })));
781
993
  }
782
- }, _callee5);
994
+ }, _callee6);
783
995
  }));
784
996
  return function getClustering(_x8, _x9) {
785
- return _ref6.apply(this, arguments);
997
+ return _ref7.apply(this, arguments);
786
998
  };
787
999
  }();
788
1000
  export var getPalette = /*#__PURE__*/function () {
789
- var _ref7 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6(image, k, options) {
790
- var wasm, o, report, clustering, palette;
791
- return _regenerator().w(function (_context6) {
792
- while (1) switch (_context6.n) {
1001
+ var _ref8 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7(image, k, options) {
1002
+ var o, wasm, report, clustering, palette, _t5;
1003
+ return _regenerator().w(function (_context7) {
1004
+ while (1) switch (_context7.n) {
793
1005
  case 0:
794
- _context6.n = 1;
795
- return acquire();
796
- case 1:
797
- wasm = _context6.v;
798
1006
  image = load(image);
799
1007
  k = check(k);
800
1008
  o = parseOptions(options, clusterOptions, image);
1009
+ _t5 = Module;
1010
+ if (_t5) {
1011
+ _context7.n = 2;
1012
+ break;
1013
+ }
1014
+ _context7.n = 1;
1015
+ return acquire();
1016
+ case 1:
1017
+ _t5 = _context7.v;
1018
+ case 2:
1019
+ wasm = _t5;
801
1020
  if (!isControlled(o)) {
802
- _context6.n = 3;
1021
+ _context7.n = 4;
803
1022
  break;
804
1023
  }
805
1024
  report = reporter(o);
806
- _context6.n = 2;
1025
+ _context7.n = 3;
807
1026
  return clusterInSlices(wasm, image, o, report, 0.99);
808
- case 2:
809
- clustering = _context6.v;
1027
+ case 3:
1028
+ clustering = _context7.v;
810
1029
  checkAborted(o.signal);
811
1030
  palette = call(wasm, [clustering], function (clusteringPointer) {
812
1031
  return wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k);
813
1032
  });
814
1033
  report(1);
815
- return _context6.a(2, markPalette(palette, colorSpaceName(o.colorSpace)));
816
- case 3:
817
- return _context6.a(2, markPalette(call(wasm, [image.data], function (imagePointer) {
1034
+ return _context7.a(2, markPalette(palette, colorSpaceName(o.colorSpace)));
1035
+ case 4:
1036
+ return _context7.a(2, markPalette(call(wasm, [image.data], function (imagePointer) {
818
1037
  return wasm._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.transparent);
819
1038
  }), colorSpaceName(o.colorSpace)));
820
1039
  }
821
- }, _callee6);
1040
+ }, _callee7);
822
1041
  }));
823
1042
  return function getPalette(_x0, _x1, _x10) {
824
- return _ref7.apply(this, arguments);
1043
+ return _ref8.apply(this, arguments);
825
1044
  };
826
1045
  }();
827
1046
  export var getPaletteFromClustering = /*#__PURE__*/function () {
828
- var _ref8 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7(clustering, k) {
829
- var wasm, header;
830
- return _regenerator().w(function (_context7) {
831
- while (1) switch (_context7.n) {
1047
+ var _ref9 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee8(clustering, k) {
1048
+ var header, wasm, _t6;
1049
+ return _regenerator().w(function (_context8) {
1050
+ while (1) switch (_context8.n) {
832
1051
  case 0:
833
- _context7.n = 1;
834
- return acquire();
835
- case 1:
836
- wasm = _context7.v;
837
1052
  header = readHeader(clustering);
838
1053
  k = check(k);
839
- return _context7.a(2, markPalette(call(wasm, [clustering], function (clusteringPointer) {
1054
+ clustering = held(clustering);
1055
+ _t6 = Module;
1056
+ if (_t6) {
1057
+ _context8.n = 2;
1058
+ break;
1059
+ }
1060
+ _context8.n = 1;
1061
+ return acquire();
1062
+ case 1:
1063
+ _t6 = _context8.v;
1064
+ case 2:
1065
+ wasm = _t6;
1066
+ return _context8.a(2, markPalette(call(wasm, [clustering], function (clusteringPointer) {
840
1067
  return wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k);
841
1068
  }), colorSpaceName(header.colorSpace)));
842
1069
  }
843
- }, _callee7);
1070
+ }, _callee8);
844
1071
  }));
845
1072
  return function getPaletteFromClustering(_x11, _x12) {
846
- return _ref8.apply(this, arguments);
1073
+ return _ref9.apply(this, arguments);
847
1074
  };
848
1075
  }();
849
1076
 
@@ -862,23 +1089,31 @@ var weightsOf = function weightsOf(wasm, clustering, header, k) {
862
1089
  // arrays line up by construction. Weights are pixels: fully transparent pixels count 0 and partly transparent ones in
863
1090
  // proportion to their opacity, as in clustering. Shares are the weights divided by their total, so they sum to 1.
864
1091
  export var getSwatchesFromClustering = /*#__PURE__*/function () {
865
- var _ref9 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee8(clustering, k) {
866
- var wasm, header, palette, weights, total, _iterator3, _step3, weight, shares, i;
867
- return _regenerator().w(function (_context8) {
868
- while (1) switch (_context8.n) {
1092
+ var _ref0 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee9(clustering, k) {
1093
+ var header, wasm, palette, weights, total, _iterator3, _step3, weight, shares, i, _t7;
1094
+ return _regenerator().w(function (_context9) {
1095
+ while (1) switch (_context9.n) {
869
1096
  case 0:
870
- _context8.n = 1;
871
- return acquire();
872
- case 1:
873
- wasm = _context8.v;
874
1097
  header = readHeader(clustering);
875
1098
  k = check(k);
876
1099
  if (!(header.version < 3)) {
877
- _context8.n = 2;
1100
+ _context9.n = 1;
878
1101
  break;
879
1102
  }
880
1103
  throw fail('unsupported-version', "Invalid clustering: format version ".concat(header.version, " (agglomerative-clustering ").concat(header.version, ".x) has no weights. Cluster the image again."), 'clustering');
1104
+ case 1:
1105
+ clustering = held(clustering);
1106
+ _t7 = Module;
1107
+ if (_t7) {
1108
+ _context9.n = 3;
1109
+ break;
1110
+ }
1111
+ _context9.n = 2;
1112
+ return acquire();
881
1113
  case 2:
1114
+ _t7 = _context9.v;
1115
+ case 3:
1116
+ wasm = _t7;
882
1117
  palette = markPalette(call(wasm, [clustering], function (clusteringPointer) {
883
1118
  return wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k);
884
1119
  }), colorSpaceName(header.colorSpace));
@@ -901,41 +1136,41 @@ export var getSwatchesFromClustering = /*#__PURE__*/function () {
901
1136
  shares[i] = weights[i] / total;
902
1137
  }
903
1138
  }
904
- return _context8.a(2, {
1139
+ return _context9.a(2, {
905
1140
  palette: palette,
906
1141
  weights: weights,
907
1142
  shares: shares
908
1143
  });
909
1144
  }
910
- }, _callee8);
1145
+ }, _callee9);
911
1146
  }));
912
1147
  return function getSwatchesFromClustering(_x13, _x14) {
913
- return _ref9.apply(this, arguments);
1148
+ return _ref0.apply(this, arguments);
914
1149
  };
915
1150
  }();
916
1151
 
917
1152
  // The same for an image: clusters it, then cuts, like getPalette.
918
1153
  export var getSwatches = /*#__PURE__*/function () {
919
- var _ref0 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee9(image, k, options) {
920
- var _t2, _t3, _t4;
921
- return _regenerator().w(function (_context9) {
922
- while (1) switch (_context9.n) {
1154
+ var _ref1 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee0(image, k, options) {
1155
+ var _t8, _t9, _t0;
1156
+ return _regenerator().w(function (_context0) {
1157
+ while (1) switch (_context0.n) {
923
1158
  case 0:
924
1159
  // Arguments are checked in the order they are given (image, then k, then options), as in every other function.
925
1160
  load(image);
926
1161
  k = check(k);
927
- _t2 = getSwatchesFromClustering;
928
- _context9.n = 1;
1162
+ _t8 = getSwatchesFromClustering;
1163
+ _context0.n = 1;
929
1164
  return getClustering(image, options);
930
1165
  case 1:
931
- _t3 = _context9.v;
932
- _t4 = k;
933
- return _context9.a(2, _t2(_t3, _t4));
1166
+ _t9 = _context0.v;
1167
+ _t0 = k;
1168
+ return _context0.a(2, _t8(_t9, _t0));
934
1169
  }
935
- }, _callee9);
1170
+ }, _callee0);
936
1171
  }));
937
1172
  return function getSwatches(_x15, _x16, _x17) {
938
- return _ref0.apply(this, arguments);
1173
+ return _ref1.apply(this, arguments);
939
1174
  };
940
1175
  }();
941
1176
 
@@ -943,10 +1178,10 @@ export var getSwatches = /*#__PURE__*/function () {
943
1178
  // squared error per channel of the k-colour clustering: each pixel's squared distance to its cluster's colour,
944
1179
  // weighted as in clustering, in 8-bit RGB values (RGB) or OKLab units (OKLab).
945
1180
  export var getClusteringInfo = /*#__PURE__*/function () {
946
- var _ref1 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee0(clustering) {
947
- var header, colors, info, view, pixels, total, remaining, i, _i4;
948
- return _regenerator().w(function (_context0) {
949
- while (1) switch (_context0.n) {
1181
+ var _ref10 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee1(clustering) {
1182
+ var header, colors, info, view, pixels, total, remaining, i, _i3, _i4;
1183
+ return _regenerator().w(function (_context1) {
1184
+ while (1) switch (_context1.n) {
950
1185
  case 0:
951
1186
  header = readHeader(clustering);
952
1187
  colors = header.merges + (clustering.length >= header.headerLength + 3 ? 1 : 0);
@@ -961,10 +1196,10 @@ export var getClusteringInfo = /*#__PURE__*/function () {
961
1196
  explained: null
962
1197
  };
963
1198
  if (!(header.version < 3)) {
964
- _context0.n = 1;
1199
+ _context1.n = 1;
965
1200
  break;
966
1201
  }
967
- return _context0.a(2, info);
1202
+ return _context1.a(2, info);
968
1203
  case 1:
969
1204
  view = new DataView(clustering.buffer, clustering.byteOffset, clustering.byteLength);
970
1205
  pixels = Math.pow(2, clustering[7]) / (clustering[6] === 1 ? 255 : 1);
@@ -981,205 +1216,273 @@ export var getClusteringInfo = /*#__PURE__*/function () {
981
1216
  remaining += view.getFloat32(header.headerLength + 3 + i * header.recordLength + 17, true);
982
1217
  info.mse[i] = remaining / total / 3;
983
1218
  }
1219
+ // Errors are sums of squares, so a cost that is negative or not a number can only come from damaged bytes (a clustering
1220
+ // from 3.0.0-beta.1 has no checksum to catch them first).
1221
+ _i3 = 0;
1222
+ case 2:
1223
+ if (!(_i3 < colors)) {
1224
+ _context1.n = 4;
1225
+ break;
1226
+ }
1227
+ if (!(!(info.mse[_i3] >= 0) || !Number.isFinite(info.mse[_i3]))) {
1228
+ _context1.n = 3;
1229
+ break;
1230
+ }
1231
+ throw fail('invalid-clustering', "Invalid clustering: its recorded errors are not valid numbers, so it is damaged. Cluster the image again.", 'clustering');
1232
+ case 3:
1233
+ _i3++;
1234
+ _context1.n = 2;
1235
+ break;
1236
+ case 4:
984
1237
  // The share of the image's variance each palette size keeps; 1 throughout for an image of one colour.
985
1238
  for (_i4 = 0; _i4 < colors; _i4++) {
986
1239
  info.explained[_i4] = info.mse[0] > 0 ? Math.max(0, Math.min(1, 1 - info.mse[_i4] / info.mse[0])) : 1;
987
1240
  }
988
- return _context0.a(2, info);
1241
+ return _context1.a(2, info);
989
1242
  }
990
- }, _callee0);
1243
+ }, _callee1);
991
1244
  }));
992
1245
  return function getClusteringInfo(_x18) {
993
- return _ref1.apply(this, arguments);
1246
+ return _ref10.apply(this, arguments);
994
1247
  };
995
1248
  }();
996
1249
  export var quantize = /*#__PURE__*/function () {
997
- var _ref10 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee1(image, k, options) {
998
- var wasm, wrap, o, report, clustering, mapped;
999
- return _regenerator().w(function (_context1) {
1000
- while (1) switch (_context1.n) {
1250
+ var _ref11 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee10(image, k, options) {
1251
+ var wrap, o, wasm, report, clustering, mapped, _t1;
1252
+ return _regenerator().w(function (_context10) {
1253
+ while (1) switch (_context10.n) {
1001
1254
  case 0:
1002
- _context1.n = 1;
1003
- return acquire();
1004
- case 1:
1005
- wasm = _context1.v;
1006
1255
  wrap = getWrapper(image);
1007
1256
  image = load(image);
1008
1257
  k = check(k);
1009
1258
  o = parseOptions(options, quantizeOptions, image);
1259
+ _t1 = Module;
1260
+ if (_t1) {
1261
+ _context10.n = 2;
1262
+ break;
1263
+ }
1264
+ _context10.n = 1;
1265
+ return acquire();
1266
+ case 1:
1267
+ _t1 = _context10.v;
1268
+ case 2:
1269
+ wasm = _t1;
1010
1270
  if (!isControlled(o)) {
1011
- _context1.n = 3;
1271
+ _context10.n = 4;
1012
1272
  break;
1013
1273
  }
1014
1274
  report = reporter(o);
1015
- _context1.n = 2;
1275
+ _context10.n = 3;
1016
1276
  return clusterInSlices(wasm, image, o, report, 0.9);
1017
- case 2:
1018
- clustering = _context1.v;
1277
+ case 3:
1278
+ clustering = _context10.v;
1019
1279
  checkAborted(o.signal);
1020
1280
  mapped = wrap(call(wasm, [image.data, clustering], function (imagePointer, clusteringPointer) {
1021
1281
  return wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, o.colorSpace, o.dither, o.width);
1022
1282
  }));
1023
1283
  report(1);
1024
- return _context1.a(2, mapped);
1025
- case 3:
1026
- return _context1.a(2, wrap(call(wasm, [image.data], function (imagePointer) {
1284
+ return _context10.a(2, mapped);
1285
+ case 4:
1286
+ return _context10.a(2, wrap(call(wasm, [image.data], function (imagePointer) {
1027
1287
  return wasm._quantize(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.width, o.transparent);
1028
1288
  })));
1029
1289
  }
1030
- }, _callee1);
1290
+ }, _callee10);
1031
1291
  }));
1032
1292
  return function quantize(_x19, _x20, _x21) {
1033
- return _ref10.apply(this, arguments);
1293
+ return _ref11.apply(this, arguments);
1034
1294
  };
1035
1295
  }();
1036
1296
  export var quantizeFromClustering = /*#__PURE__*/function () {
1037
- var _ref11 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee10(image, clustering, k, options) {
1038
- var wasm, wrap, o, colorSpace, result;
1039
- return _regenerator().w(function (_context10) {
1040
- while (1) switch (_context10.n) {
1297
+ var _ref12 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee11(image, clustering, k, options) {
1298
+ var wrap, o, wasm, colorSpace, result, _t10;
1299
+ return _regenerator().w(function (_context11) {
1300
+ while (1) switch (_context11.n) {
1041
1301
  case 0:
1042
- _context10.n = 1;
1043
- return acquire();
1044
- case 1:
1045
- wasm = _context10.v;
1046
1302
  wrap = getWrapper(image);
1047
1303
  image = load(image);
1048
1304
  readHeader(clustering);
1049
1305
  k = check(k);
1050
1306
  o = parseOptions(options, mapOptions, image);
1307
+ clustering = held(clustering);
1308
+ _t10 = Module;
1309
+ if (_t10) {
1310
+ _context11.n = 2;
1311
+ break;
1312
+ }
1313
+ _context11.n = 1;
1314
+ return acquire();
1315
+ case 1:
1316
+ _t10 = _context11.v;
1317
+ case 2:
1318
+ wasm = _t10;
1051
1319
  checkAborted(o.signal);
1052
1320
  colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
1053
1321
  result = wrap(call(wasm, [image.data, clustering], function (imagePointer, clusteringPointer) {
1054
1322
  return wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.width);
1055
1323
  }));
1056
- return _context10.a(2, result);
1324
+ return _context11.a(2, result);
1057
1325
  }
1058
- }, _callee10);
1326
+ }, _callee11);
1059
1327
  }));
1060
1328
  return function quantizeFromClustering(_x22, _x23, _x24, _x25) {
1061
- return _ref11.apply(this, arguments);
1329
+ return _ref12.apply(this, arguments);
1062
1330
  };
1063
1331
  }();
1064
1332
  export var quantizeWithPalette = /*#__PURE__*/function () {
1065
- var _ref12 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee11(image, palette, options) {
1066
- var wasm, wrap, o, result;
1067
- return _regenerator().w(function (_context11) {
1068
- while (1) switch (_context11.n) {
1333
+ var _ref13 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee12(image, palette, options) {
1334
+ var wrap, o, space, wasm, result, _t11;
1335
+ return _regenerator().w(function (_context12) {
1336
+ while (1) switch (_context12.n) {
1069
1337
  case 0:
1070
- _context11.n = 1;
1071
- return acquire();
1072
- case 1:
1073
- wasm = _context11.v;
1074
1338
  wrap = getWrapper(image);
1075
1339
  image = load(image);
1076
1340
  checkPalette(palette);
1077
1341
  o = parseOptions(options, mapOptions, image);
1342
+ checkNotEmpty(palette, image, 1);
1343
+ space = matchingSpace(o, palette);
1344
+ palette = held(palette);
1345
+ _t11 = Module;
1346
+ if (_t11) {
1347
+ _context12.n = 2;
1348
+ break;
1349
+ }
1350
+ _context12.n = 1;
1351
+ return acquire();
1352
+ case 1:
1353
+ _t11 = _context12.v;
1354
+ case 2:
1355
+ wasm = _t11;
1078
1356
  checkAborted(o.signal);
1079
1357
  result = wrap(call(wasm, [image.data, palette], function (imagePointer, palettePointer) {
1080
- return wasm._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, matchingSpace(o, palette), o.dither, o.width);
1358
+ return wasm._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.width);
1081
1359
  }));
1082
- return _context11.a(2, result);
1360
+ return _context12.a(2, result);
1083
1361
  }
1084
- }, _callee11);
1362
+ }, _callee12);
1085
1363
  }));
1086
1364
  return function quantizeWithPalette(_x26, _x27, _x28) {
1087
- return _ref12.apply(this, arguments);
1365
+ return _ref13.apply(this, arguments);
1088
1366
  };
1089
1367
  }();
1090
1368
  export var quantizeToIndices = /*#__PURE__*/function () {
1091
- var _ref13 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee12(image, k, options) {
1092
- var wasm, original, o, report, clustering, indexed;
1093
- return _regenerator().w(function (_context12) {
1094
- while (1) switch (_context12.n) {
1369
+ var _ref14 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee13(image, k, options) {
1370
+ var original, o, wasm, report, clustering, indexed, _t12;
1371
+ return _regenerator().w(function (_context13) {
1372
+ while (1) switch (_context13.n) {
1095
1373
  case 0:
1096
- _context12.n = 1;
1097
- return acquire();
1098
- case 1:
1099
- wasm = _context12.v;
1100
1374
  original = image;
1101
1375
  image = load(image);
1102
1376
  k = check(k);
1103
1377
  o = parseOptions(options, quantizeIndexOptions, image);
1378
+ _t12 = Module;
1379
+ if (_t12) {
1380
+ _context13.n = 2;
1381
+ break;
1382
+ }
1383
+ _context13.n = 1;
1384
+ return acquire();
1385
+ case 1:
1386
+ _t12 = _context13.v;
1387
+ case 2:
1388
+ wasm = _t12;
1104
1389
  if (!isControlled(o)) {
1105
- _context12.n = 3;
1390
+ _context13.n = 4;
1106
1391
  break;
1107
1392
  }
1108
1393
  report = reporter(o);
1109
- _context12.n = 2;
1394
+ _context13.n = 3;
1110
1395
  return clusterInSlices(wasm, image, o, report, 0.9);
1111
- case 2:
1112
- clustering = _context12.v;
1396
+ case 3:
1397
+ clustering = _context13.v;
1113
1398
  checkAborted(o.signal);
1114
1399
  indexed = unpackIndices(call(wasm, [image.data, clustering], function (imagePointer, clusteringPointer) {
1115
1400
  return wasm._quantize_indices_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, o.colorSpace, o.dither, o.width, o.transparent);
1116
1401
  }), original, colorSpaceName(o.colorSpace));
1117
1402
  report(1);
1118
- return _context12.a(2, indexed);
1119
- case 3:
1120
- return _context12.a(2, unpackIndices(call(wasm, [image.data], function (imagePointer) {
1403
+ return _context13.a(2, indexed);
1404
+ case 4:
1405
+ return _context13.a(2, unpackIndices(call(wasm, [image.data], function (imagePointer) {
1121
1406
  return wasm._quantize_indices(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.width, o.transparent);
1122
1407
  }), original, colorSpaceName(o.colorSpace)));
1123
1408
  }
1124
- }, _callee12);
1409
+ }, _callee13);
1125
1410
  }));
1126
1411
  return function quantizeToIndices(_x29, _x30, _x31) {
1127
- return _ref13.apply(this, arguments);
1412
+ return _ref14.apply(this, arguments);
1128
1413
  };
1129
1414
  }();
1130
1415
  export var quantizeToIndicesFromClustering = /*#__PURE__*/function () {
1131
- var _ref14 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee13(image, clustering, k, options) {
1132
- var wasm, original, header, o, colorSpace, cutoff, result;
1133
- return _regenerator().w(function (_context13) {
1134
- while (1) switch (_context13.n) {
1416
+ var _ref15 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee14(image, clustering, k, options) {
1417
+ var original, header, o, wasm, colorSpace, cutoff, result, _t13;
1418
+ return _regenerator().w(function (_context14) {
1419
+ while (1) switch (_context14.n) {
1135
1420
  case 0:
1136
- _context13.n = 1;
1137
- return acquire();
1138
- case 1:
1139
- wasm = _context13.v;
1140
1421
  original = image;
1141
1422
  image = load(image);
1142
1423
  header = readHeader(clustering);
1143
1424
  k = check(k);
1144
1425
  o = parseOptions(options, mapIndexOptions, image);
1426
+ clustering = held(clustering);
1427
+ _t13 = Module;
1428
+ if (_t13) {
1429
+ _context14.n = 2;
1430
+ break;
1431
+ }
1432
+ _context14.n = 1;
1433
+ return acquire();
1434
+ case 1:
1435
+ _t13 = _context14.v;
1436
+ case 2:
1437
+ wasm = _t13;
1145
1438
  checkAborted(o.signal);
1146
1439
  colorSpace = o.colorSpaceGiven ? o.colorSpace : -1; // The cutoff the clustering was made with is the default, so clustering and mapping agree unless a cutoff is named.
1147
1440
  cutoff = o.transparentGiven ? o.transparent : header.transparent;
1148
1441
  result = unpackIndices(call(wasm, [image.data, clustering], function (imagePointer, clusteringPointer) {
1149
1442
  return wasm._quantize_indices_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.width, cutoff);
1150
1443
  }), original, colorSpaceName(header.colorSpace));
1151
- return _context13.a(2, result);
1444
+ return _context14.a(2, result);
1152
1445
  }
1153
- }, _callee13);
1446
+ }, _callee14);
1154
1447
  }));
1155
1448
  return function quantizeToIndicesFromClustering(_x32, _x33, _x34, _x35) {
1156
- return _ref14.apply(this, arguments);
1449
+ return _ref15.apply(this, arguments);
1157
1450
  };
1158
1451
  }();
1159
1452
  export var quantizeToIndicesWithPalette = /*#__PURE__*/function () {
1160
- var _ref15 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee14(image, palette, options) {
1161
- var wasm, original, o, space, result;
1162
- return _regenerator().w(function (_context14) {
1163
- while (1) switch (_context14.n) {
1453
+ var _ref16 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee15(image, palette, options) {
1454
+ var original, o, space, paletteSpace, wasm, result, _t14;
1455
+ return _regenerator().w(function (_context15) {
1456
+ while (1) switch (_context15.n) {
1164
1457
  case 0:
1165
- _context14.n = 1;
1166
- return acquire();
1167
- case 1:
1168
- wasm = _context14.v;
1169
1458
  original = image;
1170
1459
  image = load(image);
1171
1460
  checkPalette(palette);
1172
1461
  o = parseOptions(options, mapIndexOptions, image);
1173
- checkAborted(o.signal);
1462
+ checkNotEmpty(palette, image, o.transparent > 0 ? o.transparent : 1);
1174
1463
  space = matchingSpace(o, palette);
1464
+ paletteSpace = isPalette(palette) ? palette.colorSpace : colorSpaceName(space);
1465
+ palette = held(palette);
1466
+ _t14 = Module;
1467
+ if (_t14) {
1468
+ _context15.n = 2;
1469
+ break;
1470
+ }
1471
+ _context15.n = 1;
1472
+ return acquire();
1473
+ case 1:
1474
+ _t14 = _context15.v;
1475
+ case 2:
1476
+ wasm = _t14;
1477
+ checkAborted(o.signal);
1175
1478
  result = unpackIndices(call(wasm, [image.data, palette], function (imagePointer, palettePointer) {
1176
1479
  return wasm._quantize_indices_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.width, o.transparent);
1177
- }), original, isPalette(palette) ? palette.colorSpace : colorSpaceName(space));
1178
- return _context14.a(2, result);
1480
+ }), original, paletteSpace);
1481
+ return _context15.a(2, result);
1179
1482
  }
1180
- }, _callee14);
1483
+ }, _callee15);
1181
1484
  }));
1182
1485
  return function quantizeToIndicesWithPalette(_x36, _x37, _x38) {
1183
- return _ref15.apply(this, arguments);
1486
+ return _ref16.apply(this, arguments);
1184
1487
  };
1185
1488
  }();