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

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