agglomerative-clustering 4.0.0-beta.2 → 4.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 +5 -5
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +40 -238
- package/dist/index.d.cts +15 -76
- package/dist/index.d.ts +15 -76
- package/dist/index.mjs +28 -221
- package/dist/shared.cjs +244 -84
- package/dist/shared.mjs +235 -78
- package/dist/worker-thread.mjs +16 -19
- package/dist/worker.cjs +235 -136
- package/dist/worker.d.cts +0 -32
- package/dist/worker.d.ts +0 -32
- package/dist/worker.mjs +234 -130
- 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.quantizeOptions = exports.quantizeIndexOptions = exports.parseOptions = exports.parseDither = exports.maxBytes = exports.markPalette = exports.markClustering = exports.mark = exports.mapOptions = exports.mapIndexOptions = 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.counted = exports.colorSpaces = exports.colorSpaceName = exports.colorSpaceCodes = exports.clusterOptions = exports.checkSize = exports.checkPixelArray = exports.checkPalette = exports.checkNotEmpty = exports.checkK = exports.checkImageObject = exports.checkImageKeys = exports.checkImageDataPixels = exports.checkImageBody = exports.checkChoice = exports.channels = exports.bareLayout = exports.bareImageError = exports.alphaModes = exports.alphaModeCodes = 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.4';
|
|
17
17
|
const colorSpaceCodes = exports.colorSpaceCodes = {
|
|
18
18
|
'rgb': 0,
|
|
19
19
|
'oklab': 1
|
|
@@ -119,7 +119,7 @@ const checkImageDataPixels = image => {
|
|
|
119
119
|
}
|
|
120
120
|
const needed = image.width * image.height * 4;
|
|
121
121
|
if (image.data.length !== needed) {
|
|
122
|
-
throw fail('invalid-argument', `Invalid image: this ImageData's data has ${image.data.length
|
|
122
|
+
throw fail('invalid-argument', `Invalid image: this ImageData's data has ${counted(image.data.length, 'byte', 'bytes')}, but ${image.width} x ${image.height} RGBA pixels need ${needed}.`, 'image');
|
|
123
123
|
}
|
|
124
124
|
return;
|
|
125
125
|
}
|
|
@@ -331,10 +331,12 @@ const imageCopy = image => {
|
|
|
331
331
|
|
|
332
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
333
|
// buffer is detached, then checkImageObject. The worker entry runs the same before it posts an image. Returns the premultiplied flag.
|
|
334
|
+
// What to do with 16-bit pixels (a decoder's Uint16Array for a 16-bit PNG): the library reads 8 bits per channel.
|
|
334
335
|
exports.imageCopy = imageCopy;
|
|
336
|
+
const sixteenBit = data => Object.prototype.toString.call(data) === '[object Uint16Array]' ? ' 16-bit pixels (a Uint16Array, as decoders give for a 16-bit PNG) have to be shifted down to 8 bits first: Uint8Array.from(data, (v) => v >> 8).' : '';
|
|
335
337
|
const checkImageBody = image => {
|
|
336
338
|
if (!isUint8Array(image.data) && !isUint8ClampedArray(image.data)) {
|
|
337
|
-
throw fail('invalid-argument',
|
|
339
|
+
throw fail('invalid-argument', `Invalid image data: must be Uint8Array or Uint8ClampedArray.${sixteenBit(image.data)}`, 'image');
|
|
338
340
|
}
|
|
339
341
|
if (isDetached(image.data)) {
|
|
340
342
|
throw detachedError('data');
|
|
@@ -374,7 +376,11 @@ const ditherMethodCodes = {
|
|
|
374
376
|
const ditherMethods = exports.ditherMethods = Object.freeze(Object.keys(ditherMethodCodes));
|
|
375
377
|
const ditherSteps = exports.ditherSteps = Object.freeze([2, 4, 8, 16, 32, 64]);
|
|
376
378
|
|
|
379
|
+
// A count with its noun in the right number, for messages: 1 byte, 2 bytes.
|
|
380
|
+
const counted = (n, one, many) => `${n} ${n === 1 ? one : many}`;
|
|
381
|
+
|
|
377
382
|
// A short description of a value for an error message.
|
|
383
|
+
exports.counted = counted;
|
|
378
384
|
const describe = value => typeof value === 'string' ? `'${value}'` : typeof value === 'number' || typeof value === 'boolean' || value === null ? String(value) : Array.isArray(value) ? 'an array' : typeof value === 'object' ? `a ${Object.prototype.toString.call(value).slice(8, -1)}` : `a ${typeof value}`;
|
|
379
385
|
|
|
380
386
|
// Reads every form of the dither option: false/undefined (off), true or a strength from 0 to 1 (Floyd-Steinberg, as in
|
|
@@ -533,7 +539,7 @@ const sniffImageFormat = bytes => {
|
|
|
533
539
|
// The other common way to get a bare array wrong is bytes of another layout: RGB (sharp's plain .raw()), or grey and grey
|
|
534
540
|
// with alpha (fast-png's decode() of a grey PNG). Read as RGBA, every pixel takes bytes from its neighbours and one of them
|
|
535
541
|
// as its alpha, and nothing fails while the length divides by 4. They are never reinterpreted (a bare array is RGBA,
|
|
536
|
-
// PRINCIPLES), only reported
|
|
542
|
+
// PRINCIPLES), only reported, as an error (a warning in 3.x).
|
|
537
543
|
//
|
|
538
544
|
// The rules use E(k), the mean change between a byte and the one k before it (bench/spikes/bare-rgb/ and
|
|
539
545
|
// bench/spikes/bare-grey/: no false positives on 2,984 real RGBA images).
|
|
@@ -542,8 +548,8 @@ const sniffImageFormat = bytes => {
|
|
|
542
548
|
// but where it changes its bytes come in equal triples at a step of 3 and not of 4.
|
|
543
549
|
// - 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.
|
|
544
550
|
// - Grey (1 byte a pixel): smoothest at a step of 1, unless most changing pixels have four equal bytes, which is real
|
|
545
|
-
// RGBA (grey with alpha = grey). The RGB rule goes first because near-grey RGB can look the same;
|
|
546
|
-
//
|
|
551
|
+
// RGBA (grey with alpha = grey). The RGB rule goes first because near-grey RGB can look the same; its error text
|
|
552
|
+
// covers grey too.
|
|
547
553
|
// Units equal to the one before are skipped by the equal-byte counts, since flat areas read the same either way. It
|
|
548
554
|
// samples 512 windows of 96 bytes (each on a multiple of 12, a pixel under every reading, one in each 512th of the
|
|
549
555
|
// array), so it costs about 0.35 ms at any size. Returns 'rgb', 'grey', 'grey-alpha' or null.
|
|
@@ -640,84 +646,32 @@ const bareLayout = d => {
|
|
|
640
646
|
exports.bareLayout = bareLayout;
|
|
641
647
|
const looksLikeRgb = d => bareLayout(d) === 'rgb';
|
|
642
648
|
|
|
643
|
-
//
|
|
649
|
+
// The error a bare image calls for, or null. It skips everything the main entry rejects for another reason (palettes and
|
|
650
|
+
// clusterings passed as the image, encoded files, lengths that aren't a multiple of 4), so a call never gives two
|
|
651
|
+
// errors for its image and both entries share this one order.
|
|
644
652
|
exports.looksLikeRgb = looksLikeRgb;
|
|
645
|
-
const
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
grey:
|
|
649
|
-
'grey-alpha': 'gray-as-rgba'
|
|
653
|
+
const bareText = {
|
|
654
|
+
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.`,
|
|
655
|
+
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.`,
|
|
656
|
+
'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.`
|
|
650
657
|
};
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
// and clusterings passed as the image, encoded files, lengths that aren't a multiple of 4), so a call never both warns
|
|
654
|
-
// about its image and rejects it, and both entries share this one order. An array of one layout never takes another's
|
|
655
|
-
// code because its own was already used: it is classified first, and only then is its code checked.
|
|
656
|
-
const bareImageWarning = image => {
|
|
657
|
-
if (warned.has('rgb-as-rgba') && warned.has('gray-as-rgba') || !isUint8Array(image) || isPalette(image) || isClustering(image)) {
|
|
658
|
+
const bareImageError = image => {
|
|
659
|
+
if (!isUint8Array(image) || isPalette(image) || isClustering(image)) {
|
|
658
660
|
return null;
|
|
659
661
|
}
|
|
660
662
|
if (sniffImageFormat(image) !== null || image.length % 4 !== 0) {
|
|
661
663
|
return null;
|
|
662
664
|
}
|
|
663
665
|
const layout = bareLayout(image);
|
|
664
|
-
return layout === null
|
|
665
|
-
code: bareCodes[layout],
|
|
666
|
-
layout
|
|
667
|
-
};
|
|
668
|
-
};
|
|
669
|
-
|
|
670
|
-
// The text of each warning. Delivered through process.emitWarning in Node, Bun and Deno (--no-warnings,
|
|
671
|
-
// process.on('warning') and --trace-warnings then work), else console.warn. Runtimes that imitate Node have an
|
|
672
|
-
// emitWarning that may print nothing (Cloudflare Workers with nodejs_compat), so they are told apart by
|
|
673
|
-
// navigator.userAgent, as worker.js does; a bundler's `process` polyfill has no emitWarning, and `globalThis.process`
|
|
674
|
-
// keeps Parcel from adding one.
|
|
675
|
-
exports.bareImageWarning = bareImageWarning;
|
|
676
|
-
const nodeLike = () => typeof navigator === 'undefined' || /^(Node\.js|Bun|Deno)\//.test(String(navigator.userAgent));
|
|
677
|
-
const warningText = {
|
|
678
|
-
'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.`,
|
|
679
|
-
'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.`
|
|
680
|
-
};
|
|
681
|
-
// `warning` is what bareImageWarning returned: {code, layout}.
|
|
682
|
-
const warnOnce = ({
|
|
683
|
-
code,
|
|
684
|
-
layout
|
|
685
|
-
}, byteLength) => {
|
|
686
|
-
if (warned.has(code)) {
|
|
687
|
-
return;
|
|
688
|
-
}
|
|
689
|
-
warned.add(code);
|
|
690
|
-
const message = warningText[code](byteLength, layout);
|
|
691
|
-
const runtime = globalThis.process;
|
|
692
|
-
if (runtime && typeof runtime.emitWarning === 'function' && nodeLike()) {
|
|
693
|
-
runtime.emitWarning(message, {
|
|
694
|
-
type: 'AgglomerativeClusteringWarning',
|
|
695
|
-
code
|
|
696
|
-
});
|
|
697
|
-
} else if (typeof console !== 'undefined') {
|
|
698
|
-
console.warn(`agglomerative-clustering [${code}]: ${message}`);
|
|
699
|
-
}
|
|
700
|
-
};
|
|
701
|
-
// The worker thread's copy: its caller's side checks and warns (PRINCIPLES), so here every code counts as warned, which
|
|
702
|
-
// also skips the sampling.
|
|
703
|
-
exports.warnOnce = warnOnce;
|
|
704
|
-
const silenceWarnings = () => {
|
|
705
|
-
for (const code of Object.keys(warningText)) {
|
|
706
|
-
warned.add(code);
|
|
707
|
-
}
|
|
708
|
-
};
|
|
709
|
-
// For tests.
|
|
710
|
-
exports.silenceWarnings = silenceWarnings;
|
|
711
|
-
const resetWarnings = () => {
|
|
712
|
-
warned.clear();
|
|
666
|
+
return layout === null ? null : fail('invalid-argument', bareText[layout](image.byteLength.toLocaleString('en-US')), 'image');
|
|
713
667
|
};
|
|
714
668
|
// Node's console.log and util.inspect call this (other environments ignore it), so the tag shows when debugging:
|
|
715
669
|
// `Palette(oklab) [ 12, 34, ... ]` rather than a plain `Uint8Array(…)`.
|
|
716
|
-
exports.
|
|
670
|
+
exports.bareImageError = bareImageError;
|
|
717
671
|
const inspect = Symbol.for('nodejs.util.inspect.custom');
|
|
718
672
|
const view = label => function (depth, options, nodeInspect) {
|
|
719
673
|
const plain = new Uint8Array(this.buffer, this.byteOffset, this.length);
|
|
720
|
-
return `${label(this)} ${typeof nodeInspect === 'function' ? nodeInspect(plain, options) : `[${plain.length
|
|
674
|
+
return `${label(this)} ${typeof nodeInspect === 'function' ? nodeInspect(plain, options) : `[${counted(plain.length, 'byte', 'bytes')}]`}`;
|
|
721
675
|
};
|
|
722
676
|
const paletteView = view(palette => `Palette(${palette.colorSpace})`);
|
|
723
677
|
const clusteringView = view(() => 'Clustering');
|
|
@@ -733,7 +687,7 @@ const markPalette = (bytes, colorSpace) => {
|
|
|
733
687
|
});
|
|
734
688
|
return bytes;
|
|
735
689
|
};
|
|
736
|
-
// Methods on a clustering: `clustering.getPalette(k)`
|
|
690
|
+
// Methods on a clustering: `clustering.getPalette(k)` cuts a palette from it, and so on. They are
|
|
737
691
|
// non-enumerable own properties, added with the tags, so a clustering stays a plain Uint8Array (`toEqual` and
|
|
738
692
|
// `deepStrictEqual` against plain bytes still pass), and slices and clones drop them as they drop the tags. They run on the
|
|
739
693
|
// calling thread with the main entry's functions, which the main entry puts in `engine` when it is evaluated; the worker
|
|
@@ -748,14 +702,14 @@ const setEngine = value => {
|
|
|
748
702
|
engine = value;
|
|
749
703
|
}
|
|
750
704
|
};
|
|
751
|
-
// Each method's call shape and
|
|
705
|
+
// Each method's call shape and the loaded-handle form that serves it off the thread, for messages.
|
|
752
706
|
exports.setEngine = setEngine;
|
|
753
707
|
const methodNames = {
|
|
754
|
-
getPalette: ['getPalette(k)', '
|
|
755
|
-
getSwatches: ['getSwatches(k)', '
|
|
756
|
-
getClusteringInfo: ['getClusteringInfo()', 'getClusteringInfo(clustering)
|
|
757
|
-
quantize: ['quantize(image, k)', '
|
|
758
|
-
quantizeToIndices: ['quantizeToIndices(image, k)', '
|
|
708
|
+
getPalette: ['getPalette(k)', "a loaded handle's getPalette: (await worker.load(clustering)).getPalette(k)"],
|
|
709
|
+
getSwatches: ['getSwatches(k)', "a loaded handle's getSwatches: (await worker.load(clustering)).getSwatches(k)"],
|
|
710
|
+
getClusteringInfo: ['getClusteringInfo()', "a loaded handle's getClusteringInfo: (await worker.load(clustering)).getClusteringInfo()"],
|
|
711
|
+
quantize: ['quantize(image, k)', "a loaded handle's quantize: (await worker.load(clustering)).quantize(image, k)"],
|
|
712
|
+
quantizeToIndices: ['quantizeToIndices(image, k)', "a loaded handle's quantizeToIndices: (await worker.load(clustering)).quantizeToIndices(image, k)"],
|
|
759
713
|
chooseFrom: ['chooseFrom(palette, k, options?)', "a loaded handle's chooseFrom: (await worker.load(clustering)).chooseFrom(palette, k)"]
|
|
760
714
|
};
|
|
761
715
|
// Checks the receiver before anything else, since it is written first, then (for the mapping methods) that the image isn't
|
|
@@ -879,6 +833,10 @@ Object.defineProperty(Palette, Symbol.hasInstance, {
|
|
|
879
833
|
// those of a Uint8Array (bytes to copy, or a buffer with an offset and length to view).
|
|
880
834
|
function Clustering(...args) {
|
|
881
835
|
const [source] = args;
|
|
836
|
+
// A palette gets the same hint as from every other function, before its bytes are copied.
|
|
837
|
+
if (isPalette(source)) {
|
|
838
|
+
readHeader(source);
|
|
839
|
+
}
|
|
882
840
|
// Bytes, or a buffer to view: never a number (a length would allocate and make an empty clustering) or anything a Uint8Array
|
|
883
841
|
// would coerce. A plain array must hold byte values, as for a palette.
|
|
884
842
|
const isBuffer = isArrayBufferLike(source);
|
|
@@ -968,17 +926,21 @@ const damaged = () => fail('invalid-clustering', "Invalid clustering: its bytes
|
|
|
968
926
|
// and a length of 0 or 3 more than a multiple of 9).
|
|
969
927
|
const notAClustering = clustering => {
|
|
970
928
|
const length = clustering.length;
|
|
929
|
+
// No bytes at all is not a 1.x clustering that lost its header: there is nothing to read.
|
|
930
|
+
if (length === 0) {
|
|
931
|
+
return fail('invalid-clustering', "Invalid clustering: it is empty (no bytes). A clustering comes from buildClustering, even for an image with no visible pixels.", 'clustering');
|
|
932
|
+
}
|
|
971
933
|
if (clustering[0] !== 0xAC && (length % 9 === 0 || length % 9 === 3)) {
|
|
972
934
|
return fail('invalid-clustering', "Invalid clustering: not a clustering from buildClustering. If it was stored by agglomerative-clustering 1.x, that format is no longer read: cluster the image again.", 'clustering');
|
|
973
935
|
}
|
|
974
936
|
if (clustering[0] === 0xAC && length >= 2 && (clustering[1] === 2 || clustering[1] === 3)) {
|
|
975
|
-
return fail('invalid-clustering', `Invalid clustering: it starts like a format ${clustering[1]} clustering, but its length or header doesn't fit one (${length
|
|
937
|
+
return fail('invalid-clustering', `Invalid clustering: it starts like a format ${clustering[1]} clustering, but its length or header doesn't fit one (${counted(length, 'byte', 'bytes')}): it was probably truncated or damaged. Cluster the image again.`, 'clustering');
|
|
976
938
|
}
|
|
977
|
-
return fail('invalid-clustering', `Invalid clustering: not a clustering from buildClustering (${length
|
|
939
|
+
return fail('invalid-clustering', `Invalid clustering: not a clustering from buildClustering (${counted(length, 'byte', 'bytes')} that ${length === 1 ? "doesn't" : "don't"} start with a clustering header).`, 'clustering');
|
|
978
940
|
};
|
|
979
941
|
const readHeader = clustering => {
|
|
980
942
|
if (isPalette(clustering)) {
|
|
981
|
-
throw fail('invalid-clustering', "Invalid clustering: this is a palette, not a clustering. Palettes come from buildPalette
|
|
943
|
+
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');
|
|
982
944
|
}
|
|
983
945
|
if (!isUint8Array(clustering)) {
|
|
984
946
|
throw fail('invalid-clustering', "Invalid clustering: must be a Uint8Array from buildClustering.", 'clustering');
|
|
@@ -1040,12 +1002,12 @@ const readHeader = clustering => {
|
|
|
1040
1002
|
throw notAClustering(clustering);
|
|
1041
1003
|
};
|
|
1042
1004
|
|
|
1043
|
-
// Palettes are flat RGB bytes. An empty palette is allowed: it is what
|
|
1005
|
+
// Palettes are flat RGB bytes. An empty palette is allowed: it is what buildPalette gives for a fully transparent
|
|
1044
1006
|
// image, and quantize maps such an image the same way.
|
|
1045
1007
|
exports.readHeader = readHeader;
|
|
1046
1008
|
const checkPalette = palette => {
|
|
1047
1009
|
if (isClustering(palette)) {
|
|
1048
|
-
throw fail('invalid-argument', "Invalid palette: this is a clustering (from buildClustering), not a palette. Cut a palette from it with
|
|
1010
|
+
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');
|
|
1049
1011
|
}
|
|
1050
1012
|
if (!isUint8Array(palette) && !isUint8ClampedArray(palette) && !Array.isArray(palette)) {
|
|
1051
1013
|
throw fail('invalid-argument', "Invalid palette: must be a Uint8Array of RGB bytes.", 'palette');
|
|
@@ -1123,4 +1085,202 @@ const revive = value => {
|
|
|
1123
1085
|
}
|
|
1124
1086
|
return value;
|
|
1125
1087
|
};
|
|
1126
|
-
|
|
1088
|
+
|
|
1089
|
+
// ----- Arguments both entries check ------------------------------------------------------------------------------------
|
|
1090
|
+
// What the main entry checks about k and the options before it does any work, kept here so the worker entry runs the very same
|
|
1091
|
+
// checks, in the same order, before it posts anything.
|
|
1092
|
+
exports.revive = revive;
|
|
1093
|
+
const alphaModeCodes = exports.alphaModeCodes = {
|
|
1094
|
+
'ignore': 0,
|
|
1095
|
+
'weight': 1
|
|
1096
|
+
};
|
|
1097
|
+
|
|
1098
|
+
// Returns k, validated. Any k above the number of colours means all of them, so it is capped at the largest value
|
|
1099
|
+
// the WASM side holds (a larger one would overflow its int).
|
|
1100
|
+
const checkK = k => {
|
|
1101
|
+
if (typeof k !== 'number' || !Number.isInteger(k) || k <= 0) {
|
|
1102
|
+
// A string is the usual slip (an input's `value`), so it gets its own fix.
|
|
1103
|
+
const got = typeof k === 'string' ? ` Got the string ${JSON.stringify(k.length > 20 ? `${k.slice(0, 20)}…` : k)}: convert it first, e.g. Number(input.value).` : typeof k === 'number' ? ` Got ${k}.` : ` Got ${k === null ? 'null' : typeof k}.`;
|
|
1104
|
+
throw fail('invalid-argument', `Invalid k: must be a whole number of colours, 1 or more.${got}`, 'k');
|
|
1105
|
+
}
|
|
1106
|
+
return Math.min(k, 0x7FFFFFFF);
|
|
1107
|
+
};
|
|
1108
|
+
|
|
1109
|
+
// Validates `options` against the keys a function accepts and fills in defaults:
|
|
1110
|
+
// colorSpace: 'rgb' (default) or 'oklab', the space colours are clustered and matched in; when mapping with a
|
|
1111
|
+
// clustering, the default is the space the clustering was made in (code -1)
|
|
1112
|
+
// alpha: 'weight' (default) counts RGBA pixels in proportion to their opacity; 'ignore' counts every pixel
|
|
1113
|
+
// precision: bits per channel, 1-8 (default 8, exact); lower values group similar colours before clustering
|
|
1114
|
+
// dither: false (default), true or a strength in [0, 1] (Floyd-Steinberg), a method name, or { method, strength, steps } (see parseDither)
|
|
1115
|
+
// width: image width in pixels, needed to dither a Uint8Array or a RawImage without `width`
|
|
1116
|
+
// signal, onProgress: an AbortSignal and a progress callback, which make the clustering and the mapping run in slices
|
|
1117
|
+
// (see clusterInSlices and mapInSlices)
|
|
1118
|
+
// transparent: false (default), true (cutoff 128) or a cutoff from 1 to 255: pixels with alpha below it are left out of clustering (and the rest count whole);
|
|
1119
|
+
// indexed output also gives them their own entry, which counts towards k
|
|
1120
|
+
|
|
1121
|
+
// The settings of dither, which a caller may write as options of their own; naming one of these gets a pointer to the
|
|
1122
|
+
// object form.
|
|
1123
|
+
exports.checkK = checkK;
|
|
1124
|
+
const ditherSettings = ['ditherMethod', 'ditherStrength', 'ditherSteps', 'method', 'strength', 'steps', 'mix'];
|
|
1125
|
+
const parseOptions = (options, allowed, image) => {
|
|
1126
|
+
if (options === undefined) {
|
|
1127
|
+
options = {};
|
|
1128
|
+
}
|
|
1129
|
+
if (!isOptionsObject(options)) {
|
|
1130
|
+
throw fail('invalid-argument', "Invalid options: expected an object.", 'options');
|
|
1131
|
+
}
|
|
1132
|
+
options = snapshot(options);
|
|
1133
|
+
for (const key of Object.keys(options)) {
|
|
1134
|
+
if (!allowed.includes(key)) {
|
|
1135
|
+
const hint = allowed.includes('dither') && ditherSettings.includes(key) ? ' Dithering settings go inside the dither option: dither: { method, strength, steps }.' : '';
|
|
1136
|
+
throw fail('invalid-argument', `Invalid option '${key}': expected one of ${allowed.join(', ')}.${hint}`, `options.${key}`);
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
const colorSpace = options.colorSpace === undefined ? 'rgb' : options.colorSpace;
|
|
1140
|
+
if (!colorSpaces.includes(colorSpace)) {
|
|
1141
|
+
throw fail('invalid-argument', "Invalid colorSpace: must be 'rgb' or 'oklab'.", 'options.colorSpace');
|
|
1142
|
+
}
|
|
1143
|
+
const alpha = options.alpha === undefined ? 'weight' : options.alpha;
|
|
1144
|
+
if (!alphaModes.includes(alpha)) {
|
|
1145
|
+
throw fail('invalid-argument', "Invalid alpha: must be 'weight' or 'ignore'.", 'options.alpha');
|
|
1146
|
+
}
|
|
1147
|
+
const precision = options.precision === undefined ? 8 : options.precision;
|
|
1148
|
+
if (typeof precision !== 'number' || !Number.isInteger(precision) || precision < 1 || precision > 8) {
|
|
1149
|
+
throw fail('invalid-argument', "Invalid precision: must be an integer from 1 to 8.", 'options.precision');
|
|
1150
|
+
}
|
|
1151
|
+
const {
|
|
1152
|
+
strength: dither,
|
|
1153
|
+
method: ditherMethod,
|
|
1154
|
+
steps: ditherSteps
|
|
1155
|
+
} = parseDither(options.dither);
|
|
1156
|
+
|
|
1157
|
+
// The image's own width and options.width are two sources for one fact: they may repeat each other, but not disagree
|
|
1158
|
+
// (a wrong row length would dither without an error, as long as it divides the pixel count).
|
|
1159
|
+
if (options.width !== undefined && image && image.width !== undefined && options.width !== image.width) {
|
|
1160
|
+
throw fail('invalid-argument', `Invalid width: options.width (${describe(options.width)}) does not match the image's width (${image.width}).`, 'options.width');
|
|
1161
|
+
}
|
|
1162
|
+
if (options.width !== undefined && image) {
|
|
1163
|
+
checkSize(image.data.length / channels(image.format), options.width, 'width', 'options.width');
|
|
1164
|
+
}
|
|
1165
|
+
const width = options.width !== undefined ? options.width : image ? image.width : undefined;
|
|
1166
|
+
if (dither > 0) {
|
|
1167
|
+
const stride = channels(image.format);
|
|
1168
|
+
if (typeof width !== 'number' || !Number.isInteger(width) || width <= 0) {
|
|
1169
|
+
throw fail('invalid-argument', "Invalid width: dithering needs the image width, as `options.width` or the image's `width`.", 'options.width');
|
|
1170
|
+
}
|
|
1171
|
+
if (image.data.length / stride % width !== 0) {
|
|
1172
|
+
throw fail('invalid-argument', "Invalid width: the image's pixel count is not a multiple of it.", 'options.width');
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
const signal = options.signal;
|
|
1176
|
+
if (signal !== undefined && (signal === null || typeof signal !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function')) {
|
|
1177
|
+
throw fail('invalid-argument', "Invalid signal: must be an AbortSignal.", 'options.signal');
|
|
1178
|
+
}
|
|
1179
|
+
const onProgress = options.onProgress;
|
|
1180
|
+
if (onProgress !== undefined && typeof onProgress !== 'function') {
|
|
1181
|
+
throw fail('invalid-argument', "Invalid onProgress: must be a function.", 'options.onProgress');
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
// The alpha cutoff for indexed output: 0 for none, else the pixels with alpha below it are transparent.
|
|
1185
|
+
const transparentOption = options.transparent === undefined ? false : options.transparent;
|
|
1186
|
+
const transparent = transparentOption === false ? 0 : transparentOption === true ? 128 : transparentOption;
|
|
1187
|
+
if (!Number.isInteger(transparent) || transparent < 0 || transparent > 255 || transparent === 0 && transparentOption !== false) {
|
|
1188
|
+
throw fail('invalid-argument', "Invalid transparent: must be a boolean or an integer alpha cutoff from 1 to 255.", 'options.transparent');
|
|
1189
|
+
}
|
|
1190
|
+
checkTransparentFormat(image, options);
|
|
1191
|
+
|
|
1192
|
+
// A cutoff replaces opacity weighting (pixels count whole or not at all), so naming both would leave one of them ignored.
|
|
1193
|
+
if (transparent > 0 && options.alpha !== undefined) {
|
|
1194
|
+
throw fail('invalid-argument', "Invalid options: `transparent` replaces `alpha` (with a cutoff, pixels count whole or not at all), so give one or the other.", 'options');
|
|
1195
|
+
}
|
|
1196
|
+
return {
|
|
1197
|
+
colorSpace: colorSpaceCodes[colorSpace],
|
|
1198
|
+
colorSpaceGiven: options.colorSpace !== undefined,
|
|
1199
|
+
alpha: alphaModeCodes[alpha],
|
|
1200
|
+
precision,
|
|
1201
|
+
dither,
|
|
1202
|
+
ditherMethod,
|
|
1203
|
+
ditherSteps,
|
|
1204
|
+
width: dither > 0 ? width : 0,
|
|
1205
|
+
transparent,
|
|
1206
|
+
transparentGiven: options.transparent !== undefined,
|
|
1207
|
+
signal,
|
|
1208
|
+
onProgress
|
|
1209
|
+
};
|
|
1210
|
+
};
|
|
1211
|
+
exports.parseOptions = parseOptions;
|
|
1212
|
+
const controlOptions = ['signal', 'onProgress'];
|
|
1213
|
+
// `transparent: true` or a cutoff on a format with no alpha channel can't mean anything (no pixel is transparent), so it is
|
|
1214
|
+
// an error rather than a silent no-op. Only the call's own options count: a clustering's stored cutoff never reaches here.
|
|
1215
|
+
const checkTransparentFormat = (image, options) => {
|
|
1216
|
+
if (!image || hasAlpha(image.format) || options.transparent === undefined || options.transparent === false) {
|
|
1217
|
+
return;
|
|
1218
|
+
}
|
|
1219
|
+
const hint = image.format === 'rgbx' || image.format === 'bgrx' ? " If the fourth byte really is alpha, use 'rgba' or 'bgra'." : '';
|
|
1220
|
+
throw fail('invalid-argument', `Invalid transparent: '${image.format}' has no alpha, so no pixel can be transparent. Leave transparent out (false is accepted).${hint}`, 'options.transparent');
|
|
1221
|
+
};
|
|
1222
|
+
const clusterOptions = exports.clusterOptions = ['colorSpace', 'precision', 'alpha', 'transparent', ...controlOptions];
|
|
1223
|
+
const quantizeOptions = exports.quantizeOptions = [...clusterOptions, 'dither', 'width'];
|
|
1224
|
+
const mapOptions = exports.mapOptions = ['colorSpace', 'dither', 'width', ...controlOptions];
|
|
1225
|
+
const quantizeIndexOptions = exports.quantizeIndexOptions = quantizeOptions;
|
|
1226
|
+
const mapIndexOptions = exports.mapIndexOptions = [...mapOptions, 'transparent'];
|
|
1227
|
+
|
|
1228
|
+
// What a bare typed array passed as an image must be, in the order the main entry checks it: not a clustering or a palette,
|
|
1229
|
+
// then (when it is not detached, which the caller reports) for a Uint8Array not the bytes of an image file and a whole number
|
|
1230
|
+
// of RGBA pixels, and no other kind of array. The bare-RGB and grey check (bareImageError) follows, in the caller.
|
|
1231
|
+
const checkPixelArray = image => {
|
|
1232
|
+
if (isClustering(image) || isPalette(image)) {
|
|
1233
|
+
const what = isClustering(image) ? 'a clustering (from buildClustering)' : 'a palette';
|
|
1234
|
+
const fix = isClustering(image) ? 'To cut a palette from it, use clustering.getPalette(k) (or clustering.quantize(image, k) to map an image with it).' : 'To map an image to it, use quantizeWithPalette(image, palette).';
|
|
1235
|
+
throw fail('invalid-argument', `Invalid image: this is ${what}, not pixels. ${fix}`, 'image');
|
|
1236
|
+
}
|
|
1237
|
+
if (isDetached(image)) {
|
|
1238
|
+
return;
|
|
1239
|
+
}
|
|
1240
|
+
if (isUint8Array(image)) {
|
|
1241
|
+
const encoded = sniffImageFormat(image);
|
|
1242
|
+
if (encoded) {
|
|
1243
|
+
throw fail('invalid-argument', `Invalid image: these bytes are an encoded ${encoded} file, not pixels. Decode them to pixels first and pass those ("Decoding image files" in the guides has a recipe for Node, browsers and edge runtimes). If they really are raw RGBA pixels, pass { data, format: 'rgba' } to say so.`, 'image');
|
|
1244
|
+
}
|
|
1245
|
+
if (image.length % 4 !== 0) {
|
|
1246
|
+
throw fail('invalid-argument', "Invalid image data: length must be a multiple of 4 for 'rgba'.", 'image');
|
|
1247
|
+
}
|
|
1248
|
+
return;
|
|
1249
|
+
}
|
|
1250
|
+
throw fail('invalid-argument', `Invalid image: a bare typed array must be a Uint8Array of RGBA bytes. For a Uint8ClampedArray such as imageData.data, pass the ImageData itself or { data, format: 'rgba' }.${sixteenBit(image)}`, 'image');
|
|
1251
|
+
};
|
|
1252
|
+
|
|
1253
|
+
// An empty palette is what getPalette gives for an image with no visible pixels, and mapping such an image with it is
|
|
1254
|
+
// fine. Mapping visible pixels to it has no answer (they would all come out black), so that is an error. `cutoff` is the
|
|
1255
|
+
// alpha from which an RGBA pixel needs a colour.
|
|
1256
|
+
exports.checkPixelArray = checkPixelArray;
|
|
1257
|
+
const checkNotEmpty = (palette, image, cutoff) => {
|
|
1258
|
+
if (palette.length > 0) {
|
|
1259
|
+
return;
|
|
1260
|
+
}
|
|
1261
|
+
const data = image.data;
|
|
1262
|
+
let visible = hasAlpha(image.format) ? false : data.length > 0;
|
|
1263
|
+
for (let i = 3; !visible && hasAlpha(image.format) && i < data.length; i += 4) {
|
|
1264
|
+
visible = data[i] >= cutoff;
|
|
1265
|
+
}
|
|
1266
|
+
if (visible) {
|
|
1267
|
+
throw fail('invalid-argument', "Invalid palette: it is empty, but the image has visible pixels to map to it.", 'palette');
|
|
1268
|
+
}
|
|
1269
|
+
};
|
|
1270
|
+
|
|
1271
|
+
// What clustering.chooseFrom checks about its palette and k, in order: the palette is flat RGB bytes and not empty, k is a
|
|
1272
|
+
// whole number of colours and no more than the palette has. Returns k.
|
|
1273
|
+
exports.checkNotEmpty = checkNotEmpty;
|
|
1274
|
+
const checkChoice = (palette, k) => {
|
|
1275
|
+
checkPalette(palette);
|
|
1276
|
+
if (palette.length === 0) {
|
|
1277
|
+
throw fail('invalid-argument', "Invalid palette: it is empty; give at least one RGB entry (3 bytes).", 'palette');
|
|
1278
|
+
}
|
|
1279
|
+
const count = palette.length / 3;
|
|
1280
|
+
k = checkK(k);
|
|
1281
|
+
if (k > count) {
|
|
1282
|
+
throw fail('invalid-argument', `Invalid k: ${k} is more than the ${counted(count, 'entry', 'entries')} in the palette; use ${count} or fewer.`, 'k');
|
|
1283
|
+
}
|
|
1284
|
+
return k;
|
|
1285
|
+
};
|
|
1286
|
+
exports.checkChoice = checkChoice;
|