agglomerative-clustering 2.0.0 → 3.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -3,96 +3,604 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.quantizeWithPalette = exports.quantizeWithClustering = exports.quantize = exports.init = exports.getPaletteFromClustering = exports.getPalette = exports.getClustering = void 0;
6
+ Object.defineProperty(exports, "Clustering", {
7
+ enumerable: true,
8
+ get: function get() {
9
+ return _shared.Clustering;
10
+ }
11
+ });
12
+ Object.defineProperty(exports, "Palette", {
13
+ enumerable: true,
14
+ get: function get() {
15
+ return _shared.Palette;
16
+ }
17
+ });
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
+ Object.defineProperty(exports, "version", {
20
+ enumerable: true,
21
+ get: function get() {
22
+ return _shared.version;
23
+ }
24
+ });
7
25
  var _clustering = _interopRequireDefault(require("./clustering.js"));
26
+ var _shared = require("./shared.cjs");
8
27
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
9
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; } } }; }
10
- 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; } }
11
- function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
12
- function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
13
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 }; })(); }
14
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); }
15
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); }
16
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).
41
+ // The version of stored data (clusterings) this build writes. It reads this one and format 2 (see readHeader). Unlike
42
+ // `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;
44
+
45
+ // Checked by tag rather than `instanceof`, so values from another realm are recognised: an ImageData from an iframe's
46
+ // canvas, a WebAssembly.Module compiled by a bundler's runtime (Next.js Edge's `import wasm from '…wasm?module'`), a URL
47
+ // 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
+ };
51
+ // (`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
+ };
17
61
  var codes = {
18
62
  'rgba': 0,
19
63
  'rgb': 1
20
64
  };
21
- var colorSpaces = {
22
- 'rgb': 0,
23
- 'oklab': 1
24
- };
25
65
  var alphaModes = {
26
66
  'ignore': 0,
27
67
  'weight': 1
28
68
  };
29
69
  var Module = null;
30
- var init = exports.init = /*#__PURE__*/function () {
31
- var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
70
+
71
+ // Turns init's `wasm` option into the settings the Emscripten glue understands. The glue finds its .wasm file next to
72
+ // itself by default (`new URL('clustering.wasm', import.meta.url)`); this lets a caller say where it is, or hand over
73
+ // the bytes or an already compiled module, for CDNs, strict CSPs and runtimes (such as Cloudflare Workers) that
74
+ // cannot fetch or compile it that way. `onError` receives instantiation errors, which the glue would otherwise swallow.
75
+ var wasmSettings = function wasmSettings(wasm, onError) {
76
+ if (wasm === undefined) {
77
+ return {};
78
+ }
79
+ if (typeof wasm === 'string' || isURL(wasm)) {
80
+ var location = String(wasm);
81
+ return {
82
+ locateFile: function locateFile(path, directory) {
83
+ return path.endsWith('.wasm') ? location : directory + path;
84
+ }
85
+ };
86
+ }
87
+ // Bytes and compiled modules go through `instantiateWasm`: this build of the glue reads no `wasmBinary` setting. The glue
88
+ // sets itself up on the instance inside `receive`, which throws for a module that isn't this one (it has other exports);
89
+ // 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
+ };
100
+ };
101
+ if ((0, _shared.isArrayBufferLike)(wasm) || ArrayBuffer.isView(wasm)) {
102
+ var source = (0, _shared.isArrayBufferLike)(wasm) ? wasm : new Uint8Array(wasm.buffer, wasm.byteOffset, wasm.byteLength);
103
+ 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);
109
+ }
110
+ };
111
+ }
112
+ if (isWasmModule(wasm)) {
113
+ return {
114
+ instantiateWasm: function instantiateWasm(imports, receive) {
115
+ WebAssembly.instantiate(wasm, imports).then(accept(receive), onError);
116
+ }
117
+ };
118
+ }
119
+ throw (0, _shared.fail)('invalid-argument', "Invalid wasm: must be a URL or path string, a URL, an ArrayBuffer or typed array of the .wasm bytes, or a WebAssembly.Module.", 'options.wasm');
120
+ };
121
+
122
+ // A module that cannot be loaded is the commonest first-run failure: a 404, a Content-Security-Policy that blocks it, a
123
+ // bundler that moved the file, an engine without WebAssembly SIMD. The engine's own error (a CompileError, a failed fetch)
124
+ // says little about which, so the message leads with what happened and then gives the likely fix for where it ran.
125
+ // 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() {
128
+ try {
129
+ return (typeof WebAssembly === "undefined" ? "undefined" : _typeof(WebAssembly)) === 'object' && WebAssembly.validate(new Uint8Array(simdProbe));
130
+ } catch (error) {
131
+ return false;
132
+ }
133
+ };
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];
137
+ // Emscripten appends advice about its own debug build, which doesn't apply to this package's users.
138
+ // 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);
141
+ if (aborted) {
142
+ reason = aborted[1].replace(/\.+$/, '');
143
+ }
144
+ var advice;
145
+ if (!hasSimd()) {
146
+ 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
+ } else if (given) {
148
+ advice = "Check what init({ wasm }) was given: it must be this package's clustering.wasm (its URL or path, its bytes, or the module compiled from it).";
149
+ } else if (isNodeLike) {
150
+ advice = "If the package was bundled into a server build (Next.js and others), the bundler may have moved or renamed clustering.wasm: leave the package out of the bundle (in Next.js, serverExternalPackages: ['agglomerative-clustering']) or give the module with init({ wasm }).";
151
+ } else {
152
+ 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
+ }
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
156
+ });
157
+ };
158
+
159
+ // The .wasm and the script that drives it are built together, and the byte layouts and entry points between them are
160
+ // not a public interface. One left over from another version (a stale cache, a CDN serving an old file, an `init({ wasm })`
161
+ // pointing at the wrong one) would misbehave in ways nothing explains, so the module says which version it is and a
162
+ // mismatch is reported when it loads.
163
+ var checkWasmVersion = function checkWasmVersion(instance) {
164
+ // 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
+ // this library's at all may have none either: both are reported as a version mismatch, never as a stray TypeError.
166
+ var found = '';
167
+ try {
168
+ var pointer = instance._library_version();
169
+ var heap = instance.HEAPU8;
170
+ if (typeof pointer === 'number' && pointer > 0 && heap) {
171
+ var end = pointer;
172
+ while (heap[end] !== 0 && end - pointer < 64) {
173
+ end++;
174
+ }
175
+ found = String.fromCharCode.apply(String, _toConsumableArray(heap.subarray(pointer, end)));
176
+ }
177
+ } catch (error) {/* no version export */}
178
+ var expected = "agglomerative-clustering@".concat(_shared.version);
179
+ 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."));
182
+ }
183
+ };
184
+
185
+ // 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) {
189
+ reject = r;
190
+ });
191
+ failed["catch"](function () {});
192
+ return Promise.race([(0, _clustering["default"])(wasmSettings(wasm, reject)), failed]);
193
+ };
194
+
195
+ // The bytes of this package's clustering.wasm as Node resolves it from the working directory, for when the copy next to
196
+ // 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;
32
200
  return _regenerator().w(function (_context) {
33
201
  while (1) switch (_context.n) {
34
202
  case 0:
35
- if (Module) {
36
- _context.n = 2;
37
- break;
38
- }
39
203
  _context.n = 1;
40
- return (0, _clustering["default"])();
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(':'));
41
211
  case 1:
42
- Module = _context.v;
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(':'));
43
222
  case 2:
44
- return _context.a(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));
45
227
  }
46
228
  }, _callee);
47
229
  }));
48
- return function init() {
49
- return _ref.apply(this, arguments);
230
+ return function packagedWasm() {
231
+ return _ref2.apply(this, arguments);
232
+ };
233
+ }();
234
+
235
+ // 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;
237
+
238
+ // Calls get the instance they run on from `acquire` and keep using it, so replacing the current instance (see `discard`)
239
+ // 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);
338
+ }
339
+ }, _callee3);
340
+ }));
341
+ return function acquire(_x) {
342
+ return _ref3.apply(this, arguments);
343
+ };
344
+ }();
345
+
346
+ // Loads the WebAssembly module. Every other function does this on first use, so calling it is optional, except to
347
+ // say where the .wasm file is (`wasm`), which must come before anything else. The first load that succeeds wins:
348
+ // 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);
50
363
  };
51
364
  }();
52
- var unpack = function unpack(pointer) {
53
- var lengthBuffer = new Uint8Array(Module.HEAPU8.subarray(pointer, pointer + 4));
365
+
366
+ // A WebAssembly abort, which is what running out of memory looks like, leaves the instance's heap full of whatever the
367
+ // failed call had allocated and never freed (the abort skips destructors), so every later large call on it would fail
368
+ // 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) {
373
+ if (Module === instance) {
374
+ Module = null;
375
+ loading = null;
376
+ }
377
+ };
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.");
380
+ };
381
+ var unpack = function unpack(wasm, pointer) {
382
+ var lengthBuffer = new Uint8Array(wasm.HEAPU8.subarray(pointer, pointer + 4));
54
383
  var length = lengthBuffer[0] | lengthBuffer[1] << 8 | lengthBuffer[2] << 16 | lengthBuffer[3] << 24;
55
- var outputBuffer = new Uint8Array(Module.HEAPU8.subarray(pointer + 4, pointer + 4 + length));
384
+ var outputBuffer = new Uint8Array(wasm.HEAPU8.subarray(pointer + 4, pointer + 4 + length));
56
385
  return outputBuffer;
57
386
  };
387
+
388
+ // 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
+ };
392
+
393
+ // ----- Encoded image files -------------------------------------------------------------------------------------------
394
+ // A bare Uint8Array is taken to be raw RGBA pixels, so the commonest mistake is handing over the bytes of an image *file*
395
+ // (fs.readFile, fetch().arrayBuffer()): it passes as pixels whenever its length is a multiple of 4 and gives a palette of
396
+ // nonsense. The signatures of the common formats are recognised so that it is reported instead. Only a bare Uint8Array is
397
+ // looked at: an ImageData or a { data, format } object has said what its bytes are, so it is never second-guessed, and a
398
+ // bare array that really is raw pixels can be passed as { data, format: 'rgba' } to say so.
399
+ //
400
+ // This is also where decoding would go. The library doesn't decode files today (that needs a decoder per format, and
401
+ // sharp, pngjs, createImageBitmap and the like already do it); when it does, a file recognised here is decoded into
402
+ // { 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++) {
405
+ if (bytes[at + i] !== text.charCodeAt(i)) {
406
+ return false;
407
+ }
408
+ }
409
+ return true;
410
+ };
411
+
412
+ // The name of the encoded image format `bytes` starts with, or null. Signatures are long enough, or have enough structure
413
+ // beyond the first few bytes, that raw pixels all but never match.
414
+ var sniffImageFormat = function sniffImageFormat(bytes) {
415
+ var length = bytes.length;
416
+ if (length >= 8 && bytes[0] === 0x89 && ascii(bytes, 1, 'PNG') && bytes[4] === 0x0D && bytes[5] === 0x0A && bytes[6] === 0x1A && bytes[7] === 0x0A) {
417
+ return 'PNG';
418
+ }
419
+ // JPEG: FF D8, then a first segment: a marker that has a length (not a restart or a stuffed byte) and a length that fits
420
+ if (length >= 6 && bytes[0] === 0xFF && bytes[1] === 0xD8 && bytes[2] === 0xFF && bytes[3] >= 0xC0 && bytes[3] <= 0xFE && !(bytes[3] >= 0xD0 && bytes[3] <= 0xD9) && (bytes[4] << 8 | bytes[5]) >= 2 && 4 + (bytes[4] << 8 | bytes[5]) <= length) {
421
+ return 'JPEG';
422
+ }
423
+ if (length >= 6 && (ascii(bytes, 0, 'GIF87a') || ascii(bytes, 0, 'GIF89a'))) {
424
+ return 'GIF';
425
+ }
426
+ if (length >= 12 && ascii(bytes, 0, 'RIFF') && ascii(bytes, 8, 'WEBP')) {
427
+ return 'WebP';
428
+ }
429
+ // BMP: 'BM', then the file's own length and two zero reserved fields, and a known header size
430
+ if (length >= 18 && bytes[0] === 0x42 && bytes[1] === 0x4D && bytes[6] === 0 && bytes[7] === 0 && bytes[8] === 0 && bytes[9] === 0 && (bytes[2] | bytes[3] << 8 | bytes[4] << 16 | bytes[5] << 24) === length && [12, 40, 52, 56, 64, 108, 124].includes(bytes[14]) && bytes[15] === 0 && bytes[16] === 0 && bytes[17] === 0) {
431
+ return 'BMP';
432
+ }
433
+ // 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
+ 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;
437
+ 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;
442
+ if (offset >= 8 && offset + 2 <= length && u16(offset) >= 1 && u16(offset) <= 4096) {
443
+ return 'TIFF';
444
+ }
445
+ }
446
+ }
447
+ // ISO base media: a 'ftyp' box, then a brand
448
+ if (length >= 12 && ascii(bytes, 4, 'ftyp')) {
449
+ if (ascii(bytes, 8, 'avif') || ascii(bytes, 8, 'avis')) {
450
+ return 'AVIF';
451
+ }
452
+ if (['heic', 'heix', 'hevc', 'hevx', 'heim', 'heis', 'mif1', 'msf1'].some(function (brand) {
453
+ return ascii(bytes, 8, brand);
454
+ })) {
455
+ return 'HEIC';
456
+ }
457
+ }
458
+ return null;
459
+ };
460
+
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
+ // 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;
497
+ if (typeof buffer.detached === 'boolean') {
498
+ return buffer.detached;
499
+ }
500
+ try {
501
+ new Uint8Array(buffer, 0, 0);
502
+ return false;
503
+ } catch (error) {
504
+ return true;
505
+ }
506
+ };
507
+
508
+ // 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
+ // or change the array as soon as the call returns. Once the module is loaded the bytes go into its memory before the
510
+ // 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
+ };
514
+
515
+ // width and height are copied to results and used for dithering, so each must make sense on its own: a whole number of
516
+ // 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) {
518
+ if (size === undefined) {
519
+ return;
520
+ }
521
+ if (!Number.isInteger(size) || size < 0) {
522
+ throw (0, _shared.fail)('invalid-argument', "Invalid ".concat(name, ": must be a whole number of pixels."), argument);
523
+ }
524
+ 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);
526
+ }
527
+ };
58
528
  var load = function load(image) {
59
- if (image instanceof Uint8Array) {
529
+ 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');
533
+ }
534
+ if (ArrayBuffer.isView(image) && isDetached(image)) {
535
+ 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
+ }
537
+ if ((0, _shared.isUint8Array)(image)) {
538
+ var encoded = sniffImageFormat(image);
539
+ 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');
541
+ }
542
+ if (image.length % 4 !== 0) {
543
+ throw (0, _shared.fail)('invalid-argument', "Invalid image data: length must be a multiple of 4 for 'rgba'.", 'image');
544
+ }
60
545
  return {
61
- data: image,
546
+ data: held(image),
62
547
  format: 'rgba'
63
548
  };
64
549
  }
65
- if (typeof ImageData !== 'undefined' && image instanceof ImageData) {
550
+ if (isImageData(image)) {
551
+ if (isDetached(image.data)) {
552
+ throw (0, _shared.fail)('invalid-argument', "Invalid image: the ImageData's pixels were transferred away (detached), for example to a worker created with transfer: true.", 'image');
553
+ }
66
554
  return {
67
- data: new Uint8Array(image.data.buffer),
555
+ data: held(bytes(image.data)),
68
556
  format: 'rgba',
69
557
  width: image.width
70
558
  };
71
559
  }
560
+ if (ArrayBuffer.isView(image)) {
561
+ 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
+ }
72
563
  if (_typeof(image) !== 'object' || !image || !image.data || !image.format) {
73
- throw new Error("Invalid image: expected object with `data` and `format`.");
564
+ throw (0, _shared.fail)('invalid-argument', "Invalid image: expected object with `data` and `format`.".concat(imageHint(image)), 'image');
565
+ }
566
+ if (!(0, _shared.isUint8Array)(image.data) && !(0, _shared.isUint8ClampedArray)(image.data)) {
567
+ throw (0, _shared.fail)('invalid-argument', "Invalid image data: must be Uint8Array or Uint8ClampedArray.", 'image');
74
568
  }
75
- if (!(image.data instanceof Uint8Array) && !(image.data instanceof Uint8ClampedArray)) {
76
- throw new Error("Invalid image data: must be Uint8Array or Uint8ClampedArray.");
569
+ if (isDetached(image.data)) {
570
+ throw (0, _shared.fail)('invalid-argument', "Invalid image data: its buffer was transferred away (detached), for example to a worker created with transfer: true, so it has no pixels left. Pass a copy if you need to keep using it.", 'image');
77
571
  }
78
572
  if (!Object.keys(codes).includes(image.format)) {
79
- throw new Error("Invalid format: must be 'rgb' or 'rgba'.");
573
+ throw (0, _shared.fail)('invalid-argument', "Invalid format: must be 'rgb' or 'rgba'.", 'image');
574
+ }
575
+ var channels = image.format === 'rgb' ? 3 : 4;
576
+ 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');
578
+ }
579
+ var pixels = image.data.length / channels;
580
+ checkSize(pixels, image.width, 'image width', 'image');
581
+ checkSize(pixels, image.height, 'image height', 'image');
582
+ 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');
80
584
  }
81
585
  return {
82
- data: image.data instanceof Uint8ClampedArray ? new Uint8Array(image.data.buffer) : image.data,
586
+ data: held(bytes(image.data)),
83
587
  format: image.format,
84
588
  width: image.width
85
589
  };
86
590
  };
87
591
  var getWrapper = function getWrapper(image) {
88
- if (typeof ImageData !== 'undefined' && image instanceof ImageData) {
592
+ if (isImageData(image)) {
593
+ // The pixels stay in the colour space they came in ('display-p3' canvases), so the result must say so.
89
594
  var width = image.width,
90
- height = image.height;
595
+ height = image.height,
596
+ colorSpace = image.colorSpace;
91
597
  return function (output) {
92
- return new ImageData(new Uint8ClampedArray(output.buffer), width, height);
598
+ return new ImageData(new Uint8ClampedArray(output.buffer), width, height, colorSpace ? {
599
+ colorSpace: colorSpace
600
+ } : undefined);
93
601
  };
94
602
  }
95
- if (!(image instanceof Uint8Array) && _typeof(image) === 'object' && image && image.data && image.format) {
603
+ if (!(0, _shared.isUint8Array)(image) && _typeof(image) === 'object' && image && image.data && image.format) {
96
604
  var format = image.format,
97
605
  _width = image.width,
98
606
  _height = image.height;
@@ -114,10 +622,48 @@ var getWrapper = function getWrapper(image) {
114
622
  return output;
115
623
  };
116
624
  };
625
+
626
+ // Decodes _quantize_indices output: [entries, transparent index, index bytes] as 32-bit little-endian values, then
627
+ // 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);
638
+ // Little-endian, like the WASM heap, which Emscripten's own typed-array views already assume of the host.
639
+ new Uint8Array(indices.buffer).set(output.subarray(start));
640
+ // `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,
646
+ indexBits: 8 * indexBytes,
647
+ transparentIndex: transparent < 0 ? null : transparent
648
+ };
649
+ if (!(0, _shared.isUint8Array)(image)) {
650
+ if (image.width !== undefined) {
651
+ result.width = image.width;
652
+ }
653
+ if (image.height !== undefined) {
654
+ result.height = image.height;
655
+ }
656
+ }
657
+ return result;
658
+ };
659
+
660
+ // Returns k, validated. Any k above the number of colours means all of them, so it is capped at the largest value
661
+ // the WASM side holds (a larger one would overflow its int).
117
662
  var check = function check(k) {
118
663
  if (typeof k !== 'number' || !Number.isInteger(k) || k <= 0) {
119
- throw new Error("Invalid k: must be a strictly positive integer.");
664
+ throw (0, _shared.fail)('invalid-argument', "Invalid k: must be a strictly positive integer.", 'k');
120
665
  }
666
+ return Math.min(k, 0x7FFFFFFF);
121
667
  };
122
668
 
123
669
  // Validates `options` against the keys a function accepts and fills in defaults:
@@ -127,88 +673,141 @@ var check = function check(k) {
127
673
  // precision: bits per channel, 1-8 (default 8, exact); lower values group similar colours before clustering
128
674
  // dither: false (default), true, or a strength in [0, 1]; error diffusion when mapping pixels
129
675
  // width: image width in pixels, needed to dither a Uint8Array or a RawImage without `width`
676
+ // signal, onProgress: an AbortSignal and a progress callback, which make the clustering run in slices (see clusterInSlices)
677
+ // 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
+ // indexed output also gives them their own entry, which counts towards k
679
+
130
680
  var parseOptions = function parseOptions(options, allowed, image) {
131
681
  if (options === undefined) {
132
682
  options = {};
133
683
  }
134
- if (options === null || _typeof(options) !== 'object' || Array.isArray(options)) {
135
- throw new Error("Invalid options: expected an object.");
684
+ if (!(0, _shared.isOptionsObject)(options)) {
685
+ throw (0, _shared.fail)('invalid-argument', "Invalid options: expected an object.", 'options');
136
686
  }
137
- for (var _i = 0, _Object$keys = Object.keys(options); _i < _Object$keys.length; _i++) {
138
- var key = _Object$keys[_i];
687
+ 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];
139
690
  if (!allowed.includes(key)) {
140
- throw new Error("Invalid option '".concat(key, "': expected one of ").concat(allowed.join(', '), "."));
691
+ throw (0, _shared.fail)('invalid-argument', "Invalid option '".concat(key, "': expected one of ").concat(allowed.join(', '), "."), "options.".concat(key));
141
692
  }
142
693
  }
143
694
  var colorSpace = options.colorSpace === undefined ? 'rgb' : options.colorSpace;
144
- if (!Object.keys(colorSpaces).includes(colorSpace)) {
145
- throw new Error("Invalid colorSpace: must be 'rgb' or 'oklab'.");
695
+ if (!Object.keys(_shared.colorSpaces).includes(colorSpace)) {
696
+ throw (0, _shared.fail)('invalid-argument', "Invalid colorSpace: must be 'rgb' or 'oklab'.", 'options.colorSpace');
146
697
  }
147
698
  var alpha = options.alpha === undefined ? 'weight' : options.alpha;
148
699
  if (!Object.keys(alphaModes).includes(alpha)) {
149
- throw new Error("Invalid alpha: must be 'weight' or 'ignore'.");
700
+ throw (0, _shared.fail)('invalid-argument', "Invalid alpha: must be 'weight' or 'ignore'.", 'options.alpha');
150
701
  }
151
702
  var precision = options.precision === undefined ? 8 : options.precision;
152
703
  if (typeof precision !== 'number' || !Number.isInteger(precision) || precision < 1 || precision > 8) {
153
- throw new Error("Invalid precision: must be an integer from 1 to 8.");
704
+ throw (0, _shared.fail)('invalid-argument', "Invalid precision: must be an integer from 1 to 8.", 'options.precision');
154
705
  }
155
706
  var dither = options.dither === undefined || options.dither === false ? 0 : options.dither === true ? 1 : options.dither;
156
707
  if (typeof dither !== 'number' || !Number.isFinite(dither) || dither < 0 || dither > 1) {
157
- throw new Error("Invalid dither: must be a boolean or a number from 0 to 1.");
708
+ throw (0, _shared.fail)('invalid-argument', "Invalid dither: must be a boolean or a number from 0 to 1.", 'options.dither');
709
+ }
710
+
711
+ // The image's own width and options.width are two sources for one fact: they may repeat each other, but not disagree
712
+ // (a wrong row length would dither without an error, as long as it divides the pixel count).
713
+ 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');
715
+ }
716
+ if (options.width !== undefined && image) {
717
+ checkSize(image.data.length / (image.format === 'rgb' ? 3 : 4), options.width, 'width', 'options.width');
158
718
  }
159
719
  var width = options.width !== undefined ? options.width : image ? image.width : undefined;
160
720
  if (dither > 0) {
161
721
  var channels = image.format === 'rgb' ? 3 : 4;
162
722
  if (typeof width !== 'number' || !Number.isInteger(width) || width <= 0) {
163
- throw new Error("Invalid width: dithering needs the image width, as `options.width` or the image's `width`.");
723
+ throw (0, _shared.fail)('invalid-argument', "Invalid width: dithering needs the image width, as `options.width` or the image's `width`.", 'options.width');
164
724
  }
165
725
  if (image.data.length / channels % width !== 0) {
166
- throw new Error("Invalid width: the image's pixel count is not a multiple of it.");
726
+ throw (0, _shared.fail)('invalid-argument', "Invalid width: the image's pixel count is not a multiple of it.", 'options.width');
167
727
  }
168
728
  }
729
+ var signal = options.signal;
730
+ if (signal !== undefined && (signal === null || _typeof(signal) !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function')) {
731
+ throw (0, _shared.fail)('invalid-argument', "Invalid signal: must be an AbortSignal.", 'options.signal');
732
+ }
733
+ var onProgress = options.onProgress;
734
+ if (onProgress !== undefined && typeof onProgress !== 'function') {
735
+ throw (0, _shared.fail)('invalid-argument', "Invalid onProgress: must be a function.", 'options.onProgress');
736
+ }
737
+
738
+ // 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;
741
+ if (!Number.isInteger(transparent) || transparent < 0 || transparent > 255 || transparent === 0 && transparentOption !== false) {
742
+ throw (0, _shared.fail)('invalid-argument', "Invalid transparent: must be a boolean or an integer alpha cutoff from 1 to 255.", 'options.transparent');
743
+ }
744
+
745
+ // A cutoff replaces opacity weighting (pixels count whole or not at all), so naming both would leave one of them ignored.
746
+ if (transparent > 0 && options.alpha !== undefined) {
747
+ throw (0, _shared.fail)('invalid-argument', "Invalid options: `transparent` replaces `alpha` (with a cutoff, pixels count whole or not at all), so give one or the other.", 'options');
748
+ }
169
749
  return {
170
- colorSpace: colorSpaces[colorSpace],
750
+ colorSpace: _shared.colorSpaces[colorSpace],
171
751
  colorSpaceGiven: options.colorSpace !== undefined,
172
752
  alpha: alphaModes[alpha],
173
753
  precision: precision,
174
754
  dither: dither,
175
- width: dither > 0 ? width : 0
755
+ width: dither > 0 ? width : 0,
756
+ transparent: transparent,
757
+ transparentGiven: options.transparent !== undefined,
758
+ signal: signal,
759
+ onProgress: onProgress
176
760
  };
177
761
  };
178
- var clusterOptions = ['colorSpace', 'precision', 'alpha'];
179
- var quantizeOptions = ['colorSpace', 'precision', 'alpha', 'dither', 'width'];
180
- var mapOptions = ['colorSpace', 'dither', 'width'];
762
+ var controlOptions = ['signal', 'onProgress'];
763
+ var clusterOptions = ['colorSpace', 'precision', 'alpha', 'transparent'].concat(controlOptions);
764
+ var quantizeOptions = [].concat(_toConsumableArray(clusterOptions), ['dither', 'width']);
765
+ // The functions that only map pixels take just `signal`: they finish in milliseconds, so there is nothing to report progress
766
+ // 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']);
181
770
 
182
- // Clusterings are 0 or 3 bytes more than a multiple of 9 (1.x, no header), or 4 or 7 more with the 2.x header.
183
- var checkClustering = function checkClustering(clustering) {
184
- if (!(clustering instanceof Uint8Array)) {
185
- throw new Error("Invalid clustering: must be a Uint8Array from getClustering.");
771
+ // An empty palette is what getPalette gives for an image with no visible pixels, and mapping such an image with it is
772
+ // fine. Mapping visible pixels to it has no answer (they would all come out black), so that is an error. `cutoff` is the
773
+ // alpha from which an RGBA pixel needs a colour.
774
+ var checkNotEmpty = function checkNotEmpty(palette, image, cutoff) {
775
+ if (palette.length > 0) {
776
+ return;
777
+ }
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) {
781
+ visible = data[i] >= cutoff;
186
782
  }
187
- var rest = clustering.length % 9;
188
- var legacy = clustering.length === 0 || rest === 3;
189
- var current = (clustering.length === 4 || rest === 7) && clustering[0] === 0xAC && clustering[1] === 2 && clustering[2] <= 1;
190
- if (!legacy && !current) {
191
- throw new Error("Invalid clustering: not a clustering from getClustering.");
783
+ if (visible) {
784
+ throw (0, _shared.fail)('invalid-argument', "Invalid palette: it is empty, but the image has visible pixels to map to it.", 'palette');
192
785
  }
193
786
  };
194
787
 
788
+ // 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
+ };
792
+
195
793
  // Copies each buffer into the WASM heap, calls `fn` with their pointers, and returns the unpacked output,
196
794
  // freeing everything afterwards.
197
- var call = function call(buffers, fn) {
795
+ var call = function call(wasm, buffers, fn) {
198
796
  var pointers = [];
199
797
  var outputPointer = 0;
798
+ var aborted = false;
200
799
  try {
201
800
  var _iterator = _createForOfIteratorHelper(buffers),
202
801
  _step;
203
802
  try {
204
803
  for (_iterator.s(); !(_step = _iterator.n()).done;) {
205
804
  var buffer = _step.value;
206
- var pointer = Module._malloc(buffer.length);
805
+ var pointer = wasm._malloc(buffer.length);
207
806
  if (!pointer) {
208
- throw new Error("Failed to allocate WASM memory.");
807
+ throw (0, _shared.fail)('out-of-memory', "Failed to allocate WASM memory.");
209
808
  }
210
809
  pointers.push(pointer);
211
- Module.HEAPU8.set(buffer, pointer);
810
+ wasm.HEAPU8.set(buffer, pointer);
212
811
  }
213
812
  } catch (err) {
214
813
  _iterator.e(err);
@@ -216,147 +815,709 @@ var call = function call(buffers, fn) {
216
815
  _iterator.f();
217
816
  }
218
817
  outputPointer = fn.apply(void 0, pointers);
219
- return unpack(outputPointer);
220
- } finally {
221
- for (var _i2 = 0, _pointers = pointers; _i2 < _pointers.length; _i2++) {
222
- var _pointer = _pointers[_i2];
223
- Module._free(_pointer);
818
+ // Only the functions that read a clustering return nothing: when its records don't fit together (see
819
+ // _get_palette_from_clustering), which a clustering whose checksum matches never does.
820
+ if (!outputPointer) {
821
+ throw (0, _shared.fail)('invalid-clustering', "Invalid clustering: its records don't fit together, so it is damaged or isn't a clustering. Cluster the image again.", 'clustering');
822
+ }
823
+ return unpack(wasm, outputPointer);
824
+ } catch (error) {
825
+ if (!isAbort(error)) {
826
+ throw error;
224
827
  }
225
- if (outputPointer) {
226
- Module._free(outputPointer);
828
+ aborted = true;
829
+ discard(wasm);
830
+ throw outOfMemory();
831
+ } finally {
832
+ // After an abort the instance is being thrown away, and its allocator can't be trusted.
833
+ 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();
845
+ }
846
+ if (outputPointer) {
847
+ wasm._free(outputPointer);
848
+ }
227
849
  }
228
850
  }
229
851
  };
230
- var getClustering = exports.getClustering = /*#__PURE__*/function () {
231
- var _ref2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(image, options) {
232
- var o;
233
- return _regenerator().w(function (_context2) {
234
- while (1) switch (_context2.n) {
852
+
853
+ // ----- Interruptible work -------------------------------------------------------------------------------------------
854
+ // A call given a `signal` or an `onProgress` runs its clustering in slices of about `sliceMs` milliseconds, giving the
855
+ // event loop a turn between them: the signal is checked (and progress reported) each time, other tasks can run, and
856
+ // in a worker thread the cancel message is read. Without either the call runs in one go, as it always did. The
857
+ // result is the same either way: the slices are the same steps in the same order.
858
+
859
+ var sliceMs = 10;
860
+
861
+ // Gives other tasks (a cancel message, timers, painting) a turn.
862
+ var yieldNow = function yieldNow() {
863
+ if (typeof setImmediate === 'function') {
864
+ return new Promise(function (resolve) {
865
+ return setImmediate(resolve);
866
+ });
867
+ }
868
+ 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 () {
874
+ port1.close();
875
+ port2.close();
876
+ resolve();
877
+ };
878
+ port2.postMessage(null);
879
+ });
880
+ }
881
+ return new Promise(function (resolve) {
882
+ return setTimeout(resolve, 0);
883
+ });
884
+ };
885
+
886
+ // Like fetch, an aborted call rejects with the signal's reason (an AbortError unless the caller gave another).
887
+ var checkAborted = function checkAborted(signal) {
888
+ if (signal && signal.aborted) {
889
+ throw signal.reason !== undefined ? signal.reason : new DOMException('This operation was aborted', 'AbortError');
890
+ }
891
+ };
892
+
893
+ // 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));
898
+ if (o.onProgress && value > last) {
899
+ last = value;
900
+ o.onProgress(value);
901
+ }
902
+ };
903
+ };
904
+ var isControlled = function isControlled(o) {
905
+ return o.signal !== undefined || o.onProgress !== undefined;
906
+ };
907
+
908
+ // 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) {
235
914
  case 0:
236
- _context2.n = 1;
237
- return init();
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.");
238
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);
982
+ }
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
+ }();
989
+
990
+ // Every function checks its arguments and takes its bytes (see `held`) before it waits for anything: when the module is
991
+ // already loaded, `Module || await acquire()` doesn't wait, and the work up to the first slice of a long clustering
992
+ // happens before the call returns.
993
+
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:
239
1000
  image = load(image);
240
1001
  o = parseOptions(options, clusterOptions, image);
241
- return _context2.a(2, call([image.data], function (imagePointer) {
242
- return Module._get_clustering(imagePointer, image.data.length, codes[image.format], o.colorSpace, o.precision, o.alpha);
243
- }));
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
+ })));
244
1028
  }
245
- }, _callee2);
1029
+ }, _callee6);
246
1030
  }));
247
- return function getClustering(_x, _x2) {
248
- return _ref2.apply(this, arguments);
1031
+ return function getClustering(_x8, _x9) {
1032
+ return _ref7.apply(this, arguments);
249
1033
  };
250
1034
  }();
251
1035
  var getPalette = exports.getPalette = /*#__PURE__*/function () {
252
- var _ref3 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(image, k, options) {
253
- var o;
254
- return _regenerator().w(function (_context3) {
255
- while (1) switch (_context3.n) {
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) {
256
1040
  case 0:
257
- _context3.n = 1;
258
- return init();
259
- case 1:
260
1041
  image = load(image);
261
- check(k);
1042
+ k = check(k);
262
1043
  o = parseOptions(options, clusterOptions, image);
263
- return _context3.a(2, call([image.data], function (imagePointer) {
264
- return Module._get_palette(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha);
265
- }));
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)));
266
1074
  }
267
- }, _callee3);
1075
+ }, _callee7);
268
1076
  }));
269
- return function getPalette(_x3, _x4, _x5) {
270
- return _ref3.apply(this, arguments);
1077
+ return function getPalette(_x0, _x1, _x10) {
1078
+ return _ref8.apply(this, arguments);
271
1079
  };
272
1080
  }();
273
1081
  var getPaletteFromClustering = exports.getPaletteFromClustering = /*#__PURE__*/function () {
274
- var _ref4 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(clustering, k) {
275
- return _regenerator().w(function (_context4) {
276
- while (1) switch (_context4.n) {
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) {
277
1086
  case 0:
278
- _context4.n = 1;
279
- return init();
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();
280
1097
  case 1:
281
- checkClustering(clustering);
282
- check(k);
283
- return _context4.a(2, call([clustering], function (clusteringPointer) {
284
- return Module._get_palette_from_clustering(clusteringPointer, clustering.length, k);
285
- }));
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)));
286
1104
  }
287
- }, _callee4);
1105
+ }, _callee8);
288
1106
  }));
289
- return function getPaletteFromClustering(_x6, _x7) {
290
- return _ref4.apply(this, arguments);
1107
+ return function getPaletteFromClustering(_x11, _x12) {
1108
+ return _ref9.apply(this, arguments);
291
1109
  };
292
1110
  }();
293
- var quantize = exports.quantize = /*#__PURE__*/function () {
294
- var _ref5 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(image, k, options) {
295
- var wrap, o;
296
- return _regenerator().w(function (_context5) {
297
- while (1) switch (_context5.n) {
1111
+
1112
+ // 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
+ });
1117
+ if (header.merges > 0 && bytes.length === 0) {
1118
+ throw (0, _shared.fail)('invalid-clustering', "Invalid clustering: its weights are inconsistent.", 'clustering');
1119
+ }
1120
+ return new Float64Array(bytes.buffer, bytes.byteOffset, bytes.length / 8);
1121
+ };
1122
+
1123
+ // 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
+ // arrays line up by construction. Weights are pixels: fully transparent pixels count 0 and partly transparent ones in
1125
+ // 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);
1184
+ };
1185
+ }();
1186
+
1187
+ // 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
+ }();
1211
+
1212
+ // What a clustering holds, read from its header and records without the WASM module. `mse[k - 1]` is the mean
1213
+ // squared error per channel of the k-colour clustering: each pixel's squared distance to its cluster's colour,
1214
+ // 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) {
298
1220
  case 0:
299
- _context5.n = 1;
300
- return init();
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);
301
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:
302
1290
  wrap = getWrapper(image);
303
1291
  image = load(image);
304
- check(k);
1292
+ k = check(k);
305
1293
  o = parseOptions(options, quantizeOptions, image);
306
- return _context5.a(2, wrap(call([image.data], function (imagePointer) {
307
- return Module._quantize(imagePointer, image.data.length, codes[image.format], k, o.colorSpace, o.precision, o.alpha, o.dither, o.width);
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);
308
1323
  })));
309
1324
  }
310
- }, _callee5);
1325
+ }, _callee10);
311
1326
  }));
312
- return function quantize(_x8, _x9, _x0) {
313
- return _ref5.apply(this, arguments);
1327
+ return function quantize(_x19, _x20, _x21) {
1328
+ return _ref11.apply(this, arguments);
314
1329
  };
315
1330
  }();
316
- var quantizeWithClustering = exports.quantizeWithClustering = /*#__PURE__*/function () {
317
- var _ref6 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6(image, clustering, k, options) {
318
- var wrap, o, colorSpace;
319
- return _regenerator().w(function (_context6) {
320
- while (1) switch (_context6.n) {
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) {
321
1336
  case 0:
322
- _context6.n = 1;
323
- return init();
324
- case 1:
325
1337
  wrap = getWrapper(image);
326
1338
  image = load(image);
327
- checkClustering(clustering);
328
- check(k);
1339
+ (0, _shared.readHeader)(clustering);
1340
+ k = check(k);
329
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);
330
1355
  colorSpace = o.colorSpaceGiven ? o.colorSpace : -1;
331
- return _context6.a(2, wrap(call([image.data, clustering], function (imagePointer, clusteringPointer) {
332
- return Module._quantize_with_clustering(imagePointer, image.data.length, codes[image.format], clusteringPointer, clustering.length, k, colorSpace, o.dither, o.width);
333
- })));
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);
334
1360
  }
335
- }, _callee6);
1361
+ }, _callee11);
336
1362
  }));
337
- return function quantizeWithClustering(_x1, _x10, _x11, _x12) {
338
- return _ref6.apply(this, arguments);
1363
+ return function quantizeFromClustering(_x22, _x23, _x24, _x25) {
1364
+ return _ref12.apply(this, arguments);
339
1365
  };
340
1366
  }();
341
1367
  var quantizeWithPalette = exports.quantizeWithPalette = /*#__PURE__*/function () {
342
- var _ref7 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7(image, palette, options) {
343
- var wrap, o;
344
- return _regenerator().w(function (_context7) {
345
- while (1) switch (_context7.n) {
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) {
346
1372
  case 0:
347
- _context7.n = 1;
348
- return init();
349
- case 1:
350
1373
  wrap = getWrapper(image);
351
1374
  image = load(image);
1375
+ (0, _shared.checkPalette)(palette);
352
1376
  o = parseOptions(options, mapOptions, image);
353
- return _context7.a(2, wrap(call([image.data, palette], function (imagePointer, palettePointer) {
354
- return Module._quantize_with_palette(imagePointer, image.data.length, codes[image.format], palettePointer, palette.length, o.colorSpace, o.dither, o.width);
355
- })));
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);
356
1396
  }
357
- }, _callee7);
1397
+ }, _callee12);
358
1398
  }));
359
- return function quantizeWithPalette(_x13, _x14, _x15) {
360
- return _ref7.apply(this, arguments);
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);
361
1522
  };
362
1523
  }();