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/README.md +193 -26
- package/dist/clustering.cjs +3 -0
- package/dist/clustering.js +1 -1
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +559 -1055
- package/dist/index.d.cts +3 -2
- package/dist/index.d.ts +3 -2
- package/dist/index.mjs +531 -1035
- package/dist/shared.cjs +204 -151
- package/dist/shared.mjs +184 -149
- package/dist/worker-thread.mjs +150 -354
- package/dist/worker.d.ts +21 -2
- package/dist/worker.mjs +548 -753
- package/package.json +7 -2
package/dist/shared.mjs
CHANGED
|
@@ -1,31 +1,15 @@
|
|
|
1
|
-
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
|
|
2
|
-
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."); }
|
|
3
|
-
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; } }
|
|
4
|
-
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
|
|
5
|
-
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; }
|
|
6
|
-
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
|
|
7
|
-
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); }
|
|
8
|
-
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; } } }; }
|
|
9
|
-
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; } }
|
|
10
|
-
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; }
|
|
11
|
-
function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; }
|
|
12
|
-
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
|
|
13
|
-
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
|
|
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
1
|
// Shared by both entries (index.js and worker.js) and the worker thread: errors, option snapshots, reading a clustering's
|
|
16
2
|
// header, the Palette and Clustering types, and the markers that carry those types across the worker boundary. Imported as
|
|
17
3
|
// './shared.js'; the build rewrites that to './shared.mjs' or './shared.cjs' (scripts/babel-import-extensions.cjs).
|
|
18
4
|
|
|
19
5
|
// The library's version: package.json is the source, and scripts/sync-version.mjs keeps this line (and the copy the .wasm
|
|
20
6
|
// is built from, src/version.hpp) in step with it. Do not edit it by hand.
|
|
21
|
-
export
|
|
22
|
-
export
|
|
7
|
+
export const version = '3.0.0-beta.4';
|
|
8
|
+
export const colorSpaces = {
|
|
23
9
|
'rgb': 0,
|
|
24
10
|
'oklab': 1
|
|
25
11
|
};
|
|
26
|
-
export
|
|
27
|
-
return code === 1 ? 'oklab' : 'rgb';
|
|
28
|
-
};
|
|
12
|
+
export const colorSpaceName = code => code === 1 ? 'oklab' : 'rgb';
|
|
29
13
|
|
|
30
14
|
// Every error this library throws is an Error with a `code` saying what went wrong, so callers needn't match on message
|
|
31
15
|
// text: 'invalid-argument' (image, k, options, palette), 'invalid-clustering', 'unsupported-version' (a clustering from a
|
|
@@ -33,44 +17,98 @@ export var colorSpaceName = function colorSpaceName(code) {
|
|
|
33
17
|
// 'worker-terminated', 'worker-failed' and 'invalid-handle'. When the error is about one argument, `argument` names it
|
|
34
18
|
// for programs (the message is for people): 'image', 'k', 'clustering', 'palette', 'options', or 'options.<key>' for
|
|
35
19
|
// one option.
|
|
36
|
-
export
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
});
|
|
43
|
-
};
|
|
20
|
+
export const fail = (code, message, argument) => Object.assign(new Error(message), argument === undefined ? {
|
|
21
|
+
code
|
|
22
|
+
} : {
|
|
23
|
+
code,
|
|
24
|
+
argument
|
|
25
|
+
});
|
|
44
26
|
|
|
45
27
|
// Type checks by tag rather than `instanceof`, so values from another realm (an iframe, a vm context, a test sandbox,
|
|
46
28
|
// whose Uint8Array is a different constructor) are recognised. A Node Buffer is a Uint8Array by tag too.
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
export
|
|
51
|
-
|
|
29
|
+
const tag = value => Object.prototype.toString.call(value);
|
|
30
|
+
export const isUint8Array = value => ArrayBuffer.isView(value) && tag(value) === '[object Uint8Array]';
|
|
31
|
+
export const isUint8ClampedArray = value => ArrayBuffer.isView(value) && tag(value) === '[object Uint8ClampedArray]';
|
|
32
|
+
export const isArrayBufferLike = value => tag(value) === '[object ArrayBuffer]' || tag(value) === '[object SharedArrayBuffer]';
|
|
33
|
+
|
|
34
|
+
// A typed array whose buffer was transferred away (to a worker, say) is empty and can't be read or viewed.
|
|
35
|
+
export const isDetached = view => {
|
|
36
|
+
const buffer = view.buffer;
|
|
37
|
+
if (typeof buffer.detached === 'boolean') {
|
|
38
|
+
return buffer.detached;
|
|
39
|
+
}
|
|
40
|
+
try {
|
|
41
|
+
new Uint8Array(buffer, 0, 0);
|
|
42
|
+
return false;
|
|
43
|
+
} catch (error) {
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
52
46
|
};
|
|
53
|
-
|
|
54
|
-
|
|
47
|
+
|
|
48
|
+
// An ImageData like `like`, with these pixels: made with `like`'s own class where it has one, so an ImageData from another
|
|
49
|
+
// implementation (node-canvas, in Node or under jsdom) comes back as one that implementation accepts, and where there is
|
|
50
|
+
// no global ImageData at all. The colour space is kept ('display-p3' canvases), since the pixels are still in it.
|
|
51
|
+
export const imageDataLike = (like, pixels) => {
|
|
52
|
+
const {
|
|
53
|
+
width,
|
|
54
|
+
height,
|
|
55
|
+
colorSpace
|
|
56
|
+
} = like;
|
|
57
|
+
const own = like.constructor;
|
|
58
|
+
const make = typeof own === 'function' && own.name === 'ImageData' ? own : typeof ImageData === 'function' ? ImageData : null;
|
|
59
|
+
if (!make) {
|
|
60
|
+
throw fail('invalid-argument', "Invalid image: an ImageData whose class can't be used to make the result. Pass { data, format: 'rgba', width } instead.", 'image');
|
|
61
|
+
}
|
|
62
|
+
return colorSpace ? new make(pixels, width, height, {
|
|
63
|
+
colorSpace
|
|
64
|
+
}) : new make(pixels, width, height);
|
|
55
65
|
};
|
|
56
|
-
|
|
57
|
-
|
|
66
|
+
|
|
67
|
+
// 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.
|
|
68
|
+
export const imageHint = image => {
|
|
69
|
+
const decode = " Decode it to pixels first, then pass them.";
|
|
70
|
+
if (image === undefined || image === null) {
|
|
71
|
+
return ` Got ${image}.`;
|
|
72
|
+
}
|
|
73
|
+
if (typeof image === 'string') {
|
|
74
|
+
return ` Got a string (a file name, URL or data URL?): load and decode it to pixels first.`;
|
|
75
|
+
}
|
|
76
|
+
if (typeof image !== 'object') {
|
|
77
|
+
return ` Got a ${typeof image}.`;
|
|
78
|
+
}
|
|
79
|
+
if (Array.isArray(image)) {
|
|
80
|
+
return " Got a plain array: use new Uint8Array(array) for RGBA bytes, or { data: new Uint8Array(array), format: 'rgb' }.";
|
|
81
|
+
}
|
|
82
|
+
if (isArrayBufferLike(image)) {
|
|
83
|
+
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).";
|
|
84
|
+
}
|
|
85
|
+
if (typeof image.getContext === 'function') {
|
|
86
|
+
return " Got a canvas: pass its pixels, canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height).";
|
|
87
|
+
}
|
|
88
|
+
if (typeof image.arrayBuffer === 'function' && typeof image.type === 'string') {
|
|
89
|
+
return " Got a Blob or File, which is an encoded image:" + decode + " (createImageBitmap(blob), draw it to a canvas, then getImageData()).";
|
|
90
|
+
}
|
|
91
|
+
if (typeof image.close === 'function' || typeof image.nodeName === 'string') {
|
|
92
|
+
return " Got an image element or ImageBitmap: draw it to a canvas (or OffscreenCanvas) and pass getImageData().";
|
|
93
|
+
}
|
|
94
|
+
if (image.data && !image.format) {
|
|
95
|
+
return " It has `data` but no `format`: add format: 'rgba' (or 'rgb') to use it as a RawImage.";
|
|
96
|
+
}
|
|
97
|
+
return '';
|
|
58
98
|
};
|
|
59
99
|
|
|
60
100
|
// An options object is an ordinary object. A Map, Date, ArrayBuffer or typed array has no own keys and would pass as
|
|
61
101
|
// `{}`, silently ignoring what the caller meant. Checked by tag rather than prototype so objects from another realm
|
|
62
102
|
// (an iframe, a test sandbox) are fine.
|
|
63
|
-
export
|
|
64
|
-
return value !== null && _typeof(value) === 'object' && Object.prototype.toString.call(value) === '[object Object]';
|
|
65
|
-
};
|
|
103
|
+
export const isOptionsObject = value => value !== null && typeof value === 'object' && Object.prototype.toString.call(value) === '[object Object]';
|
|
66
104
|
|
|
67
105
|
// One plain copy of an options object, taken once: every enumerable property, own or inherited (so options layered with
|
|
68
106
|
// Object.create(defaults) work and an inherited typo is still caught), each read a single time. Everything after this
|
|
69
107
|
// uses the copy, so what is validated is what is used, even if a property is a getter that answers differently each time.
|
|
70
108
|
// The copy has no prototype, so a key like '__proto__' is just a name.
|
|
71
|
-
export
|
|
72
|
-
|
|
73
|
-
for (
|
|
109
|
+
export const snapshot = options => {
|
|
110
|
+
const copy = Object.create(null);
|
|
111
|
+
for (const key in options) {
|
|
74
112
|
copy[key] = options[key];
|
|
75
113
|
}
|
|
76
114
|
return copy;
|
|
@@ -85,30 +123,20 @@ export var snapshot = function snapshot(options) {
|
|
|
85
123
|
// IndexedDB) give plain untagged Uint8Arrays. `Palette` and `Clustering` are how to make one by hand, and `instanceof`
|
|
86
124
|
// recognises them. The tags are found by a symbol registered with Symbol.for, so a copy of the library loaded twice (the
|
|
87
125
|
// ES module and CommonJS builds, a bundler's duplicate, the worker entry's own copy) recognises the other's.
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
export
|
|
91
|
-
|
|
92
|
-
};
|
|
93
|
-
export var isClustering = function isClustering(value) {
|
|
94
|
-
return isUint8Array(value) && value[clusteringBrand] === true;
|
|
95
|
-
};
|
|
126
|
+
const paletteBrand = Symbol.for('agglomerative-clustering.palette');
|
|
127
|
+
const clusteringBrand = Symbol.for('agglomerative-clustering.clustering');
|
|
128
|
+
export const isPalette = value => isUint8Array(value) && value[paletteBrand] === true;
|
|
129
|
+
export const isClustering = value => isUint8Array(value) && value[clusteringBrand] === true;
|
|
96
130
|
// Node's console.log and util.inspect call this (other environments ignore it), so the tag shows when debugging:
|
|
97
131
|
// `Palette(oklab) [ 12, 34, ... ]` rather than a plain `Uint8Array(…)`.
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
return "".concat(label(this), " ").concat(typeof nodeInspect === 'function' ? nodeInspect(plain, options) : "[".concat(plain.length, " bytes]"));
|
|
103
|
-
};
|
|
132
|
+
const inspect = Symbol.for('nodejs.util.inspect.custom');
|
|
133
|
+
const view = label => function (depth, options, nodeInspect) {
|
|
134
|
+
const plain = new Uint8Array(this.buffer, this.byteOffset, this.length);
|
|
135
|
+
return `${label(this)} ${typeof nodeInspect === 'function' ? nodeInspect(plain, options) : `[${plain.length} bytes]`}`;
|
|
104
136
|
};
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
var clusteringView = view(function () {
|
|
109
|
-
return 'Clustering';
|
|
110
|
-
});
|
|
111
|
-
export var markPalette = function markPalette(bytes, colorSpace) {
|
|
137
|
+
const paletteView = view(palette => `Palette(${palette.colorSpace})`);
|
|
138
|
+
const clusteringView = view(() => 'Clustering');
|
|
139
|
+
export const markPalette = (bytes, colorSpace) => {
|
|
112
140
|
Object.defineProperty(bytes, paletteBrand, {
|
|
113
141
|
value: true
|
|
114
142
|
});
|
|
@@ -120,7 +148,7 @@ export var markPalette = function markPalette(bytes, colorSpace) {
|
|
|
120
148
|
});
|
|
121
149
|
return bytes;
|
|
122
150
|
};
|
|
123
|
-
export
|
|
151
|
+
export const markClustering = bytes => {
|
|
124
152
|
// Made by this library (or checked by `Clustering`), so its checksum needn't be checked again (see readHeader).
|
|
125
153
|
checked.add(bytes);
|
|
126
154
|
Object.defineProperty(bytes, clusteringBrand, {
|
|
@@ -136,8 +164,7 @@ export var markClustering = function markClustering(bytes) {
|
|
|
136
164
|
// 'oklab')` copies `bytes` (or makes `length` zeros, or takes an array of byte values) and returns a Uint8Array tagged so.
|
|
137
165
|
// A function and not a `class`, because it returns a plain Uint8Array and answers `instanceof` itself, which transpiled class
|
|
138
166
|
// checks would trip over.
|
|
139
|
-
export function Palette(source) {
|
|
140
|
-
var colorSpace = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'rgb';
|
|
167
|
+
export function Palette(source, colorSpace = 'rgb') {
|
|
141
168
|
if (!Object.keys(colorSpaces).includes(colorSpace)) {
|
|
142
169
|
throw fail('invalid-argument', "Invalid colorSpace: must be 'rgb' or 'oklab'.", 'colorSpace');
|
|
143
170
|
}
|
|
@@ -161,27 +188,22 @@ Object.defineProperty(Palette, Symbol.hasInstance, {
|
|
|
161
188
|
|
|
162
189
|
// The bytes of a clustering, checked: `new Clustering(bytes)` is how stored clusterings get their type back. Arguments are
|
|
163
190
|
// those of a Uint8Array (bytes to copy, or a buffer with an offset and length to view).
|
|
164
|
-
export function Clustering() {
|
|
165
|
-
|
|
166
|
-
args[_key] = arguments[_key];
|
|
167
|
-
}
|
|
168
|
-
var source = args[0];
|
|
191
|
+
export function Clustering(...args) {
|
|
192
|
+
const [source] = args;
|
|
169
193
|
// Bytes, or a buffer to view: never a number (a length would allocate and make an empty clustering) or anything a Uint8Array
|
|
170
194
|
// would coerce. A plain array must hold byte values, as for a palette.
|
|
171
|
-
|
|
195
|
+
const isBuffer = isArrayBufferLike(source);
|
|
172
196
|
if (!isUint8Array(source) && !isUint8ClampedArray(source) && !isBuffer && !Array.isArray(source)) {
|
|
173
197
|
throw fail('invalid-clustering', "Invalid clustering: expected its bytes (a Uint8Array, or an ArrayBuffer with an optional offset and length) from getClustering.", 'clustering');
|
|
174
198
|
}
|
|
175
|
-
if (Array.isArray(source) && !source.every(
|
|
176
|
-
return Number.isInteger(value) && value >= 0 && value <= 255;
|
|
177
|
-
})) {
|
|
199
|
+
if (Array.isArray(source) && !source.every(value => Number.isInteger(value) && value >= 0 && value <= 255)) {
|
|
178
200
|
throw fail('invalid-clustering', "Invalid clustering: a plain array must hold byte values, integers from 0 to 255.", 'clustering');
|
|
179
201
|
}
|
|
180
|
-
|
|
202
|
+
let bytes;
|
|
181
203
|
try {
|
|
182
|
-
bytes =
|
|
204
|
+
bytes = new Uint8Array(...args);
|
|
183
205
|
} catch (error) {
|
|
184
|
-
throw fail('invalid-clustering',
|
|
206
|
+
throw fail('invalid-clustering', `Invalid clustering: ${error.message}.`, 'clustering');
|
|
185
207
|
}
|
|
186
208
|
readHeader(bytes);
|
|
187
209
|
return markClustering(bytes);
|
|
@@ -198,11 +220,11 @@ Object.defineProperty(Clustering, Symbol.hasInstance, {
|
|
|
198
220
|
// version 3: [0xAC, 3, header length, record length, colour space, precision, weight unit, weight shift,
|
|
199
221
|
// total weight (u32 LE), 0, grouped error (f32 LE, from header length 17), ...], then records of
|
|
200
222
|
// colours, parent index, lighter weight and cost; from 3.0.0-beta.2 the header holds a checksum (bytes 17-20)
|
|
201
|
-
export
|
|
223
|
+
export const latestVersion = 3;
|
|
202
224
|
|
|
203
225
|
// The version of stored data (clusterings) this build writes. It reads this one and format 2 (see readHeader). Unlike
|
|
204
226
|
// `version`, it changes only when the stored format does, so a 3.x release that keeps the format keeps this number.
|
|
205
|
-
export
|
|
227
|
+
export const formatVersion = latestVersion;
|
|
206
228
|
|
|
207
229
|
// ----- Checksums -----------------------------------------------------------------------------------------------------
|
|
208
230
|
// From 3.0.0-beta.2, a version 3 header holds the CRC-32 of the whole clustering (bytes 17-20, read as zeros while it is
|
|
@@ -210,56 +232,74 @@ export var formatVersion = latestVersion;
|
|
|
210
232
|
// is used, and the arrays that passed (and the ones this library made) are remembered, so cutting one clustering
|
|
211
233
|
// again and again checks it once. Changing a clustering's bytes after that is not detected here, but the records are
|
|
212
234
|
// also checked as they are replayed, so it still can't give a palette of the wrong size.
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
235
|
+
const checksumAt = 17;
|
|
236
|
+
// Computed 8 bytes at a time with eight tables (slicing-by-8), about 4 times faster than byte by byte: a clustering of a
|
|
237
|
+
// photo is 1-2 MB, and is checked the first time it is used.
|
|
238
|
+
let crcTables = null;
|
|
239
|
+
const crc32 = bytes => {
|
|
240
|
+
if (!crcTables) {
|
|
241
|
+
crcTables = Array.from({
|
|
242
|
+
length: 8
|
|
243
|
+
}, () => new Uint32Array(256));
|
|
244
|
+
for (let n = 0; n < 256; n++) {
|
|
245
|
+
let c = n;
|
|
246
|
+
for (let b = 0; b < 8; b++) {
|
|
221
247
|
c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1;
|
|
222
248
|
}
|
|
223
|
-
|
|
249
|
+
crcTables[0][n] = c >>> 0;
|
|
250
|
+
}
|
|
251
|
+
for (let n = 0; n < 256; n++) {
|
|
252
|
+
for (let t = 1; t < 8; t++) {
|
|
253
|
+
crcTables[t][n] = crcTables[t - 1][n] >>> 8 ^ crcTables[0][crcTables[t - 1][n] & 0xFF];
|
|
254
|
+
}
|
|
224
255
|
}
|
|
225
256
|
}
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
257
|
+
const [t0, t1, t2, t3, t4, t5, t6, t7] = crcTables;
|
|
258
|
+
let crc = 0xFFFFFFFF;
|
|
259
|
+
const byte = i => i >= checksumAt && i < checksumAt + 4 ? 0 : bytes[i];
|
|
260
|
+
let i = 0;
|
|
261
|
+
// The checksum field lies in the first 24 bytes, which go byte by byte; the rest 8 at a time.
|
|
262
|
+
for (; i < Math.min(24, bytes.length); i++) {
|
|
263
|
+
crc = t0[(crc ^ byte(i)) & 0xFF] ^ crc >>> 8;
|
|
264
|
+
}
|
|
265
|
+
const end = bytes.length - 7;
|
|
266
|
+
for (; i < end; i += 8) {
|
|
267
|
+
const a = (crc ^ (bytes[i] | bytes[i + 1] << 8 | bytes[i + 2] << 16 | bytes[i + 3] << 24)) >>> 0;
|
|
268
|
+
crc = t7[a & 0xFF] ^ t6[a >>> 8 & 0xFF] ^ t5[a >>> 16 & 0xFF] ^ t4[a >>> 24] ^ t3[bytes[i + 4]] ^ t2[bytes[i + 5]] ^ t1[bytes[i + 6]] ^ t0[bytes[i + 7]];
|
|
269
|
+
}
|
|
270
|
+
for (; i < bytes.length; i++) {
|
|
271
|
+
crc = t0[(crc ^ bytes[i]) & 0xFF] ^ crc >>> 8;
|
|
230
272
|
}
|
|
231
273
|
return (crc ^ 0xFFFFFFFF) >>> 0;
|
|
232
274
|
};
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
return fail('invalid-clustering', "Invalid clustering: its bytes are damaged (the checksum doesn't match): it was truncated, changed or mixed up with other data after getClustering made it. Cluster the image again.", 'clustering');
|
|
236
|
-
};
|
|
275
|
+
const checked = new WeakSet();
|
|
276
|
+
const damaged = () => fail('invalid-clustering', "Invalid clustering: its bytes are damaged (the checksum doesn't match): it was truncated, changed or mixed up with other data after getClustering made it. Cluster the image again.", 'clustering');
|
|
237
277
|
|
|
238
278
|
// The message for bytes that aren't a clustering: 1.x clusterings are mentioned only for bytes that could be one (no header,
|
|
239
279
|
// and a length of 0 or 3 more than a multiple of 9).
|
|
240
|
-
|
|
241
|
-
|
|
280
|
+
const notAClustering = clustering => {
|
|
281
|
+
const length = clustering.length;
|
|
242
282
|
if (clustering[0] !== 0xAC && (length % 9 === 0 || length % 9 === 3)) {
|
|
243
283
|
return fail('invalid-clustering', "Invalid clustering: not a clustering from getClustering. If it was stored by agglomerative-clustering 1.x, that format is no longer read: cluster the image again.", 'clustering');
|
|
244
284
|
}
|
|
245
285
|
if (clustering[0] === 0xAC && length >= 2 && (clustering[1] === 2 || clustering[1] === 3)) {
|
|
246
|
-
return fail('invalid-clustering',
|
|
286
|
+
return fail('invalid-clustering', `Invalid clustering: it starts like a format ${clustering[1]} clustering, but its length or header doesn't fit one (${length} bytes): it was probably truncated or damaged. Cluster the image again.`, 'clustering');
|
|
247
287
|
}
|
|
248
|
-
return fail('invalid-clustering',
|
|
288
|
+
return fail('invalid-clustering', `Invalid clustering: not a clustering from getClustering (${length} bytes that don't start with a clustering header).`, 'clustering');
|
|
249
289
|
};
|
|
250
|
-
export
|
|
290
|
+
export const readHeader = clustering => {
|
|
251
291
|
if (isPalette(clustering)) {
|
|
252
292
|
throw fail('invalid-clustering', "Invalid clustering: this is a palette, not a clustering. Palettes come from getPalette and getPaletteFromClustering; a clustering comes from getClustering.", 'clustering');
|
|
253
293
|
}
|
|
254
294
|
if (!isUint8Array(clustering)) {
|
|
255
295
|
throw fail('invalid-clustering', "Invalid clustering: must be a Uint8Array from getClustering.", 'clustering');
|
|
256
296
|
}
|
|
257
|
-
|
|
297
|
+
const length = clustering.length;
|
|
258
298
|
if (length >= 4 && clustering[0] === 0xAC) {
|
|
259
|
-
|
|
260
|
-
if (
|
|
299
|
+
const version = clustering[1];
|
|
300
|
+
if (version === 2 && clustering[2] <= 1 && (length === 4 || length % 9 === 7)) {
|
|
261
301
|
return {
|
|
262
|
-
version
|
|
302
|
+
version,
|
|
263
303
|
colorSpace: clustering[2],
|
|
264
304
|
precision: clustering[3],
|
|
265
305
|
transparent: 0,
|
|
@@ -268,41 +308,41 @@ export var readHeader = function readHeader(clustering) {
|
|
|
268
308
|
merges: length === 4 ? 0 : (length - 7) / 9
|
|
269
309
|
};
|
|
270
310
|
}
|
|
271
|
-
if (
|
|
272
|
-
|
|
311
|
+
if (version === 3 && length >= 13) {
|
|
312
|
+
const headerLength = clustering[2],
|
|
273
313
|
recordLength = clustering[3];
|
|
274
314
|
if (headerLength >= 13 && recordLength >= 21 && headerLength <= length) {
|
|
275
315
|
// A header field with a fixed set of meanings (colour space, weight unit) that holds a value this version
|
|
276
316
|
// doesn't know is how a later release would add one, so it asks for an upgrade rather than misreading it.
|
|
277
317
|
if (clustering[4] > 1 || clustering[6] > 1) {
|
|
278
|
-
throw fail('unsupported-version', "
|
|
318
|
+
throw fail('unsupported-version', "Unsupported clustering: it uses a colour space or weight unit that this version of agglomerative-clustering does not know. If it came from a newer version, upgrade the package; otherwise it is damaged.", 'clustering');
|
|
279
319
|
}
|
|
280
|
-
|
|
281
|
-
|
|
320
|
+
const merges = length < headerLength + 3 ? 0 : Math.floor((length - headerLength - 3) / recordLength);
|
|
321
|
+
const padding = length < headerLength + 3 ? length - headerLength : length - headerLength - 3 - merges * recordLength;
|
|
282
322
|
if (padding < 9) {
|
|
283
323
|
// Headers shorter than 21 bytes (from before 3.0.0-beta.1) have no checksum field. A damaged header length that
|
|
284
324
|
// makes one look that short skips this check, but then the records don't line up, which the replay reports.
|
|
285
325
|
if (!checked.has(clustering) && headerLength >= checksumAt + 4) {
|
|
286
|
-
|
|
326
|
+
const stored = (clustering[checksumAt] | clustering[checksumAt + 1] << 8 | clustering[checksumAt + 2] << 16 | clustering[checksumAt + 3] << 24) >>> 0;
|
|
287
327
|
if (stored !== 0 && stored !== crc32(clustering)) {
|
|
288
328
|
throw damaged();
|
|
289
329
|
}
|
|
290
330
|
checked.add(clustering);
|
|
291
331
|
}
|
|
292
332
|
return {
|
|
293
|
-
version
|
|
333
|
+
version,
|
|
294
334
|
colorSpace: clustering[4],
|
|
295
335
|
precision: clustering[5],
|
|
296
336
|
transparent: clustering[12],
|
|
297
|
-
headerLength
|
|
298
|
-
recordLength
|
|
299
|
-
merges
|
|
337
|
+
headerLength,
|
|
338
|
+
recordLength,
|
|
339
|
+
merges
|
|
300
340
|
};
|
|
301
341
|
}
|
|
302
342
|
}
|
|
303
343
|
}
|
|
304
|
-
if (
|
|
305
|
-
throw fail('unsupported-version',
|
|
344
|
+
if (version > latestVersion) {
|
|
345
|
+
throw fail('unsupported-version', `Unsupported clustering: format version ${version} is newer than this version of agglomerative-clustering reads. Upgrade the package.`, 'clustering');
|
|
306
346
|
}
|
|
307
347
|
}
|
|
308
348
|
throw notAClustering(clustering);
|
|
@@ -310,32 +350,26 @@ export var readHeader = function readHeader(clustering) {
|
|
|
310
350
|
|
|
311
351
|
// Palettes are flat RGB bytes. An empty palette is allowed: it is what getPalette gives for a fully transparent
|
|
312
352
|
// image, and quantize maps such an image the same way.
|
|
313
|
-
export
|
|
353
|
+
export const checkPalette = palette => {
|
|
314
354
|
if (isClustering(palette)) {
|
|
315
355
|
throw fail('invalid-argument', "Invalid palette: this is a clustering (from getClustering), not a palette. Cut a palette from it with getPaletteFromClustering, or map with quantizeFromClustering.", 'palette');
|
|
316
356
|
}
|
|
317
357
|
if (!isUint8Array(palette) && !isUint8ClampedArray(palette) && !Array.isArray(palette)) {
|
|
318
358
|
throw fail('invalid-argument', "Invalid palette: must be a Uint8Array of RGB bytes.", 'palette');
|
|
319
359
|
}
|
|
360
|
+
if (Array.isArray(palette) && palette.some(value => Array.isArray(value) || ArrayBuffer.isView(value))) {
|
|
361
|
+
throw fail('invalid-argument', "Invalid palette: a plain array must be flat RGB bytes, integers from 0 to 255, not an array of [r, g, b] colours. Flatten it first: colours.flat().", 'palette');
|
|
362
|
+
}
|
|
320
363
|
if (palette.length % 3 !== 0) {
|
|
321
364
|
throw fail('invalid-argument', "Invalid palette: length must be a multiple of 3 (flat RGB bytes).", 'palette');
|
|
322
365
|
}
|
|
323
366
|
// Typed arrays are bytes already. A plain array is copied into bytes, which would turn an array of [r, g, b] colours
|
|
324
367
|
// into zeros, strings into numbers and 300 into 44 without a word, so it must hold byte values.
|
|
325
368
|
if (Array.isArray(palette)) {
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
for (_iterator.s(); !(_step = _iterator.n()).done;) {
|
|
330
|
-
var value = _step.value;
|
|
331
|
-
if (!Number.isInteger(value) || value < 0 || value > 255) {
|
|
332
|
-
throw fail('invalid-argument', "Invalid palette: a plain array must be flat RGB bytes, integers from 0 to 255 (not an array of [r, g, b] colours).", 'palette');
|
|
333
|
-
}
|
|
369
|
+
for (const value of palette) {
|
|
370
|
+
if (!Number.isInteger(value) || value < 0 || value > 255) {
|
|
371
|
+
throw fail('invalid-argument', "Invalid palette: a plain array must be flat RGB bytes, integers from 0 to 255 (not an array of [r, g, b] colours).", 'palette');
|
|
334
372
|
}
|
|
335
|
-
} catch (err) {
|
|
336
|
-
_iterator.e(err);
|
|
337
|
-
} finally {
|
|
338
|
-
_iterator.f();
|
|
339
373
|
}
|
|
340
374
|
}
|
|
341
375
|
};
|
|
@@ -344,32 +378,34 @@ export var checkPalette = function checkPalette(palette) {
|
|
|
344
378
|
// A structured clone drops the tags (a palette's colour space with them), so palettes and clusterings cross to and from the
|
|
345
379
|
// worker thread as small markers and become typed arrays again on the other side: `mark` before posting (an argument, a
|
|
346
380
|
// result, or a property of a result), `revive` after receiving.
|
|
347
|
-
export
|
|
348
|
-
|
|
381
|
+
export const MARK = '__agglomerativeClustering';
|
|
382
|
+
const markOne = value => {
|
|
349
383
|
if (isPalette(value)) {
|
|
350
|
-
return
|
|
384
|
+
return {
|
|
385
|
+
[MARK]: 'palette',
|
|
386
|
+
bytes: new Uint8Array(value.buffer, value.byteOffset, value.length),
|
|
387
|
+
colorSpace: value.colorSpace
|
|
388
|
+
};
|
|
351
389
|
}
|
|
352
390
|
if (isClustering(value)) {
|
|
353
|
-
return
|
|
391
|
+
return {
|
|
392
|
+
[MARK]: 'clustering',
|
|
393
|
+
bytes: new Uint8Array(value.buffer, value.byteOffset, value.length)
|
|
394
|
+
};
|
|
354
395
|
}
|
|
355
396
|
return value;
|
|
356
397
|
};
|
|
357
|
-
export
|
|
358
|
-
if (!value ||
|
|
398
|
+
export const mark = value => {
|
|
399
|
+
if (!value || typeof value !== 'object' || ArrayBuffer.isView(value)) {
|
|
359
400
|
return markOne(value);
|
|
360
401
|
}
|
|
361
402
|
if (!isOptionsObject(value)) {
|
|
362
403
|
return value;
|
|
363
404
|
}
|
|
364
|
-
return Object.fromEntries(Object.entries(value).map(
|
|
365
|
-
var _ref4 = _slicedToArray(_ref3, 2),
|
|
366
|
-
key = _ref4[0],
|
|
367
|
-
part = _ref4[1];
|
|
368
|
-
return [key, markOne(part)];
|
|
369
|
-
}));
|
|
405
|
+
return Object.fromEntries(Object.entries(value).map(([key, part]) => [key, markOne(part)]));
|
|
370
406
|
};
|
|
371
|
-
|
|
372
|
-
if (!value ||
|
|
407
|
+
const reviveOne = value => {
|
|
408
|
+
if (!value || typeof value !== 'object' || !value[MARK]) {
|
|
373
409
|
return value;
|
|
374
410
|
}
|
|
375
411
|
if (value[MARK] === 'palette') {
|
|
@@ -377,8 +413,8 @@ var reviveOne = function reviveOne(value) {
|
|
|
377
413
|
}
|
|
378
414
|
return markClustering(new Uint8Array(value.bytes.buffer, value.bytes.byteOffset, value.bytes.length));
|
|
379
415
|
};
|
|
380
|
-
export
|
|
381
|
-
if (!value ||
|
|
416
|
+
export const revive = value => {
|
|
417
|
+
if (!value || typeof value !== 'object' || ArrayBuffer.isView(value)) {
|
|
382
418
|
return value;
|
|
383
419
|
}
|
|
384
420
|
if (value[MARK]) {
|
|
@@ -387,8 +423,7 @@ export var revive = function revive(value) {
|
|
|
387
423
|
if (!isOptionsObject(value)) {
|
|
388
424
|
return value;
|
|
389
425
|
}
|
|
390
|
-
for (
|
|
391
|
-
var key = _Object$keys[_i];
|
|
426
|
+
for (const key of Object.keys(value)) {
|
|
392
427
|
value[key] = reviveOne(value[key]);
|
|
393
428
|
}
|
|
394
429
|
return value;
|