agglomerative-clustering 3.0.0-beta.1 → 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 +192 -49
- package/dist/clustering.js +1 -1
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +649 -830
- package/dist/index.d.cts +16 -15
- package/dist/index.d.ts +16 -15
- package/dist/index.mjs +633 -828
- package/dist/shared.cjs +202 -132
- package/dist/shared.mjs +184 -130
- package/dist/worker-thread.mjs +115 -349
- package/dist/worker.d.ts +2 -2
- package/dist/worker.mjs +480 -646
- package/package.json +4 -1
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.3';
|
|
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,65 @@ 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
|
-
|
|
52
|
-
|
|
53
|
-
export
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
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
|
+
// 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.
|
|
35
|
+
export const imageHint = image => {
|
|
36
|
+
const decode = " Decode it to pixels first, then pass them.";
|
|
37
|
+
if (image === undefined || image === null) {
|
|
38
|
+
return ` Got ${image}.`;
|
|
39
|
+
}
|
|
40
|
+
if (typeof image === 'string') {
|
|
41
|
+
return ` Got a string (a file name, URL or data URL?): load and decode it to pixels first.`;
|
|
42
|
+
}
|
|
43
|
+
if (typeof image !== 'object') {
|
|
44
|
+
return ` Got a ${typeof image}.`;
|
|
45
|
+
}
|
|
46
|
+
if (Array.isArray(image)) {
|
|
47
|
+
return " Got a plain array: use new Uint8Array(array) for RGBA bytes, or { data: new Uint8Array(array), format: 'rgb' }.";
|
|
48
|
+
}
|
|
49
|
+
if (isArrayBufferLike(image)) {
|
|
50
|
+
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).";
|
|
51
|
+
}
|
|
52
|
+
if (typeof image.getContext === 'function') {
|
|
53
|
+
return " Got a canvas: pass its pixels, canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height).";
|
|
54
|
+
}
|
|
55
|
+
if (typeof image.arrayBuffer === 'function' && typeof image.type === 'string') {
|
|
56
|
+
return " Got a Blob or File, which is an encoded image:" + decode + " (createImageBitmap(blob), draw it to a canvas, then getImageData()).";
|
|
57
|
+
}
|
|
58
|
+
if (typeof image.close === 'function' || typeof image.nodeName === 'string') {
|
|
59
|
+
return " Got an image element or ImageBitmap: draw it to a canvas (or OffscreenCanvas) and pass getImageData().";
|
|
60
|
+
}
|
|
61
|
+
if (image.data && !image.format) {
|
|
62
|
+
return " It has `data` but no `format`: add format: 'rgba' (or 'rgb') to use it as a RawImage.";
|
|
63
|
+
}
|
|
64
|
+
return '';
|
|
58
65
|
};
|
|
59
66
|
|
|
60
67
|
// An options object is an ordinary object. A Map, Date, ArrayBuffer or typed array has no own keys and would pass as
|
|
61
68
|
// `{}`, silently ignoring what the caller meant. Checked by tag rather than prototype so objects from another realm
|
|
62
69
|
// (an iframe, a test sandbox) are fine.
|
|
63
|
-
export
|
|
64
|
-
return value !== null && _typeof(value) === 'object' && Object.prototype.toString.call(value) === '[object Object]';
|
|
65
|
-
};
|
|
70
|
+
export const isOptionsObject = value => value !== null && typeof value === 'object' && Object.prototype.toString.call(value) === '[object Object]';
|
|
66
71
|
|
|
67
72
|
// One plain copy of an options object, taken once: every enumerable property, own or inherited (so options layered with
|
|
68
73
|
// Object.create(defaults) work and an inherited typo is still caught), each read a single time. Everything after this
|
|
69
74
|
// uses the copy, so what is validated is what is used, even if a property is a getter that answers differently each time.
|
|
70
75
|
// The copy has no prototype, so a key like '__proto__' is just a name.
|
|
71
|
-
export
|
|
72
|
-
|
|
73
|
-
for (
|
|
76
|
+
export const snapshot = options => {
|
|
77
|
+
const copy = Object.create(null);
|
|
78
|
+
for (const key in options) {
|
|
74
79
|
copy[key] = options[key];
|
|
75
80
|
}
|
|
76
81
|
return copy;
|
|
@@ -85,30 +90,20 @@ export var snapshot = function snapshot(options) {
|
|
|
85
90
|
// IndexedDB) give plain untagged Uint8Arrays. `Palette` and `Clustering` are how to make one by hand, and `instanceof`
|
|
86
91
|
// recognises them. The tags are found by a symbol registered with Symbol.for, so a copy of the library loaded twice (the
|
|
87
92
|
// 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
|
-
};
|
|
93
|
+
const paletteBrand = Symbol.for('agglomerative-clustering.palette');
|
|
94
|
+
const clusteringBrand = Symbol.for('agglomerative-clustering.clustering');
|
|
95
|
+
export const isPalette = value => isUint8Array(value) && value[paletteBrand] === true;
|
|
96
|
+
export const isClustering = value => isUint8Array(value) && value[clusteringBrand] === true;
|
|
96
97
|
// Node's console.log and util.inspect call this (other environments ignore it), so the tag shows when debugging:
|
|
97
98
|
// `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
|
-
};
|
|
99
|
+
const inspect = Symbol.for('nodejs.util.inspect.custom');
|
|
100
|
+
const view = label => function (depth, options, nodeInspect) {
|
|
101
|
+
const plain = new Uint8Array(this.buffer, this.byteOffset, this.length);
|
|
102
|
+
return `${label(this)} ${typeof nodeInspect === 'function' ? nodeInspect(plain, options) : `[${plain.length} bytes]`}`;
|
|
104
103
|
};
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
var clusteringView = view(function () {
|
|
109
|
-
return 'Clustering';
|
|
110
|
-
});
|
|
111
|
-
export var markPalette = function markPalette(bytes, colorSpace) {
|
|
104
|
+
const paletteView = view(palette => `Palette(${palette.colorSpace})`);
|
|
105
|
+
const clusteringView = view(() => 'Clustering');
|
|
106
|
+
export const markPalette = (bytes, colorSpace) => {
|
|
112
107
|
Object.defineProperty(bytes, paletteBrand, {
|
|
113
108
|
value: true
|
|
114
109
|
});
|
|
@@ -120,7 +115,9 @@ export var markPalette = function markPalette(bytes, colorSpace) {
|
|
|
120
115
|
});
|
|
121
116
|
return bytes;
|
|
122
117
|
};
|
|
123
|
-
export
|
|
118
|
+
export const markClustering = bytes => {
|
|
119
|
+
// Made by this library (or checked by `Clustering`), so its checksum needn't be checked again (see readHeader).
|
|
120
|
+
checked.add(bytes);
|
|
124
121
|
Object.defineProperty(bytes, clusteringBrand, {
|
|
125
122
|
value: true
|
|
126
123
|
});
|
|
@@ -134,8 +131,7 @@ export var markClustering = function markClustering(bytes) {
|
|
|
134
131
|
// 'oklab')` copies `bytes` (or makes `length` zeros, or takes an array of byte values) and returns a Uint8Array tagged so.
|
|
135
132
|
// A function and not a `class`, because it returns a plain Uint8Array and answers `instanceof` itself, which transpiled class
|
|
136
133
|
// checks would trip over.
|
|
137
|
-
export function Palette(source) {
|
|
138
|
-
var colorSpace = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'rgb';
|
|
134
|
+
export function Palette(source, colorSpace = 'rgb') {
|
|
139
135
|
if (!Object.keys(colorSpaces).includes(colorSpace)) {
|
|
140
136
|
throw fail('invalid-argument', "Invalid colorSpace: must be 'rgb' or 'oklab'.", 'colorSpace');
|
|
141
137
|
}
|
|
@@ -159,27 +155,22 @@ Object.defineProperty(Palette, Symbol.hasInstance, {
|
|
|
159
155
|
|
|
160
156
|
// The bytes of a clustering, checked: `new Clustering(bytes)` is how stored clusterings get their type back. Arguments are
|
|
161
157
|
// those of a Uint8Array (bytes to copy, or a buffer with an offset and length to view).
|
|
162
|
-
export function Clustering() {
|
|
163
|
-
|
|
164
|
-
args[_key] = arguments[_key];
|
|
165
|
-
}
|
|
166
|
-
var source = args[0];
|
|
158
|
+
export function Clustering(...args) {
|
|
159
|
+
const [source] = args;
|
|
167
160
|
// Bytes, or a buffer to view: never a number (a length would allocate and make an empty clustering) or anything a Uint8Array
|
|
168
161
|
// would coerce. A plain array must hold byte values, as for a palette.
|
|
169
|
-
|
|
162
|
+
const isBuffer = isArrayBufferLike(source);
|
|
170
163
|
if (!isUint8Array(source) && !isUint8ClampedArray(source) && !isBuffer && !Array.isArray(source)) {
|
|
171
164
|
throw fail('invalid-clustering', "Invalid clustering: expected its bytes (a Uint8Array, or an ArrayBuffer with an optional offset and length) from getClustering.", 'clustering');
|
|
172
165
|
}
|
|
173
|
-
if (Array.isArray(source) && !source.every(
|
|
174
|
-
return Number.isInteger(value) && value >= 0 && value <= 255;
|
|
175
|
-
})) {
|
|
166
|
+
if (Array.isArray(source) && !source.every(value => Number.isInteger(value) && value >= 0 && value <= 255)) {
|
|
176
167
|
throw fail('invalid-clustering', "Invalid clustering: a plain array must hold byte values, integers from 0 to 255.", 'clustering');
|
|
177
168
|
}
|
|
178
|
-
|
|
169
|
+
let bytes;
|
|
179
170
|
try {
|
|
180
|
-
bytes =
|
|
171
|
+
bytes = new Uint8Array(...args);
|
|
181
172
|
} catch (error) {
|
|
182
|
-
throw fail('invalid-clustering',
|
|
173
|
+
throw fail('invalid-clustering', `Invalid clustering: ${error.message}.`, 'clustering');
|
|
183
174
|
}
|
|
184
175
|
readHeader(bytes);
|
|
185
176
|
return markClustering(bytes);
|
|
@@ -195,25 +186,87 @@ Object.defineProperty(Clustering, Symbol.hasInstance, {
|
|
|
195
186
|
// version 2: [0xAC, 2, colour space, precision], then 9-byte records of colours
|
|
196
187
|
// version 3: [0xAC, 3, header length, record length, colour space, precision, weight unit, weight shift,
|
|
197
188
|
// total weight (u32 LE), 0, grouped error (f32 LE, from header length 17), ...], then records of
|
|
198
|
-
// colours, parent index, lighter weight and cost
|
|
199
|
-
export
|
|
189
|
+
// colours, parent index, lighter weight and cost; from 3.0.0-beta.2 the header holds a checksum (bytes 17-20)
|
|
190
|
+
export const latestVersion = 3;
|
|
200
191
|
|
|
201
192
|
// The version of stored data (clusterings) this build writes. It reads this one and format 2 (see readHeader). Unlike
|
|
202
193
|
// `version`, it changes only when the stored format does, so a 3.x release that keeps the format keeps this number.
|
|
203
|
-
export
|
|
204
|
-
|
|
194
|
+
export const formatVersion = latestVersion;
|
|
195
|
+
|
|
196
|
+
// ----- Checksums -----------------------------------------------------------------------------------------------------
|
|
197
|
+
// 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
|
|
198
|
+
// computed; see src/clustering.cpp). 0 means none: beta.1 wrote zeros there. A clustering is checked the first time it
|
|
199
|
+
// is used, and the arrays that passed (and the ones this library made) are remembered, so cutting one clustering
|
|
200
|
+
// again and again checks it once. Changing a clustering's bytes after that is not detected here, but the records are
|
|
201
|
+
// also checked as they are replayed, so it still can't give a palette of the wrong size.
|
|
202
|
+
const checksumAt = 17;
|
|
203
|
+
// Computed 8 bytes at a time with eight tables (slicing-by-8), about 4 times faster than byte by byte: a clustering of a
|
|
204
|
+
// photo is 1-2 MB, and is checked the first time it is used.
|
|
205
|
+
let crcTables = null;
|
|
206
|
+
const crc32 = bytes => {
|
|
207
|
+
if (!crcTables) {
|
|
208
|
+
crcTables = Array.from({
|
|
209
|
+
length: 8
|
|
210
|
+
}, () => new Uint32Array(256));
|
|
211
|
+
for (let n = 0; n < 256; n++) {
|
|
212
|
+
let c = n;
|
|
213
|
+
for (let b = 0; b < 8; b++) {
|
|
214
|
+
c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1;
|
|
215
|
+
}
|
|
216
|
+
crcTables[0][n] = c >>> 0;
|
|
217
|
+
}
|
|
218
|
+
for (let n = 0; n < 256; n++) {
|
|
219
|
+
for (let t = 1; t < 8; t++) {
|
|
220
|
+
crcTables[t][n] = crcTables[t - 1][n] >>> 8 ^ crcTables[0][crcTables[t - 1][n] & 0xFF];
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
const [t0, t1, t2, t3, t4, t5, t6, t7] = crcTables;
|
|
225
|
+
let crc = 0xFFFFFFFF;
|
|
226
|
+
const byte = i => i >= checksumAt && i < checksumAt + 4 ? 0 : bytes[i];
|
|
227
|
+
let i = 0;
|
|
228
|
+
// The checksum field lies in the first 24 bytes, which go byte by byte; the rest 8 at a time.
|
|
229
|
+
for (; i < Math.min(24, bytes.length); i++) {
|
|
230
|
+
crc = t0[(crc ^ byte(i)) & 0xFF] ^ crc >>> 8;
|
|
231
|
+
}
|
|
232
|
+
const end = bytes.length - 7;
|
|
233
|
+
for (; i < end; i += 8) {
|
|
234
|
+
const a = (crc ^ (bytes[i] | bytes[i + 1] << 8 | bytes[i + 2] << 16 | bytes[i + 3] << 24)) >>> 0;
|
|
235
|
+
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]];
|
|
236
|
+
}
|
|
237
|
+
for (; i < bytes.length; i++) {
|
|
238
|
+
crc = t0[(crc ^ bytes[i]) & 0xFF] ^ crc >>> 8;
|
|
239
|
+
}
|
|
240
|
+
return (crc ^ 0xFFFFFFFF) >>> 0;
|
|
241
|
+
};
|
|
242
|
+
const checked = new WeakSet();
|
|
243
|
+
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');
|
|
244
|
+
|
|
245
|
+
// The message for bytes that aren't a clustering: 1.x clusterings are mentioned only for bytes that could be one (no header,
|
|
246
|
+
// and a length of 0 or 3 more than a multiple of 9).
|
|
247
|
+
const notAClustering = clustering => {
|
|
248
|
+
const length = clustering.length;
|
|
249
|
+
if (clustering[0] !== 0xAC && (length % 9 === 0 || length % 9 === 3)) {
|
|
250
|
+
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');
|
|
251
|
+
}
|
|
252
|
+
if (clustering[0] === 0xAC && length >= 2 && (clustering[1] === 2 || clustering[1] === 3)) {
|
|
253
|
+
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');
|
|
254
|
+
}
|
|
255
|
+
return fail('invalid-clustering', `Invalid clustering: not a clustering from getClustering (${length} bytes that don't start with a clustering header).`, 'clustering');
|
|
256
|
+
};
|
|
257
|
+
export const readHeader = clustering => {
|
|
205
258
|
if (isPalette(clustering)) {
|
|
206
259
|
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');
|
|
207
260
|
}
|
|
208
261
|
if (!isUint8Array(clustering)) {
|
|
209
262
|
throw fail('invalid-clustering', "Invalid clustering: must be a Uint8Array from getClustering.", 'clustering');
|
|
210
263
|
}
|
|
211
|
-
|
|
264
|
+
const length = clustering.length;
|
|
212
265
|
if (length >= 4 && clustering[0] === 0xAC) {
|
|
213
|
-
|
|
214
|
-
if (
|
|
266
|
+
const version = clustering[1];
|
|
267
|
+
if (version === 2 && clustering[2] <= 1 && (length === 4 || length % 9 === 7)) {
|
|
215
268
|
return {
|
|
216
|
-
version
|
|
269
|
+
version,
|
|
217
270
|
colorSpace: clustering[2],
|
|
218
271
|
precision: clustering[3],
|
|
219
272
|
transparent: 0,
|
|
@@ -222,8 +275,8 @@ export var readHeader = function readHeader(clustering) {
|
|
|
222
275
|
merges: length === 4 ? 0 : (length - 7) / 9
|
|
223
276
|
};
|
|
224
277
|
}
|
|
225
|
-
if (
|
|
226
|
-
|
|
278
|
+
if (version === 3 && length >= 13) {
|
|
279
|
+
const headerLength = clustering[2],
|
|
227
280
|
recordLength = clustering[3];
|
|
228
281
|
if (headerLength >= 13 && recordLength >= 21 && headerLength <= length) {
|
|
229
282
|
// A header field with a fixed set of meanings (colour space, weight unit) that holds a value this version
|
|
@@ -231,31 +284,40 @@ export var readHeader = function readHeader(clustering) {
|
|
|
231
284
|
if (clustering[4] > 1 || clustering[6] > 1) {
|
|
232
285
|
throw fail('unsupported-version', "Invalid 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');
|
|
233
286
|
}
|
|
234
|
-
|
|
235
|
-
|
|
287
|
+
const merges = length < headerLength + 3 ? 0 : Math.floor((length - headerLength - 3) / recordLength);
|
|
288
|
+
const padding = length < headerLength + 3 ? length - headerLength : length - headerLength - 3 - merges * recordLength;
|
|
236
289
|
if (padding < 9) {
|
|
290
|
+
// Headers shorter than 21 bytes (from before 3.0.0-beta.1) have no checksum field. A damaged header length that
|
|
291
|
+
// makes one look that short skips this check, but then the records don't line up, which the replay reports.
|
|
292
|
+
if (!checked.has(clustering) && headerLength >= checksumAt + 4) {
|
|
293
|
+
const stored = (clustering[checksumAt] | clustering[checksumAt + 1] << 8 | clustering[checksumAt + 2] << 16 | clustering[checksumAt + 3] << 24) >>> 0;
|
|
294
|
+
if (stored !== 0 && stored !== crc32(clustering)) {
|
|
295
|
+
throw damaged();
|
|
296
|
+
}
|
|
297
|
+
checked.add(clustering);
|
|
298
|
+
}
|
|
237
299
|
return {
|
|
238
|
-
version
|
|
300
|
+
version,
|
|
239
301
|
colorSpace: clustering[4],
|
|
240
302
|
precision: clustering[5],
|
|
241
303
|
transparent: clustering[12],
|
|
242
|
-
headerLength
|
|
243
|
-
recordLength
|
|
244
|
-
merges
|
|
304
|
+
headerLength,
|
|
305
|
+
recordLength,
|
|
306
|
+
merges
|
|
245
307
|
};
|
|
246
308
|
}
|
|
247
309
|
}
|
|
248
310
|
}
|
|
249
|
-
if (
|
|
250
|
-
throw fail('unsupported-version',
|
|
311
|
+
if (version > latestVersion) {
|
|
312
|
+
throw fail('unsupported-version', `Invalid clustering: format version ${version} is newer than this version of agglomerative-clustering reads. Upgrade the package.`, 'clustering');
|
|
251
313
|
}
|
|
252
314
|
}
|
|
253
|
-
throw
|
|
315
|
+
throw notAClustering(clustering);
|
|
254
316
|
};
|
|
255
317
|
|
|
256
318
|
// Palettes are flat RGB bytes. An empty palette is allowed: it is what getPalette gives for a fully transparent
|
|
257
319
|
// image, and quantize maps such an image the same way.
|
|
258
|
-
export
|
|
320
|
+
export const checkPalette = palette => {
|
|
259
321
|
if (isClustering(palette)) {
|
|
260
322
|
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');
|
|
261
323
|
}
|
|
@@ -268,19 +330,10 @@ export var checkPalette = function checkPalette(palette) {
|
|
|
268
330
|
// Typed arrays are bytes already. A plain array is copied into bytes, which would turn an array of [r, g, b] colours
|
|
269
331
|
// into zeros, strings into numbers and 300 into 44 without a word, so it must hold byte values.
|
|
270
332
|
if (Array.isArray(palette)) {
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
for (_iterator.s(); !(_step = _iterator.n()).done;) {
|
|
275
|
-
var value = _step.value;
|
|
276
|
-
if (!Number.isInteger(value) || value < 0 || value > 255) {
|
|
277
|
-
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');
|
|
278
|
-
}
|
|
333
|
+
for (const value of palette) {
|
|
334
|
+
if (!Number.isInteger(value) || value < 0 || value > 255) {
|
|
335
|
+
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');
|
|
279
336
|
}
|
|
280
|
-
} catch (err) {
|
|
281
|
-
_iterator.e(err);
|
|
282
|
-
} finally {
|
|
283
|
-
_iterator.f();
|
|
284
337
|
}
|
|
285
338
|
}
|
|
286
339
|
};
|
|
@@ -289,32 +342,34 @@ export var checkPalette = function checkPalette(palette) {
|
|
|
289
342
|
// A structured clone drops the tags (a palette's colour space with them), so palettes and clusterings cross to and from the
|
|
290
343
|
// worker thread as small markers and become typed arrays again on the other side: `mark` before posting (an argument, a
|
|
291
344
|
// result, or a property of a result), `revive` after receiving.
|
|
292
|
-
export
|
|
293
|
-
|
|
345
|
+
export const MARK = '__agglomerativeClustering';
|
|
346
|
+
const markOne = value => {
|
|
294
347
|
if (isPalette(value)) {
|
|
295
|
-
return
|
|
348
|
+
return {
|
|
349
|
+
[MARK]: 'palette',
|
|
350
|
+
bytes: new Uint8Array(value.buffer, value.byteOffset, value.length),
|
|
351
|
+
colorSpace: value.colorSpace
|
|
352
|
+
};
|
|
296
353
|
}
|
|
297
354
|
if (isClustering(value)) {
|
|
298
|
-
return
|
|
355
|
+
return {
|
|
356
|
+
[MARK]: 'clustering',
|
|
357
|
+
bytes: new Uint8Array(value.buffer, value.byteOffset, value.length)
|
|
358
|
+
};
|
|
299
359
|
}
|
|
300
360
|
return value;
|
|
301
361
|
};
|
|
302
|
-
export
|
|
303
|
-
if (!value ||
|
|
362
|
+
export const mark = value => {
|
|
363
|
+
if (!value || typeof value !== 'object' || ArrayBuffer.isView(value)) {
|
|
304
364
|
return markOne(value);
|
|
305
365
|
}
|
|
306
366
|
if (!isOptionsObject(value)) {
|
|
307
367
|
return value;
|
|
308
368
|
}
|
|
309
|
-
return Object.fromEntries(Object.entries(value).map(
|
|
310
|
-
var _ref4 = _slicedToArray(_ref3, 2),
|
|
311
|
-
key = _ref4[0],
|
|
312
|
-
part = _ref4[1];
|
|
313
|
-
return [key, markOne(part)];
|
|
314
|
-
}));
|
|
369
|
+
return Object.fromEntries(Object.entries(value).map(([key, part]) => [key, markOne(part)]));
|
|
315
370
|
};
|
|
316
|
-
|
|
317
|
-
if (!value ||
|
|
371
|
+
const reviveOne = value => {
|
|
372
|
+
if (!value || typeof value !== 'object' || !value[MARK]) {
|
|
318
373
|
return value;
|
|
319
374
|
}
|
|
320
375
|
if (value[MARK] === 'palette') {
|
|
@@ -322,8 +377,8 @@ var reviveOne = function reviveOne(value) {
|
|
|
322
377
|
}
|
|
323
378
|
return markClustering(new Uint8Array(value.bytes.buffer, value.bytes.byteOffset, value.bytes.length));
|
|
324
379
|
};
|
|
325
|
-
export
|
|
326
|
-
if (!value ||
|
|
380
|
+
export const revive = value => {
|
|
381
|
+
if (!value || typeof value !== 'object' || ArrayBuffer.isView(value)) {
|
|
327
382
|
return value;
|
|
328
383
|
}
|
|
329
384
|
if (value[MARK]) {
|
|
@@ -332,8 +387,7 @@ export var revive = function revive(value) {
|
|
|
332
387
|
if (!isOptionsObject(value)) {
|
|
333
388
|
return value;
|
|
334
389
|
}
|
|
335
|
-
for (
|
|
336
|
-
var key = _Object$keys[_i];
|
|
390
|
+
for (const key of Object.keys(value)) {
|
|
337
391
|
value[key] = reviveOne(value[key]);
|
|
338
392
|
}
|
|
339
393
|
return value;
|