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

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.cjs CHANGED
@@ -5,113 +5,88 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  Object.defineProperty(exports, "Clustering", {
7
7
  enumerable: true,
8
- get: function get() {
8
+ get: function () {
9
9
  return _shared.Clustering;
10
10
  }
11
11
  });
12
12
  Object.defineProperty(exports, "Palette", {
13
13
  enumerable: true,
14
- get: function get() {
14
+ get: function () {
15
15
  return _shared.Palette;
16
16
  }
17
17
  });
18
18
  exports.quantizeWithPalette = exports.quantizeToIndicesWithPalette = exports.quantizeToIndicesFromClustering = exports.quantizeToIndices = exports.quantizeFromClustering = exports.quantize = exports.init = exports.getSwatchesFromClustering = exports.getSwatches = exports.getPaletteFromClustering = exports.getPalette = exports.getClusteringInfo = exports.getClustering = exports.formatVersion = void 0;
19
19
  Object.defineProperty(exports, "version", {
20
20
  enumerable: true,
21
- get: function get() {
21
+ get: function () {
22
22
  return _shared.version;
23
23
  }
24
24
  });
25
25
  var _clustering = _interopRequireDefault(require("./clustering.js"));
26
26
  var _shared = require("./shared.cjs");
27
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
28
- 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; } } }; }
29
- 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 }; })(); }
30
- 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); }
31
- function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t15 in e) "default" !== _t15 && {}.hasOwnProperty.call(e, _t15) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t15)) && (i.get || i.set) ? o(f, _t15, i) : f[_t15] = e[_t15]); return f; })(e, t); }
32
- 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); }
33
- function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
34
- function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
35
- function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
36
- function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
37
- function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
38
- function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
39
- 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; }
40
- 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); } // The library's version, the stored-data format version, and the Palette and Clustering types (see shared.js).
27
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
28
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } // The library's version, the stored-data format version, and the Palette and Clustering types (see shared.js).
41
29
  // The version of stored data (clusterings) this build writes. It reads this one and format 2 (see readHeader). Unlike
42
30
  // `version`, it changes only when the stored format does, so a 3.x release that keeps the format keeps this number.
43
- var formatVersion = exports.formatVersion = _shared.latestVersion;
31
+ const formatVersion = exports.formatVersion = _shared.latestVersion;
44
32
 
45
33
  // Checked by tag rather than `instanceof`, so values from another realm are recognised: an ImageData from an iframe's
46
34
  // canvas, a WebAssembly.Module compiled by a bundler's runtime (Next.js Edge's `import wasm from '…wasm?module'`), a URL
47
35
  // 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.
48
- var tagOf = function tagOf(value) {
49
- return Object.prototype.toString.call(value);
50
- };
36
+ const tagOf = value => Object.prototype.toString.call(value);
51
37
  // (`instanceof` is kept too, for implementations without the tag, such as node-canvas's ImageData.)
52
- var isImageData = function isImageData(value) {
53
- return _typeof(value) === 'object' && value !== null && (typeof ImageData !== 'undefined' && value instanceof ImageData || tagOf(value) === '[object ImageData]');
54
- };
55
- var isWasmModule = function isWasmModule(value) {
56
- return _typeof(value) === 'object' && value !== null && (typeof WebAssembly !== 'undefined' && value instanceof WebAssembly.Module || tagOf(value) === '[object WebAssembly.Module]');
57
- };
58
- var isURL = function isURL(value) {
59
- return _typeof(value) === 'object' && value !== null && (typeof URL !== 'undefined' && value instanceof URL || tagOf(value) === '[object URL]');
60
- };
61
- var codes = {
38
+ const isImageData = value => typeof value === 'object' && value !== null && (typeof ImageData !== 'undefined' && value instanceof ImageData || tagOf(value) === '[object ImageData]');
39
+ const isWasmModule = value => typeof value === 'object' && value !== null && (typeof WebAssembly !== 'undefined' && value instanceof WebAssembly.Module || tagOf(value) === '[object WebAssembly.Module]');
40
+ const isURL = value => typeof value === 'object' && value !== null && (typeof URL !== 'undefined' && value instanceof URL || tagOf(value) === '[object URL]');
41
+ const codes = {
62
42
  'rgba': 0,
63
43
  'rgb': 1
64
44
  };
65
- var alphaModes = {
45
+ const alphaModes = {
66
46
  'ignore': 0,
67
47
  'weight': 1
68
48
  };
69
- var Module = null;
49
+ let Module = null;
70
50
 
71
51
  // Turns init's `wasm` option into the settings the Emscripten glue understands. The glue finds its .wasm file next to
72
52
  // itself by default (`new URL('clustering.wasm', import.meta.url)`); this lets a caller say where it is, or hand over
73
53
  // the bytes or an already compiled module, for CDNs, strict CSPs and runtimes (such as Cloudflare Workers) that
74
54
  // cannot fetch or compile it that way. `onError` receives instantiation errors, which the glue would otherwise swallow.
75
- var wasmSettings = function wasmSettings(wasm, onError) {
55
+ const wasmSettings = (wasm, onError) => {
76
56
  if (wasm === undefined) {
77
57
  return {};
78
58
  }
79
59
  if (typeof wasm === 'string' || isURL(wasm)) {
80
- var location = String(wasm);
60
+ const location = String(wasm);
81
61
  return {
82
- locateFile: function locateFile(path, directory) {
83
- return path.endsWith('.wasm') ? location : directory + path;
84
- }
62
+ locateFile: (path, directory) => path.endsWith('.wasm') ? location : directory + path
85
63
  };
86
64
  }
87
65
  // Bytes and compiled modules go through `instantiateWasm`: this build of the glue reads no `wasmBinary` setting. The glue
88
66
  // sets itself up on the instance inside `receive`, which throws for a module that isn't this one (it has other exports);
89
67
  // that is reported as a failed load rather than left to escape, which would leave the load waiting forever.
90
- var accept = function accept(receive) {
91
- return function (instance) {
92
- try {
93
- receive(instance);
94
- } catch (error) {
95
- onError(Object.assign(new Error("it is not agglomerative-clustering's module (it lacks the memory and functions this script uses)"), {
96
- cause: error
97
- }));
98
- }
99
- };
68
+ const accept = receive => 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
+ }
100
76
  };
101
77
  if ((0, _shared.isArrayBufferLike)(wasm) || ArrayBuffer.isView(wasm)) {
102
- var source = (0, _shared.isArrayBufferLike)(wasm) ? wasm : new Uint8Array(wasm.buffer, wasm.byteOffset, wasm.byteLength);
78
+ const source = (0, _shared.isArrayBufferLike)(wasm) ? wasm : new Uint8Array(wasm.buffer, wasm.byteOffset, wasm.byteLength);
103
79
  return {
104
- instantiateWasm: function instantiateWasm(imports, receive) {
105
- WebAssembly.instantiate(source, imports).then(function (_ref) {
106
- var instance = _ref.instance;
107
- return accept(receive)(instance);
108
- }, onError);
80
+ instantiateWasm: (imports, receive) => {
81
+ WebAssembly.instantiate(source, imports).then(({
82
+ instance
83
+ }) => accept(receive)(instance), onError);
109
84
  }
110
85
  };
111
86
  }
112
87
  if (isWasmModule(wasm)) {
113
88
  return {
114
- instantiateWasm: function instantiateWasm(imports, receive) {
89
+ instantiateWasm: (imports, receive) => {
115
90
  WebAssembly.instantiate(wasm, imports).then(accept(receive), onError);
116
91
  }
117
92
  };
@@ -123,25 +98,27 @@ var wasmSettings = function wasmSettings(wasm, onError) {
123
98
  // bundler that moved the file, an engine without WebAssembly SIMD. The engine's own error (a CompileError, a failed fetch)
124
99
  // says little about which, so the message leads with what happened and then gives the likely fix for where it ran.
125
100
  // The smallest module that uses a SIMD instruction (from wasm-feature-detect), to tell an old engine from a missing file.
126
- 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];
127
- var hasSimd = function hasSimd() {
101
+ const 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];
102
+ const hasSimd = () => {
128
103
  try {
129
- return (typeof WebAssembly === "undefined" ? "undefined" : _typeof(WebAssembly)) === 'object' && WebAssembly.validate(new Uint8Array(simdProbe));
104
+ return typeof WebAssembly === 'object' && WebAssembly.validate(new Uint8Array(simdProbe));
130
105
  } catch (error) {
131
106
  return false;
132
107
  }
133
108
  };
134
- var isNodeLike = typeof process !== 'undefined' && !!(process.versions && process.versions.node);
135
- var wasmLoadFailed = function wasmLoadFailed(cause, given) {
136
- var text = String(cause && cause.message !== undefined ? cause.message : cause).split('\n')[0];
109
+ // Node itself (or Bun), not a runtime that imitates it: Cloudflare Workers with nodejs_compat and Deno also define
110
+ // process.versions.node, but their navigator.userAgent says what they are (Node 20 has no navigator at all).
111
+ const isNodeLike = typeof process !== 'undefined' && !!(process.versions && process.versions.node) && (typeof navigator === 'undefined' || /^(Node\.js|Bun)\//.test(String(navigator.userAgent)));
112
+ const wasmLoadFailed = (cause, given) => {
113
+ const text = String(cause && cause.message !== undefined ? cause.message : cause).split('\n')[0];
137
114
  // Emscripten appends advice about its own debug build, which doesn't apply to this package's users.
138
115
  // and wraps a failed compile in Aborted(...), which is how it stops itself, not part of the reason.
139
- var reason = text.replace(/\s*\(?Build with -sASSERTIONS for more info\.?\)?/, '').trim().replace(/\.+$/, '');
140
- var aborted = /^Aborted\((.*)\)$/.exec(reason);
116
+ let reason = text.replace(/\s*\(?Build with -sASSERTIONS for more info\.?\)?/, '').trim().replace(/\.+$/, '');
117
+ const aborted = /^Aborted\((.*)\)$/.exec(reason);
141
118
  if (aborted) {
142
119
  reason = aborted[1].replace(/\.+$/, '');
143
120
  }
144
- var advice;
121
+ let advice;
145
122
  if (!hasSimd()) {
146
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).";
147
124
  } else if (given) {
@@ -151,8 +128,8 @@ var wasmLoadFailed = function wasmLoadFailed(cause, given) {
151
128
  } else {
152
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 }).";
153
130
  }
154
- return Object.assign((0, _shared.fail)('wasm-load-failed', "Could not load the WebAssembly module: ".concat(reason || 'unknown error', ". ").concat(advice)), {
155
- cause: cause
131
+ return Object.assign((0, _shared.fail)('wasm-load-failed', `Could not load the WebAssembly module: ${reason || 'unknown error'}. ${advice}`), {
132
+ cause
156
133
  });
157
134
  };
158
135
 
@@ -160,235 +137,149 @@ var wasmLoadFailed = function wasmLoadFailed(cause, given) {
160
137
  // not a public interface. One left over from another version (a stale cache, a CDN serving an old file, an `init({ wasm })`
161
138
  // pointing at the wrong one) would misbehave in ways nothing explains, so the module says which version it is and a
162
139
  // mismatch is reported when it loads.
163
- var checkWasmVersion = function checkWasmVersion(instance) {
140
+ const checkWasmVersion = instance => {
164
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
165
142
  // this library's at all may have none either: both are reported as a version mismatch, never as a stray TypeError.
166
- var found = '';
143
+ let found = '';
167
144
  try {
168
- var pointer = instance._library_version();
169
- var heap = instance.HEAPU8;
145
+ const pointer = instance._library_version();
146
+ const heap = instance.HEAPU8;
170
147
  if (typeof pointer === 'number' && pointer > 0 && heap) {
171
- var end = pointer;
148
+ let end = pointer;
172
149
  while (heap[end] !== 0 && end - pointer < 64) {
173
150
  end++;
174
151
  }
175
- found = String.fromCharCode.apply(String, _toConsumableArray(heap.subarray(pointer, end)));
152
+ found = String.fromCharCode(...heap.subarray(pointer, end));
176
153
  }
177
154
  } catch (error) {/* no version export */}
178
- var expected = "agglomerative-clustering@".concat(_shared.version);
155
+ const expected = `agglomerative-clustering@${_shared.version}`;
179
156
  if (found !== expected) {
180
- 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)';
181
- throw (0, _shared.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."));
157
+ const 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 (0, _shared.fail)('wasm-load-failed', `The WebAssembly module is ${what}, but this script is ${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.`);
182
159
  }
183
160
  };
184
161
 
185
162
  // Instantiates the module from init's `wasm` option (undefined: the glue finds the .wasm next to itself).
186
- var instantiate = function instantiate(wasm) {
187
- var reject;
188
- var failed = new Promise(function (_, r) {
163
+ const instantiate = wasm => {
164
+ let reject;
165
+ const failed = new Promise((_, r) => {
189
166
  reject = r;
190
167
  });
191
- failed["catch"](function () {});
192
- return Promise.race([(0, _clustering["default"])(wasmSettings(wasm, reject)), failed]);
168
+ failed.catch(() => {});
169
+ // The glue's own console output (failed fetches, "Aborted()") is turned off: every failure reaches the caller as an error.
170
+ const quiet = {
171
+ print: () => {},
172
+ printErr: () => {}
173
+ };
174
+ return Promise.race([(0, _clustering.default)({
175
+ ...quiet,
176
+ ...wasmSettings(wasm, reject)
177
+ }), failed]);
193
178
  };
194
179
 
195
180
  // The bytes of this package's clustering.wasm as Node resolves it from the working directory, for when the copy next to
196
181
  // the script is missing (see acquire). The specifiers are built at run time so bundlers leave them alone (see worker.js).
197
- var packagedWasm = /*#__PURE__*/function () {
198
- var _ref2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
199
- var _yield$import, createRequire, _yield$import2, readFile, file;
200
- return _regenerator().w(function (_context) {
201
- while (1) switch (_context.n) {
202
- case 0:
203
- _context.n = 1;
204
- return function (specifier) {
205
- return new Promise(function (r) {
206
- return r("".concat(specifier));
207
- }).then(function (s) {
208
- return _interopRequireWildcard(require(s));
209
- });
210
- }(/* webpackIgnore: true */ /* @vite-ignore */['node', 'module'].join(':'));
211
- case 1:
212
- _yield$import = _context.v;
213
- createRequire = _yield$import.createRequire;
214
- _context.n = 2;
215
- return function (specifier) {
216
- return new Promise(function (r) {
217
- return r("".concat(specifier));
218
- }).then(function (s) {
219
- return _interopRequireWildcard(require(s));
220
- });
221
- }(/* webpackIgnore: true */ /* @vite-ignore */['node', 'fs/promises'].join(':'));
222
- case 2:
223
- _yield$import2 = _context.v;
224
- readFile = _yield$import2.readFile;
225
- file = createRequire("".concat(process.cwd(), "/")).resolve('agglomerative-clustering/clustering.wasm');
226
- return _context.a(2, readFile(file));
227
- }
228
- }, _callee);
229
- }));
230
- return function packagedWasm() {
231
- return _ref2.apply(this, arguments);
232
- };
233
- }();
182
+ const packagedWasm = async () => {
183
+ const {
184
+ createRequire
185
+ } = await (specifier => new Promise(r => r(`${specifier}`)).then(s => _interopRequireWildcard(require(s))))(/* webpackIgnore: true */ /* @vite-ignore */['node', 'module'].join(':'));
186
+ const {
187
+ readFile
188
+ } = await (specifier => new Promise(r => r(`${specifier}`)).then(s => _interopRequireWildcard(require(s))))(/* webpackIgnore: true */ /* @vite-ignore */['node', 'fs/promises'].join(':'));
189
+ const file = createRequire(`${process.cwd()}/`).resolve('agglomerative-clustering/clustering.wasm');
190
+ return readFile(file);
191
+ };
234
192
 
235
193
  // The module loads once: concurrent calls share one load, and a load that fails is forgotten, so it can be retried.
236
- var loading = null;
194
+ let loading = null;
237
195
 
238
196
  // Calls get the instance they run on from `acquire` and keep using it, so replacing the current instance (see `discard`)
239
197
  // never changes the module under a call already in flight.
240
- var acquire = /*#__PURE__*/function () {
241
- var _ref3 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(options) {
242
- var _i, _Object$keys, key, wasm;
243
- return _regenerator().w(function (_context3) {
244
- while (1) switch (_context3.n) {
245
- case 0:
246
- if (options === undefined) {
247
- options = {};
248
- }
249
- if ((0, _shared.isOptionsObject)(options)) {
250
- _context3.n = 1;
251
- break;
252
- }
253
- throw (0, _shared.fail)('invalid-argument', "Invalid options: expected an object.", 'options');
254
- case 1:
255
- options = (0, _shared.snapshot)(options);
256
- _i = 0, _Object$keys = Object.keys(options);
257
- case 2:
258
- if (!(_i < _Object$keys.length)) {
259
- _context3.n = 4;
260
- break;
261
- }
262
- key = _Object$keys[_i];
263
- if (!(key !== 'wasm')) {
264
- _context3.n = 3;
265
- break;
266
- }
267
- throw (0, _shared.fail)('invalid-argument', "Invalid option '".concat(key, "': expected wasm."), "options.".concat(key));
268
- case 3:
269
- _i++;
270
- _context3.n = 2;
271
- break;
272
- case 4:
273
- // Checked on every call, so a bad value is reported even when the module is already loaded.
274
- wasmSettings(options.wasm, function () {});
275
- if (!Module) {
276
- _context3.n = 5;
277
- break;
278
- }
279
- return _context3.a(2, Module);
280
- case 5:
281
- if (!loading) {
282
- wasm = options.wasm;
283
- loading = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2() {
284
- var instance, fallback, _t, _t2;
285
- return _regenerator().w(function (_context2) {
286
- while (1) switch (_context2.n) {
287
- case 0:
288
- _context2.p = 0;
289
- _context2.n = 1;
290
- return instantiate(wasm);
291
- case 1:
292
- instance = _context2.v;
293
- _context2.n = 8;
294
- break;
295
- case 2:
296
- _context2.p = 2;
297
- _t = _context2.v;
298
- if (!(wasm === undefined && isNodeLike)) {
299
- _context2.n = 4;
300
- break;
301
- }
302
- _context2.n = 3;
303
- return packagedWasm()["catch"](function () {
304
- return null;
305
- });
306
- case 3:
307
- _t2 = _context2.v;
308
- _context2.n = 5;
309
- break;
310
- case 4:
311
- _t2 = null;
312
- case 5:
313
- fallback = _t2;
314
- if (fallback) {
315
- _context2.n = 6;
316
- break;
317
- }
318
- throw wasmLoadFailed(_t, wasm !== undefined);
319
- case 6:
320
- _context2.n = 7;
321
- return instantiate(fallback)["catch"](function () {
322
- throw wasmLoadFailed(_t, false);
323
- });
324
- case 7:
325
- instance = _context2.v;
326
- case 8:
327
- checkWasmVersion(instance);
328
- Module = instance;
329
- return _context2.a(2, instance);
330
- }
331
- }, _callee2, null, [[0, 2]]);
332
- }))()["catch"](function (error) {
333
- loading = null;
334
- throw error;
335
- });
336
- }
337
- return _context3.a(2, loading);
198
+ const acquire = async options => {
199
+ if (options === undefined) {
200
+ options = {};
201
+ }
202
+ if (!(0, _shared.isOptionsObject)(options)) {
203
+ throw (0, _shared.fail)('invalid-argument', "Invalid options: expected an object.", 'options');
204
+ }
205
+ options = (0, _shared.snapshot)(options);
206
+ for (const key of Object.keys(options)) {
207
+ if (key !== 'wasm') {
208
+ throw (0, _shared.fail)('invalid-argument', `Invalid option '${key}': expected wasm.`, `options.${key}`);
209
+ }
210
+ }
211
+ // Checked on every call, so a bad value is reported even when the module is already loaded.
212
+ wasmSettings(options.wasm, () => {});
213
+ if (Module) {
214
+ return Module;
215
+ }
216
+ if (!loading) {
217
+ const wasm = options.wasm;
218
+ loading = (async () => {
219
+ let instance;
220
+ try {
221
+ instance = await instantiate(wasm);
222
+ } catch (error) {
223
+ // In Node, a bundler that rewrote the glue's `new URL('clustering.wasm', import.meta.url)` (a Next.js server
224
+ // build, say) leaves it pointing at a file that isn't there. The package's own copy is then looked for the
225
+ // way Node resolves packages, from the working directory; if that fails too, the first error is reported.
226
+ const fallback = wasm === undefined && isNodeLike ? await packagedWasm().catch(() => null) : null;
227
+ if (!fallback) {
228
+ throw wasmLoadFailed(error, wasm !== undefined);
229
+ }
230
+ instance = await instantiate(fallback).catch(() => {
231
+ throw wasmLoadFailed(error, false);
232
+ });
338
233
  }
339
- }, _callee3);
340
- }));
341
- return function acquire(_x) {
342
- return _ref3.apply(this, arguments);
343
- };
344
- }();
234
+ checkWasmVersion(instance);
235
+ Module = instance;
236
+ return instance;
237
+ })().catch(error => {
238
+ loading = null;
239
+ throw error;
240
+ });
241
+ }
242
+ return loading;
243
+ };
345
244
 
346
245
  // Loads the WebAssembly module. Every other function does this on first use, so calling it is optional, except to
347
246
  // say where the .wasm file is (`wasm`), which must come before anything else. The first load that succeeds wins:
348
247
  // later calls, with or without options, get the same module.
349
- var init = exports.init = /*#__PURE__*/function () {
350
- var _ref5 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(options) {
351
- return _regenerator().w(function (_context4) {
352
- while (1) switch (_context4.n) {
353
- case 0:
354
- _context4.n = 1;
355
- return acquire(options);
356
- case 1:
357
- return _context4.a(2);
358
- }
359
- }, _callee4);
360
- }));
361
- return function init(_x2) {
362
- return _ref5.apply(this, arguments);
363
- };
364
- }();
248
+ const init = async options => {
249
+ await acquire(options);
250
+ };
365
251
 
366
252
  // A WebAssembly abort, which is what running out of memory looks like, leaves the instance's heap full of whatever the
367
253
  // failed call had allocated and never freed (the abort skips destructors), so every later large call on it would fail
368
254
  // too. The instance is therefore discarded: the next call loads a fresh one, and calls already running keep theirs.
369
- var isAbort = function isAbort(error) {
370
- return error instanceof Error && error.name === 'RuntimeError' && /^Aborted\(/.test(error.message);
371
- };
372
- var discard = function discard(instance) {
255
+ exports.init = init;
256
+ const isAbort = error => error instanceof Error && error.name === 'RuntimeError' && /^Aborted\(/.test(error.message);
257
+ const discard = instance => {
373
258
  if (Module === instance) {
374
259
  Module = null;
375
260
  loading = null;
376
261
  }
377
262
  };
378
- var outOfMemory = function outOfMemory() {
379
- return (0, _shared.fail)('out-of-memory', "The WebAssembly module ran out of memory (it can use up to 2 GB for one image). Try `precision: 6`, which bounds the memory an image with very many colours needs, or a smaller image.");
263
+ // WebAssembly memory only grows: an instance that once held a huge image keeps all that memory for the life of the process.
264
+ // So when a call leaves the heap larger than this, the instance is retired like an aborted one: calls already running keep
265
+ // it, the next call loads a fresh one (a few milliseconds, next to the seconds such an image took), and the old memory is
266
+ // freed when nothing uses it any more.
267
+ const retireAbove = 256 * 1024 * 1024;
268
+ const retireIfLarge = instance => {
269
+ if (instance.HEAPU8 && instance.HEAPU8.length > retireAbove) {
270
+ discard(instance);
271
+ }
380
272
  };
381
- var unpack = function unpack(wasm, pointer) {
382
- var lengthBuffer = new Uint8Array(wasm.HEAPU8.subarray(pointer, pointer + 4));
383
- var length = lengthBuffer[0] | lengthBuffer[1] << 8 | lengthBuffer[2] << 16 | lengthBuffer[3] << 24;
384
- var outputBuffer = new Uint8Array(wasm.HEAPU8.subarray(pointer + 4, pointer + 4 + length));
273
+ const outOfMemory = () => (0, _shared.fail)('out-of-memory', "The WebAssembly module ran out of memory (it can use up to 2 GB for one image). Try `precision: 6`, which bounds the memory an image with very many colours needs, or a smaller image.");
274
+ const unpack = (wasm, pointer) => {
275
+ const lengthBuffer = new Uint8Array(wasm.HEAPU8.subarray(pointer, pointer + 4));
276
+ const length = lengthBuffer[0] | lengthBuffer[1] << 8 | lengthBuffer[2] << 16 | lengthBuffer[3] << 24;
277
+ const outputBuffer = new Uint8Array(wasm.HEAPU8.subarray(pointer + 4, pointer + 4 + length));
385
278
  return outputBuffer;
386
279
  };
387
280
 
388
281
  // A Uint8Array over exactly the same bytes, so views into a larger buffer (subarrays) stay views of their own range.
389
- var bytes = function bytes(data) {
390
- return (0, _shared.isUint8Array)(data) ? data : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
391
- };
282
+ const bytes = data => (0, _shared.isUint8Array)(data) ? data : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
392
283
 
393
284
  // ----- Encoded image files -------------------------------------------------------------------------------------------
394
285
  // A bare Uint8Array is taken to be raw RGBA pixels, so the commonest mistake is handing over the bytes of an image *file*
@@ -400,8 +291,8 @@ var bytes = function bytes(data) {
400
291
  // This is also where decoding would go. The library doesn't decode files today (that needs a decoder per format, and
401
292
  // sharp, pngjs, createImageBitmap and the like already do it); when it does, a file recognised here is decoded into
402
293
  // { data, format, width, height } instead of rejected, and `load` becomes asynchronous. See docs/ROADMAP.md.
403
- var ascii = function ascii(bytes, at, text) {
404
- for (var i = 0; i < text.length; i++) {
294
+ const ascii = (bytes, at, text) => {
295
+ for (let i = 0; i < text.length; i++) {
405
296
  if (bytes[at + i] !== text.charCodeAt(i)) {
406
297
  return false;
407
298
  }
@@ -411,8 +302,8 @@ var ascii = function ascii(bytes, at, text) {
411
302
 
412
303
  // The name of the encoded image format `bytes` starts with, or null. Signatures are long enough, or have enough structure
413
304
  // beyond the first few bytes, that raw pixels all but never match.
414
- var sniffImageFormat = function sniffImageFormat(bytes) {
415
- var length = bytes.length;
305
+ const sniffImageFormat = bytes => {
306
+ const length = bytes.length;
416
307
  if (length >= 8 && bytes[0] === 0x89 && ascii(bytes, 1, 'PNG') && bytes[4] === 0x0D && bytes[5] === 0x0A && bytes[6] === 0x1A && bytes[7] === 0x0A) {
417
308
  return 'PNG';
418
309
  }
@@ -432,13 +323,11 @@ var sniffImageFormat = function sniffImageFormat(bytes) {
432
323
  }
433
324
  // TIFF: a byte order mark and 42, then the offset of the first directory, which must lie in the file and start with a plausible entry count
434
325
  if (length >= 12) {
435
- var little = bytes[0] === 0x49 && bytes[1] === 0x49 && bytes[2] === 0x2A && bytes[3] === 0;
436
- var big = bytes[0] === 0x4D && bytes[1] === 0x4D && bytes[2] === 0 && bytes[3] === 0x2A;
326
+ const little = bytes[0] === 0x49 && bytes[1] === 0x49 && bytes[2] === 0x2A && bytes[3] === 0;
327
+ const big = bytes[0] === 0x4D && bytes[1] === 0x4D && bytes[2] === 0 && bytes[3] === 0x2A;
437
328
  if (little || big) {
438
- var u16 = function u16(at) {
439
- return little ? bytes[at] | bytes[at + 1] << 8 : bytes[at] << 8 | bytes[at + 1];
440
- };
441
- var offset = little ? (bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24) >>> 0 : (bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7]) >>> 0;
329
+ const u16 = at => little ? bytes[at] | bytes[at + 1] << 8 : bytes[at] << 8 | bytes[at + 1];
330
+ const offset = little ? (bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24) >>> 0 : (bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7]) >>> 0;
442
331
  if (offset >= 8 && offset + 2 <= length && u16(offset) >= 1 && u16(offset) <= 4096) {
443
332
  return 'TIFF';
444
333
  }
@@ -449,51 +338,16 @@ var sniffImageFormat = function sniffImageFormat(bytes) {
449
338
  if (ascii(bytes, 8, 'avif') || ascii(bytes, 8, 'avis')) {
450
339
  return 'AVIF';
451
340
  }
452
- if (['heic', 'heix', 'hevc', 'hevx', 'heim', 'heis', 'mif1', 'msf1'].some(function (brand) {
453
- return ascii(bytes, 8, brand);
454
- })) {
341
+ if (['heic', 'heix', 'hevc', 'hevx', 'heim', 'heis', 'mif1', 'msf1'].some(brand => ascii(bytes, 8, brand))) {
455
342
  return 'HEIC';
456
343
  }
457
344
  }
458
345
  return null;
459
346
  };
460
347
 
461
- // What to say about something that isn't an image, when it is a common thing to pass by mistake: each has a one-line fix.
462
- var imageHint = function imageHint(image) {
463
- var decode = " Decode it to pixels first, then pass them.";
464
- if (image === undefined || image === null) {
465
- return " Got ".concat(image, ".");
466
- }
467
- if (typeof image === 'string') {
468
- return " Got a string (a file name, URL or data URL?): load and decode it to pixels first.";
469
- }
470
- if (_typeof(image) !== 'object') {
471
- return " Got a ".concat(_typeof(image), ".");
472
- }
473
- if (Array.isArray(image)) {
474
- return " Got a plain array: use new Uint8Array(array) for RGBA bytes, or { data: new Uint8Array(array), format: 'rgb' }.";
475
- }
476
- if ((0, _shared.isArrayBufferLike)(image)) {
477
- return " Got an ArrayBuffer, which has no pixel layout: wrap it, new Uint8Array(buffer) for RGBA bytes (if it holds an encoded image file, decode it first).";
478
- }
479
- if (typeof image.getContext === 'function') {
480
- return " Got a canvas: pass its pixels, canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height).";
481
- }
482
- if (typeof image.arrayBuffer === 'function' && typeof image.type === 'string') {
483
- return " Got a Blob or File, which is an encoded image:" + decode + " (createImageBitmap(blob), draw it to a canvas, then getImageData()).";
484
- }
485
- if (typeof image.close === 'function' || typeof image.nodeName === 'string') {
486
- return " Got an image element or ImageBitmap: draw it to a canvas (or OffscreenCanvas) and pass getImageData().";
487
- }
488
- if (image.data && !image.format) {
489
- return " It has `data` but no `format`: add format: 'rgba' (or 'rgb') to use it as a RawImage.";
490
- }
491
- return '';
492
- };
493
-
494
348
  // A typed array whose buffer was transferred away (to a worker, say) is empty and can't be read or viewed.
495
- var isDetached = function isDetached(view) {
496
- var buffer = view.buffer;
349
+ const isDetached = view => {
350
+ const buffer = view.buffer;
497
351
  if (typeof buffer.detached === 'boolean') {
498
352
  return buffer.detached;
499
353
  }
@@ -508,36 +362,34 @@ var isDetached = function isDetached(view) {
508
362
  // The bytes a call works on are read when it is made, as with any function that takes an array: the caller may reuse
509
363
  // or change the array as soon as the call returns. Once the module is loaded the bytes go into its memory before the
510
364
  // call returns; until then (the first call) a copy is kept for when it has loaded.
511
- var held = function held(data) {
512
- return Module ? data : data.slice();
513
- };
365
+ const held = data => Module ? data : data.slice();
514
366
 
515
367
  // width and height are copied to results and used for dithering, so each must make sense on its own: a whole number of
516
368
  // pixels that divides the pixel count (and, when both are given, account for exactly the pixels in the data).
517
- var checkSize = function checkSize(pixels, size, name, argument) {
369
+ const checkSize = (pixels, size, name, argument) => {
518
370
  if (size === undefined) {
519
371
  return;
520
372
  }
521
373
  if (!Number.isInteger(size) || size < 0) {
522
- throw (0, _shared.fail)('invalid-argument', "Invalid ".concat(name, ": must be a whole number of pixels."), argument);
374
+ throw (0, _shared.fail)('invalid-argument', `Invalid ${name}: must be a whole number of pixels.`, argument);
523
375
  }
524
376
  if (pixels > 0 && (size === 0 || pixels % size !== 0)) {
525
- throw (0, _shared.fail)('invalid-argument', "Invalid ".concat(name, ": ").concat(size, " does not divide the image's ").concat(pixels, " pixels into whole rows."), argument);
377
+ throw (0, _shared.fail)('invalid-argument', `Invalid ${name}: ${size} does not divide the image's ${pixels} pixels into whole rows.`, argument);
526
378
  }
527
379
  };
528
- var load = function load(image) {
380
+ const load = image => {
529
381
  if ((0, _shared.isClustering)(image) || (0, _shared.isPalette)(image)) {
530
- var what = (0, _shared.isClustering)(image) ? 'a clustering (from getClustering)' : 'a palette';
531
- var fix = (0, _shared.isClustering)(image) ? 'To cut a palette from it, use getPaletteFromClustering (or quantizeFromClustering to map an image with it).' : 'To map an image to it, use quantizeWithPalette(image, palette).';
532
- throw (0, _shared.fail)('invalid-argument', "Invalid image: this is ".concat(what, ", not pixels. ").concat(fix), 'image');
382
+ const what = (0, _shared.isClustering)(image) ? 'a clustering (from getClustering)' : 'a palette';
383
+ const fix = (0, _shared.isClustering)(image) ? 'To cut a palette from it, use getPaletteFromClustering (or quantizeFromClustering to map an image with it).' : 'To map an image to it, use quantizeWithPalette(image, palette).';
384
+ throw (0, _shared.fail)('invalid-argument', `Invalid image: this is ${what}, not pixels. ${fix}`, 'image');
533
385
  }
534
386
  if (ArrayBuffer.isView(image) && isDetached(image)) {
535
387
  throw (0, _shared.fail)('invalid-argument', "Invalid image: its buffer was transferred away (detached), for example to a worker created with transfer: true, so it has no pixels left. Pass a copy if you need to keep using it.", 'image');
536
388
  }
537
389
  if ((0, _shared.isUint8Array)(image)) {
538
- var encoded = sniffImageFormat(image);
390
+ const encoded = sniffImageFormat(image);
539
391
  if (encoded) {
540
- throw (0, _shared.fail)('invalid-argument', "Invalid image: these bytes are an encoded ".concat(encoded, " file, not pixels. Decode it first (in a browser, draw it to a canvas or use createImageBitmap, then pass getImageData(); in Node use sharp, pngjs or similar) and pass the raw pixels. If they really are raw RGBA pixels, pass { data, format: 'rgba' } to say so."), 'image');
392
+ throw (0, _shared.fail)('invalid-argument', `Invalid image: these bytes are an encoded ${encoded} file, not pixels. Decode it first (in a browser, draw it to a canvas or use createImageBitmap, then pass getImageData(); in Node use sharp, pngjs or similar) and pass the raw pixels. If they really are raw RGBA pixels, pass { data, format: 'rgba' } to say so.`, 'image');
541
393
  }
542
394
  if (image.length % 4 !== 0) {
543
395
  throw (0, _shared.fail)('invalid-argument', "Invalid image data: length must be a multiple of 4 for 'rgba'.", 'image');
@@ -560,8 +412,8 @@ var load = function load(image) {
560
412
  if (ArrayBuffer.isView(image)) {
561
413
  throw (0, _shared.fail)('invalid-argument', "Invalid image: a bare typed array must be a Uint8Array of RGBA bytes. For a Uint8ClampedArray such as imageData.data, pass the ImageData itself or { data, format: 'rgba' }.", 'image');
562
414
  }
563
- if (_typeof(image) !== 'object' || !image || !image.data || !image.format) {
564
- throw (0, _shared.fail)('invalid-argument', "Invalid image: expected object with `data` and `format`.".concat(imageHint(image)), 'image');
415
+ if (typeof image !== 'object' || !image || !image.data || !image.format) {
416
+ throw (0, _shared.fail)('invalid-argument', `Invalid image: expected object with \`data\` and \`format\`.${(0, _shared.imageHint)(image)}`, 'image');
565
417
  }
566
418
  if (!(0, _shared.isUint8Array)(image.data) && !(0, _shared.isUint8ClampedArray)(image.data)) {
567
419
  throw (0, _shared.fail)('invalid-argument', "Invalid image data: must be Uint8Array or Uint8ClampedArray.", 'image');
@@ -572,15 +424,15 @@ var load = function load(image) {
572
424
  if (!Object.keys(codes).includes(image.format)) {
573
425
  throw (0, _shared.fail)('invalid-argument', "Invalid format: must be 'rgb' or 'rgba'.", 'image');
574
426
  }
575
- var channels = image.format === 'rgb' ? 3 : 4;
427
+ const channels = image.format === 'rgb' ? 3 : 4;
576
428
  if (image.data.length % channels !== 0) {
577
- throw (0, _shared.fail)('invalid-argument', "Invalid image data: length must be a multiple of ".concat(channels, " for '").concat(image.format, "'."), 'image');
429
+ throw (0, _shared.fail)('invalid-argument', `Invalid image data: length must be a multiple of ${channels} for '${image.format}'.`, 'image');
578
430
  }
579
- var pixels = image.data.length / channels;
431
+ const pixels = image.data.length / channels;
580
432
  checkSize(pixels, image.width, 'image width', 'image');
581
433
  checkSize(pixels, image.height, 'image height', 'image');
582
434
  if (image.width !== undefined && image.height !== undefined && image.width * image.height !== pixels) {
583
- throw (0, _shared.fail)('invalid-argument', "Invalid image: width x height (".concat(image.width, " x ").concat(image.height, ") does not match its ").concat(pixels, " pixels."), 'image');
435
+ throw (0, _shared.fail)('invalid-argument', `Invalid image: width x height (${image.width} x ${image.height}) does not match its ${pixels} pixels.`, 'image');
584
436
  }
585
437
  return {
586
438
  data: held(bytes(image.data)),
@@ -588,61 +440,61 @@ var load = function load(image) {
588
440
  width: image.width
589
441
  };
590
442
  };
591
- var getWrapper = function getWrapper(image) {
443
+ const getWrapper = image => {
592
444
  if (isImageData(image)) {
593
445
  // The pixels stay in the colour space they came in ('display-p3' canvases), so the result must say so.
594
- var width = image.width,
595
- height = image.height,
596
- colorSpace = image.colorSpace;
597
- return function (output) {
598
- return new ImageData(new Uint8ClampedArray(output.buffer), width, height, colorSpace ? {
599
- colorSpace: colorSpace
600
- } : undefined);
601
- };
602
- }
603
- if (!(0, _shared.isUint8Array)(image) && _typeof(image) === 'object' && image && image.data && image.format) {
604
- var format = image.format,
605
- _width = image.width,
606
- _height = image.height;
607
- return function (output) {
608
- var result = {
446
+ const {
447
+ width,
448
+ height,
449
+ colorSpace
450
+ } = image;
451
+ return output => new ImageData(new Uint8ClampedArray(output.buffer), width, height, colorSpace ? {
452
+ colorSpace
453
+ } : undefined);
454
+ }
455
+ if (!(0, _shared.isUint8Array)(image) && typeof image === 'object' && image && image.data && image.format) {
456
+ const {
457
+ format,
458
+ width,
459
+ height
460
+ } = image;
461
+ return output => {
462
+ const result = {
609
463
  data: output,
610
- format: format
464
+ format
611
465
  };
612
- if (_width !== undefined) {
613
- result.width = _width;
466
+ if (width !== undefined) {
467
+ result.width = width;
614
468
  }
615
- if (_height !== undefined) {
616
- result.height = _height;
469
+ if (height !== undefined) {
470
+ result.height = height;
617
471
  }
618
472
  return result;
619
473
  };
620
474
  }
621
- return function (output) {
622
- return output;
623
- };
475
+ return output => output;
624
476
  };
625
477
 
626
478
  // Decodes _quantize_indices output: [entries, transparent index, index bytes] as 32-bit little-endian values, then
627
479
  // the palette, then the indices. `image` is the caller's original input, for its width and height.
628
- var unpackIndices = function unpackIndices(output, image, colorSpace) {
629
- var view = new DataView(output.buffer, output.byteOffset, output.byteLength);
630
- var entries = view.getUint32(0, true);
631
- var transparent = view.getInt32(4, true);
632
- var indexBytes = view.getUint32(8, true);
633
- var palette = (0, _shared.markPalette)(output.slice(12, 12 + 3 * entries), colorSpace);
634
- var start = 12 + 3 * entries;
635
- var count = (output.length - start) / indexBytes;
636
- var Indices = indexBytes === 1 ? Uint8Array : indexBytes === 2 ? Uint16Array : Uint32Array;
637
- var indices = new Indices(count);
480
+ const unpackIndices = (output, image, colorSpace) => {
481
+ const view = new DataView(output.buffer, output.byteOffset, output.byteLength);
482
+ const entries = view.getUint32(0, true);
483
+ const transparent = view.getInt32(4, true);
484
+ const indexBytes = view.getUint32(8, true);
485
+ const palette = (0, _shared.markPalette)(output.slice(12, 12 + 3 * entries), colorSpace);
486
+ const start = 12 + 3 * entries;
487
+ const count = (output.length - start) / indexBytes;
488
+ const Indices = indexBytes === 1 ? Uint8Array : indexBytes === 2 ? Uint16Array : Uint32Array;
489
+ const indices = new Indices(count);
638
490
  // Little-endian, like the WASM heap, which Emscripten's own typed-array views already assume of the host.
639
491
  new Uint8Array(indices.buffer).set(output.subarray(start));
640
492
  // `colors` is the palette without the transparent entry, ready to map with again (the entry is black and takes no part in matching)
641
- var colors = transparent < 0 ? palette : (0, _shared.markPalette)(palette.slice(0, 3 * transparent), colorSpace);
642
- var result = {
643
- palette: palette,
644
- colors: colors,
645
- indices: indices,
493
+ const colors = transparent < 0 ? palette : (0, _shared.markPalette)(palette.slice(0, 3 * transparent), colorSpace);
494
+ const result = {
495
+ palette,
496
+ colors,
497
+ indices,
646
498
  indexBits: 8 * indexBytes,
647
499
  transparentIndex: transparent < 0 ? null : transparent
648
500
  };
@@ -659,9 +511,11 @@ var unpackIndices = function unpackIndices(output, image, colorSpace) {
659
511
 
660
512
  // Returns k, validated. Any k above the number of colours means all of them, so it is capped at the largest value
661
513
  // the WASM side holds (a larger one would overflow its int).
662
- var check = function check(k) {
514
+ const check = k => {
663
515
  if (typeof k !== 'number' || !Number.isInteger(k) || k <= 0) {
664
- throw (0, _shared.fail)('invalid-argument', "Invalid k: must be a strictly positive integer.", 'k');
516
+ // A string is the usual slip (an input's `value`), so it gets its own fix.
517
+ const got = typeof k === 'string' ? ` Got the string ${JSON.stringify(k.length > 20 ? `${k.slice(0, 20)}…` : k)}: convert it first, e.g. Number(input.value).` : typeof k === 'number' ? ` Got ${k}.` : ` Got ${k === null ? 'null' : typeof k}.`;
518
+ throw (0, _shared.fail)('invalid-argument', `Invalid k: must be a whole number of colours, 1 or more.${got}`, 'k');
665
519
  }
666
520
  return Math.min(k, 0x7FFFFFFF);
667
521
  };
@@ -677,7 +531,7 @@ var check = function check(k) {
677
531
  // transparent: false (default), true (cutoff 128) or a cutoff from 1 to 255: pixels with alpha below it are left out of clustering (and the rest count whole);
678
532
  // indexed output also gives them their own entry, which counts towards k
679
533
 
680
- var parseOptions = function parseOptions(options, allowed, image) {
534
+ const parseOptions = (options, allowed, image) => {
681
535
  if (options === undefined) {
682
536
  options = {};
683
537
  }
@@ -685,25 +539,24 @@ var parseOptions = function parseOptions(options, allowed, image) {
685
539
  throw (0, _shared.fail)('invalid-argument', "Invalid options: expected an object.", 'options');
686
540
  }
687
541
  options = (0, _shared.snapshot)(options);
688
- for (var _i2 = 0, _Object$keys2 = Object.keys(options); _i2 < _Object$keys2.length; _i2++) {
689
- var key = _Object$keys2[_i2];
542
+ for (const key of Object.keys(options)) {
690
543
  if (!allowed.includes(key)) {
691
- throw (0, _shared.fail)('invalid-argument', "Invalid option '".concat(key, "': expected one of ").concat(allowed.join(', '), "."), "options.".concat(key));
544
+ throw (0, _shared.fail)('invalid-argument', `Invalid option '${key}': expected one of ${allowed.join(', ')}.`, `options.${key}`);
692
545
  }
693
546
  }
694
- var colorSpace = options.colorSpace === undefined ? 'rgb' : options.colorSpace;
547
+ const colorSpace = options.colorSpace === undefined ? 'rgb' : options.colorSpace;
695
548
  if (!Object.keys(_shared.colorSpaces).includes(colorSpace)) {
696
549
  throw (0, _shared.fail)('invalid-argument', "Invalid colorSpace: must be 'rgb' or 'oklab'.", 'options.colorSpace');
697
550
  }
698
- var alpha = options.alpha === undefined ? 'weight' : options.alpha;
551
+ const alpha = options.alpha === undefined ? 'weight' : options.alpha;
699
552
  if (!Object.keys(alphaModes).includes(alpha)) {
700
553
  throw (0, _shared.fail)('invalid-argument', "Invalid alpha: must be 'weight' or 'ignore'.", 'options.alpha');
701
554
  }
702
- var precision = options.precision === undefined ? 8 : options.precision;
555
+ const precision = options.precision === undefined ? 8 : options.precision;
703
556
  if (typeof precision !== 'number' || !Number.isInteger(precision) || precision < 1 || precision > 8) {
704
557
  throw (0, _shared.fail)('invalid-argument', "Invalid precision: must be an integer from 1 to 8.", 'options.precision');
705
558
  }
706
- var dither = options.dither === undefined || options.dither === false ? 0 : options.dither === true ? 1 : options.dither;
559
+ const dither = options.dither === undefined || options.dither === false ? 0 : options.dither === true ? 1 : options.dither;
707
560
  if (typeof dither !== 'number' || !Number.isFinite(dither) || dither < 0 || dither > 1) {
708
561
  throw (0, _shared.fail)('invalid-argument', "Invalid dither: must be a boolean or a number from 0 to 1.", 'options.dither');
709
562
  }
@@ -711,14 +564,14 @@ var parseOptions = function parseOptions(options, allowed, image) {
711
564
  // The image's own width and options.width are two sources for one fact: they may repeat each other, but not disagree
712
565
  // (a wrong row length would dither without an error, as long as it divides the pixel count).
713
566
  if (options.width !== undefined && image && image.width !== undefined && options.width !== image.width) {
714
- throw (0, _shared.fail)('invalid-argument', "Invalid width: options.width (".concat(options.width, ") does not match the image's width (").concat(image.width, ")."), 'options.width');
567
+ throw (0, _shared.fail)('invalid-argument', `Invalid width: options.width (${options.width}) does not match the image's width (${image.width}).`, 'options.width');
715
568
  }
716
569
  if (options.width !== undefined && image) {
717
570
  checkSize(image.data.length / (image.format === 'rgb' ? 3 : 4), options.width, 'width', 'options.width');
718
571
  }
719
- var width = options.width !== undefined ? options.width : image ? image.width : undefined;
572
+ const width = options.width !== undefined ? options.width : image ? image.width : undefined;
720
573
  if (dither > 0) {
721
- var channels = image.format === 'rgb' ? 3 : 4;
574
+ const channels = image.format === 'rgb' ? 3 : 4;
722
575
  if (typeof width !== 'number' || !Number.isInteger(width) || width <= 0) {
723
576
  throw (0, _shared.fail)('invalid-argument', "Invalid width: dithering needs the image width, as `options.width` or the image's `width`.", 'options.width');
724
577
  }
@@ -726,18 +579,18 @@ var parseOptions = function parseOptions(options, allowed, image) {
726
579
  throw (0, _shared.fail)('invalid-argument', "Invalid width: the image's pixel count is not a multiple of it.", 'options.width');
727
580
  }
728
581
  }
729
- var signal = options.signal;
730
- if (signal !== undefined && (signal === null || _typeof(signal) !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function')) {
582
+ const signal = options.signal;
583
+ if (signal !== undefined && (signal === null || typeof signal !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function')) {
731
584
  throw (0, _shared.fail)('invalid-argument', "Invalid signal: must be an AbortSignal.", 'options.signal');
732
585
  }
733
- var onProgress = options.onProgress;
586
+ const onProgress = options.onProgress;
734
587
  if (onProgress !== undefined && typeof onProgress !== 'function') {
735
588
  throw (0, _shared.fail)('invalid-argument', "Invalid onProgress: must be a function.", 'options.onProgress');
736
589
  }
737
590
 
738
591
  // The alpha cutoff for indexed output: 0 for none, else the pixels with alpha below it are transparent.
739
- var transparentOption = options.transparent === undefined ? false : options.transparent;
740
- var transparent = transparentOption === false ? 0 : transparentOption === true ? 128 : transparentOption;
592
+ const transparentOption = options.transparent === undefined ? false : options.transparent;
593
+ const transparent = transparentOption === false ? 0 : transparentOption === true ? 128 : transparentOption;
741
594
  if (!Number.isInteger(transparent) || transparent < 0 || transparent > 255 || transparent === 0 && transparentOption !== false) {
742
595
  throw (0, _shared.fail)('invalid-argument', "Invalid transparent: must be a boolean or an integer alpha cutoff from 1 to 255.", 'options.transparent');
743
596
  }
@@ -750,34 +603,34 @@ var parseOptions = function parseOptions(options, allowed, image) {
750
603
  colorSpace: _shared.colorSpaces[colorSpace],
751
604
  colorSpaceGiven: options.colorSpace !== undefined,
752
605
  alpha: alphaModes[alpha],
753
- precision: precision,
754
- dither: dither,
606
+ precision,
607
+ dither,
755
608
  width: dither > 0 ? width : 0,
756
- transparent: transparent,
609
+ transparent,
757
610
  transparentGiven: options.transparent !== undefined,
758
- signal: signal,
759
- onProgress: onProgress
611
+ signal,
612
+ onProgress
760
613
  };
761
614
  };
762
- var controlOptions = ['signal', 'onProgress'];
763
- var clusterOptions = ['colorSpace', 'precision', 'alpha', 'transparent'].concat(controlOptions);
764
- var quantizeOptions = [].concat(_toConsumableArray(clusterOptions), ['dither', 'width']);
615
+ const controlOptions = ['signal', 'onProgress'];
616
+ const clusterOptions = ['colorSpace', 'precision', 'alpha', 'transparent', ...controlOptions];
617
+ const quantizeOptions = [...clusterOptions, 'dither', 'width'];
765
618
  // The functions that only map pixels take just `signal`: they finish in milliseconds, so there is nothing to report progress
766
619
  // on or to interrupt part way; a signal that is already aborted does no work, which is all it can mean.
767
- var mapOptions = ['colorSpace', 'dither', 'width', 'signal'];
768
- var quantizeIndexOptions = quantizeOptions;
769
- var mapIndexOptions = [].concat(mapOptions, ['transparent']);
620
+ const mapOptions = ['colorSpace', 'dither', 'width', 'signal'];
621
+ const quantizeIndexOptions = quantizeOptions;
622
+ const mapIndexOptions = [...mapOptions, 'transparent'];
770
623
 
771
624
  // An empty palette is what getPalette gives for an image with no visible pixels, and mapping such an image with it is
772
625
  // fine. Mapping visible pixels to it has no answer (they would all come out black), so that is an error. `cutoff` is the
773
626
  // alpha from which an RGBA pixel needs a colour.
774
- var checkNotEmpty = function checkNotEmpty(palette, image, cutoff) {
627
+ const checkNotEmpty = (palette, image, cutoff) => {
775
628
  if (palette.length > 0) {
776
629
  return;
777
630
  }
778
- var data = image.data;
779
- var visible = image.format === 'rgb' ? data.length > 0 : false;
780
- for (var i = 3; !visible && i < data.length; i += 4) {
631
+ const data = image.data;
632
+ let visible = image.format === 'rgb' ? data.length > 0 : false;
633
+ for (let i = 3; !visible && i < data.length; i += 4) {
781
634
  visible = data[i] >= cutoff;
782
635
  }
783
636
  if (visible) {
@@ -786,35 +639,24 @@ var checkNotEmpty = function checkNotEmpty(palette, image, cutoff) {
786
639
  };
787
640
 
788
641
  // The space to match pixels to a palette in: the one the caller names, else the one a Palette was made in, else RGB.
789
- var matchingSpace = function matchingSpace(o, palette) {
790
- return o.colorSpaceGiven ? o.colorSpace : _shared.colorSpaces[(0, _shared.isPalette)(palette) ? palette.colorSpace : 'rgb'];
791
- };
642
+ const matchingSpace = (o, palette) => o.colorSpaceGiven ? o.colorSpace : _shared.colorSpaces[(0, _shared.isPalette)(palette) ? palette.colorSpace : 'rgb'];
792
643
 
793
644
  // Copies each buffer into the WASM heap, calls `fn` with their pointers, and returns the unpacked output,
794
645
  // freeing everything afterwards.
795
- var call = function call(wasm, buffers, fn) {
796
- var pointers = [];
797
- var outputPointer = 0;
798
- var aborted = false;
646
+ const call = (wasm, buffers, fn) => {
647
+ const pointers = [];
648
+ let outputPointer = 0;
649
+ let aborted = false;
799
650
  try {
800
- var _iterator = _createForOfIteratorHelper(buffers),
801
- _step;
802
- try {
803
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
804
- var buffer = _step.value;
805
- var pointer = wasm._malloc(buffer.length);
806
- if (!pointer) {
807
- throw (0, _shared.fail)('out-of-memory', "Failed to allocate WASM memory.");
808
- }
809
- pointers.push(pointer);
810
- wasm.HEAPU8.set(buffer, pointer);
651
+ for (const buffer of buffers) {
652
+ const pointer = wasm._malloc(buffer.length);
653
+ if (!pointer) {
654
+ throw (0, _shared.fail)('out-of-memory', "Failed to allocate WASM memory.");
811
655
  }
812
- } catch (err) {
813
- _iterator.e(err);
814
- } finally {
815
- _iterator.f();
656
+ pointers.push(pointer);
657
+ wasm.HEAPU8.set(buffer, pointer);
816
658
  }
817
- outputPointer = fn.apply(void 0, pointers);
659
+ outputPointer = fn(...pointers);
818
660
  // Only the functions that read a clustering return nothing: when its records don't fit together (see
819
661
  // _get_palette_from_clustering), which a clustering whose checksum matches never does.
820
662
  if (!outputPointer) {
@@ -831,21 +673,13 @@ var call = function call(wasm, buffers, fn) {
831
673
  } finally {
832
674
  // After an abort the instance is being thrown away, and its allocator can't be trusted.
833
675
  if (!aborted) {
834
- var _iterator2 = _createForOfIteratorHelper(pointers),
835
- _step2;
836
- try {
837
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
838
- var _pointer = _step2.value;
839
- wasm._free(_pointer);
840
- }
841
- } catch (err) {
842
- _iterator2.e(err);
843
- } finally {
844
- _iterator2.f();
676
+ for (const pointer of pointers) {
677
+ wasm._free(pointer);
845
678
  }
846
679
  if (outputPointer) {
847
680
  wasm._free(outputPointer);
848
681
  }
682
+ retireIfLarge(wasm);
849
683
  }
850
684
  }
851
685
  };
@@ -856,21 +690,20 @@ var call = function call(wasm, buffers, fn) {
856
690
  // in a worker thread the cancel message is read. Without either the call runs in one go, as it always did. The
857
691
  // result is the same either way: the slices are the same steps in the same order.
858
692
 
859
- var sliceMs = 10;
693
+ const sliceMs = 10;
860
694
 
861
695
  // Gives other tasks (a cancel message, timers, painting) a turn.
862
- var yieldNow = function yieldNow() {
696
+ const yieldNow = () => {
863
697
  if (typeof setImmediate === 'function') {
864
- return new Promise(function (resolve) {
865
- return setImmediate(resolve);
866
- });
698
+ return new Promise(resolve => setImmediate(resolve));
867
699
  }
868
700
  if (typeof MessageChannel === 'function') {
869
- return new Promise(function (resolve) {
870
- var _MessageChannel = new MessageChannel(),
871
- port1 = _MessageChannel.port1,
872
- port2 = _MessageChannel.port2;
873
- port1.onmessage = function () {
701
+ return new Promise(resolve => {
702
+ const {
703
+ port1,
704
+ port2
705
+ } = new MessageChannel();
706
+ port1.onmessage = () => {
874
707
  port1.close();
875
708
  port2.close();
876
709
  resolve();
@@ -878,242 +711,129 @@ var yieldNow = function yieldNow() {
878
711
  port2.postMessage(null);
879
712
  });
880
713
  }
881
- return new Promise(function (resolve) {
882
- return setTimeout(resolve, 0);
883
- });
714
+ return new Promise(resolve => setTimeout(resolve, 0));
884
715
  };
885
716
 
886
717
  // Like fetch, an aborted call rejects with the signal's reason (an AbortError unless the caller gave another).
887
- var checkAborted = function checkAborted(signal) {
718
+ const checkAborted = signal => {
888
719
  if (signal && signal.aborted) {
889
720
  throw signal.reason !== undefined ? signal.reason : new DOMException('This operation was aborted', 'AbortError');
890
721
  }
891
722
  };
892
723
 
893
724
  // Reports progress as a fraction from 0 to 1, never going backwards and only when it changes.
894
- var reporter = function reporter(o) {
895
- var last = -1;
896
- return function (fraction) {
897
- var value = Math.min(1, Math.max(0, fraction));
725
+ const reporter = o => {
726
+ let last = -1;
727
+ return fraction => {
728
+ const value = Math.min(1, Math.max(0, fraction));
898
729
  if (o.onProgress && value > last) {
899
730
  last = value;
900
731
  o.onProgress(value);
901
732
  }
902
733
  };
903
734
  };
904
- var isControlled = function isControlled(o) {
905
- return o.signal !== undefined || o.onProgress !== undefined;
906
- };
735
+ const isControlled = o => o.signal !== undefined || o.onProgress !== undefined;
907
736
 
908
737
  // Clusters in slices and returns the clustering. `share` is the part of the whole call's progress this takes.
909
- var clusterInSlices = /*#__PURE__*/function () {
910
- var _ref6 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(wasm, image, o, report, share) {
911
- var imagePointer, job, aborted, progress, pointer, _t3;
912
- return _regenerator().w(function (_context5) {
913
- while (1) switch (_context5.n) {
914
- case 0:
915
- checkAborted(o.signal);
916
- imagePointer = wasm._malloc(image.data.length);
917
- if (imagePointer) {
918
- _context5.n = 1;
919
- break;
920
- }
921
- throw (0, _shared.fail)('out-of-memory', "Failed to allocate WASM memory.");
922
- case 1:
923
- job = 0;
924
- aborted = false;
925
- _context5.p = 2;
926
- wasm.HEAPU8.set(image.data, imagePointer);
927
- job = wasm._clustering_job_start(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent);
928
- report(0);
929
- case 3:
930
- if (!true) {
931
- _context5.n = 6;
932
- break;
933
- }
934
- progress = wasm._clustering_job_step(job, sliceMs);
935
- if (!(progress >= 1000)) {
936
- _context5.n = 4;
937
- break;
938
- }
939
- return _context5.a(3, 6);
940
- case 4:
941
- report(share * progress / 1000);
942
- _context5.n = 5;
943
- return yieldNow();
944
- case 5:
945
- checkAborted(o.signal);
946
- _context5.n = 3;
947
- break;
948
- case 6:
949
- pointer = wasm._clustering_job_result(job);
950
- _context5.p = 7;
951
- return _context5.a(2, unpack(wasm, pointer));
952
- case 8:
953
- _context5.p = 8;
954
- wasm._free(pointer);
955
- return _context5.f(8);
956
- case 9:
957
- _context5.n = 12;
958
- break;
959
- case 10:
960
- _context5.p = 10;
961
- _t3 = _context5.v;
962
- if (isAbort(_t3)) {
963
- _context5.n = 11;
964
- break;
965
- }
966
- throw _t3;
967
- case 11:
968
- aborted = true;
969
- discard(wasm);
970
- throw outOfMemory();
971
- case 12:
972
- _context5.p = 12;
973
- if (!aborted) {
974
- if (job) {
975
- wasm._clustering_job_free(job);
976
- }
977
- wasm._free(imagePointer);
978
- }
979
- return _context5.f(12);
980
- case 13:
981
- return _context5.a(2);
738
+ const clusterInSlices = async (wasm, image, o, report, share) => {
739
+ checkAborted(o.signal);
740
+ const imagePointer = wasm._malloc(image.data.length);
741
+ if (!imagePointer) {
742
+ throw (0, _shared.fail)('out-of-memory', "Failed to allocate WASM memory.");
743
+ }
744
+ let job = 0;
745
+ let aborted = false;
746
+ try {
747
+ wasm.HEAPU8.set(image.data, imagePointer);
748
+ job = wasm._clustering_job_start(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent);
749
+ report(0);
750
+ while (true) {
751
+ const progress = wasm._clustering_job_step(job, sliceMs);
752
+ if (progress >= 1000) {
753
+ break;
982
754
  }
983
- }, _callee5, null, [[7,, 8, 9], [2, 10, 12, 13]]);
984
- }));
985
- return function clusterInSlices(_x3, _x4, _x5, _x6, _x7) {
986
- return _ref6.apply(this, arguments);
987
- };
988
- }();
755
+ report(share * progress / 1000);
756
+ await yieldNow();
757
+ checkAborted(o.signal);
758
+ }
759
+ const pointer = wasm._clustering_job_result(job);
760
+ try {
761
+ return unpack(wasm, pointer);
762
+ } finally {
763
+ wasm._free(pointer);
764
+ }
765
+ } catch (error) {
766
+ if (!isAbort(error)) {
767
+ throw error;
768
+ }
769
+ aborted = true;
770
+ discard(wasm);
771
+ throw outOfMemory();
772
+ } finally {
773
+ if (!aborted) {
774
+ if (job) {
775
+ wasm._clustering_job_free(job);
776
+ }
777
+ wasm._free(imagePointer);
778
+ retireIfLarge(wasm);
779
+ }
780
+ }
781
+ };
782
+
783
+ // The functions that read a clustering take no options: a clustering already says how it was made. An options object passed
784
+ // anyway (say { colorSpace: 'oklab' }, expecting it to apply) would be silently ignored, so it is an error. undefined is fine.
785
+ const noOptions = (name, extra) => {
786
+ if (extra.some(value => value !== undefined)) {
787
+ throw (0, _shared.fail)('invalid-argument', `Invalid arguments: ${name} takes no options (a clustering already records its colour space, precision and cutoff). To map pixels with other options, use quantizeFromClustering.`, 'options');
788
+ }
789
+ };
989
790
 
990
791
  // Every function checks its arguments and takes its bytes (see `held`) before it waits for anything: when the module is
991
792
  // already loaded, `Module || await acquire()` doesn't wait, and the work up to the first slice of a long clustering
992
793
  // happens before the call returns.
993
794
 
994
- var getClustering = exports.getClustering = /*#__PURE__*/function () {
995
- var _ref7 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6(image, options) {
996
- var o, wasm, report, clustering, _t4;
997
- return _regenerator().w(function (_context6) {
998
- while (1) switch (_context6.n) {
999
- case 0:
1000
- image = load(image);
1001
- o = parseOptions(options, clusterOptions, image);
1002
- _t4 = Module;
1003
- if (_t4) {
1004
- _context6.n = 2;
1005
- break;
1006
- }
1007
- _context6.n = 1;
1008
- return acquire();
1009
- case 1:
1010
- _t4 = _context6.v;
1011
- case 2:
1012
- wasm = _t4;
1013
- if (!isControlled(o)) {
1014
- _context6.n = 4;
1015
- break;
1016
- }
1017
- report = reporter(o);
1018
- _context6.n = 3;
1019
- return clusterInSlices(wasm, image, o, report, 1);
1020
- case 3:
1021
- clustering = _context6.v;
1022
- report(1);
1023
- return _context6.a(2, (0, _shared.markClustering)(clustering));
1024
- case 4:
1025
- return _context6.a(2, (0, _shared.markClustering)(call(wasm, [image.data], function (imagePointer) {
1026
- return wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent);
1027
- })));
1028
- }
1029
- }, _callee6);
1030
- }));
1031
- return function getClustering(_x8, _x9) {
1032
- return _ref7.apply(this, arguments);
1033
- };
1034
- }();
1035
- var getPalette = exports.getPalette = /*#__PURE__*/function () {
1036
- var _ref8 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7(image, k, options) {
1037
- var o, wasm, report, clustering, palette, _t5;
1038
- return _regenerator().w(function (_context7) {
1039
- while (1) switch (_context7.n) {
1040
- case 0:
1041
- image = load(image);
1042
- k = check(k);
1043
- o = parseOptions(options, clusterOptions, image);
1044
- _t5 = Module;
1045
- if (_t5) {
1046
- _context7.n = 2;
1047
- break;
1048
- }
1049
- _context7.n = 1;
1050
- return acquire();
1051
- case 1:
1052
- _t5 = _context7.v;
1053
- case 2:
1054
- wasm = _t5;
1055
- if (!isControlled(o)) {
1056
- _context7.n = 4;
1057
- break;
1058
- }
1059
- report = reporter(o);
1060
- _context7.n = 3;
1061
- return clusterInSlices(wasm, image, o, report, 0.99);
1062
- case 3:
1063
- clustering = _context7.v;
1064
- checkAborted(o.signal);
1065
- palette = call(wasm, [clustering], function (clusteringPointer) {
1066
- return wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k);
1067
- });
1068
- report(1);
1069
- return _context7.a(2, (0, _shared.markPalette)(palette, (0, _shared.colorSpaceName)(o.colorSpace)));
1070
- case 4:
1071
- return _context7.a(2, (0, _shared.markPalette)(call(wasm, [image.data], function (imagePointer) {
1072
- return wasm._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.transparent);
1073
- }), (0, _shared.colorSpaceName)(o.colorSpace)));
1074
- }
1075
- }, _callee7);
1076
- }));
1077
- return function getPalette(_x0, _x1, _x10) {
1078
- return _ref8.apply(this, arguments);
1079
- };
1080
- }();
1081
- var getPaletteFromClustering = exports.getPaletteFromClustering = /*#__PURE__*/function () {
1082
- var _ref9 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee8(clustering, k) {
1083
- var header, wasm, _t6;
1084
- return _regenerator().w(function (_context8) {
1085
- while (1) switch (_context8.n) {
1086
- case 0:
1087
- header = (0, _shared.readHeader)(clustering);
1088
- k = check(k);
1089
- clustering = held(clustering);
1090
- _t6 = Module;
1091
- if (_t6) {
1092
- _context8.n = 2;
1093
- break;
1094
- }
1095
- _context8.n = 1;
1096
- return acquire();
1097
- case 1:
1098
- _t6 = _context8.v;
1099
- case 2:
1100
- wasm = _t6;
1101
- return _context8.a(2, (0, _shared.markPalette)(call(wasm, [clustering], function (clusteringPointer) {
1102
- return wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k);
1103
- }), (0, _shared.colorSpaceName)(header.colorSpace)));
1104
- }
1105
- }, _callee8);
1106
- }));
1107
- return function getPaletteFromClustering(_x11, _x12) {
1108
- return _ref9.apply(this, arguments);
1109
- };
1110
- }();
795
+ const getClustering = async (image, options) => {
796
+ image = load(image);
797
+ const o = parseOptions(options, clusterOptions, image);
798
+ const wasm = Module || (await acquire());
799
+ if (isControlled(o)) {
800
+ const report = reporter(o);
801
+ const clustering = await clusterInSlices(wasm, image, o, report, 1);
802
+ report(1);
803
+ return (0, _shared.markClustering)(clustering);
804
+ }
805
+ return (0, _shared.markClustering)(call(wasm, [image.data], imagePointer => wasm._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha, o.transparent)));
806
+ };
807
+ exports.getClustering = getClustering;
808
+ const getPalette = async (image, k, options) => {
809
+ image = load(image);
810
+ k = check(k);
811
+ const o = parseOptions(options, clusterOptions, image);
812
+ const wasm = Module || (await acquire());
813
+ if (isControlled(o)) {
814
+ const report = reporter(o);
815
+ const clustering = await clusterInSlices(wasm, image, o, report, 0.99);
816
+ checkAborted(o.signal);
817
+ const palette = call(wasm, [clustering], clusteringPointer => wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k));
818
+ report(1);
819
+ return (0, _shared.markPalette)(palette, (0, _shared.colorSpaceName)(o.colorSpace));
820
+ }
821
+ return (0, _shared.markPalette)(call(wasm, [image.data], imagePointer => wasm._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.transparent)), (0, _shared.colorSpaceName)(o.colorSpace));
822
+ };
823
+ exports.getPalette = getPalette;
824
+ const getPaletteFromClustering = async (clustering, k, ...extra) => {
825
+ const header = (0, _shared.readHeader)(clustering);
826
+ k = check(k);
827
+ noOptions('getPaletteFromClustering', extra);
828
+ clustering = held(clustering);
829
+ const wasm = Module || (await acquire());
830
+ return (0, _shared.markPalette)(call(wasm, [clustering], clusteringPointer => wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k)), (0, _shared.colorSpaceName)(header.colorSpace));
831
+ };
1111
832
 
1112
833
  // The weight of each colour in the k-colour cut, in pixels (opacity-weighted), read from the clustering's records.
1113
- var weightsOf = function weightsOf(wasm, clustering, header, k) {
1114
- var bytes = call(wasm, [clustering], function (clusteringPointer) {
1115
- return wasm._get_palette_weights(clusteringPointer, clustering.length, k);
1116
- });
834
+ exports.getPaletteFromClustering = getPaletteFromClustering;
835
+ const weightsOf = (wasm, clustering, header, k) => {
836
+ const bytes = call(wasm, [clustering], clusteringPointer => wasm._get_palette_weights(clusteringPointer, clustering.length, k));
1117
837
  if (header.merges > 0 && bytes.length === 0) {
1118
838
  throw (0, _shared.fail)('invalid-clustering', "Invalid clustering: its weights are inconsistent.", 'clustering');
1119
839
  }
@@ -1123,401 +843,184 @@ var weightsOf = function weightsOf(wasm, clustering, header, k) {
1123
843
  // A palette with the weight and share of the image of each of its colours, from one cut of one clustering, so the three
1124
844
  // arrays line up by construction. Weights are pixels: fully transparent pixels count 0 and partly transparent ones in
1125
845
  // proportion to their opacity, as in clustering. Shares are the weights divided by their total, so they sum to 1.
1126
- var getSwatchesFromClustering = exports.getSwatchesFromClustering = /*#__PURE__*/function () {
1127
- var _ref0 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee9(clustering, k) {
1128
- var header, wasm, palette, weights, total, _iterator3, _step3, weight, shares, i, _t7;
1129
- return _regenerator().w(function (_context9) {
1130
- while (1) switch (_context9.n) {
1131
- case 0:
1132
- header = (0, _shared.readHeader)(clustering);
1133
- k = check(k);
1134
- if (!(header.version < 3)) {
1135
- _context9.n = 1;
1136
- break;
1137
- }
1138
- throw (0, _shared.fail)('unsupported-version', "Invalid clustering: format version ".concat(header.version, " (agglomerative-clustering ").concat(header.version, ".x) has no weights. Cluster the image again."), 'clustering');
1139
- case 1:
1140
- clustering = held(clustering);
1141
- _t7 = Module;
1142
- if (_t7) {
1143
- _context9.n = 3;
1144
- break;
1145
- }
1146
- _context9.n = 2;
1147
- return acquire();
1148
- case 2:
1149
- _t7 = _context9.v;
1150
- case 3:
1151
- wasm = _t7;
1152
- palette = (0, _shared.markPalette)(call(wasm, [clustering], function (clusteringPointer) {
1153
- return wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k);
1154
- }), (0, _shared.colorSpaceName)(header.colorSpace));
1155
- weights = weightsOf(wasm, clustering, header, k);
1156
- total = 0;
1157
- _iterator3 = _createForOfIteratorHelper(weights);
1158
- try {
1159
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
1160
- weight = _step3.value;
1161
- total += weight;
1162
- }
1163
- } catch (err) {
1164
- _iterator3.e(err);
1165
- } finally {
1166
- _iterator3.f();
1167
- }
1168
- shares = new Float64Array(weights.length);
1169
- if (total > 0) {
1170
- for (i = 0; i < weights.length; i++) {
1171
- shares[i] = weights[i] / total;
1172
- }
1173
- }
1174
- return _context9.a(2, {
1175
- palette: palette,
1176
- weights: weights,
1177
- shares: shares
1178
- });
1179
- }
1180
- }, _callee9);
1181
- }));
1182
- return function getSwatchesFromClustering(_x13, _x14) {
1183
- return _ref0.apply(this, arguments);
846
+ const getSwatchesFromClustering = async (clustering, k, ...extra) => {
847
+ const header = (0, _shared.readHeader)(clustering);
848
+ k = check(k);
849
+ noOptions('getSwatchesFromClustering', extra);
850
+ if (header.version < 3) {
851
+ throw (0, _shared.fail)('unsupported-version', `Invalid clustering: format version ${header.version} (agglomerative-clustering ${header.version}.x) has no weights. Cluster the image again.`, 'clustering');
852
+ }
853
+ clustering = held(clustering);
854
+ const wasm = Module || (await acquire());
855
+ const palette = (0, _shared.markPalette)(call(wasm, [clustering], clusteringPointer => wasm._get_palette_from_clustering(clusteringPointer, clustering.length, k)), (0, _shared.colorSpaceName)(header.colorSpace));
856
+ const weights = weightsOf(wasm, clustering, header, k);
857
+ let total = 0;
858
+ for (const weight of weights) {
859
+ total += weight;
860
+ }
861
+ const shares = new Float64Array(weights.length);
862
+ if (total > 0) {
863
+ for (let i = 0; i < weights.length; i++) {
864
+ shares[i] = weights[i] / total;
865
+ }
866
+ }
867
+ return {
868
+ palette,
869
+ weights,
870
+ shares
1184
871
  };
1185
- }();
872
+ };
1186
873
 
1187
874
  // The same for an image: clusters it, then cuts, like getPalette.
1188
- var getSwatches = exports.getSwatches = /*#__PURE__*/function () {
1189
- var _ref1 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee0(image, k, options) {
1190
- var _t8, _t9, _t0;
1191
- return _regenerator().w(function (_context0) {
1192
- while (1) switch (_context0.n) {
1193
- case 0:
1194
- // Arguments are checked in the order they are given (image, then k, then options), as in every other function.
1195
- load(image);
1196
- k = check(k);
1197
- _t8 = getSwatchesFromClustering;
1198
- _context0.n = 1;
1199
- return getClustering(image, options);
1200
- case 1:
1201
- _t9 = _context0.v;
1202
- _t0 = k;
1203
- return _context0.a(2, _t8(_t9, _t0));
1204
- }
1205
- }, _callee0);
1206
- }));
1207
- return function getSwatches(_x15, _x16, _x17) {
1208
- return _ref1.apply(this, arguments);
1209
- };
1210
- }();
875
+ exports.getSwatchesFromClustering = getSwatchesFromClustering;
876
+ const getSwatches = async (image, k, options) => {
877
+ // Arguments are checked in the order they are given (image, then k, then options), as in every other function.
878
+ load(image);
879
+ k = check(k);
880
+ return getSwatchesFromClustering(await getClustering(image, options), k);
881
+ };
1211
882
 
1212
883
  // What a clustering holds, read from its header and records without the WASM module. `mse[k - 1]` is the mean
1213
884
  // squared error per channel of the k-colour clustering: each pixel's squared distance to its cluster's colour,
1214
885
  // weighted as in clustering, in 8-bit RGB values (RGB) or OKLab units (OKLab).
1215
- var getClusteringInfo = exports.getClusteringInfo = /*#__PURE__*/function () {
1216
- var _ref10 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee1(clustering) {
1217
- var header, colors, info, view, pixels, total, remaining, i, _i3, _i4;
1218
- return _regenerator().w(function (_context1) {
1219
- while (1) switch (_context1.n) {
1220
- case 0:
1221
- header = (0, _shared.readHeader)(clustering);
1222
- colors = header.merges + (clustering.length >= header.headerLength + 3 ? 1 : 0);
1223
- info = {
1224
- formatVersion: header.version,
1225
- colorSpace: (0, _shared.colorSpaceName)(header.colorSpace),
1226
- precision: header.precision,
1227
- transparent: header.transparent === 0 ? false : header.transparent,
1228
- maxColors: colors,
1229
- totalWeight: null,
1230
- mse: null,
1231
- explained: null
1232
- };
1233
- if (!(header.version < 3)) {
1234
- _context1.n = 1;
1235
- break;
1236
- }
1237
- return _context1.a(2, info);
1238
- case 1:
1239
- view = new DataView(clustering.buffer, clustering.byteOffset, clustering.byteLength);
1240
- pixels = Math.pow(2, clustering[7]) / (clustering[6] === 1 ? 255 : 1);
1241
- total = view.getUint32(8, true);
1242
- info.totalWeight = total * pixels;
1243
- info.mse = new Float64Array(colors);
1244
- info.explained = new Float64Array(colors);
1245
- // The error of the leaf clusters: what `precision` below 8 discarded by grouping colours (0 before it was recorded).
1246
- remaining = header.headerLength >= 17 ? view.getFloat32(13, true) : 0;
1247
- if (colors > 0) {
1248
- info.mse[colors - 1] = remaining / total / 3;
1249
- }
1250
- for (i = header.merges - 1; i >= 0; i--) {
1251
- remaining += view.getFloat32(header.headerLength + 3 + i * header.recordLength + 17, true);
1252
- info.mse[i] = remaining / total / 3;
1253
- }
1254
- // Errors are sums of squares, so a cost that is negative or not a number can only come from damaged bytes (a clustering
1255
- // from 3.0.0-beta.1 has no checksum to catch them first).
1256
- _i3 = 0;
1257
- case 2:
1258
- if (!(_i3 < colors)) {
1259
- _context1.n = 4;
1260
- break;
1261
- }
1262
- if (!(!(info.mse[_i3] >= 0) || !Number.isFinite(info.mse[_i3]))) {
1263
- _context1.n = 3;
1264
- break;
1265
- }
1266
- throw (0, _shared.fail)('invalid-clustering', "Invalid clustering: its recorded errors are not valid numbers, so it is damaged. Cluster the image again.", 'clustering');
1267
- case 3:
1268
- _i3++;
1269
- _context1.n = 2;
1270
- break;
1271
- case 4:
1272
- // The share of the image's variance each palette size keeps; 1 throughout for an image of one colour.
1273
- for (_i4 = 0; _i4 < colors; _i4++) {
1274
- info.explained[_i4] = info.mse[0] > 0 ? Math.max(0, Math.min(1, 1 - info.mse[_i4] / info.mse[0])) : 1;
1275
- }
1276
- return _context1.a(2, info);
1277
- }
1278
- }, _callee1);
1279
- }));
1280
- return function getClusteringInfo(_x18) {
1281
- return _ref10.apply(this, arguments);
1282
- };
1283
- }();
1284
- var quantize = exports.quantize = /*#__PURE__*/function () {
1285
- var _ref11 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee10(image, k, options) {
1286
- var wrap, o, wasm, report, clustering, mapped, _t1;
1287
- return _regenerator().w(function (_context10) {
1288
- while (1) switch (_context10.n) {
1289
- case 0:
1290
- wrap = getWrapper(image);
1291
- image = load(image);
1292
- k = check(k);
1293
- o = parseOptions(options, quantizeOptions, image);
1294
- _t1 = Module;
1295
- if (_t1) {
1296
- _context10.n = 2;
1297
- break;
1298
- }
1299
- _context10.n = 1;
1300
- return acquire();
1301
- case 1:
1302
- _t1 = _context10.v;
1303
- case 2:
1304
- wasm = _t1;
1305
- if (!isControlled(o)) {
1306
- _context10.n = 4;
1307
- break;
1308
- }
1309
- report = reporter(o);
1310
- _context10.n = 3;
1311
- return clusterInSlices(wasm, image, o, report, 0.9);
1312
- case 3:
1313
- clustering = _context10.v;
1314
- checkAborted(o.signal);
1315
- mapped = wrap(call(wasm, [image.data, clustering], function (imagePointer, clusteringPointer) {
1316
- return wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, o.colorSpace, o.dither, o.width);
1317
- }));
1318
- report(1);
1319
- return _context10.a(2, mapped);
1320
- case 4:
1321
- return _context10.a(2, wrap(call(wasm, [image.data], function (imagePointer) {
1322
- return wasm._quantize(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.width, o.transparent);
1323
- })));
1324
- }
1325
- }, _callee10);
1326
- }));
1327
- return function quantize(_x19, _x20, _x21) {
1328
- return _ref11.apply(this, arguments);
886
+ exports.getSwatches = getSwatches;
887
+ const getClusteringInfo = async (clustering, ...extra) => {
888
+ const header = (0, _shared.readHeader)(clustering);
889
+ noOptions('getClusteringInfo', extra);
890
+ const colors = header.merges + (clustering.length >= header.headerLength + 3 ? 1 : 0);
891
+ const info = {
892
+ formatVersion: header.version,
893
+ colorSpace: (0, _shared.colorSpaceName)(header.colorSpace),
894
+ precision: header.precision,
895
+ transparent: header.transparent === 0 ? false : header.transparent,
896
+ maxColors: colors,
897
+ totalWeight: null,
898
+ mse: null,
899
+ explained: null
1329
900
  };
1330
- }();
1331
- var quantizeFromClustering = exports.quantizeFromClustering = /*#__PURE__*/function () {
1332
- var _ref12 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee11(image, clustering, k, options) {
1333
- var wrap, o, wasm, colorSpace, result, _t10;
1334
- return _regenerator().w(function (_context11) {
1335
- while (1) switch (_context11.n) {
1336
- case 0:
1337
- wrap = getWrapper(image);
1338
- image = load(image);
1339
- (0, _shared.readHeader)(clustering);
1340
- k = check(k);
1341
- o = parseOptions(options, mapOptions, image);
1342
- clustering = held(clustering);
1343
- _t10 = Module;
1344
- if (_t10) {
1345
- _context11.n = 2;
1346
- break;
1347
- }
1348
- _context11.n = 1;
1349
- return acquire();
1350
- case 1:
1351
- _t10 = _context11.v;
1352
- case 2:
1353
- wasm = _t10;
1354
- checkAborted(o.signal);
1355
- colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
1356
- result = wrap(call(wasm, [image.data, clustering], function (imagePointer, clusteringPointer) {
1357
- return wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.width);
1358
- }));
1359
- return _context11.a(2, result);
1360
- }
1361
- }, _callee11);
1362
- }));
1363
- return function quantizeFromClustering(_x22, _x23, _x24, _x25) {
1364
- return _ref12.apply(this, arguments);
1365
- };
1366
- }();
1367
- var quantizeWithPalette = exports.quantizeWithPalette = /*#__PURE__*/function () {
1368
- var _ref13 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee12(image, palette, options) {
1369
- var wrap, o, space, wasm, result, _t11;
1370
- return _regenerator().w(function (_context12) {
1371
- while (1) switch (_context12.n) {
1372
- case 0:
1373
- wrap = getWrapper(image);
1374
- image = load(image);
1375
- (0, _shared.checkPalette)(palette);
1376
- o = parseOptions(options, mapOptions, image);
1377
- checkNotEmpty(palette, image, 1);
1378
- space = matchingSpace(o, palette);
1379
- palette = held(palette);
1380
- _t11 = Module;
1381
- if (_t11) {
1382
- _context12.n = 2;
1383
- break;
1384
- }
1385
- _context12.n = 1;
1386
- return acquire();
1387
- case 1:
1388
- _t11 = _context12.v;
1389
- case 2:
1390
- wasm = _t11;
1391
- checkAborted(o.signal);
1392
- result = wrap(call(wasm, [image.data, palette], function (imagePointer, palettePointer) {
1393
- return wasm._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.width);
1394
- }));
1395
- return _context12.a(2, result);
1396
- }
1397
- }, _callee12);
1398
- }));
1399
- return function quantizeWithPalette(_x26, _x27, _x28) {
1400
- return _ref13.apply(this, arguments);
1401
- };
1402
- }();
1403
- var quantizeToIndices = exports.quantizeToIndices = /*#__PURE__*/function () {
1404
- var _ref14 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee13(image, k, options) {
1405
- var original, o, wasm, report, clustering, indexed, _t12;
1406
- return _regenerator().w(function (_context13) {
1407
- while (1) switch (_context13.n) {
1408
- case 0:
1409
- original = image;
1410
- image = load(image);
1411
- k = check(k);
1412
- o = parseOptions(options, quantizeIndexOptions, image);
1413
- _t12 = Module;
1414
- if (_t12) {
1415
- _context13.n = 2;
1416
- break;
1417
- }
1418
- _context13.n = 1;
1419
- return acquire();
1420
- case 1:
1421
- _t12 = _context13.v;
1422
- case 2:
1423
- wasm = _t12;
1424
- if (!isControlled(o)) {
1425
- _context13.n = 4;
1426
- break;
1427
- }
1428
- report = reporter(o);
1429
- _context13.n = 3;
1430
- return clusterInSlices(wasm, image, o, report, 0.9);
1431
- case 3:
1432
- clustering = _context13.v;
1433
- checkAborted(o.signal);
1434
- indexed = unpackIndices(call(wasm, [image.data, clustering], function (imagePointer, clusteringPointer) {
1435
- 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);
1436
- }), original, (0, _shared.colorSpaceName)(o.colorSpace));
1437
- report(1);
1438
- return _context13.a(2, indexed);
1439
- case 4:
1440
- return _context13.a(2, unpackIndices(call(wasm, [image.data], function (imagePointer) {
1441
- return wasm._quantize_indices(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.width, o.transparent);
1442
- }), original, (0, _shared.colorSpaceName)(o.colorSpace)));
1443
- }
1444
- }, _callee13);
1445
- }));
1446
- return function quantizeToIndices(_x29, _x30, _x31) {
1447
- return _ref14.apply(this, arguments);
1448
- };
1449
- }();
1450
- var quantizeToIndicesFromClustering = exports.quantizeToIndicesFromClustering = /*#__PURE__*/function () {
1451
- var _ref15 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee14(image, clustering, k, options) {
1452
- var original, header, o, wasm, colorSpace, cutoff, result, _t13;
1453
- return _regenerator().w(function (_context14) {
1454
- while (1) switch (_context14.n) {
1455
- case 0:
1456
- original = image;
1457
- image = load(image);
1458
- header = (0, _shared.readHeader)(clustering);
1459
- k = check(k);
1460
- o = parseOptions(options, mapIndexOptions, image);
1461
- clustering = held(clustering);
1462
- _t13 = Module;
1463
- if (_t13) {
1464
- _context14.n = 2;
1465
- break;
1466
- }
1467
- _context14.n = 1;
1468
- return acquire();
1469
- case 1:
1470
- _t13 = _context14.v;
1471
- case 2:
1472
- wasm = _t13;
1473
- checkAborted(o.signal);
1474
- 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.
1475
- cutoff = o.transparentGiven ? o.transparent : header.transparent;
1476
- result = unpackIndices(call(wasm, [image.data, clustering], function (imagePointer, clusteringPointer) {
1477
- return wasm._quantize_indices_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.width, cutoff);
1478
- }), original, (0, _shared.colorSpaceName)(header.colorSpace));
1479
- return _context14.a(2, result);
1480
- }
1481
- }, _callee14);
1482
- }));
1483
- return function quantizeToIndicesFromClustering(_x32, _x33, _x34, _x35) {
1484
- return _ref15.apply(this, arguments);
1485
- };
1486
- }();
1487
- var quantizeToIndicesWithPalette = exports.quantizeToIndicesWithPalette = /*#__PURE__*/function () {
1488
- var _ref16 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee15(image, palette, options) {
1489
- var original, o, space, paletteSpace, wasm, result, _t14;
1490
- return _regenerator().w(function (_context15) {
1491
- while (1) switch (_context15.n) {
1492
- case 0:
1493
- original = image;
1494
- image = load(image);
1495
- (0, _shared.checkPalette)(palette);
1496
- o = parseOptions(options, mapIndexOptions, image);
1497
- checkNotEmpty(palette, image, o.transparent > 0 ? o.transparent : 1);
1498
- space = matchingSpace(o, palette);
1499
- paletteSpace = (0, _shared.isPalette)(palette) ? palette.colorSpace : (0, _shared.colorSpaceName)(space);
1500
- palette = held(palette);
1501
- _t14 = Module;
1502
- if (_t14) {
1503
- _context15.n = 2;
1504
- break;
1505
- }
1506
- _context15.n = 1;
1507
- return acquire();
1508
- case 1:
1509
- _t14 = _context15.v;
1510
- case 2:
1511
- wasm = _t14;
1512
- checkAborted(o.signal);
1513
- result = unpackIndices(call(wasm, [image.data, palette], function (imagePointer, palettePointer) {
1514
- return wasm._quantize_indices_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.width, o.transparent);
1515
- }), original, paletteSpace);
1516
- return _context15.a(2, result);
1517
- }
1518
- }, _callee15);
1519
- }));
1520
- return function quantizeToIndicesWithPalette(_x36, _x37, _x38) {
1521
- return _ref16.apply(this, arguments);
1522
- };
1523
- }();
901
+ if (header.version < 3) {
902
+ return info;
903
+ }
904
+ const view = new DataView(clustering.buffer, clustering.byteOffset, clustering.byteLength);
905
+ const pixels = 2 ** clustering[7] / (clustering[6] === 1 ? 255 : 1);
906
+ const total = view.getUint32(8, true);
907
+ info.totalWeight = total * pixels;
908
+ info.mse = new Float64Array(colors);
909
+ info.explained = new Float64Array(colors);
910
+ // The error of the leaf clusters: what `precision` below 8 discarded by grouping colours (0 before it was recorded).
911
+ let remaining = header.headerLength >= 17 ? view.getFloat32(13, true) : 0;
912
+ if (colors > 0) {
913
+ info.mse[colors - 1] = remaining / total / 3;
914
+ }
915
+ for (let i = header.merges - 1; i >= 0; i--) {
916
+ remaining += view.getFloat32(header.headerLength + 3 + i * header.recordLength + 17, true);
917
+ info.mse[i] = remaining / total / 3;
918
+ }
919
+ // Errors are sums of squares, so a cost that is negative or not a number can only come from damaged bytes (a clustering
920
+ // from 3.0.0-beta.1 has no checksum to catch them first).
921
+ for (let i = 0; i < colors; i++) {
922
+ if (!(info.mse[i] >= 0) || !Number.isFinite(info.mse[i])) {
923
+ throw (0, _shared.fail)('invalid-clustering', "Invalid clustering: its recorded errors are not valid numbers, so it is damaged. Cluster the image again.", 'clustering');
924
+ }
925
+ }
926
+ // The share of the image's variance each palette size keeps; 1 throughout for an image of one colour.
927
+ for (let i = 0; i < colors; i++) {
928
+ info.explained[i] = info.mse[0] > 0 ? Math.max(0, Math.min(1, 1 - info.mse[i] / info.mse[0])) : 1;
929
+ }
930
+ return info;
931
+ };
932
+ exports.getClusteringInfo = getClusteringInfo;
933
+ const quantize = async (image, k, options) => {
934
+ const wrap = getWrapper(image);
935
+ image = load(image);
936
+ k = check(k);
937
+ const o = parseOptions(options, quantizeOptions, image);
938
+ const wasm = Module || (await acquire());
939
+ if (isControlled(o)) {
940
+ const report = reporter(o);
941
+ const clustering = await clusterInSlices(wasm, image, o, report, 0.9);
942
+ checkAborted(o.signal);
943
+ const mapped = wrap(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, o.colorSpace, o.dither, o.width)));
944
+ report(1);
945
+ return mapped;
946
+ }
947
+ return wrap(call(wasm, [image.data], imagePointer => wasm._quantize(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.width, o.transparent)));
948
+ };
949
+ exports.quantize = quantize;
950
+ const quantizeFromClustering = async (image, clustering, k, options) => {
951
+ const wrap = getWrapper(image);
952
+ image = load(image);
953
+ (0, _shared.readHeader)(clustering);
954
+ k = check(k);
955
+ const o = parseOptions(options, mapOptions, image);
956
+ clustering = held(clustering);
957
+ const wasm = Module || (await acquire());
958
+ checkAborted(o.signal);
959
+ const colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
960
+ const result = wrap(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.width)));
961
+ return result;
962
+ };
963
+ exports.quantizeFromClustering = quantizeFromClustering;
964
+ const quantizeWithPalette = async (image, palette, options) => {
965
+ const wrap = getWrapper(image);
966
+ image = load(image);
967
+ (0, _shared.checkPalette)(palette);
968
+ const o = parseOptions(options, mapOptions, image);
969
+ checkNotEmpty(palette, image, 1);
970
+ const space = matchingSpace(o, palette);
971
+ palette = held(palette);
972
+ const wasm = Module || (await acquire());
973
+ checkAborted(o.signal);
974
+ const result = wrap(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.width)));
975
+ return result;
976
+ };
977
+ exports.quantizeWithPalette = quantizeWithPalette;
978
+ const quantizeToIndices = async (image, k, options) => {
979
+ const original = image;
980
+ image = load(image);
981
+ k = check(k);
982
+ const o = parseOptions(options, quantizeIndexOptions, image);
983
+ const wasm = Module || (await acquire());
984
+ if (isControlled(o)) {
985
+ const report = reporter(o);
986
+ const clustering = await clusterInSlices(wasm, image, o, report, 0.9);
987
+ checkAborted(o.signal);
988
+ const indexed = unpackIndices(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_indices_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, o.colorSpace, o.dither, o.width, o.transparent)), original, (0, _shared.colorSpaceName)(o.colorSpace));
989
+ report(1);
990
+ return indexed;
991
+ }
992
+ return unpackIndices(call(wasm, [image.data], imagePointer => wasm._quantize_indices(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.width, o.transparent)), original, (0, _shared.colorSpaceName)(o.colorSpace));
993
+ };
994
+ exports.quantizeToIndices = quantizeToIndices;
995
+ const quantizeToIndicesFromClustering = async (image, clustering, k, options) => {
996
+ const original = image;
997
+ image = load(image);
998
+ const header = (0, _shared.readHeader)(clustering);
999
+ k = check(k);
1000
+ const o = parseOptions(options, mapIndexOptions, image);
1001
+ clustering = held(clustering);
1002
+ const wasm = Module || (await acquire());
1003
+ checkAborted(o.signal);
1004
+ const colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
1005
+
1006
+ // The cutoff the clustering was made with is the default, so clustering and mapping agree unless a cutoff is named.
1007
+ const cutoff = o.transparentGiven ? o.transparent : header.transparent;
1008
+ const result = unpackIndices(call(wasm, [image.data, clustering], (imagePointer, clusteringPointer) => wasm._quantize_indices_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.width, cutoff)), original, (0, _shared.colorSpaceName)(header.colorSpace));
1009
+ return result;
1010
+ };
1011
+ exports.quantizeToIndicesFromClustering = quantizeToIndicesFromClustering;
1012
+ const quantizeToIndicesWithPalette = async (image, palette, options) => {
1013
+ const original = image;
1014
+ image = load(image);
1015
+ (0, _shared.checkPalette)(palette);
1016
+ const o = parseOptions(options, mapIndexOptions, image);
1017
+ checkNotEmpty(palette, image, o.transparent > 0 ? o.transparent : 1);
1018
+ const space = matchingSpace(o, palette);
1019
+ const paletteSpace = (0, _shared.isPalette)(palette) ? palette.colorSpace : (0, _shared.colorSpaceName)(space);
1020
+ palette = held(palette);
1021
+ const wasm = Module || (await acquire());
1022
+ checkAborted(o.signal);
1023
+ const result = unpackIndices(call(wasm, [image.data, palette], (imagePointer, palettePointer) => wasm._quantize_indices_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, space, o.dither, o.width, o.transparent)), original, paletteSpace);
1024
+ return result;
1025
+ };
1026
+ exports.quantizeToIndicesWithPalette = quantizeToIndicesWithPalette;