agglomerative-clustering 4.0.0-beta.1 → 4.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 +5 -5
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +37 -63
- package/dist/index.d.cts +15 -76
- package/dist/index.d.ts +15 -76
- package/dist/index.mjs +36 -57
- package/dist/shared.cjs +73 -79
- package/dist/shared.mjs +68 -73
- package/dist/worker-thread.mjs +15 -18
- package/dist/worker.cjs +139 -84
- package/dist/worker.d.cts +0 -32
- package/dist/worker.d.ts +0 -32
- package/dist/worker.mjs +138 -78
- package/package.json +2 -2
package/dist/shared.cjs
CHANGED
|
@@ -6,14 +6,14 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
6
6
|
exports.Clustering = Clustering;
|
|
7
7
|
exports.MARK = void 0;
|
|
8
8
|
exports.Palette = Palette;
|
|
9
|
-
exports.
|
|
9
|
+
exports.version = exports.tooLarge = exports.sniffImageFormat = exports.snapshot = exports.sizeText = exports.setEngine = exports.revive = exports.readHeader = exports.parseDither = exports.maxBytes = exports.markPalette = exports.markClustering = exports.mark = exports.looksLikeRgb = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isImageData = exports.isDetached = exports.isCodedError = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageFormats = exports.imageDataLike = exports.imageCopy = exports.hasAlpha = exports.formatVersion = exports.formatNames = exports.formatHint = exports.fail = exports.errorCodes = exports.ditherSteps = exports.ditherMethods = exports.detachedError = exports.describe = exports.colorSpaces = exports.colorSpaceName = exports.colorSpaceCodes = exports.checkSize = exports.checkPalette = exports.checkImageObject = exports.checkImageKeys = exports.checkImageDataPixels = exports.checkImageBody = exports.channels = exports.bareLayout = exports.bareImageError = exports.alphaModes = void 0;
|
|
10
10
|
// Shared by both entries (index.js and worker.js) and the worker thread: errors, option snapshots, reading a clustering's
|
|
11
11
|
// header, the Palette and Clustering types, and the markers that carry those types across the worker boundary. Imported as
|
|
12
12
|
// './shared.js'; the build rewrites that to './shared.mjs' or './shared.cjs' (scripts/babel-import-extensions.cjs).
|
|
13
13
|
|
|
14
14
|
// The library's version: package.json is the source, and scripts/sync-version.mjs keeps this line (and the copy the .wasm
|
|
15
15
|
// is built from, src/version.hpp) in step with it. Do not edit it by hand.
|
|
16
|
-
const version = exports.version = '4.0.0-beta.
|
|
16
|
+
const version = exports.version = '4.0.0-beta.3';
|
|
17
17
|
const colorSpaceCodes = exports.colorSpaceCodes = {
|
|
18
18
|
'rgb': 0,
|
|
19
19
|
'oklab': 1
|
|
@@ -300,10 +300,52 @@ const checkImageObject = image => {
|
|
|
300
300
|
return checkPremultiplied(image);
|
|
301
301
|
};
|
|
302
302
|
|
|
303
|
+
// The image object's own fields, read once: `data`, `format`, `width`, `height` and `premultiplied` are taken from it here, and
|
|
304
|
+
// everything after (validation and use) reads the copy, so a getter that answers differently on a later read changes nothing.
|
|
305
|
+
// The copy also names the object's other own enumerable keys (with no value, never read), in order, for the unknown-key check.
|
|
306
|
+
// Anything that isn't an object with `data` and `format` is returned as it is (a bare array, ImageData, a function...), or, for
|
|
307
|
+
// an object without them, rejected here with the shape error the main entry gives.
|
|
308
|
+
exports.checkImageObject = checkImageObject;
|
|
309
|
+
const imageCopy = image => {
|
|
310
|
+
if (typeof image !== 'object' || image === null || ArrayBuffer.isView(image) || isImageData(image)) {
|
|
311
|
+
return image;
|
|
312
|
+
}
|
|
313
|
+
const data = image.data;
|
|
314
|
+
const format = image.format;
|
|
315
|
+
if (!data || !format) {
|
|
316
|
+
throw fail('invalid-argument', `Invalid image: expected object with \`data\` and \`format\`.${imageHint(image)}`, 'image');
|
|
317
|
+
}
|
|
318
|
+
const copy = Object.create(null);
|
|
319
|
+
copy.data = data;
|
|
320
|
+
copy.format = format;
|
|
321
|
+
copy.width = image.width;
|
|
322
|
+
copy.height = image.height;
|
|
323
|
+
copy.premultiplied = image.premultiplied;
|
|
324
|
+
for (const key of Object.keys(image)) {
|
|
325
|
+
if (!imageKeys.includes(key)) {
|
|
326
|
+
copy[key] = undefined;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
return copy;
|
|
330
|
+
};
|
|
331
|
+
|
|
332
|
+
// What the main entry's `load` checks about an image object, from the copy imageCopy made, in its order: data's type, whether its
|
|
333
|
+
// buffer is detached, then checkImageObject. The worker entry runs the same before it posts an image. Returns the premultiplied flag.
|
|
334
|
+
exports.imageCopy = imageCopy;
|
|
335
|
+
const checkImageBody = image => {
|
|
336
|
+
if (!isUint8Array(image.data) && !isUint8ClampedArray(image.data)) {
|
|
337
|
+
throw fail('invalid-argument', "Invalid image data: must be Uint8Array or Uint8ClampedArray.", 'image');
|
|
338
|
+
}
|
|
339
|
+
if (isDetached(image.data)) {
|
|
340
|
+
throw detachedError('data');
|
|
341
|
+
}
|
|
342
|
+
return checkImageObject(image);
|
|
343
|
+
};
|
|
344
|
+
|
|
303
345
|
// An options object is an ordinary object. A Map, Date, ArrayBuffer or typed array has no own keys and would pass as
|
|
304
346
|
// `{}`, silently ignoring what the caller meant. Checked by tag rather than prototype so objects from another realm
|
|
305
347
|
// (an iframe, a test sandbox) are fine.
|
|
306
|
-
exports.
|
|
348
|
+
exports.checkImageBody = checkImageBody;
|
|
307
349
|
const isOptionsObject = value => value !== null && typeof value === 'object' && Object.prototype.toString.call(value) === '[object Object]';
|
|
308
350
|
|
|
309
351
|
// One plain copy of an options object, taken once: every enumerable property, own or inherited (so options layered with
|
|
@@ -491,7 +533,7 @@ const sniffImageFormat = bytes => {
|
|
|
491
533
|
// The other common way to get a bare array wrong is bytes of another layout: RGB (sharp's plain .raw()), or grey and grey
|
|
492
534
|
// with alpha (fast-png's decode() of a grey PNG). Read as RGBA, every pixel takes bytes from its neighbours and one of them
|
|
493
535
|
// as its alpha, and nothing fails while the length divides by 4. They are never reinterpreted (a bare array is RGBA,
|
|
494
|
-
// PRINCIPLES), only reported
|
|
536
|
+
// PRINCIPLES), only reported, as an error (a warning in 3.x).
|
|
495
537
|
//
|
|
496
538
|
// The rules use E(k), the mean change between a byte and the one k before it (bench/spikes/bare-rgb/ and
|
|
497
539
|
// bench/spikes/bare-grey/: no false positives on 2,984 real RGBA images).
|
|
@@ -500,8 +542,8 @@ const sniffImageFormat = bytes => {
|
|
|
500
542
|
// but where it changes its bytes come in equal triples at a step of 3 and not of 4.
|
|
501
543
|
// - Grey and alpha (2 bytes a pixel): smooth at a step of 2 and rough at a step of 1, since grey and alpha bytes alternate.
|
|
502
544
|
// - Grey (1 byte a pixel): smoothest at a step of 1, unless most changing pixels have four equal bytes, which is real
|
|
503
|
-
// RGBA (grey with alpha = grey). The RGB rule goes first because near-grey RGB can look the same;
|
|
504
|
-
//
|
|
545
|
+
// RGBA (grey with alpha = grey). The RGB rule goes first because near-grey RGB can look the same; its error text
|
|
546
|
+
// covers grey too.
|
|
505
547
|
// Units equal to the one before are skipped by the equal-byte counts, since flat areas read the same either way. It
|
|
506
548
|
// samples 512 windows of 96 bytes (each on a multiple of 12, a pixel under every reading, one in each 512th of the
|
|
507
549
|
// array), so it costs about 0.35 ms at any size. Returns 'rgb', 'grey', 'grey-alpha' or null.
|
|
@@ -598,80 +640,28 @@ const bareLayout = d => {
|
|
|
598
640
|
exports.bareLayout = bareLayout;
|
|
599
641
|
const looksLikeRgb = d => bareLayout(d) === 'rgb';
|
|
600
642
|
|
|
601
|
-
//
|
|
643
|
+
// The error a bare image calls for, or null. It skips everything the main entry rejects for another reason (palettes and
|
|
644
|
+
// clusterings passed as the image, encoded files, lengths that aren't a multiple of 4), so a call never gives two
|
|
645
|
+
// errors for its image and both entries share this one order.
|
|
602
646
|
exports.looksLikeRgb = looksLikeRgb;
|
|
603
|
-
const
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
grey:
|
|
607
|
-
'grey-alpha': 'gray-as-rgba'
|
|
647
|
+
const bareText = {
|
|
648
|
+
rgb: n => `Invalid image: these ${n} bytes look like RGB (3 per pixel) or grey, not RGBA, and a bare Uint8Array is read as RGBA (4 per pixel). If it is RGB, pass { data, format: 'rgb' } (sharp's .raw() gives RGB for an image without alpha unless you add .ensureAlpha()). If it is grey (fast-png's decode() of a grey PNG), expand it to RGBA: format: 'rgb' would misread it too. If it really is RGBA, pass { data, format: 'rgba' } to say so.`,
|
|
649
|
+
grey: n => `Invalid image: these ${n} bytes look like grey (1 per pixel), not RGBA, and a bare Uint8Array is read as RGBA (4 per pixel). fast-png's decode() gives this for a grey PNG (rows below 8 bits stay packed) and for a palette PNG's indices. Expand 8-bit grey to RGBA, or decode with something that gives RGBA (pngjs, or sharp with .ensureAlpha()); there is no grey format to pass. If it really is RGBA, pass { data, format: 'rgba' } to say so.`,
|
|
650
|
+
'grey-alpha': n => `Invalid image: these ${n} bytes look like grey and alpha (2 per pixel), not RGBA, and a bare Uint8Array is read as RGBA (4 per pixel). fast-png's decode() gives this for a grey PNG with alpha. Expand it to RGBA, or decode with something that gives RGBA (pngjs, or sharp with .ensureAlpha()); there is no grey format to pass. If it really is RGBA, pass { data, format: 'rgba' } to say so.`
|
|
608
651
|
};
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
// and clusterings passed as the image, encoded files, lengths that aren't a multiple of 4), so a call never both warns
|
|
612
|
-
// about its image and rejects it, and both entries share this one order. An array of one layout never takes another's
|
|
613
|
-
// code because its own was already used: it is classified first, and only then is its code checked.
|
|
614
|
-
const bareImageWarning = image => {
|
|
615
|
-
if (warned.has('rgb-as-rgba') && warned.has('gray-as-rgba') || !isUint8Array(image) || isPalette(image) || isClustering(image)) {
|
|
652
|
+
const bareImageError = image => {
|
|
653
|
+
if (!isUint8Array(image) || isPalette(image) || isClustering(image)) {
|
|
616
654
|
return null;
|
|
617
655
|
}
|
|
618
656
|
if (sniffImageFormat(image) !== null || image.length % 4 !== 0) {
|
|
619
657
|
return null;
|
|
620
658
|
}
|
|
621
659
|
const layout = bareLayout(image);
|
|
622
|
-
return layout === null
|
|
623
|
-
code: bareCodes[layout],
|
|
624
|
-
layout
|
|
625
|
-
};
|
|
626
|
-
};
|
|
627
|
-
|
|
628
|
-
// The text of each warning. Delivered through process.emitWarning in Node, Bun and Deno (--no-warnings,
|
|
629
|
-
// process.on('warning') and --trace-warnings then work), else console.warn. Runtimes that imitate Node have an
|
|
630
|
-
// emitWarning that may print nothing (Cloudflare Workers with nodejs_compat), so they are told apart by
|
|
631
|
-
// navigator.userAgent, as worker.js does; a bundler's `process` polyfill has no emitWarning, and `globalThis.process`
|
|
632
|
-
// keeps Parcel from adding one.
|
|
633
|
-
exports.bareImageWarning = bareImageWarning;
|
|
634
|
-
const nodeLike = () => typeof navigator === 'undefined' || /^(Node\.js|Bun|Deno)\//.test(String(navigator.userAgent));
|
|
635
|
-
const warningText = {
|
|
636
|
-
'rgb-as-rgba': byteLength => `This image (${byteLength.toLocaleString('en-US')} bytes) looks like RGB bytes (3 per pixel), or grey, passed as a bare Uint8Array, which is read as RGBA (4 per pixel) and would give wrong colours. If it is RGB, pass { data, format: 'rgb' } (sharp's .raw() gives RGB for an image without alpha unless you add .ensureAlpha()). If it is grey (fast-png's decode() of a grey PNG), expand it to RGBA; format: 'rgb' would misread it too. If it really is RGBA, pass { data, format: 'rgba' } to say so. From 4.0 this is an error. Shown once.`,
|
|
637
|
-
'gray-as-rgba': (byteLength, layout) => (layout === 'grey-alpha' ? `This image (${byteLength.toLocaleString('en-US')} bytes) looks like grey and alpha bytes (2 per pixel) passed as a bare Uint8Array, which is read as RGBA (4 per pixel) and would give wrong colours. fast-png's decode() gives this for a grey PNG with alpha.` : `This image (${byteLength.toLocaleString('en-US')} bytes) looks like grey bytes (1 per pixel) passed as a bare Uint8Array, which is read as RGBA (4 per pixel) and would give wrong colours. fast-png's decode() gives this for a grey PNG (rows below 8 bits stay packed) and for a palette PNG's indices.`) + ` Expand ${layout === 'grey-alpha' ? 'it' : '8-bit grey'} to RGBA, or decode with something that gives RGBA (pngjs, or sharp with .ensureAlpha()). There is no grey format to pass. If it really is RGBA, pass { data, format: 'rgba' } to say so. From 4.0 this is an error. Shown once.`
|
|
638
|
-
};
|
|
639
|
-
// `warning` is what bareImageWarning returned: {code, layout}.
|
|
640
|
-
const warnOnce = ({
|
|
641
|
-
code,
|
|
642
|
-
layout
|
|
643
|
-
}, byteLength) => {
|
|
644
|
-
if (warned.has(code)) {
|
|
645
|
-
return;
|
|
646
|
-
}
|
|
647
|
-
warned.add(code);
|
|
648
|
-
const message = warningText[code](byteLength, layout);
|
|
649
|
-
const runtime = globalThis.process;
|
|
650
|
-
if (runtime && typeof runtime.emitWarning === 'function' && nodeLike()) {
|
|
651
|
-
runtime.emitWarning(message, {
|
|
652
|
-
type: 'AgglomerativeClusteringWarning',
|
|
653
|
-
code
|
|
654
|
-
});
|
|
655
|
-
} else if (typeof console !== 'undefined') {
|
|
656
|
-
console.warn(`agglomerative-clustering [${code}]: ${message}`);
|
|
657
|
-
}
|
|
658
|
-
};
|
|
659
|
-
// The worker thread's copy: its caller's side checks and warns (PRINCIPLES), so here every code counts as warned, which
|
|
660
|
-
// also skips the sampling.
|
|
661
|
-
exports.warnOnce = warnOnce;
|
|
662
|
-
const silenceWarnings = () => {
|
|
663
|
-
for (const code of Object.keys(warningText)) {
|
|
664
|
-
warned.add(code);
|
|
665
|
-
}
|
|
666
|
-
};
|
|
667
|
-
// For tests.
|
|
668
|
-
exports.silenceWarnings = silenceWarnings;
|
|
669
|
-
const resetWarnings = () => {
|
|
670
|
-
warned.clear();
|
|
660
|
+
return layout === null ? null : fail('invalid-argument', bareText[layout](image.byteLength.toLocaleString('en-US')), 'image');
|
|
671
661
|
};
|
|
672
662
|
// Node's console.log and util.inspect call this (other environments ignore it), so the tag shows when debugging:
|
|
673
663
|
// `Palette(oklab) [ 12, 34, ... ]` rather than a plain `Uint8Array(…)`.
|
|
674
|
-
exports.
|
|
664
|
+
exports.bareImageError = bareImageError;
|
|
675
665
|
const inspect = Symbol.for('nodejs.util.inspect.custom');
|
|
676
666
|
const view = label => function (depth, options, nodeInspect) {
|
|
677
667
|
const plain = new Uint8Array(this.buffer, this.byteOffset, this.length);
|
|
@@ -691,7 +681,7 @@ const markPalette = (bytes, colorSpace) => {
|
|
|
691
681
|
});
|
|
692
682
|
return bytes;
|
|
693
683
|
};
|
|
694
|
-
// Methods on a clustering: `clustering.getPalette(k)`
|
|
684
|
+
// Methods on a clustering: `clustering.getPalette(k)` cuts a palette from it, and so on. They are
|
|
695
685
|
// non-enumerable own properties, added with the tags, so a clustering stays a plain Uint8Array (`toEqual` and
|
|
696
686
|
// `deepStrictEqual` against plain bytes still pass), and slices and clones drop them as they drop the tags. They run on the
|
|
697
687
|
// calling thread with the main entry's functions, which the main entry puts in `engine` when it is evaluated; the worker
|
|
@@ -706,14 +696,14 @@ const setEngine = value => {
|
|
|
706
696
|
engine = value;
|
|
707
697
|
}
|
|
708
698
|
};
|
|
709
|
-
// Each method's call shape and
|
|
699
|
+
// Each method's call shape and the loaded-handle form that serves it off the thread, for messages.
|
|
710
700
|
exports.setEngine = setEngine;
|
|
711
701
|
const methodNames = {
|
|
712
|
-
getPalette: ['getPalette(k)', '
|
|
713
|
-
getSwatches: ['getSwatches(k)', '
|
|
714
|
-
getClusteringInfo: ['getClusteringInfo()', 'getClusteringInfo(clustering)
|
|
715
|
-
quantize: ['quantize(image, k)', '
|
|
716
|
-
quantizeToIndices: ['quantizeToIndices(image, k)', '
|
|
702
|
+
getPalette: ['getPalette(k)', "a loaded handle's getPalette: (await worker.load(clustering)).getPalette(k)"],
|
|
703
|
+
getSwatches: ['getSwatches(k)', "a loaded handle's getSwatches: (await worker.load(clustering)).getSwatches(k)"],
|
|
704
|
+
getClusteringInfo: ['getClusteringInfo()', "a loaded handle's getClusteringInfo: (await worker.load(clustering)).getClusteringInfo()"],
|
|
705
|
+
quantize: ['quantize(image, k)', "a loaded handle's quantize: (await worker.load(clustering)).quantize(image, k)"],
|
|
706
|
+
quantizeToIndices: ['quantizeToIndices(image, k)', "a loaded handle's quantizeToIndices: (await worker.load(clustering)).quantizeToIndices(image, k)"],
|
|
717
707
|
chooseFrom: ['chooseFrom(palette, k, options?)', "a loaded handle's chooseFrom: (await worker.load(clustering)).chooseFrom(palette, k)"]
|
|
718
708
|
};
|
|
719
709
|
// Checks the receiver before anything else, since it is written first, then (for the mapping methods) that the image isn't
|
|
@@ -837,6 +827,10 @@ Object.defineProperty(Palette, Symbol.hasInstance, {
|
|
|
837
827
|
// those of a Uint8Array (bytes to copy, or a buffer with an offset and length to view).
|
|
838
828
|
function Clustering(...args) {
|
|
839
829
|
const [source] = args;
|
|
830
|
+
// A palette gets the same hint as from every other function, before its bytes are copied.
|
|
831
|
+
if (isPalette(source)) {
|
|
832
|
+
readHeader(source);
|
|
833
|
+
}
|
|
840
834
|
// Bytes, or a buffer to view: never a number (a length would allocate and make an empty clustering) or anything a Uint8Array
|
|
841
835
|
// would coerce. A plain array must hold byte values, as for a palette.
|
|
842
836
|
const isBuffer = isArrayBufferLike(source);
|
|
@@ -936,7 +930,7 @@ const notAClustering = clustering => {
|
|
|
936
930
|
};
|
|
937
931
|
const readHeader = clustering => {
|
|
938
932
|
if (isPalette(clustering)) {
|
|
939
|
-
throw fail('invalid-clustering', "Invalid clustering: this is a palette, not a clustering. Palettes come from buildPalette
|
|
933
|
+
throw fail('invalid-clustering', "Invalid clustering: this is a palette, not a clustering. Palettes come from buildPalette or clustering.getPalette(k); a clustering comes from buildClustering.", 'clustering');
|
|
940
934
|
}
|
|
941
935
|
if (!isUint8Array(clustering)) {
|
|
942
936
|
throw fail('invalid-clustering', "Invalid clustering: must be a Uint8Array from buildClustering.", 'clustering');
|
|
@@ -998,12 +992,12 @@ const readHeader = clustering => {
|
|
|
998
992
|
throw notAClustering(clustering);
|
|
999
993
|
};
|
|
1000
994
|
|
|
1001
|
-
// Palettes are flat RGB bytes. An empty palette is allowed: it is what
|
|
995
|
+
// Palettes are flat RGB bytes. An empty palette is allowed: it is what buildPalette gives for a fully transparent
|
|
1002
996
|
// image, and quantize maps such an image the same way.
|
|
1003
997
|
exports.readHeader = readHeader;
|
|
1004
998
|
const checkPalette = palette => {
|
|
1005
999
|
if (isClustering(palette)) {
|
|
1006
|
-
throw fail('invalid-argument', "Invalid palette: this is a clustering (from buildClustering), not a palette. Cut a palette from it with
|
|
1000
|
+
throw fail('invalid-argument', "Invalid palette: this is a clustering (from buildClustering), not a palette. Cut a palette from it with clustering.getPalette(k), or map with clustering.quantize(image, k).", 'palette');
|
|
1007
1001
|
}
|
|
1008
1002
|
if (!isUint8Array(palette) && !isUint8ClampedArray(palette) && !Array.isArray(palette)) {
|
|
1009
1003
|
throw fail('invalid-argument', "Invalid palette: must be a Uint8Array of RGB bytes.", 'palette');
|
package/dist/shared.mjs
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
// The library's version: package.json is the source, and scripts/sync-version.mjs keeps this line (and the copy the .wasm
|
|
6
6
|
// is built from, src/version.hpp) in step with it. Do not edit it by hand.
|
|
7
|
-
export const version = '4.0.0-beta.
|
|
7
|
+
export const version = '4.0.0-beta.3';
|
|
8
8
|
export const colorSpaceCodes = {
|
|
9
9
|
'rgb': 0,
|
|
10
10
|
'oklab': 1
|
|
@@ -272,6 +272,46 @@ export const checkImageObject = image => {
|
|
|
272
272
|
return checkPremultiplied(image);
|
|
273
273
|
};
|
|
274
274
|
|
|
275
|
+
// The image object's own fields, read once: `data`, `format`, `width`, `height` and `premultiplied` are taken from it here, and
|
|
276
|
+
// everything after (validation and use) reads the copy, so a getter that answers differently on a later read changes nothing.
|
|
277
|
+
// The copy also names the object's other own enumerable keys (with no value, never read), in order, for the unknown-key check.
|
|
278
|
+
// Anything that isn't an object with `data` and `format` is returned as it is (a bare array, ImageData, a function...), or, for
|
|
279
|
+
// an object without them, rejected here with the shape error the main entry gives.
|
|
280
|
+
export const imageCopy = image => {
|
|
281
|
+
if (typeof image !== 'object' || image === null || ArrayBuffer.isView(image) || isImageData(image)) {
|
|
282
|
+
return image;
|
|
283
|
+
}
|
|
284
|
+
const data = image.data;
|
|
285
|
+
const format = image.format;
|
|
286
|
+
if (!data || !format) {
|
|
287
|
+
throw fail('invalid-argument', `Invalid image: expected object with \`data\` and \`format\`.${imageHint(image)}`, 'image');
|
|
288
|
+
}
|
|
289
|
+
const copy = Object.create(null);
|
|
290
|
+
copy.data = data;
|
|
291
|
+
copy.format = format;
|
|
292
|
+
copy.width = image.width;
|
|
293
|
+
copy.height = image.height;
|
|
294
|
+
copy.premultiplied = image.premultiplied;
|
|
295
|
+
for (const key of Object.keys(image)) {
|
|
296
|
+
if (!imageKeys.includes(key)) {
|
|
297
|
+
copy[key] = undefined;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
return copy;
|
|
301
|
+
};
|
|
302
|
+
|
|
303
|
+
// What the main entry's `load` checks about an image object, from the copy imageCopy made, in its order: data's type, whether its
|
|
304
|
+
// buffer is detached, then checkImageObject. The worker entry runs the same before it posts an image. Returns the premultiplied flag.
|
|
305
|
+
export const checkImageBody = image => {
|
|
306
|
+
if (!isUint8Array(image.data) && !isUint8ClampedArray(image.data)) {
|
|
307
|
+
throw fail('invalid-argument', "Invalid image data: must be Uint8Array or Uint8ClampedArray.", 'image');
|
|
308
|
+
}
|
|
309
|
+
if (isDetached(image.data)) {
|
|
310
|
+
throw detachedError('data');
|
|
311
|
+
}
|
|
312
|
+
return checkImageObject(image);
|
|
313
|
+
};
|
|
314
|
+
|
|
275
315
|
// An options object is an ordinary object. A Map, Date, ArrayBuffer or typed array has no own keys and would pass as
|
|
276
316
|
// `{}`, silently ignoring what the caller meant. Checked by tag rather than prototype so objects from another realm
|
|
277
317
|
// (an iframe, a test sandbox) are fine.
|
|
@@ -456,7 +496,7 @@ export const sniffImageFormat = bytes => {
|
|
|
456
496
|
// The other common way to get a bare array wrong is bytes of another layout: RGB (sharp's plain .raw()), or grey and grey
|
|
457
497
|
// with alpha (fast-png's decode() of a grey PNG). Read as RGBA, every pixel takes bytes from its neighbours and one of them
|
|
458
498
|
// as its alpha, and nothing fails while the length divides by 4. They are never reinterpreted (a bare array is RGBA,
|
|
459
|
-
// PRINCIPLES), only reported
|
|
499
|
+
// PRINCIPLES), only reported, as an error (a warning in 3.x).
|
|
460
500
|
//
|
|
461
501
|
// The rules use E(k), the mean change between a byte and the one k before it (bench/spikes/bare-rgb/ and
|
|
462
502
|
// bench/spikes/bare-grey/: no false positives on 2,984 real RGBA images).
|
|
@@ -465,8 +505,8 @@ export const sniffImageFormat = bytes => {
|
|
|
465
505
|
// but where it changes its bytes come in equal triples at a step of 3 and not of 4.
|
|
466
506
|
// - Grey and alpha (2 bytes a pixel): smooth at a step of 2 and rough at a step of 1, since grey and alpha bytes alternate.
|
|
467
507
|
// - Grey (1 byte a pixel): smoothest at a step of 1, unless most changing pixels have four equal bytes, which is real
|
|
468
|
-
// RGBA (grey with alpha = grey). The RGB rule goes first because near-grey RGB can look the same;
|
|
469
|
-
//
|
|
508
|
+
// RGBA (grey with alpha = grey). The RGB rule goes first because near-grey RGB can look the same; its error text
|
|
509
|
+
// covers grey too.
|
|
470
510
|
// Units equal to the one before are skipped by the equal-byte counts, since flat areas read the same either way. It
|
|
471
511
|
// samples 512 windows of 96 bytes (each on a multiple of 12, a pixel under every reading, one in each 512th of the
|
|
472
512
|
// array), so it costs about 0.35 ms at any size. Returns 'rgb', 'grey', 'grey-alpha' or null.
|
|
@@ -561,72 +601,23 @@ export const bareLayout = d => {
|
|
|
561
601
|
};
|
|
562
602
|
export const looksLikeRgb = d => bareLayout(d) === 'rgb';
|
|
563
603
|
|
|
564
|
-
//
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
grey: '
|
|
569
|
-
'grey-
|
|
604
|
+
// The error a bare image calls for, or null. It skips everything the main entry rejects for another reason (palettes and
|
|
605
|
+
// clusterings passed as the image, encoded files, lengths that aren't a multiple of 4), so a call never gives two
|
|
606
|
+
// errors for its image and both entries share this one order.
|
|
607
|
+
const bareText = {
|
|
608
|
+
rgb: n => `Invalid image: these ${n} bytes look like RGB (3 per pixel) or grey, not RGBA, and a bare Uint8Array is read as RGBA (4 per pixel). If it is RGB, pass { data, format: 'rgb' } (sharp's .raw() gives RGB for an image without alpha unless you add .ensureAlpha()). If it is grey (fast-png's decode() of a grey PNG), expand it to RGBA: format: 'rgb' would misread it too. If it really is RGBA, pass { data, format: 'rgba' } to say so.`,
|
|
609
|
+
grey: n => `Invalid image: these ${n} bytes look like grey (1 per pixel), not RGBA, and a bare Uint8Array is read as RGBA (4 per pixel). fast-png's decode() gives this for a grey PNG (rows below 8 bits stay packed) and for a palette PNG's indices. Expand 8-bit grey to RGBA, or decode with something that gives RGBA (pngjs, or sharp with .ensureAlpha()); there is no grey format to pass. If it really is RGBA, pass { data, format: 'rgba' } to say so.`,
|
|
610
|
+
'grey-alpha': n => `Invalid image: these ${n} bytes look like grey and alpha (2 per pixel), not RGBA, and a bare Uint8Array is read as RGBA (4 per pixel). fast-png's decode() gives this for a grey PNG with alpha. Expand it to RGBA, or decode with something that gives RGBA (pngjs, or sharp with .ensureAlpha()); there is no grey format to pass. If it really is RGBA, pass { data, format: 'rgba' } to say so.`
|
|
570
611
|
};
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
// and clusterings passed as the image, encoded files, lengths that aren't a multiple of 4), so a call never both warns
|
|
574
|
-
// about its image and rejects it, and both entries share this one order. An array of one layout never takes another's
|
|
575
|
-
// code because its own was already used: it is classified first, and only then is its code checked.
|
|
576
|
-
export const bareImageWarning = image => {
|
|
577
|
-
if (warned.has('rgb-as-rgba') && warned.has('gray-as-rgba') || !isUint8Array(image) || isPalette(image) || isClustering(image)) {
|
|
612
|
+
export const bareImageError = image => {
|
|
613
|
+
if (!isUint8Array(image) || isPalette(image) || isClustering(image)) {
|
|
578
614
|
return null;
|
|
579
615
|
}
|
|
580
616
|
if (sniffImageFormat(image) !== null || image.length % 4 !== 0) {
|
|
581
617
|
return null;
|
|
582
618
|
}
|
|
583
619
|
const layout = bareLayout(image);
|
|
584
|
-
return layout === null
|
|
585
|
-
code: bareCodes[layout],
|
|
586
|
-
layout
|
|
587
|
-
};
|
|
588
|
-
};
|
|
589
|
-
|
|
590
|
-
// The text of each warning. Delivered through process.emitWarning in Node, Bun and Deno (--no-warnings,
|
|
591
|
-
// process.on('warning') and --trace-warnings then work), else console.warn. Runtimes that imitate Node have an
|
|
592
|
-
// emitWarning that may print nothing (Cloudflare Workers with nodejs_compat), so they are told apart by
|
|
593
|
-
// navigator.userAgent, as worker.js does; a bundler's `process` polyfill has no emitWarning, and `globalThis.process`
|
|
594
|
-
// keeps Parcel from adding one.
|
|
595
|
-
const nodeLike = () => typeof navigator === 'undefined' || /^(Node\.js|Bun|Deno)\//.test(String(navigator.userAgent));
|
|
596
|
-
const warningText = {
|
|
597
|
-
'rgb-as-rgba': byteLength => `This image (${byteLength.toLocaleString('en-US')} bytes) looks like RGB bytes (3 per pixel), or grey, passed as a bare Uint8Array, which is read as RGBA (4 per pixel) and would give wrong colours. If it is RGB, pass { data, format: 'rgb' } (sharp's .raw() gives RGB for an image without alpha unless you add .ensureAlpha()). If it is grey (fast-png's decode() of a grey PNG), expand it to RGBA; format: 'rgb' would misread it too. If it really is RGBA, pass { data, format: 'rgba' } to say so. From 4.0 this is an error. Shown once.`,
|
|
598
|
-
'gray-as-rgba': (byteLength, layout) => (layout === 'grey-alpha' ? `This image (${byteLength.toLocaleString('en-US')} bytes) looks like grey and alpha bytes (2 per pixel) passed as a bare Uint8Array, which is read as RGBA (4 per pixel) and would give wrong colours. fast-png's decode() gives this for a grey PNG with alpha.` : `This image (${byteLength.toLocaleString('en-US')} bytes) looks like grey bytes (1 per pixel) passed as a bare Uint8Array, which is read as RGBA (4 per pixel) and would give wrong colours. fast-png's decode() gives this for a grey PNG (rows below 8 bits stay packed) and for a palette PNG's indices.`) + ` Expand ${layout === 'grey-alpha' ? 'it' : '8-bit grey'} to RGBA, or decode with something that gives RGBA (pngjs, or sharp with .ensureAlpha()). There is no grey format to pass. If it really is RGBA, pass { data, format: 'rgba' } to say so. From 4.0 this is an error. Shown once.`
|
|
599
|
-
};
|
|
600
|
-
// `warning` is what bareImageWarning returned: {code, layout}.
|
|
601
|
-
export const warnOnce = ({
|
|
602
|
-
code,
|
|
603
|
-
layout
|
|
604
|
-
}, byteLength) => {
|
|
605
|
-
if (warned.has(code)) {
|
|
606
|
-
return;
|
|
607
|
-
}
|
|
608
|
-
warned.add(code);
|
|
609
|
-
const message = warningText[code](byteLength, layout);
|
|
610
|
-
const runtime = globalThis.process;
|
|
611
|
-
if (runtime && typeof runtime.emitWarning === 'function' && nodeLike()) {
|
|
612
|
-
runtime.emitWarning(message, {
|
|
613
|
-
type: 'AgglomerativeClusteringWarning',
|
|
614
|
-
code
|
|
615
|
-
});
|
|
616
|
-
} else if (typeof console !== 'undefined') {
|
|
617
|
-
console.warn(`agglomerative-clustering [${code}]: ${message}`);
|
|
618
|
-
}
|
|
619
|
-
};
|
|
620
|
-
// The worker thread's copy: its caller's side checks and warns (PRINCIPLES), so here every code counts as warned, which
|
|
621
|
-
// also skips the sampling.
|
|
622
|
-
export const silenceWarnings = () => {
|
|
623
|
-
for (const code of Object.keys(warningText)) {
|
|
624
|
-
warned.add(code);
|
|
625
|
-
}
|
|
626
|
-
};
|
|
627
|
-
// For tests.
|
|
628
|
-
export const resetWarnings = () => {
|
|
629
|
-
warned.clear();
|
|
620
|
+
return layout === null ? null : fail('invalid-argument', bareText[layout](image.byteLength.toLocaleString('en-US')), 'image');
|
|
630
621
|
};
|
|
631
622
|
// Node's console.log and util.inspect call this (other environments ignore it), so the tag shows when debugging:
|
|
632
623
|
// `Palette(oklab) [ 12, 34, ... ]` rather than a plain `Uint8Array(…)`.
|
|
@@ -649,7 +640,7 @@ export const markPalette = (bytes, colorSpace) => {
|
|
|
649
640
|
});
|
|
650
641
|
return bytes;
|
|
651
642
|
};
|
|
652
|
-
// Methods on a clustering: `clustering.getPalette(k)`
|
|
643
|
+
// Methods on a clustering: `clustering.getPalette(k)` cuts a palette from it, and so on. They are
|
|
653
644
|
// non-enumerable own properties, added with the tags, so a clustering stays a plain Uint8Array (`toEqual` and
|
|
654
645
|
// `deepStrictEqual` against plain bytes still pass), and slices and clones drop them as they drop the tags. They run on the
|
|
655
646
|
// calling thread with the main entry's functions, which the main entry puts in `engine` when it is evaluated; the worker
|
|
@@ -663,13 +654,13 @@ export const setEngine = value => {
|
|
|
663
654
|
engine = value;
|
|
664
655
|
}
|
|
665
656
|
};
|
|
666
|
-
// Each method's call shape and
|
|
657
|
+
// Each method's call shape and the loaded-handle form that serves it off the thread, for messages.
|
|
667
658
|
const methodNames = {
|
|
668
|
-
getPalette: ['getPalette(k)', '
|
|
669
|
-
getSwatches: ['getSwatches(k)', '
|
|
670
|
-
getClusteringInfo: ['getClusteringInfo()', 'getClusteringInfo(clustering)
|
|
671
|
-
quantize: ['quantize(image, k)', '
|
|
672
|
-
quantizeToIndices: ['quantizeToIndices(image, k)', '
|
|
659
|
+
getPalette: ['getPalette(k)', "a loaded handle's getPalette: (await worker.load(clustering)).getPalette(k)"],
|
|
660
|
+
getSwatches: ['getSwatches(k)', "a loaded handle's getSwatches: (await worker.load(clustering)).getSwatches(k)"],
|
|
661
|
+
getClusteringInfo: ['getClusteringInfo()', "a loaded handle's getClusteringInfo: (await worker.load(clustering)).getClusteringInfo()"],
|
|
662
|
+
quantize: ['quantize(image, k)', "a loaded handle's quantize: (await worker.load(clustering)).quantize(image, k)"],
|
|
663
|
+
quantizeToIndices: ['quantizeToIndices(image, k)', "a loaded handle's quantizeToIndices: (await worker.load(clustering)).quantizeToIndices(image, k)"],
|
|
673
664
|
chooseFrom: ['chooseFrom(palette, k, options?)', "a loaded handle's chooseFrom: (await worker.load(clustering)).chooseFrom(palette, k)"]
|
|
674
665
|
};
|
|
675
666
|
// Checks the receiver before anything else, since it is written first, then (for the mapping methods) that the image isn't
|
|
@@ -792,6 +783,10 @@ Object.defineProperty(Palette, Symbol.hasInstance, {
|
|
|
792
783
|
// those of a Uint8Array (bytes to copy, or a buffer with an offset and length to view).
|
|
793
784
|
export function Clustering(...args) {
|
|
794
785
|
const [source] = args;
|
|
786
|
+
// A palette gets the same hint as from every other function, before its bytes are copied.
|
|
787
|
+
if (isPalette(source)) {
|
|
788
|
+
readHeader(source);
|
|
789
|
+
}
|
|
795
790
|
// Bytes, or a buffer to view: never a number (a length would allocate and make an empty clustering) or anything a Uint8Array
|
|
796
791
|
// would coerce. A plain array must hold byte values, as for a palette.
|
|
797
792
|
const isBuffer = isArrayBufferLike(source);
|
|
@@ -891,7 +886,7 @@ const notAClustering = clustering => {
|
|
|
891
886
|
};
|
|
892
887
|
export const readHeader = clustering => {
|
|
893
888
|
if (isPalette(clustering)) {
|
|
894
|
-
throw fail('invalid-clustering', "Invalid clustering: this is a palette, not a clustering. Palettes come from buildPalette
|
|
889
|
+
throw fail('invalid-clustering', "Invalid clustering: this is a palette, not a clustering. Palettes come from buildPalette or clustering.getPalette(k); a clustering comes from buildClustering.", 'clustering');
|
|
895
890
|
}
|
|
896
891
|
if (!isUint8Array(clustering)) {
|
|
897
892
|
throw fail('invalid-clustering', "Invalid clustering: must be a Uint8Array from buildClustering.", 'clustering');
|
|
@@ -953,11 +948,11 @@ export const readHeader = clustering => {
|
|
|
953
948
|
throw notAClustering(clustering);
|
|
954
949
|
};
|
|
955
950
|
|
|
956
|
-
// Palettes are flat RGB bytes. An empty palette is allowed: it is what
|
|
951
|
+
// Palettes are flat RGB bytes. An empty palette is allowed: it is what buildPalette gives for a fully transparent
|
|
957
952
|
// image, and quantize maps such an image the same way.
|
|
958
953
|
export const checkPalette = palette => {
|
|
959
954
|
if (isClustering(palette)) {
|
|
960
|
-
throw fail('invalid-argument', "Invalid palette: this is a clustering (from buildClustering), not a palette. Cut a palette from it with
|
|
955
|
+
throw fail('invalid-argument', "Invalid palette: this is a clustering (from buildClustering), not a palette. Cut a palette from it with clustering.getPalette(k), or map with clustering.quantize(image, k).", 'palette');
|
|
961
956
|
}
|
|
962
957
|
if (!isUint8Array(palette) && !isUint8ClampedArray(palette) && !Array.isArray(palette)) {
|
|
963
958
|
throw fail('invalid-argument', "Invalid palette: must be a Uint8Array of RGB bytes.", 'palette');
|
package/dist/worker-thread.mjs
CHANGED
|
@@ -1,10 +1,7 @@
|
|
|
1
1
|
// Runs inside the worker started by worker.js: receives calls, runs them with the main entry, and posts results
|
|
2
2
|
// back, transferring every result buffer. Imports `./index.mjs`, which exists only in dist/ (like clustering.js).
|
|
3
3
|
import * as ac from './index.mjs';
|
|
4
|
-
import { MARK, mark, revive, isPalette
|
|
5
|
-
|
|
6
|
-
// The caller's side checks for warnings and gives them (PRINCIPLES "Warnings"), so this copy stays quiet.
|
|
7
|
-
silenceWarnings();
|
|
4
|
+
import { version, MARK, mark, revive, isPalette } from "./shared.mjs";
|
|
8
5
|
|
|
9
6
|
// Images kept in the worker by `cluster`, with their clusterings, and clusterings alone from `load`, by handle id.
|
|
10
7
|
const handles = new Map();
|
|
@@ -31,7 +28,7 @@ const inClusteringSpace = async (id, options, palette) => {
|
|
|
31
28
|
}
|
|
32
29
|
const {
|
|
33
30
|
colorSpace
|
|
34
|
-
} = await
|
|
31
|
+
} = await handle(id).clustering.getClusteringInfo();
|
|
35
32
|
return {
|
|
36
33
|
...options,
|
|
37
34
|
colorSpace: options && options.colorSpace !== undefined ? options.colorSpace : colorSpace
|
|
@@ -44,10 +41,12 @@ const inClusteringSpace = async (id, options, palette) => {
|
|
|
44
41
|
const functions = Object.fromEntries(Object.entries(ac).filter(([name, value]) => typeof value === 'function' && !/^[A-Z]/.test(name)));
|
|
45
42
|
const methods = {
|
|
46
43
|
...functions,
|
|
44
|
+
// The first message every worker entry sends: which version this script is.
|
|
45
|
+
handshake: async () => version,
|
|
47
46
|
cluster: async (id, image, options) => {
|
|
48
47
|
handles.set(id, {
|
|
49
48
|
image,
|
|
50
|
-
clustering: await ac.
|
|
49
|
+
clustering: await ac.buildClustering(image, options)
|
|
51
50
|
});
|
|
52
51
|
},
|
|
53
52
|
load: async (id, clustering) => {
|
|
@@ -59,14 +58,14 @@ const methods = {
|
|
|
59
58
|
handles.delete(id);
|
|
60
59
|
},
|
|
61
60
|
handleGetClustering: async id => new ac.Clustering(handle(id).clustering),
|
|
62
|
-
handleGetPalette: async (id, k) =>
|
|
63
|
-
handleGetSwatches: async (id, k) =>
|
|
64
|
-
handleGetClusteringInfo: async id =>
|
|
61
|
+
handleGetPalette: async (id, k) => handle(id).clustering.getPalette(k),
|
|
62
|
+
handleGetSwatches: async (id, k) => handle(id).clustering.getSwatches(k),
|
|
63
|
+
handleGetClusteringInfo: async id => handle(id).clustering.getClusteringInfo(),
|
|
65
64
|
handleChooseFrom: async (id, palette, k, options) => handle(id).clustering.chooseFrom(palette, k, options),
|
|
66
|
-
handleQuantize: async (id, k, options) =>
|
|
67
|
-
handleQuantizeToIndices: async (id, k, options) =>
|
|
68
|
-
handleQuantizeImage: async (id, image, k, options) =>
|
|
69
|
-
handleQuantizeToIndicesImage: async (id, image, k, options) =>
|
|
65
|
+
handleQuantize: async (id, k, options) => handle(id).clustering.quantize(handle(id).image, k, options),
|
|
66
|
+
handleQuantizeToIndices: async (id, k, options) => handle(id).clustering.quantizeToIndices(handle(id).image, k, options),
|
|
67
|
+
handleQuantizeImage: async (id, image, k, options) => handle(id).clustering.quantize(image, k, options),
|
|
68
|
+
handleQuantizeToIndicesImage: async (id, image, k, options) => handle(id).clustering.quantizeToIndices(image, k, options),
|
|
70
69
|
handleQuantizeWithPalette: async (id, palette, options) => ac.quantizeWithPalette(handle(id).image, palette, await inClusteringSpace(id, options, palette)),
|
|
71
70
|
handleQuantizeToIndicesWithPalette: async (id, palette, options) => ac.quantizeToIndicesWithPalette(handle(id).image, palette, await inClusteringSpace(id, options, palette))
|
|
72
71
|
};
|
|
@@ -87,14 +86,12 @@ const buffers = value => {
|
|
|
87
86
|
|
|
88
87
|
// Where the options sit among each method's arguments, to give them the call's signal and progress callback.
|
|
89
88
|
const optionsIndex = {
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
89
|
+
buildClustering: 1,
|
|
90
|
+
buildPalette: 2,
|
|
91
|
+
buildSwatches: 2,
|
|
93
92
|
quantize: 2,
|
|
94
|
-
quantizeFromClustering: 3,
|
|
95
93
|
quantizeWithPalette: 2,
|
|
96
94
|
quantizeToIndices: 2,
|
|
97
|
-
quantizeToIndicesFromClustering: 3,
|
|
98
95
|
quantizeToIndicesWithPalette: 2,
|
|
99
96
|
cluster: 2,
|
|
100
97
|
handleQuantize: 2,
|