agglomerative-clustering 3.0.0-beta.2 → 3.0.0-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +101 -17
- package/dist/clustering.js +1 -1
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +537 -1034
- package/dist/index.d.cts +3 -2
- package/dist/index.d.ts +3 -2
- package/dist/index.mjs +520 -1018
- package/dist/shared.cjs +167 -152
- package/dist/shared.mjs +149 -150
- package/dist/worker-thread.mjs +115 -349
- package/dist/worker.mjs +435 -746
- package/package.json +4 -1
package/dist/worker.mjs
CHANGED
|
@@ -1,215 +1,147 @@
|
|
|
1
|
-
var _excluded = ["signal", "onProgress"];
|
|
2
|
-
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
|
|
3
|
-
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."); }
|
|
4
|
-
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
|
|
5
|
-
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
|
|
6
|
-
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
|
|
7
|
-
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
|
|
8
|
-
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
|
|
9
|
-
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
|
|
10
|
-
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
|
|
11
|
-
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
|
|
12
|
-
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
|
|
13
|
-
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; } } }; }
|
|
14
|
-
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); }
|
|
15
|
-
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 }; })(); }
|
|
16
|
-
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); }
|
|
17
|
-
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
|
|
18
|
-
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
|
|
19
|
-
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; } }
|
|
20
|
-
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; }
|
|
21
|
-
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
|
|
22
|
-
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
|
|
23
|
-
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); }
|
|
24
|
-
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); }); }; }
|
|
25
1
|
// The `agglomerative-clustering/worker` entry: the same API, run in a Web Worker (browsers) or a worker thread
|
|
26
2
|
// (Node), so clustering doesn't block the calling thread. `createWorker()` starts a worker with every function of
|
|
27
3
|
// the main entry as a method, plus `cluster`, which keeps an image and its clustering in the worker behind a
|
|
28
4
|
// handle, so re-cutting and re-mapping it copies nothing across. The functions exported directly use one shared
|
|
29
5
|
// worker, started on first use.
|
|
30
6
|
|
|
31
|
-
import { fail, isOptionsObject, snapshot, mark, revive, latestVersion } from "./shared.mjs";
|
|
7
|
+
import { fail, isOptionsObject, snapshot, mark, revive, latestVersion, imageHint } from "./shared.mjs";
|
|
32
8
|
|
|
33
9
|
// The same version, types and data-format version as the main entry (one implementation, in shared.js).
|
|
34
10
|
export { version, Palette, Clustering } from "./shared.mjs";
|
|
35
|
-
export
|
|
36
|
-
|
|
11
|
+
export const formatVersion = latestVersion;
|
|
12
|
+
|
|
13
|
+
// Node's worker_threads, where this script runs from a file in Node, Bun or Deno (from npm). A runtime that only imitates Node
|
|
14
|
+
// (Cloudflare Workers with nodejs_compat, a CDN copy in Deno) defines process.versions.node too, but isn't loaded from a file.
|
|
15
|
+
const isNode = typeof process !== 'undefined' && !!(process.versions && process.versions.node) && typeof window === 'undefined' && typeof import.meta.url === 'string' && import.meta.url.startsWith('file:');
|
|
37
16
|
|
|
38
17
|
// The worker thread's script in Node: the one next to this file, which imports the main entry (index.mjs) next to it. A
|
|
39
18
|
// server bundle (Next.js with webpack or Turbopack) copies the script elsewhere without what it imports, and may hand
|
|
40
19
|
// over its URL as another realm's URL object, which Node's Worker rejects. Then the package's own copy is used, found the
|
|
41
20
|
// way Node resolves packages from the working directory. Built from strings so Node's own URL class makes it.
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
case 5:
|
|
84
|
-
_context.n = 7;
|
|
85
|
-
break;
|
|
86
|
-
case 6:
|
|
87
|
-
_context.p = 6;
|
|
88
|
-
_t = _context.v;
|
|
89
|
-
case 7:
|
|
90
|
-
return _context.a(2, script || new URL('./worker-thread.mjs', import.meta.url));
|
|
91
|
-
}
|
|
92
|
-
}, _callee, null, [[1, 6]]);
|
|
93
|
-
}));
|
|
94
|
-
return function nodeWorkerScript() {
|
|
95
|
-
return _ref.apply(this, arguments);
|
|
96
|
-
};
|
|
97
|
-
}();
|
|
21
|
+
const nodeWorkerScript = async () => {
|
|
22
|
+
const load = name => import(/* webpackIgnore: true */ /* @vite-ignore */['node', name].join(':'));
|
|
23
|
+
// The base is a variable so bundlers don't take this Node-only URL for an asset to emit (Vite would copy the script a
|
|
24
|
+
// second time for it): they look for `new URL('…', import.meta.url)` written out, which the browser branch of `start` keeps.
|
|
25
|
+
const here = import.meta.url;
|
|
26
|
+
const file = './worker-thread.mjs';
|
|
27
|
+
let script = null;
|
|
28
|
+
try {
|
|
29
|
+
const made = new URL(file, here);
|
|
30
|
+
script = new URL(typeof made.href === 'string' ? made.href : String(made));
|
|
31
|
+
} catch (error) {/* a URL Node can't read: use the package's copy */}
|
|
32
|
+
try {
|
|
33
|
+
const [{
|
|
34
|
+
existsSync
|
|
35
|
+
}, {
|
|
36
|
+
fileURLToPath,
|
|
37
|
+
pathToFileURL
|
|
38
|
+
}] = await Promise.all([load('fs'), load('url')]);
|
|
39
|
+
if (script && script.protocol === 'file:' && existsSync(fileURLToPath(script)) && existsSync(fileURLToPath(new URL('./index.mjs', script)))) {
|
|
40
|
+
return script;
|
|
41
|
+
}
|
|
42
|
+
const {
|
|
43
|
+
createRequire
|
|
44
|
+
} = await load('module');
|
|
45
|
+
const packaged = new URL('./dist/worker-thread.mjs', pathToFileURL(createRequire(`${process.cwd()}/`).resolve('agglomerative-clustering/package.json')));
|
|
46
|
+
if (existsSync(fileURLToPath(packaged))) {
|
|
47
|
+
return packaged;
|
|
48
|
+
}
|
|
49
|
+
} catch (error) {/* not found: start the script as it is, and report what happens */}
|
|
50
|
+
return script || new URL(file, here);
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
// Whether a worker script at `url` is on another origin than the page (or worker) starting it.
|
|
54
|
+
const isCrossOrigin = url => {
|
|
55
|
+
try {
|
|
56
|
+
const here = typeof location !== 'undefined' && location.origin;
|
|
57
|
+
return Boolean(here) && here !== 'null' && (url.protocol === 'http:' || url.protocol === 'https:') && url.origin !== here;
|
|
58
|
+
} catch (error) {
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
98
62
|
|
|
99
63
|
// Starts the worker and returns {post, terminate, ref, unref}, with messages delivered to `receive`.
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
});
|
|
152
|
-
});
|
|
153
|
-
worker.on('exit', function (code) {
|
|
154
|
-
return receive({
|
|
155
|
-
failure: "The worker exited unexpectedly (code ".concat(code, ").")
|
|
156
|
-
});
|
|
157
|
-
});
|
|
158
|
-
worker.unref();
|
|
159
|
-
return _context2.a(2, {
|
|
160
|
-
post: function post(message, transfer) {
|
|
161
|
-
return worker.postMessage(message, transfer);
|
|
162
|
-
},
|
|
163
|
-
terminate: function terminate() {
|
|
164
|
-
return worker.terminate();
|
|
165
|
-
},
|
|
166
|
-
ref: function ref() {
|
|
167
|
-
return worker.ref();
|
|
168
|
-
},
|
|
169
|
-
unref: function unref() {
|
|
170
|
-
return worker.unref();
|
|
171
|
-
}
|
|
172
|
-
});
|
|
173
|
-
}
|
|
174
|
-
}, _callee2);
|
|
64
|
+
const start = async receive => {
|
|
65
|
+
if (!isNode) {
|
|
66
|
+
if (typeof Worker !== 'function') {
|
|
67
|
+
throw fail('worker-failed', "Worker failed: this runtime has no Worker (Cloudflare Workers, for one, can't start threads). Use the main entry, 'agglomerative-clustering', instead.");
|
|
68
|
+
}
|
|
69
|
+
// Where the script is when the package is used unbundled (from a CDN, say). The base is a variable so bundlers
|
|
70
|
+
// leave this one alone; they rewrite the literal `new Worker(new URL(...))` below, which must stay written out.
|
|
71
|
+
const here = import.meta.url;
|
|
72
|
+
const script = new URL('./worker-thread.mjs', here);
|
|
73
|
+
const crossOrigin = isCrossOrigin(script);
|
|
74
|
+
let worker,
|
|
75
|
+
source = null;
|
|
76
|
+
if (crossOrigin) {
|
|
77
|
+
// A page can't start a worker from another origin's script, but a worker of its own can import one: a one-line
|
|
78
|
+
// module from a blob URL, which imports the script by its full URL (CDNs send the CORS headers that needs). A
|
|
79
|
+
// Content-Security-Policy then needs `worker-src blob:`.
|
|
80
|
+
source = URL.createObjectURL(new Blob([`import ${JSON.stringify(script.href)};`], {
|
|
81
|
+
type: 'text/javascript'
|
|
82
|
+
}));
|
|
83
|
+
worker = new Worker(source, {
|
|
84
|
+
type: 'module'
|
|
85
|
+
});
|
|
86
|
+
setTimeout(() => URL.revokeObjectURL(source), 60000);
|
|
87
|
+
} else {
|
|
88
|
+
// Written out in full so bundlers (Vite, webpack 5, Parcel) find and bundle the worker script.
|
|
89
|
+
worker = new Worker(new URL('./worker-thread.mjs', import.meta.url), {
|
|
90
|
+
type: 'module'
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
worker.addEventListener('message', event => receive(event.data));
|
|
94
|
+
worker.addEventListener('error', event => receive({
|
|
95
|
+
failure: event.message || (crossOrigin ? `The worker failed to start: its script comes from another origin (${script.origin}), so it was started through a blob: URL, which also failed. Check that the server sends CORS headers and that a Content-Security-Policy allows worker-src blob:.` : 'The worker failed to start: check that its script (worker-thread) is served next to the package, or emitted by your bundler, and that a Content-Security-Policy allows it as a worker.')
|
|
96
|
+
}));
|
|
97
|
+
return {
|
|
98
|
+
post: (message, transfer) => worker.postMessage(message, transfer),
|
|
99
|
+
terminate: () => worker.terminate(),
|
|
100
|
+
ref: () => {},
|
|
101
|
+
unref: () => {}
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
// The specifier is built at run time so no bundler tries to resolve it (esbuild ignores comment hints on a literal).
|
|
105
|
+
const {
|
|
106
|
+
Worker: NodeWorker
|
|
107
|
+
} = await import(/* webpackIgnore: true */ /* @vite-ignore */['node', 'worker_threads'].join(':'));
|
|
108
|
+
// The worker script needs none of the parent's flags, and some (like --input-type) are invalid in a worker.
|
|
109
|
+
const worker = new NodeWorker(await nodeWorkerScript(), {
|
|
110
|
+
execArgv: []
|
|
111
|
+
});
|
|
112
|
+
worker.on('message', receive);
|
|
113
|
+
worker.on('error', error => receive({
|
|
114
|
+
failure: error.message
|
|
175
115
|
}));
|
|
176
|
-
|
|
177
|
-
|
|
116
|
+
worker.on('exit', code => receive({
|
|
117
|
+
failure: `The worker exited unexpectedly (code ${code}).`
|
|
118
|
+
}));
|
|
119
|
+
worker.unref();
|
|
120
|
+
return {
|
|
121
|
+
post: (message, transfer) => worker.postMessage(message, transfer),
|
|
122
|
+
terminate: () => worker.terminate(),
|
|
123
|
+
ref: () => worker.ref(),
|
|
124
|
+
unref: () => worker.unref()
|
|
178
125
|
};
|
|
179
|
-
}
|
|
126
|
+
};
|
|
180
127
|
|
|
181
128
|
// Checked by tag as well as `instanceof`, so an ImageData from another realm (an iframe's canvas) or a module compiled by a
|
|
182
129
|
// bundler's runtime is recognised (see index.js).
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
var isImageData = function isImageData(value) {
|
|
187
|
-
return _typeof(value) === 'object' && value !== null && (typeof ImageData !== 'undefined' && value instanceof ImageData || tagOf(value) === '[object ImageData]');
|
|
188
|
-
};
|
|
189
|
-
var isWasmModule = function isWasmModule(value) {
|
|
190
|
-
return _typeof(value) === 'object' && value !== null && (typeof WebAssembly !== 'undefined' && value instanceof WebAssembly.Module || tagOf(value) === '[object WebAssembly.Module]');
|
|
191
|
-
};
|
|
130
|
+
const tagOf = value => Object.prototype.toString.call(value);
|
|
131
|
+
const isImageData = value => typeof value === 'object' && value !== null && (typeof ImageData !== 'undefined' && value instanceof ImageData || tagOf(value) === '[object ImageData]');
|
|
132
|
+
const isWasmModule = value => typeof value === 'object' && value !== null && (typeof WebAssembly !== 'undefined' && value instanceof WebAssembly.Module || tagOf(value) === '[object WebAssembly.Module]');
|
|
192
133
|
|
|
193
134
|
// A copy of the bytes in an argument (a typed array, or an image's `data`), for a call made before the worker is ready to
|
|
194
135
|
// take it: the caller may change or reuse its arrays as soon as the call returns, as with the main entry. Once the worker
|
|
195
136
|
// is running, a call posts (and so copies or transfers) its arguments before it returns.
|
|
196
|
-
|
|
137
|
+
const own = value => {
|
|
197
138
|
if (ArrayBuffer.isView(value)) {
|
|
198
|
-
|
|
139
|
+
const copy = value.slice();
|
|
199
140
|
// A Palette or Clustering keeps its tags (slice gives a plain array).
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
var key = _step.value;
|
|
205
|
-
Object.defineProperty(copy, key, {
|
|
206
|
-
value: value[key]
|
|
207
|
-
});
|
|
208
|
-
}
|
|
209
|
-
} catch (err) {
|
|
210
|
-
_iterator.e(err);
|
|
211
|
-
} finally {
|
|
212
|
-
_iterator.f();
|
|
141
|
+
for (const key of Object.getOwnPropertySymbols(value)) {
|
|
142
|
+
Object.defineProperty(copy, key, {
|
|
143
|
+
value: value[key]
|
|
144
|
+
});
|
|
213
145
|
}
|
|
214
146
|
if (Object.prototype.hasOwnProperty.call(value, 'colorSpace')) {
|
|
215
147
|
Object.defineProperty(copy, 'colorSpace', {
|
|
@@ -219,9 +151,10 @@ var own = function own(value) {
|
|
|
219
151
|
return copy;
|
|
220
152
|
}
|
|
221
153
|
if (isOptionsObject(value) && ArrayBuffer.isView(value.data)) {
|
|
222
|
-
return
|
|
154
|
+
return {
|
|
155
|
+
...value,
|
|
223
156
|
data: value.data.slice()
|
|
224
|
-
}
|
|
157
|
+
};
|
|
225
158
|
}
|
|
226
159
|
return value;
|
|
227
160
|
};
|
|
@@ -229,9 +162,15 @@ var own = function own(value) {
|
|
|
229
162
|
// Images cross to the worker as plain {data, format, width?, height?} objects (ImageData can't cross into Node
|
|
230
163
|
// worker threads, and its clamped array needn't), and mapped images are rebuilt in the caller's type on return.
|
|
231
164
|
// Anything else is sent as it is, so the worker's validation gives the usual errors.
|
|
232
|
-
|
|
165
|
+
// Things that aren't pixels and can't be posted (a canvas, an image element, an ImageBitmap, a Blob) are reported here with
|
|
166
|
+
// the main entry's hint, rather than as the structured clone's own error, which says nothing about what to pass instead.
|
|
167
|
+
const notPixels = image => image !== null && typeof image === 'object' && !ArrayBuffer.isView(image) && !isImageData(image) && (typeof image.getContext === 'function' || typeof image.close === 'function' || typeof image.nodeName === 'string' || typeof image.arrayBuffer === 'function' && typeof image.type === 'string');
|
|
168
|
+
const send = image => {
|
|
169
|
+
if (notPixels(image)) {
|
|
170
|
+
throw fail('invalid-argument', `Invalid image: expected object with \`data\` and \`format\`.${imageHint(image)}`, 'image');
|
|
171
|
+
}
|
|
233
172
|
if (isImageData(image)) {
|
|
234
|
-
|
|
173
|
+
const data = image.data;
|
|
235
174
|
return {
|
|
236
175
|
data: new Uint8Array(data.buffer, data.byteOffset, data.byteLength),
|
|
237
176
|
format: 'rgba',
|
|
@@ -239,8 +178,8 @@ var send = function send(image) {
|
|
|
239
178
|
height: image.height
|
|
240
179
|
};
|
|
241
180
|
}
|
|
242
|
-
if (image &&
|
|
243
|
-
|
|
181
|
+
if (image && typeof image === 'object' && !ArrayBuffer.isView(image) && ArrayBuffer.isView(image.data)) {
|
|
182
|
+
const sent = {
|
|
244
183
|
data: image.data,
|
|
245
184
|
format: image.format
|
|
246
185
|
};
|
|
@@ -257,27 +196,25 @@ var send = function send(image) {
|
|
|
257
196
|
|
|
258
197
|
// The worker returns what the main entry gives for the image it was sent: the same type for a Uint8Array or a
|
|
259
198
|
// RawImage, and a RawImage for ImageData, which is turned back into ImageData here.
|
|
260
|
-
|
|
199
|
+
const rebuild = image => {
|
|
261
200
|
if (isImageData(image)) {
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
};
|
|
201
|
+
const {
|
|
202
|
+
width,
|
|
203
|
+
height,
|
|
204
|
+
colorSpace
|
|
205
|
+
} = image;
|
|
206
|
+
return result => new ImageData(new Uint8ClampedArray(result.data.buffer, result.data.byteOffset, result.data.byteLength), width, height, colorSpace ? {
|
|
207
|
+
colorSpace
|
|
208
|
+
} : undefined);
|
|
270
209
|
}
|
|
271
|
-
return
|
|
272
|
-
return result;
|
|
273
|
-
};
|
|
210
|
+
return result => result;
|
|
274
211
|
};
|
|
275
212
|
|
|
276
213
|
// The buffer behind an image's pixels, to transfer when the worker was created with `transfer: true`: only when the
|
|
277
214
|
// pixels are the whole of an ordinary ArrayBuffer. Transferring empties every view of the buffer, so a view into part
|
|
278
215
|
// of a larger one (a subarray, a small Node Buffer from Node's shared pool) is copied instead, as is shared memory.
|
|
279
|
-
|
|
280
|
-
|
|
216
|
+
const pixelBuffers = sent => {
|
|
217
|
+
const data = ArrayBuffer.isView(sent) ? sent : sent && ArrayBuffer.isView(sent.data) ? sent.data : null;
|
|
281
218
|
if (!data || !(data.buffer instanceof ArrayBuffer) || data.byteOffset !== 0 || data.byteLength !== data.buffer.byteLength) {
|
|
282
219
|
return [];
|
|
283
220
|
}
|
|
@@ -286,8 +223,8 @@ var pixelBuffers = function pixelBuffers(sent) {
|
|
|
286
223
|
|
|
287
224
|
// Rebuilds an error that happened in the worker: same name, message and code as the main entry gives for the same
|
|
288
225
|
// input, the stack of the call that failed (`origin`, made when the call was sent), and the worker's own stack as `cause`.
|
|
289
|
-
|
|
290
|
-
|
|
226
|
+
const remoteError = (info, origin) => {
|
|
227
|
+
const error = new Error(info.message);
|
|
291
228
|
if (info.name && info.name !== 'Error') {
|
|
292
229
|
error.name = info.name;
|
|
293
230
|
}
|
|
@@ -298,10 +235,10 @@ var remoteError = function remoteError(info, origin) {
|
|
|
298
235
|
error.argument = info.argument;
|
|
299
236
|
}
|
|
300
237
|
if (origin.stack) {
|
|
301
|
-
error.stack =
|
|
238
|
+
error.stack = `${error.name}: ${error.message}${origin.stack.slice(origin.stack.indexOf('\n'))}`;
|
|
302
239
|
}
|
|
303
240
|
if (info.stack) {
|
|
304
|
-
|
|
241
|
+
const cause = new Error(info.message);
|
|
305
242
|
cause.name = error.name;
|
|
306
243
|
cause.stack = info.stack;
|
|
307
244
|
error.cause = cause;
|
|
@@ -311,11 +248,11 @@ var remoteError = function remoteError(info, origin) {
|
|
|
311
248
|
|
|
312
249
|
// Checks the `wasm` option (see init in the main entry) and makes it fit for posting to the worker: a URL becomes its
|
|
313
250
|
// string, and bytes and compiled modules are cloned across.
|
|
314
|
-
|
|
251
|
+
const wasmOption = wasm => {
|
|
315
252
|
if (typeof wasm === 'string') {
|
|
316
253
|
return wasm;
|
|
317
254
|
}
|
|
318
|
-
if (
|
|
255
|
+
if (typeof wasm === 'object' && wasm !== null && (typeof URL !== 'undefined' && wasm instanceof URL || tagOf(wasm) === '[object URL]')) {
|
|
319
256
|
return wasm.href;
|
|
320
257
|
}
|
|
321
258
|
if (wasm instanceof ArrayBuffer || tagOf(wasm) === '[object ArrayBuffer]' || ArrayBuffer.isView(wasm)) {
|
|
@@ -328,7 +265,7 @@ var wasmOption = function wasmOption(wasm) {
|
|
|
328
265
|
};
|
|
329
266
|
|
|
330
267
|
// Options for init: only `wasm`, or none.
|
|
331
|
-
|
|
268
|
+
const initOptions = options => {
|
|
332
269
|
if (options === undefined) {
|
|
333
270
|
return undefined;
|
|
334
271
|
}
|
|
@@ -336,10 +273,9 @@ var initOptions = function initOptions(options) {
|
|
|
336
273
|
throw fail('invalid-argument', "Invalid options: expected an object.", 'options');
|
|
337
274
|
}
|
|
338
275
|
options = snapshot(options);
|
|
339
|
-
for (
|
|
340
|
-
var key = _Object$keys[_i];
|
|
276
|
+
for (const key of Object.keys(options)) {
|
|
341
277
|
if (key !== 'wasm') {
|
|
342
|
-
throw fail('invalid-argument',
|
|
278
|
+
throw fail('invalid-argument', `Invalid option '${key}': expected wasm.`, `options.${key}`);
|
|
343
279
|
}
|
|
344
280
|
}
|
|
345
281
|
return options.wasm === undefined ? {} : {
|
|
@@ -349,50 +285,51 @@ var initOptions = function initOptions(options) {
|
|
|
349
285
|
|
|
350
286
|
// A signal and a progress callback can't cross to the worker, so they stay on this side: the options are sent without
|
|
351
287
|
// them, a cancel message is sent when the signal aborts, and the worker's progress messages call the callback.
|
|
352
|
-
|
|
353
|
-
var progressAllowed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
|
|
288
|
+
const takeControls = (options, progressAllowed = true) => {
|
|
354
289
|
// Anything but an ordinary object goes on as it is, for the worker's own validation to reject. An ordinary one is copied
|
|
355
290
|
// once first: structured cloning drops inherited properties, and the copy is what gets validated and sent.
|
|
356
291
|
if (!isOptionsObject(options)) {
|
|
357
292
|
return {
|
|
358
|
-
options
|
|
293
|
+
options,
|
|
359
294
|
signal: undefined,
|
|
360
295
|
onProgress: undefined
|
|
361
296
|
};
|
|
362
297
|
}
|
|
363
298
|
options = snapshot(options);
|
|
364
|
-
|
|
365
|
-
signal
|
|
366
|
-
onProgress
|
|
299
|
+
const {
|
|
300
|
+
signal,
|
|
301
|
+
onProgress
|
|
302
|
+
} = options;
|
|
367
303
|
if (!progressAllowed && onProgress !== undefined) {
|
|
368
304
|
throw fail('invalid-argument', "Invalid option 'onProgress': the functions that only map pixels take just `signal`.", 'options.onProgress');
|
|
369
305
|
}
|
|
370
306
|
if (signal === undefined && onProgress === undefined) {
|
|
371
307
|
return {
|
|
372
|
-
options
|
|
373
|
-
signal
|
|
374
|
-
onProgress
|
|
308
|
+
options,
|
|
309
|
+
signal,
|
|
310
|
+
onProgress
|
|
375
311
|
};
|
|
376
312
|
}
|
|
377
|
-
if (signal !== undefined && (signal === null ||
|
|
313
|
+
if (signal !== undefined && (signal === null || typeof signal !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function')) {
|
|
378
314
|
throw fail('invalid-argument', "Invalid signal: must be an AbortSignal.", 'options.signal');
|
|
379
315
|
}
|
|
380
316
|
if (onProgress !== undefined && typeof onProgress !== 'function') {
|
|
381
317
|
throw fail('invalid-argument', "Invalid onProgress: must be a function.", 'options.onProgress');
|
|
382
318
|
}
|
|
383
|
-
|
|
384
|
-
_signal
|
|
385
|
-
_onProgress
|
|
386
|
-
rest
|
|
319
|
+
const {
|
|
320
|
+
signal: _signal,
|
|
321
|
+
onProgress: _onProgress,
|
|
322
|
+
...rest
|
|
323
|
+
} = options;
|
|
387
324
|
return {
|
|
388
325
|
options: rest,
|
|
389
|
-
signal
|
|
390
|
-
onProgress
|
|
326
|
+
signal,
|
|
327
|
+
onProgress
|
|
391
328
|
};
|
|
392
329
|
};
|
|
393
330
|
|
|
394
331
|
// Where the options sit among a function's arguments after the image (see takeControls).
|
|
395
|
-
|
|
332
|
+
const optionsPosition = {
|
|
396
333
|
getClustering: 0,
|
|
397
334
|
getPalette: 1,
|
|
398
335
|
getSwatches: 1,
|
|
@@ -405,15 +342,13 @@ var optionsPosition = {
|
|
|
405
342
|
};
|
|
406
343
|
|
|
407
344
|
// Like fetch: an aborted call rejects with the signal's reason, an AbortError unless the caller gave another.
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
var imageFunctions = ['getClustering', 'getPalette', 'getSwatches', 'quantize', 'quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndices', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
|
|
412
|
-
var mappedImageFunctions = ['quantize', 'quantizeFromClustering', 'quantizeWithPalette'];
|
|
345
|
+
const abortReason = signal => signal.reason !== undefined ? signal.reason : new DOMException('This operation was aborted', 'AbortError');
|
|
346
|
+
const imageFunctions = ['getClustering', 'getPalette', 'getSwatches', 'quantize', 'quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndices', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
|
|
347
|
+
const mappedImageFunctions = ['quantize', 'quantizeFromClustering', 'quantizeWithPalette'];
|
|
413
348
|
// These only map pixels, so they take a signal but no progress callback (see mapOptions in index.js).
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
export
|
|
349
|
+
const mappingOnlyFunctions = ['quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
|
|
350
|
+
const otherFunctions = ['getPaletteFromClustering', 'getSwatchesFromClustering', 'getClusteringInfo'];
|
|
351
|
+
export const createWorker = options => {
|
|
417
352
|
if (options === undefined) {
|
|
418
353
|
options = {};
|
|
419
354
|
}
|
|
@@ -421,40 +356,37 @@ export var createWorker = function createWorker(options) {
|
|
|
421
356
|
throw fail('invalid-argument', "Invalid options: expected an object.", 'options');
|
|
422
357
|
}
|
|
423
358
|
options = snapshot(options);
|
|
424
|
-
for (
|
|
425
|
-
var key = _Object$keys2[_i2];
|
|
359
|
+
for (const key of Object.keys(options)) {
|
|
426
360
|
if (key !== 'transfer' && key !== 'wasm') {
|
|
427
|
-
throw fail('invalid-argument',
|
|
361
|
+
throw fail('invalid-argument', `Invalid option '${key}': expected transfer, wasm.`, `options.${key}`);
|
|
428
362
|
}
|
|
429
363
|
}
|
|
430
364
|
if (options.transfer !== undefined && typeof options.transfer !== 'boolean') {
|
|
431
365
|
throw fail('invalid-argument', "Invalid transfer: must be a boolean.", 'options.transfer');
|
|
432
366
|
}
|
|
433
|
-
|
|
367
|
+
const transfer = options.transfer === true;
|
|
434
368
|
// Where the worker finds its .wasm: sent as the worker's first call, and repeated until it has succeeded.
|
|
435
|
-
|
|
436
|
-
|
|
369
|
+
const initialWasm = options.wasm === undefined ? undefined : wasmOption(options.wasm);
|
|
370
|
+
let initial = initialWasm === undefined ? null : {
|
|
437
371
|
wasm: initialWasm
|
|
438
372
|
};
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
373
|
+
let initialising = null;
|
|
374
|
+
let connection = null;
|
|
375
|
+
let starting = null;
|
|
442
376
|
// Counts the workers this instance has started, so a late message or error from one it already dropped is ignored.
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
377
|
+
let generation = 0;
|
|
378
|
+
let startingGeneration = 0;
|
|
379
|
+
let terminated = false;
|
|
380
|
+
let nextId = 1;
|
|
381
|
+
let nextHandle = 1;
|
|
382
|
+
const pending = new Map();
|
|
449
383
|
// Whether a call made now is posted before it returns (see `own`).
|
|
450
|
-
|
|
451
|
-
return connection !== null && !initial;
|
|
452
|
-
};
|
|
384
|
+
const ready = () => connection !== null && !initial;
|
|
453
385
|
// The image of a call made before the worker is ready: with `transfer: true` its buffer is moved out of the caller's
|
|
454
386
|
// hands at once (a structured clone that transfers it, so the caller's array empties now, as it would on posting),
|
|
455
387
|
// otherwise copied.
|
|
456
|
-
|
|
457
|
-
|
|
388
|
+
const take = sent => {
|
|
389
|
+
const buffers = transfer ? pixelBuffers(sent) : [];
|
|
458
390
|
if (buffers.length > 0 && typeof structuredClone === 'function') {
|
|
459
391
|
try {
|
|
460
392
|
return structuredClone(sent, {
|
|
@@ -467,17 +399,17 @@ export var createWorker = function createWorker(options) {
|
|
|
467
399
|
|
|
468
400
|
// Safety net for handles dropped without release(): when a handle is garbage-collected, the worker frees what it
|
|
469
401
|
// kept for it. Best-effort, since collection time is up to the engine; release() or `await using` is the contract.
|
|
470
|
-
|
|
402
|
+
const reclaim = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(id => {
|
|
471
403
|
if (!terminated) {
|
|
472
|
-
invoke('release', [id], [], new Error())
|
|
404
|
+
invoke('release', [id], [], new Error()).catch(() => {});
|
|
473
405
|
}
|
|
474
406
|
}) : null;
|
|
475
407
|
|
|
476
408
|
// A worker that failed (could not start, crashed or exited) is dropped: the calls waiting on it get the failure, and
|
|
477
409
|
// the next call starts a new one, which either works or fails the same clear way. Without this, later calls would be
|
|
478
410
|
// posted to a thread that will never answer and hang forever. Handles kept in the dropped worker are gone with it.
|
|
479
|
-
|
|
480
|
-
|
|
411
|
+
const lose = reason => {
|
|
412
|
+
const lost = connection;
|
|
481
413
|
generation++;
|
|
482
414
|
connection = null;
|
|
483
415
|
starting = null;
|
|
@@ -487,35 +419,26 @@ export var createWorker = function createWorker(options) {
|
|
|
487
419
|
wasm: initialWasm
|
|
488
420
|
};
|
|
489
421
|
}
|
|
490
|
-
|
|
422
|
+
const calls = [...pending.values()];
|
|
491
423
|
pending.clear();
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
|
|
496
|
-
var call = _step2.value;
|
|
497
|
-
call.cleanup();
|
|
498
|
-
call.reject(fail('worker-failed', reason));
|
|
499
|
-
}
|
|
500
|
-
} catch (err) {
|
|
501
|
-
_iterator2.e(err);
|
|
502
|
-
} finally {
|
|
503
|
-
_iterator2.f();
|
|
424
|
+
for (const call of calls) {
|
|
425
|
+
call.cleanup();
|
|
426
|
+
call.reject(fail('worker-failed', reason));
|
|
504
427
|
}
|
|
505
428
|
if (lost) {
|
|
506
429
|
try {
|
|
507
|
-
Promise.resolve(lost.terminate())
|
|
430
|
+
Promise.resolve(lost.terminate()).catch(() => {});
|
|
508
431
|
} catch (ignored) {/* already gone */}
|
|
509
432
|
}
|
|
510
433
|
};
|
|
511
|
-
|
|
434
|
+
const receive = message => {
|
|
512
435
|
if (message.failure !== undefined) {
|
|
513
436
|
if (!terminated) {
|
|
514
|
-
lose(
|
|
437
|
+
lose(`Worker failed: ${message.failure}`);
|
|
515
438
|
}
|
|
516
439
|
return;
|
|
517
440
|
}
|
|
518
|
-
|
|
441
|
+
const call = pending.get(message.id);
|
|
519
442
|
if (!call) {
|
|
520
443
|
return;
|
|
521
444
|
}
|
|
@@ -525,7 +448,7 @@ export var createWorker = function createWorker(options) {
|
|
|
525
448
|
try {
|
|
526
449
|
call.onProgress(message.progress);
|
|
527
450
|
} catch (error) {
|
|
528
|
-
pending
|
|
451
|
+
pending.delete(message.id);
|
|
529
452
|
call.cleanup();
|
|
530
453
|
if (pending.size === 0 && connection) {
|
|
531
454
|
connection.unref();
|
|
@@ -540,7 +463,7 @@ export var createWorker = function createWorker(options) {
|
|
|
540
463
|
}
|
|
541
464
|
return;
|
|
542
465
|
}
|
|
543
|
-
pending
|
|
466
|
+
pending.delete(message.id);
|
|
544
467
|
call.cleanup();
|
|
545
468
|
if (pending.size === 0 && connection) {
|
|
546
469
|
connection.unref();
|
|
@@ -554,112 +477,78 @@ export var createWorker = function createWorker(options) {
|
|
|
554
477
|
|
|
555
478
|
// `origin` is an Error made in the caller's own (non-async) function, for the stack of a failure: async helpers
|
|
556
479
|
// from transpiled code would otherwise fill the stack's frame limit before the caller shows up.
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
case 3:
|
|
607
|
-
if (!(waitingFor !== generation)) {
|
|
608
|
-
_context3.n = 4;
|
|
609
|
-
break;
|
|
610
|
-
}
|
|
611
|
-
throw fail('worker-failed', 'Worker failed while starting.');
|
|
612
|
-
case 4:
|
|
613
|
-
connection = connection || started;
|
|
614
|
-
case 5:
|
|
615
|
-
if (!(initial && !(method === 'init' && args.length > 0 && args[0].wasm !== undefined))) {
|
|
616
|
-
_context3.n = 6;
|
|
617
|
-
break;
|
|
618
|
-
}
|
|
619
|
-
initialising = initialising || post('init', [initial], [], origin).then(function () {
|
|
620
|
-
initial = null;
|
|
621
|
-
}, function (error) {
|
|
622
|
-
initialising = null;
|
|
623
|
-
throw error;
|
|
624
|
-
});
|
|
625
|
-
_context3.n = 6;
|
|
626
|
-
return initialising;
|
|
627
|
-
case 6:
|
|
628
|
-
return _context3.a(2, post(method, args, transferable, origin, controls));
|
|
629
|
-
}
|
|
630
|
-
}, _callee3);
|
|
631
|
-
}));
|
|
632
|
-
return function invoke(_x2, _x3, _x4, _x5) {
|
|
633
|
-
return _ref3.apply(this, arguments);
|
|
634
|
-
};
|
|
635
|
-
}();
|
|
636
|
-
var post = function post(method, args, transferable, origin) {
|
|
637
|
-
var _ref4 = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {},
|
|
638
|
-
signal = _ref4.signal,
|
|
639
|
-
onProgress = _ref4.onProgress;
|
|
480
|
+
const invoke = async (method, args, transferable, origin, controls = {}) => {
|
|
481
|
+
if (terminated) {
|
|
482
|
+
throw fail('worker-terminated', "Worker terminated.");
|
|
483
|
+
}
|
|
484
|
+
if (!connection) {
|
|
485
|
+
if (!starting) {
|
|
486
|
+
const mine = ++generation;
|
|
487
|
+
startingGeneration = mine;
|
|
488
|
+
// A start that fails is not kept, so the next call tries again.
|
|
489
|
+
starting = start(message => {
|
|
490
|
+
if (mine === generation) {
|
|
491
|
+
receive(message);
|
|
492
|
+
}
|
|
493
|
+
}).catch(error => {
|
|
494
|
+
if (mine === generation) {
|
|
495
|
+
starting = null;
|
|
496
|
+
}
|
|
497
|
+
throw Object.assign(fail('worker-failed', `Worker failed: ${error && error.message}`), {
|
|
498
|
+
cause: error
|
|
499
|
+
});
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
const waitingFor = startingGeneration;
|
|
503
|
+
const started = await starting;
|
|
504
|
+
if (terminated) {
|
|
505
|
+
started.terminate();
|
|
506
|
+
throw fail('worker-terminated', "Worker terminated.");
|
|
507
|
+
}
|
|
508
|
+
// The worker may have failed in the instant between starting and being adopted; it has been dropped then.
|
|
509
|
+
if (waitingFor !== generation) {
|
|
510
|
+
throw fail('worker-failed', 'Worker failed while starting.');
|
|
511
|
+
}
|
|
512
|
+
connection = connection || started;
|
|
513
|
+
}
|
|
514
|
+
if (initial && !(method === 'init' && args.length > 0 && args[0].wasm !== undefined)) {
|
|
515
|
+
initialising = initialising || post('init', [initial], [], origin).then(() => {
|
|
516
|
+
initial = null;
|
|
517
|
+
}, error => {
|
|
518
|
+
initialising = null;
|
|
519
|
+
throw error;
|
|
520
|
+
});
|
|
521
|
+
await initialising;
|
|
522
|
+
}
|
|
523
|
+
return post(method, args, transferable, origin, controls);
|
|
524
|
+
};
|
|
525
|
+
const post = (method, args, transferable, origin, {
|
|
526
|
+
signal,
|
|
527
|
+
onProgress
|
|
528
|
+
} = {}) => {
|
|
640
529
|
if (terminated) {
|
|
641
530
|
return Promise.reject(fail('worker-terminated', "Worker terminated."));
|
|
642
531
|
}
|
|
643
532
|
if (signal && signal.aborted) {
|
|
644
533
|
return Promise.reject(abortReason(signal));
|
|
645
534
|
}
|
|
646
|
-
|
|
647
|
-
return new Promise(
|
|
535
|
+
const id = nextId++;
|
|
536
|
+
return new Promise((resolve, reject) => {
|
|
648
537
|
if (pending.size === 0) {
|
|
649
538
|
connection.ref();
|
|
650
539
|
}
|
|
651
|
-
|
|
652
|
-
resolve
|
|
653
|
-
reject
|
|
654
|
-
origin
|
|
655
|
-
onProgress
|
|
656
|
-
cleanup:
|
|
540
|
+
const call = {
|
|
541
|
+
resolve,
|
|
542
|
+
reject,
|
|
543
|
+
origin,
|
|
544
|
+
onProgress,
|
|
545
|
+
cleanup: () => {}
|
|
657
546
|
};
|
|
658
547
|
if (signal) {
|
|
659
548
|
// Rejects at once; the worker is told to stop (it may still be working on an earlier call or this one,
|
|
660
549
|
// and drops whatever it produces). The thread no longer keeps a Node process alive for this call.
|
|
661
|
-
|
|
662
|
-
if (!pending
|
|
550
|
+
const abort = () => {
|
|
551
|
+
if (!pending.delete(id)) {
|
|
663
552
|
return;
|
|
664
553
|
}
|
|
665
554
|
if (pending.size === 0) {
|
|
@@ -675,15 +564,13 @@ export var createWorker = function createWorker(options) {
|
|
|
675
564
|
signal.addEventListener('abort', abort, {
|
|
676
565
|
once: true
|
|
677
566
|
});
|
|
678
|
-
call.cleanup =
|
|
679
|
-
return signal.removeEventListener('abort', abort);
|
|
680
|
-
};
|
|
567
|
+
call.cleanup = () => signal.removeEventListener('abort', abort);
|
|
681
568
|
}
|
|
682
569
|
pending.set(id, call);
|
|
683
570
|
try {
|
|
684
|
-
|
|
685
|
-
id
|
|
686
|
-
method
|
|
571
|
+
const message = {
|
|
572
|
+
id,
|
|
573
|
+
method,
|
|
687
574
|
args: args.map(mark),
|
|
688
575
|
cancellable: signal !== undefined || onProgress !== undefined,
|
|
689
576
|
progress: onProgress !== undefined
|
|
@@ -699,400 +586,202 @@ export var createWorker = function createWorker(options) {
|
|
|
699
586
|
connection.post(message, []);
|
|
700
587
|
}
|
|
701
588
|
} catch (error) {
|
|
702
|
-
pending
|
|
589
|
+
pending.delete(id);
|
|
703
590
|
call.cleanup();
|
|
704
591
|
if (pending.size === 0) {
|
|
705
592
|
connection.unref();
|
|
706
593
|
}
|
|
707
594
|
// A value that can't be structured-cloned (a function, symbol or promise) is an invalid argument, as it
|
|
708
595
|
// would be if the main entry were called with it.
|
|
709
|
-
reject(error && error.name === 'DataCloneError' ? Object.assign(fail('invalid-argument',
|
|
596
|
+
reject(error && error.name === 'DataCloneError' ? Object.assign(fail('invalid-argument', `Invalid argument: it cannot be sent to the worker (${error.message})`), {
|
|
710
597
|
cause: error
|
|
711
598
|
}) : error);
|
|
712
599
|
}
|
|
713
600
|
});
|
|
714
601
|
};
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
_context4.n = 2;
|
|
747
|
-
return invoke(name, [sent].concat(_toConsumableArray(args)), pixelBuffers(sent), origin, {
|
|
748
|
-
signal: signal,
|
|
749
|
-
onProgress: onProgress
|
|
750
|
-
});
|
|
751
|
-
case 2:
|
|
752
|
-
result = _context4.v;
|
|
753
|
-
return _context4.a(2, mapped ? rebuild(image)(result) : result);
|
|
754
|
-
}
|
|
755
|
-
}, _callee4);
|
|
756
|
-
}))();
|
|
602
|
+
const instance = {};
|
|
603
|
+
for (const name of imageFunctions) {
|
|
604
|
+
const mapped = mappedImageFunctions.includes(name);
|
|
605
|
+
instance[name] = (image, ...rest) => {
|
|
606
|
+
const origin = new Error();
|
|
607
|
+
return (async () => {
|
|
608
|
+
const position = optionsPosition[name];
|
|
609
|
+
const {
|
|
610
|
+
options,
|
|
611
|
+
signal,
|
|
612
|
+
onProgress
|
|
613
|
+
} = takeControls(rest[position], !mappingOnlyFunctions.includes(name));
|
|
614
|
+
// Checked before the image is copied or transferred away, so an aborted call leaves it with the caller.
|
|
615
|
+
if (signal && signal.aborted) {
|
|
616
|
+
throw abortReason(signal);
|
|
617
|
+
}
|
|
618
|
+
let args = rest.slice();
|
|
619
|
+
if (position < args.length) {
|
|
620
|
+
args[position] = options;
|
|
621
|
+
}
|
|
622
|
+
let sent = send(image);
|
|
623
|
+
if (!ready()) {
|
|
624
|
+
sent = take(sent);
|
|
625
|
+
args = args.map(own);
|
|
626
|
+
}
|
|
627
|
+
const result = await invoke(name, [sent, ...args], pixelBuffers(sent), origin, {
|
|
628
|
+
signal,
|
|
629
|
+
onProgress
|
|
630
|
+
});
|
|
631
|
+
return mapped ? rebuild(image)(result) : result;
|
|
632
|
+
})();
|
|
757
633
|
};
|
|
758
|
-
};
|
|
759
|
-
for (var _i3 = 0, _imageFunctions = imageFunctions; _i3 < _imageFunctions.length; _i3++) {
|
|
760
|
-
_loop();
|
|
761
634
|
}
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
instance[name] = function () {
|
|
765
|
-
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
|
|
766
|
-
args[_key2] = arguments[_key2];
|
|
767
|
-
}
|
|
768
|
-
return invoke(name, ready() ? args : args.map(own), [], new Error());
|
|
769
|
-
};
|
|
770
|
-
};
|
|
771
|
-
for (var _i4 = 0, _otherFunctions = otherFunctions; _i4 < _otherFunctions.length; _i4++) {
|
|
772
|
-
_loop2();
|
|
635
|
+
for (const name of otherFunctions) {
|
|
636
|
+
instance[name] = (...args) => invoke(name, ready() ? args : args.map(own), [], new Error());
|
|
773
637
|
}
|
|
774
|
-
instance.init =
|
|
775
|
-
|
|
776
|
-
|
|
638
|
+
instance.init = initArgs => {
|
|
639
|
+
const origin = new Error();
|
|
640
|
+
let checked;
|
|
777
641
|
try {
|
|
778
642
|
checked = initOptions(initArgs);
|
|
779
643
|
} catch (error) {
|
|
780
644
|
return Promise.reject(error);
|
|
781
645
|
}
|
|
782
|
-
return invoke('init', checked === undefined ? [] : [checked], [], origin).then(
|
|
783
|
-
return undefined;
|
|
784
|
-
});
|
|
646
|
+
return invoke('init', checked === undefined ? [] : [checked], [], origin).then(() => undefined);
|
|
785
647
|
};
|
|
786
648
|
|
|
787
649
|
// Clusters `image` and keeps it, with its clustering, in the worker.
|
|
788
|
-
instance.cluster =
|
|
789
|
-
|
|
790
|
-
return
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
break;
|
|
813
|
-
case 4:
|
|
814
|
-
_context8.p = 4;
|
|
815
|
-
_t0 = _context8.v;
|
|
816
|
-
// A cancelled call is rejected at once, but the worker may have finished it just before it heard: it
|
|
817
|
-
// would then keep the image and clustering with nobody able to release them. Releasing an unknown handle
|
|
818
|
-
// is harmless, and this message follows the cluster call in the worker's queue.
|
|
819
|
-
if (!terminated) {
|
|
820
|
-
invoke('release', [id], [], new Error())["catch"](function () {});
|
|
821
|
-
}
|
|
822
|
-
throw _t0;
|
|
823
|
-
case 5:
|
|
824
|
-
output = rebuild(image);
|
|
825
|
-
released = false; // Every method goes through `use`, which refers to `handle`, so a method kept after the handle itself is dropped
|
|
826
|
-
// keeps it alive and it is not reclaimed while still in use.
|
|
827
|
-
use = function use(method, args, controls) {
|
|
828
|
-
if (released || !handle) {
|
|
829
|
-
return Promise.reject(fail('invalid-handle', "Invalid handle: it was released."));
|
|
830
|
-
}
|
|
831
|
-
return invoke(method, [id].concat(_toConsumableArray(args)), [], new Error(), controls);
|
|
832
|
-
}; // Calls with mapping options, whose signal and progress callback stay on this side (see takeControls).
|
|
833
|
-
withControls = function withControls(method, leading, mapOptions) {
|
|
834
|
-
var taken;
|
|
835
|
-
try {
|
|
836
|
-
taken = takeControls(mapOptions, false);
|
|
837
|
-
} catch (error) {
|
|
838
|
-
return Promise.reject(error);
|
|
839
|
-
}
|
|
840
|
-
return use(method, [].concat(_toConsumableArray(leading), [taken.options]), {
|
|
841
|
-
signal: taken.signal,
|
|
842
|
-
onProgress: taken.onProgress
|
|
843
|
-
});
|
|
844
|
-
};
|
|
845
|
-
handle = {
|
|
846
|
-
getClustering: function getClustering() {
|
|
847
|
-
return use('handleGetClustering', []);
|
|
848
|
-
},
|
|
849
|
-
getPalette: function getPalette(k) {
|
|
850
|
-
return use('handleGetPalette', [k]);
|
|
851
|
-
},
|
|
852
|
-
getSwatches: function getSwatches(k) {
|
|
853
|
-
return use('handleGetSwatches', [k]);
|
|
854
|
-
},
|
|
855
|
-
getClusteringInfo: function getClusteringInfo() {
|
|
856
|
-
return use('handleGetClusteringInfo', []);
|
|
857
|
-
},
|
|
858
|
-
quantize: function () {
|
|
859
|
-
var _quantize = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(k, mapOptions) {
|
|
860
|
-
var _t5, _t6;
|
|
861
|
-
return _regenerator().w(function (_context5) {
|
|
862
|
-
while (1) switch (_context5.n) {
|
|
863
|
-
case 0:
|
|
864
|
-
_t5 = output;
|
|
865
|
-
_context5.n = 1;
|
|
866
|
-
return withControls('handleQuantize', [k], mapOptions);
|
|
867
|
-
case 1:
|
|
868
|
-
_t6 = _context5.v;
|
|
869
|
-
return _context5.a(2, _t5(_t6));
|
|
870
|
-
}
|
|
871
|
-
}, _callee5);
|
|
872
|
-
}));
|
|
873
|
-
function quantize(_x6, _x7) {
|
|
874
|
-
return _quantize.apply(this, arguments);
|
|
875
|
-
}
|
|
876
|
-
return quantize;
|
|
877
|
-
}(),
|
|
878
|
-
quantizeToIndices: function quantizeToIndices(k, mapOptions) {
|
|
879
|
-
return withControls('handleQuantizeToIndices', [k], mapOptions);
|
|
880
|
-
},
|
|
881
|
-
quantizeWithPalette: function () {
|
|
882
|
-
var _quantizeWithPalette = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6(palette, mapOptions) {
|
|
883
|
-
var _t7, _t8;
|
|
884
|
-
return _regenerator().w(function (_context6) {
|
|
885
|
-
while (1) switch (_context6.n) {
|
|
886
|
-
case 0:
|
|
887
|
-
_t7 = output;
|
|
888
|
-
_context6.n = 1;
|
|
889
|
-
return withControls('handleQuantizeWithPalette', [palette], mapOptions);
|
|
890
|
-
case 1:
|
|
891
|
-
_t8 = _context6.v;
|
|
892
|
-
return _context6.a(2, _t7(_t8));
|
|
893
|
-
}
|
|
894
|
-
}, _callee6);
|
|
895
|
-
}));
|
|
896
|
-
function quantizeWithPalette(_x8, _x9) {
|
|
897
|
-
return _quantizeWithPalette.apply(this, arguments);
|
|
898
|
-
}
|
|
899
|
-
return quantizeWithPalette;
|
|
900
|
-
}(),
|
|
901
|
-
quantizeToIndicesWithPalette: function quantizeToIndicesWithPalette(palette, mapOptions) {
|
|
902
|
-
return withControls('handleQuantizeToIndicesWithPalette', [palette], mapOptions);
|
|
903
|
-
},
|
|
904
|
-
release: function () {
|
|
905
|
-
var _release = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7() {
|
|
906
|
-
var _t9;
|
|
907
|
-
return _regenerator().w(function (_context7) {
|
|
908
|
-
while (1) switch (_context7.n) {
|
|
909
|
-
case 0:
|
|
910
|
-
if (!released) {
|
|
911
|
-
_context7.n = 1;
|
|
912
|
-
break;
|
|
913
|
-
}
|
|
914
|
-
return _context7.a(2);
|
|
915
|
-
case 1:
|
|
916
|
-
released = true;
|
|
917
|
-
if (reclaim) {
|
|
918
|
-
reclaim.unregister(handle);
|
|
919
|
-
}
|
|
920
|
-
// If the worker has been terminated there is nothing left to free (so `await using` and
|
|
921
|
-
// terminate() can come in either order); any other failure is reported.
|
|
922
|
-
_context7.p = 2;
|
|
923
|
-
_context7.n = 3;
|
|
924
|
-
return invoke('release', [id], [], new Error());
|
|
925
|
-
case 3:
|
|
926
|
-
_context7.n = 5;
|
|
927
|
-
break;
|
|
928
|
-
case 4:
|
|
929
|
-
_context7.p = 4;
|
|
930
|
-
_t9 = _context7.v;
|
|
931
|
-
if (!(_t9.code !== 'worker-terminated')) {
|
|
932
|
-
_context7.n = 5;
|
|
933
|
-
break;
|
|
934
|
-
}
|
|
935
|
-
throw _t9;
|
|
936
|
-
case 5:
|
|
937
|
-
return _context7.a(2);
|
|
938
|
-
}
|
|
939
|
-
}, _callee7, null, [[2, 4]]);
|
|
940
|
-
}));
|
|
941
|
-
function release() {
|
|
942
|
-
return _release.apply(this, arguments);
|
|
943
|
-
}
|
|
944
|
-
return release;
|
|
945
|
-
}()
|
|
946
|
-
}; // `await using handle = await worker.cluster(image)` releases it at the end of the block.
|
|
947
|
-
if (_typeof(Symbol.asyncDispose) === 'symbol') {
|
|
948
|
-
handle[Symbol.asyncDispose] = handle.release;
|
|
949
|
-
}
|
|
950
|
-
if (reclaim) {
|
|
951
|
-
reclaim.register(handle, id, handle);
|
|
952
|
-
}
|
|
953
|
-
return _context8.a(2, handle);
|
|
650
|
+
instance.cluster = (image, clusterOptions) => {
|
|
651
|
+
const origin = new Error();
|
|
652
|
+
return (async () => {
|
|
653
|
+
const {
|
|
654
|
+
options,
|
|
655
|
+
signal,
|
|
656
|
+
onProgress
|
|
657
|
+
} = takeControls(clusterOptions);
|
|
658
|
+
if (signal && signal.aborted) {
|
|
659
|
+
throw abortReason(signal);
|
|
660
|
+
}
|
|
661
|
+
const id = nextHandle++;
|
|
662
|
+
const sent = ready() ? send(image) : take(send(image));
|
|
663
|
+
try {
|
|
664
|
+
await invoke('cluster', [id, sent, options], pixelBuffers(sent), origin, {
|
|
665
|
+
signal,
|
|
666
|
+
onProgress
|
|
667
|
+
});
|
|
668
|
+
} catch (error) {
|
|
669
|
+
// A cancelled call is rejected at once, but the worker may have finished it just before it heard: it
|
|
670
|
+
// would then keep the image and clustering with nobody able to release them. Releasing an unknown handle
|
|
671
|
+
// is harmless, and this message follows the cluster call in the worker's queue.
|
|
672
|
+
if (!terminated) {
|
|
673
|
+
invoke('release', [id], [], new Error()).catch(() => {});
|
|
954
674
|
}
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
675
|
+
throw error;
|
|
676
|
+
}
|
|
677
|
+
const output = rebuild(image);
|
|
678
|
+
let released = false;
|
|
679
|
+
// Every method goes through `use`, which refers to `handle`, so a method kept after the handle itself is dropped
|
|
680
|
+
// keeps it alive and it is not reclaimed while still in use.
|
|
681
|
+
const use = (method, args, controls) => {
|
|
682
|
+
if (released || !handle) {
|
|
683
|
+
return Promise.reject(fail('invalid-handle', "Invalid handle: it was released."));
|
|
684
|
+
}
|
|
685
|
+
return invoke(method, [id, ...args], [], new Error(), controls);
|
|
686
|
+
};
|
|
687
|
+
// Calls with mapping options, whose signal and progress callback stay on this side (see takeControls).
|
|
688
|
+
const withControls = (method, leading, mapOptions) => {
|
|
689
|
+
let taken;
|
|
690
|
+
try {
|
|
691
|
+
taken = takeControls(mapOptions, false);
|
|
692
|
+
} catch (error) {
|
|
693
|
+
return Promise.reject(error);
|
|
694
|
+
}
|
|
695
|
+
return use(method, [...leading, taken.options], {
|
|
696
|
+
signal: taken.signal,
|
|
697
|
+
onProgress: taken.onProgress
|
|
698
|
+
});
|
|
699
|
+
};
|
|
700
|
+
// The cuts take no options (the handle's clustering already says how it was made): one passed anyway is an error,
|
|
701
|
+
// as in the main entry, rather than silently ignored.
|
|
702
|
+
const plain = (method, name, args, extra) => extra.some(value => value !== undefined) ? Promise.reject(fail('invalid-argument', `Invalid arguments: handle.${name} takes no options. To map pixels with options, use handle.quantize.`, 'options')) : use(method, args);
|
|
703
|
+
const handle = {
|
|
704
|
+
getClustering: (...extra) => plain('handleGetClustering', 'getClustering', [], extra),
|
|
705
|
+
getPalette: (k, ...extra) => plain('handleGetPalette', 'getPalette', [k], extra),
|
|
706
|
+
getSwatches: (k, ...extra) => plain('handleGetSwatches', 'getSwatches', [k], extra),
|
|
707
|
+
getClusteringInfo: (...extra) => plain('handleGetClusteringInfo', 'getClusteringInfo', [], extra),
|
|
708
|
+
quantize: async (k, mapOptions) => output(await withControls('handleQuantize', [k], mapOptions)),
|
|
709
|
+
quantizeToIndices: (k, mapOptions) => withControls('handleQuantizeToIndices', [k], mapOptions),
|
|
710
|
+
quantizeWithPalette: async (palette, mapOptions) => output(await withControls('handleQuantizeWithPalette', [palette], mapOptions)),
|
|
711
|
+
quantizeToIndicesWithPalette: (palette, mapOptions) => withControls('handleQuantizeToIndicesWithPalette', [palette], mapOptions),
|
|
712
|
+
release: async () => {
|
|
713
|
+
if (released) {
|
|
714
|
+
return;
|
|
968
715
|
}
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
716
|
+
released = true;
|
|
717
|
+
if (reclaim) {
|
|
718
|
+
reclaim.unregister(handle);
|
|
719
|
+
}
|
|
720
|
+
// If the worker has been terminated there is nothing left to free (so `await using` and
|
|
721
|
+
// terminate() can come in either order); any other failure is reported.
|
|
973
722
|
try {
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
723
|
+
await invoke('release', [id], [], new Error());
|
|
724
|
+
} catch (error) {
|
|
725
|
+
if (error.code !== 'worker-terminated') {
|
|
726
|
+
throw error;
|
|
978
727
|
}
|
|
979
|
-
} catch (err) {
|
|
980
|
-
_iterator3.e(err);
|
|
981
|
-
} finally {
|
|
982
|
-
_iterator3.f();
|
|
983
|
-
}
|
|
984
|
-
pending.clear();
|
|
985
|
-
if (!connection) {
|
|
986
|
-
_context9.n = 3;
|
|
987
|
-
break;
|
|
988
728
|
}
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
case 3:
|
|
995
|
-
if (!starting) {
|
|
996
|
-
_context9.n = 7;
|
|
997
|
-
break;
|
|
998
|
-
}
|
|
999
|
-
_context9.p = 4;
|
|
1000
|
-
_context9.n = 5;
|
|
1001
|
-
return starting;
|
|
1002
|
-
case 5:
|
|
1003
|
-
_context9.v.terminate();
|
|
1004
|
-
_context9.n = 7;
|
|
1005
|
-
break;
|
|
1006
|
-
case 6:
|
|
1007
|
-
_context9.p = 6;
|
|
1008
|
-
_t1 = _context9.v;
|
|
1009
|
-
case 7:
|
|
1010
|
-
return _context9.a(2);
|
|
729
|
+
}
|
|
730
|
+
};
|
|
731
|
+
// `await using handle = await worker.cluster(image)` releases it at the end of the block.
|
|
732
|
+
if (typeof Symbol.asyncDispose === 'symbol') {
|
|
733
|
+
handle[Symbol.asyncDispose] = handle.release;
|
|
1011
734
|
}
|
|
1012
|
-
|
|
1013
|
-
|
|
735
|
+
if (reclaim) {
|
|
736
|
+
reclaim.register(handle, id, handle);
|
|
737
|
+
}
|
|
738
|
+
return handle;
|
|
739
|
+
})();
|
|
740
|
+
};
|
|
741
|
+
|
|
742
|
+
// Stops the worker. Calls still waiting are rejected, and later calls fail.
|
|
743
|
+
instance.terminate = async () => {
|
|
744
|
+
if (terminated) {
|
|
745
|
+
return;
|
|
746
|
+
}
|
|
747
|
+
terminated = true;
|
|
748
|
+
for (const call of pending.values()) {
|
|
749
|
+
call.cleanup();
|
|
750
|
+
call.reject(fail('worker-terminated', "Worker terminated."));
|
|
751
|
+
}
|
|
752
|
+
pending.clear();
|
|
753
|
+
if (connection) {
|
|
754
|
+
await connection.terminate();
|
|
755
|
+
} else if (starting) {
|
|
756
|
+
try {
|
|
757
|
+
(await starting).terminate();
|
|
758
|
+
} catch (ignored) {/* it never started */}
|
|
759
|
+
}
|
|
760
|
+
};
|
|
1014
761
|
return instance;
|
|
1015
762
|
};
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
return shared = shared || createWorker();
|
|
1019
|
-
};
|
|
763
|
+
let shared = null;
|
|
764
|
+
const sharedWorker = () => shared = shared || createWorker();
|
|
1020
765
|
|
|
1021
766
|
// Stops the shared worker, rejecting calls still waiting. The next call starts a fresh one.
|
|
1022
|
-
export
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
_context0.n = 1;
|
|
1030
|
-
break;
|
|
1031
|
-
}
|
|
1032
|
-
return _context0.a(2);
|
|
1033
|
-
case 1:
|
|
1034
|
-
stopping = shared;
|
|
1035
|
-
shared = null;
|
|
1036
|
-
_context0.n = 2;
|
|
1037
|
-
return stopping.terminate();
|
|
1038
|
-
case 2:
|
|
1039
|
-
return _context0.a(2);
|
|
1040
|
-
}
|
|
1041
|
-
}, _callee0);
|
|
1042
|
-
}));
|
|
1043
|
-
return function terminate() {
|
|
1044
|
-
return _ref8.apply(this, arguments);
|
|
1045
|
-
};
|
|
1046
|
-
}();
|
|
1047
|
-
export var init = function init() {
|
|
1048
|
-
var _sharedWorker;
|
|
1049
|
-
return (_sharedWorker = sharedWorker()).init.apply(_sharedWorker, arguments);
|
|
1050
|
-
};
|
|
1051
|
-
export var getClustering = function getClustering() {
|
|
1052
|
-
var _sharedWorker2;
|
|
1053
|
-
return (_sharedWorker2 = sharedWorker()).getClustering.apply(_sharedWorker2, arguments);
|
|
1054
|
-
};
|
|
1055
|
-
export var getPalette = function getPalette() {
|
|
1056
|
-
var _sharedWorker3;
|
|
1057
|
-
return (_sharedWorker3 = sharedWorker()).getPalette.apply(_sharedWorker3, arguments);
|
|
1058
|
-
};
|
|
1059
|
-
export var getPaletteFromClustering = function getPaletteFromClustering() {
|
|
1060
|
-
var _sharedWorker4;
|
|
1061
|
-
return (_sharedWorker4 = sharedWorker()).getPaletteFromClustering.apply(_sharedWorker4, arguments);
|
|
1062
|
-
};
|
|
1063
|
-
export var getSwatches = function getSwatches() {
|
|
1064
|
-
var _sharedWorker5;
|
|
1065
|
-
return (_sharedWorker5 = sharedWorker()).getSwatches.apply(_sharedWorker5, arguments);
|
|
1066
|
-
};
|
|
1067
|
-
export var getSwatchesFromClustering = function getSwatchesFromClustering() {
|
|
1068
|
-
var _sharedWorker6;
|
|
1069
|
-
return (_sharedWorker6 = sharedWorker()).getSwatchesFromClustering.apply(_sharedWorker6, arguments);
|
|
1070
|
-
};
|
|
1071
|
-
export var getClusteringInfo = function getClusteringInfo() {
|
|
1072
|
-
var _sharedWorker7;
|
|
1073
|
-
return (_sharedWorker7 = sharedWorker()).getClusteringInfo.apply(_sharedWorker7, arguments);
|
|
1074
|
-
};
|
|
1075
|
-
export var quantize = function quantize() {
|
|
1076
|
-
var _sharedWorker8;
|
|
1077
|
-
return (_sharedWorker8 = sharedWorker()).quantize.apply(_sharedWorker8, arguments);
|
|
1078
|
-
};
|
|
1079
|
-
export var quantizeFromClustering = function quantizeFromClustering() {
|
|
1080
|
-
var _sharedWorker9;
|
|
1081
|
-
return (_sharedWorker9 = sharedWorker()).quantizeFromClustering.apply(_sharedWorker9, arguments);
|
|
1082
|
-
};
|
|
1083
|
-
export var quantizeWithPalette = function quantizeWithPalette() {
|
|
1084
|
-
var _sharedWorker0;
|
|
1085
|
-
return (_sharedWorker0 = sharedWorker()).quantizeWithPalette.apply(_sharedWorker0, arguments);
|
|
1086
|
-
};
|
|
1087
|
-
export var quantizeToIndices = function quantizeToIndices() {
|
|
1088
|
-
var _sharedWorker1;
|
|
1089
|
-
return (_sharedWorker1 = sharedWorker()).quantizeToIndices.apply(_sharedWorker1, arguments);
|
|
1090
|
-
};
|
|
1091
|
-
export var quantizeToIndicesFromClustering = function quantizeToIndicesFromClustering() {
|
|
1092
|
-
var _sharedWorker10;
|
|
1093
|
-
return (_sharedWorker10 = sharedWorker()).quantizeToIndicesFromClustering.apply(_sharedWorker10, arguments);
|
|
767
|
+
export const terminate = async () => {
|
|
768
|
+
if (!shared) {
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
const stopping = shared;
|
|
772
|
+
shared = null;
|
|
773
|
+
await stopping.terminate();
|
|
1094
774
|
};
|
|
1095
|
-
export
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
775
|
+
export const init = (...args) => sharedWorker().init(...args);
|
|
776
|
+
export const getClustering = (...args) => sharedWorker().getClustering(...args);
|
|
777
|
+
export const getPalette = (...args) => sharedWorker().getPalette(...args);
|
|
778
|
+
export const getPaletteFromClustering = (...args) => sharedWorker().getPaletteFromClustering(...args);
|
|
779
|
+
export const getSwatches = (...args) => sharedWorker().getSwatches(...args);
|
|
780
|
+
export const getSwatchesFromClustering = (...args) => sharedWorker().getSwatchesFromClustering(...args);
|
|
781
|
+
export const getClusteringInfo = (...args) => sharedWorker().getClusteringInfo(...args);
|
|
782
|
+
export const quantize = (...args) => sharedWorker().quantize(...args);
|
|
783
|
+
export const quantizeFromClustering = (...args) => sharedWorker().quantizeFromClustering(...args);
|
|
784
|
+
export const quantizeWithPalette = (...args) => sharedWorker().quantizeWithPalette(...args);
|
|
785
|
+
export const quantizeToIndices = (...args) => sharedWorker().quantizeToIndices(...args);
|
|
786
|
+
export const quantizeToIndicesFromClustering = (...args) => sharedWorker().quantizeToIndicesFromClustering(...args);
|
|
787
|
+
export const quantizeToIndicesWithPalette = (...args) => sharedWorker().quantizeToIndicesWithPalette(...args);
|