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/dist/worker.cjs CHANGED
@@ -49,7 +49,7 @@ Object.defineProperty(exports, "errorCodes", {
49
49
  return _shared.errorCodes;
50
50
  }
51
51
  });
52
- exports.getSwatchesFromClustering = exports.getSwatches = exports.getPaletteFromClustering = exports.getPalette = exports.getClusteringInfo = exports.getClustering = exports.formatVersion = void 0;
52
+ exports.formatVersion = void 0;
53
53
  Object.defineProperty(exports, "imageFormats", {
54
54
  enumerable: true,
55
55
  get: function () {
@@ -63,7 +63,7 @@ Object.defineProperty(exports, "isCodedError", {
63
63
  return _shared.isCodedError;
64
64
  }
65
65
  });
66
- exports.terminate = exports.quantizeWithPalette = exports.quantizeToIndicesWithPalette = exports.quantizeToIndicesFromClustering = exports.quantizeToIndices = exports.quantizeFromClustering = exports.quantize = void 0;
66
+ exports.terminate = exports.quantizeWithPalette = exports.quantizeToIndicesWithPalette = exports.quantizeToIndices = exports.quantize = void 0;
67
67
  Object.defineProperty(exports, "version", {
68
68
  enumerable: true,
69
69
  get: function () {
@@ -207,7 +207,7 @@ const start = async (receive, chosen) => {
207
207
  // A page with an opaque origin (a sandboxed iframe without allow-same-origin, as plugin hosts such as Figma use) can't
208
208
  // start a worker from any http(s) script, nor, in Chromium, from a blob: URL; a data: URL module can, and imports it.
209
209
  const opaque = !crossOrigin && isOpaqueOrigin() && webOrigins.includes(script.protocol);
210
- const scriptHint = "Check that worker-thread.mjs is served (open its URL), with index.mjs, shared.mjs, choose.mjs, clustering.js and clustering.wasm next to it, which it imports, or say where your copy of dist/ is with createWorker({ script }) or, for the shared worker, init({ script }).";
210
+ const scriptHint = "Check that worker-thread.mjs is served (open its URL), with index.mjs, shared.mjs, choose.mjs, clustering.js and clustering.wasm next to it, which it imports, or say where your copy of dist/ is with createWorker({ script }) or, for the shared worker, init({ script }). The worker's files can also be from different versions of agglomerative-clustering: serve all of dist/ from this version.";
211
211
  let worker,
212
212
  source = null;
213
213
  try {
@@ -264,11 +264,12 @@ const start = async (receive, chosen) => {
264
264
  });
265
265
  worker.on('message', receive);
266
266
  // A worker script that can't be found, or that can't find what it imports: a copy of dist/ split up or bundled away.
267
+ const versions = " The worker's files can also be from different versions of agglomerative-clustering: serve all of dist/ from this version.";
267
268
  const missing = error => error && (error.code === 'ERR_MODULE_NOT_FOUND' || /Cannot find module|import\.meta' outside a module|Qualified path resolution failed/.test(String(error.message)));
268
269
  // Yarn Plug'n'Play keeps packages in zip archives, which Node reads ES modules from only through Yarn's loader.
269
270
  const inZip = error => /\.zip[\\/]/.test(String(error && error.message));
270
271
  worker.on('error', error => receive({
271
- failure: missing(error) ? inZip(error) ? `${String(error.message).split('\n')[0]}. Under Yarn Plug'n'Play the package sits in a zip archive, which a worker thread can load its ES modules from only through Yarn's loader: run the app with yarn node (or node --require ./.pnp.cjs --loader ./.pnp.loader.mjs), or unplug the package (yarn unplug agglomerative-clustering). Otherwise keep dist/ together and say where it is with createWorker({ script }).` : `${String(error.message).split('\n')[0]}. The worker script (worker-thread.mjs) needs index.mjs, shared.mjs, choose.mjs, clustering.js and clustering.wasm next to it: keep dist/ together, and say where it is with createWorker({ script }) or, for the shared worker, init({ script }) (a path, or a file: URL). In a serverless deployment (AWS Lambda, Vercel or Netlify functions), the file tracer may have left them out: include node_modules/agglomerative-clustering/dist in the function's files.` : error.message
272
+ failure: missing(error) ? inZip(error) ? `${String(error.message).split('\n')[0]}. Under Yarn Plug'n'Play the package sits in a zip archive, which a worker thread can load its ES modules from only through Yarn's loader: run the app with yarn node (or node --require ./.pnp.cjs --loader ./.pnp.loader.mjs), or unplug the package (yarn unplug agglomerative-clustering). Otherwise keep dist/ together and say where it is with createWorker({ script }).${versions}` : `${String(error.message).split('\n')[0]}. The worker script (worker-thread.mjs) needs index.mjs, shared.mjs, choose.mjs, clustering.js and clustering.wasm next to it: keep dist/ together, and say where it is with createWorker({ script }) or, for the shared worker, init({ script }) (a path, or a file: URL). In a serverless deployment (AWS Lambda, Vercel or Netlify functions), the file tracer may have left them out: include node_modules/agglomerative-clustering/dist in the function's files.${versions}` : error.message
272
273
  }));
273
274
  worker.on('exit', code => receive({
274
275
  failure: `The worker exited unexpectedly (code ${code}).`
@@ -327,6 +328,10 @@ const send = image => {
327
328
  // An image object goes through the main entry's own checks here (its fields read once, then shape, data, detached buffer, format,
328
329
  // sizes, unknown keys, premultiplied), so what can't be sent is reported as the main entry reports it, before anything is posted.
329
330
  // A function, a Symbol or a thenable gets the shape error rather than the structured clone's.
331
+ // A bare array has to be what the main entry accepts as one (the checks it makes before its options).
332
+ if (ArrayBuffer.isView(image)) {
333
+ (0, _shared.checkPixelArray)(image);
334
+ }
330
335
  if (!ArrayBuffer.isView(image) && !(0, _shared.isImageData)(image)) {
331
336
  const copy = (0, _shared.imageCopy)(image);
332
337
  if (copy === image) {
@@ -488,81 +493,68 @@ const initOptions = (options, allowScript) => {
488
493
  return checked;
489
494
  };
490
495
 
496
+ // What the options of a call are checked against: the image's data length, format and width (a bare array is RGBA).
497
+ const imageShape = sent => ArrayBuffer.isView(sent) ? {
498
+ data: sent,
499
+ format: 'rgba',
500
+ width: undefined
501
+ } : {
502
+ data: sent.data,
503
+ format: sent.format,
504
+ width: sent.width
505
+ };
506
+
507
+ // Checks a call's options exactly as the main entry does (the same parseOptions, `allowed` being the keys the function takes,
508
+ // `image` the shape of the image it maps, if any), so a wrong option is reported here, in the main entry's order and words,
509
+ // before anything is posted or a buffer is transferred. What it returns is what is sent: the options as one plain copy, and
510
+ // `parsed`, what parseOptions made of them.
491
511
  // A signal and a progress callback can't cross to the worker, so they stay on this side: the options are sent without
492
512
  // them, a cancel message is sent when the signal aborts, and the worker's progress messages call the callback.
493
- const takeControls = (options, ditherAllowed = true) => {
494
- // Anything but an ordinary object goes on as it is, for the worker's own validation to reject. An ordinary one is copied
495
- // once first: structured cloning drops inherited properties, and the copy is what gets validated and sent.
496
- if (!(0, _shared.isOptionsObject)(options)) {
513
+ const takeControls = (options, allowed, image) => {
514
+ if (options === undefined) {
497
515
  return {
498
516
  options,
499
517
  signal: undefined,
500
- onProgress: undefined
518
+ onProgress: undefined,
519
+ parsed: (0, _shared.parseOptions)(options, allowed, image)
501
520
  };
502
521
  }
522
+ // Anything but an ordinary object is rejected by parseOptions, as in the main entry. An ordinary one is copied once first:
523
+ // structured cloning drops inherited properties, and the copy is what gets validated and sent.
524
+ if (!(0, _shared.isOptionsObject)(options)) {
525
+ (0, _shared.parseOptions)(options, allowed, image);
526
+ }
503
527
  options = (0, _shared.snapshot)(options);
504
528
  // The dither setting is an object of its own, which structured cloning would copy without its inherited keys (or not
505
- // at all, for a Proxy or a function): read it here the way the main entry does, and send a plain copy.
506
- // A function that takes no dither option rejects the key whatever its value, as the main entry does: send a value that
507
- // can cross, for the worker's validation to name the option.
508
- if (!ditherAllowed && 'dither' in options) {
509
- options.dither = null;
510
- }
529
+ // at all, for a Proxy or a function): read it here the way the main entry does, once, and validate and send the copy.
511
530
  if (options.dither !== null && (typeof options.dither === 'object' || typeof options.dither === 'function' || typeof options.dither === 'symbol')) {
512
- // One read of each setting (a getter could answer differently twice): the copy is what is checked and sent.
513
- const copy = (0, _shared.isOptionsObject)(options.dither) ? Object.assign({}, (0, _shared.snapshot)(options.dither)) : options.dither;
514
- // A wrong setting is the worker's to report, after the image and k, as the main entry orders its checks. Only a
515
- // copy that can't be sent is reported here.
516
- try {
517
- (0, _shared.parseDither)(copy);
518
- } catch (error) {
519
- if (!sendable(copy)) {
520
- throw error;
521
- }
522
- }
523
- options.dither = copy;
531
+ options.dither = (0, _shared.isOptionsObject)(options.dither) ? Object.assign({}, (0, _shared.snapshot)(options.dither)) : options.dither;
524
532
  }
525
- // The signal and the progress callback can't cross to the worker, so they are kept here and the worker gets its own.
526
- // A wrong one crosses as `null` instead, which the worker's validation
527
- // rejects with the main entry's error, after the image and k: the main entry checks the options last. (This relies on
528
- // those messages not echoing the value: if they ever say what they got, send a stand-in that reads the same.)
533
+ const parsed = (0, _shared.parseOptions)(options, allowed, image);
534
+ // Every value left is a primitive, a copy of the dither object or the signal and callback taken out here, so what is
535
+ // posted can be cloned. (The `cannot be sent` error in `unsendable` stays as a safety net for anything that still isn't.)
529
536
  const {
530
537
  signal,
531
538
  onProgress
532
539
  } = options;
533
- const badSignal = signal !== undefined && (signal === null || typeof signal !== 'object' || typeof signal.aborted !== 'boolean' || typeof signal.addEventListener !== 'function');
534
- const badProgress = onProgress !== undefined && typeof onProgress !== 'function';
535
540
  const {
536
541
  signal: _signal,
537
542
  onProgress: _onProgress,
538
543
  ...rest
539
544
  } = options;
540
- if (badSignal || badProgress) {
541
- return {
542
- options: {
543
- ...rest,
544
- ...(badSignal ? {
545
- signal: null
546
- } : {}),
547
- ...(badProgress ? {
548
- onProgress: null
549
- } : {})
550
- },
551
- signal: undefined,
552
- onProgress: undefined
553
- };
554
- }
555
545
  if (signal === undefined && onProgress === undefined) {
556
546
  return {
557
547
  options,
558
548
  signal,
559
- onProgress
549
+ onProgress,
550
+ parsed
560
551
  };
561
552
  }
562
553
  return {
563
554
  options: rest,
564
555
  signal,
565
- onProgress
556
+ onProgress,
557
+ parsed
566
558
  };
567
559
  };
568
560
 
@@ -581,24 +573,63 @@ const sendable = value => {
581
573
 
582
574
  // Where the options sit among a function's arguments after the image (see takeControls).
583
575
  const optionsPosition = {
584
- getClustering: 0,
585
- getPalette: 1,
586
- getSwatches: 1,
576
+ buildClustering: 0,
577
+ buildPalette: 1,
578
+ buildSwatches: 1,
587
579
  quantize: 1,
588
- quantizeFromClustering: 2,
589
580
  quantizeWithPalette: 1,
590
581
  quantizeToIndices: 1,
591
- quantizeToIndicesFromClustering: 2,
592
582
  quantizeToIndicesWithPalette: 1
593
583
  };
594
584
 
585
+ // The names of the arguments each call posts, for saying which one can't be sent.
586
+ const argumentNames = {
587
+ buildClustering: ['image', 'options'],
588
+ buildPalette: ['image', 'k', 'options'],
589
+ buildSwatches: ['image', 'k', 'options'],
590
+ quantize: ['image', 'k', 'options'],
591
+ quantizeToIndices: ['image', 'k', 'options'],
592
+ quantizeWithPalette: ['image', 'palette', 'options'],
593
+ quantizeToIndicesWithPalette: ['image', 'palette', 'options'],
594
+ init: ['options'],
595
+ cluster: [null, 'image', 'options'],
596
+ load: [null, 'clustering'],
597
+ handleGetPalette: [null, 'k'],
598
+ handleGetSwatches: [null, 'k'],
599
+ handleChooseFrom: [null, 'palette', 'k', 'options'],
600
+ handleQuantize: [null, 'k', 'options'],
601
+ handleQuantizeToIndices: [null, 'k', 'options'],
602
+ handleQuantizeWithPalette: [null, 'palette', 'options'],
603
+ handleQuantizeToIndicesWithPalette: [null, 'palette', 'options'],
604
+ handleQuantizeImage: [null, 'image', 'k', 'options'],
605
+ handleQuantizeToIndicesImage: [null, 'image', 'k', 'options']
606
+ };
607
+
608
+ // The error for a call whose message can't be cloned: the first argument that fails alone names itself.
609
+ const unsendable = (method, args, error) => {
610
+ const names = argumentNames[method] || [];
611
+ const index = args.findIndex((value, at) => names[at] && !sendable(value));
612
+ const cause = {
613
+ cause: error
614
+ };
615
+ return index < 0 ? Object.assign((0, _shared.fail)('invalid-argument', `Invalid argument: it cannot be sent to the worker.`), cause) : Object.assign((0, _shared.fail)('invalid-argument', `Invalid ${names[index]}: it cannot be sent to the worker.`, names[index]), cause);
616
+ };
617
+
595
618
  // Like fetch: an aborted call rejects with the signal's reason, an AbortError unless the caller gave another.
596
619
  const abortReason = signal => signal.reason !== undefined ? signal.reason : new DOMException('This operation was aborted', 'AbortError');
597
- const imageFunctions = ['getClustering', 'getPalette', 'getSwatches', 'quantize', 'quantizeFromClustering', 'quantizeWithPalette', 'quantizeToIndices', 'quantizeToIndicesFromClustering', 'quantizeToIndicesWithPalette'];
598
- const mappedImageFunctions = ['quantize', 'quantizeFromClustering', 'quantizeWithPalette'];
599
- // The functions that only cluster, and so take no dither option.
600
- const clusteringOnlyFunctions = ['getClustering', 'getPalette', 'getSwatches'];
601
- const otherFunctions = ['getPaletteFromClustering', 'getSwatchesFromClustering', 'getClusteringInfo'];
620
+
621
+ // The option keys each function takes (the main entry's lists).
622
+ const keysOf = {
623
+ buildClustering: _shared.clusterOptions,
624
+ buildPalette: _shared.clusterOptions,
625
+ buildSwatches: _shared.clusterOptions,
626
+ quantize: _shared.quantizeOptions,
627
+ quantizeToIndices: _shared.quantizeOptions,
628
+ quantizeWithPalette: _shared.mapOptions,
629
+ quantizeToIndicesWithPalette: _shared.mapIndexOptions
630
+ };
631
+ const imageFunctions = ['buildClustering', 'buildPalette', 'buildSwatches', 'quantize', 'quantizeWithPalette', 'quantizeToIndices', 'quantizeToIndicesWithPalette'];
632
+ const mappedImageFunctions = ['quantize', 'quantizeWithPalette'];
602
633
 
603
634
  // Calls each worker's `abandon` once the worker made by createWorker() has been garbage-collected (see `abandoned`).
604
635
  const abandonment = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(abandon => abandon()) : null;
@@ -629,6 +660,9 @@ const makeWorker = (options, allowScript) => {
629
660
  wasm: initialWasm
630
661
  };
631
662
  let initialising = null;
663
+ // Whether the worker script has said it is this version (the first message to every worker), and that exchange.
664
+ let shaken = false;
665
+ let shaking = null;
632
666
  let connection = null;
633
667
  let starting = null;
634
668
  // Counts the workers this instance has started, so a late message or error from one it already dropped is ignored.
@@ -646,7 +680,7 @@ const makeWorker = (options, allowScript) => {
646
680
  let nextHandle = 1;
647
681
  const pending = new Map();
648
682
  // Whether a call made now is posted before it returns (see `own`).
649
- const ready = () => connection !== null && !initial;
683
+ const ready = () => connection !== null && shaken && !initial;
650
684
  // The image of a call made before the worker is ready: with `transfer: true` its buffer is moved out of the caller's
651
685
  // hands at once (a structured clone that transfers it, so the caller's array empties now, as it would on posting),
652
686
  // otherwise copied.
@@ -685,6 +719,8 @@ const makeWorker = (options, allowScript) => {
685
719
  connection = null;
686
720
  starting = null;
687
721
  initialising = null;
722
+ shaken = false;
723
+ shaking = null;
688
724
  if (initialWasm !== undefined) {
689
725
  initial = {
690
726
  wasm: initialWasm
@@ -785,6 +821,41 @@ const makeWorker = (options, allowScript) => {
785
821
  }
786
822
  connection = connection || started;
787
823
  }
824
+ if (!shaken) {
825
+ // The first message to a worker: its script must be this version's (an older thread answers `handshake` as an
826
+ // unknown method; a 3.4-3.8 one would otherwise run calls but never see their signals or progress callbacks).
827
+ // Nothing else is posted before it answers, so a mismatch is reported to every call waiting on the worker.
828
+ if (!shaking) {
829
+ const mine = generation;
830
+ shaking = post('handshake', [], [], origin).then(theirs => {
831
+ if (theirs === _shared.version) {
832
+ shaken = true;
833
+ return;
834
+ }
835
+ throw theirs;
836
+ }, error => {
837
+ // A coded error from the call itself (terminated, failed) is passed on; only a reply that is an error
838
+ // from the thread (an unknown method) means an older script.
839
+ if (error && error.code !== undefined && error.code !== 'invalid-argument') {
840
+ throw error;
841
+ }
842
+ throw undefined;
843
+ }).catch(theirs => {
844
+ if (theirs instanceof Error) {
845
+ throw theirs;
846
+ }
847
+ if (terminated) {
848
+ throw (0, _shared.fail)('worker-terminated', "Worker terminated.");
849
+ }
850
+ const reason = `The worker script is from another version of agglomerative-clustering (${typeof theirs === 'string' ? theirs : 'an older one'}; this is ${_shared.version}). Use the worker-thread.mjs from this version.`;
851
+ if (mine === generation) {
852
+ lose(reason);
853
+ }
854
+ throw (0, _shared.fail)('worker-failed', reason);
855
+ });
856
+ }
857
+ await shaking;
858
+ }
788
859
  if (initial && !(method === 'init' && args.length > 0 && args[0].wasm !== undefined)) {
789
860
  initialising = initialising || post('init', [initial], [], origin).then(() => {
790
861
  initial = null;
@@ -887,10 +958,8 @@ const makeWorker = (options, allowScript) => {
887
958
  connection.unref();
888
959
  }
889
960
  // A value that can't be structured-cloned (a function, symbol or promise) is an invalid argument, as it
890
- // would be if the main entry were called with it.
891
- reject(error && error.name === 'DataCloneError' ? Object.assign((0, _shared.fail)('invalid-argument', `Invalid argument: it cannot be sent to the worker (${error.message})`), {
892
- cause: error
893
- }) : error);
961
+ // would be if the main entry were called with it; the first argument that fails alone is named.
962
+ reject(error && error.name === 'DataCloneError' ? unsendable(method, args.map(_shared.mark), error) : error);
894
963
  }
895
964
  });
896
965
  };
@@ -900,12 +969,34 @@ const makeWorker = (options, allowScript) => {
900
969
  instance[name] = (image, ...rest) => {
901
970
  const origin = new Error();
902
971
  return (async () => {
972
+ // A bare RGB or grey array is refused first, as in the main entry (before the options are read, an abort is
973
+ // honoured, or anything is posted or a transfer can empty the array).
974
+ const bare = (0, _shared.bareImageError)(image);
975
+ if (bare) {
976
+ throw bare;
977
+ }
978
+ // then the rest of the image's checks (its fields are read once here), before the options, as in the main entry
979
+ const checked = send(image);
903
980
  const position = optionsPosition[name];
981
+ // then the argument before the options (k, or a palette), and the options, as the main entry orders them
982
+ const shape = imageShape(checked);
983
+ const byPalette = name.endsWith('WithPalette');
984
+ if (position === 1) {
985
+ if (byPalette) {
986
+ (0, _shared.checkPalette)(rest[0]);
987
+ } else {
988
+ (0, _shared.checkK)(rest[0]);
989
+ }
990
+ }
904
991
  const {
905
992
  options,
906
993
  signal,
907
- onProgress
908
- } = takeControls(rest[position], !clusteringOnlyFunctions.includes(name));
994
+ onProgress,
995
+ parsed
996
+ } = takeControls(rest[position], keysOf[name], shape);
997
+ if (byPalette) {
998
+ (0, _shared.checkNotEmpty)(rest[0], shape, name === 'quantizeToIndicesWithPalette' && parsed.transparent > 0 ? parsed.transparent : 1);
999
+ }
909
1000
  let args = rest.slice();
910
1001
  if (position < args.length) {
911
1002
  args[position] = options;
@@ -914,7 +1005,7 @@ const makeWorker = (options, allowScript) => {
914
1005
  // The main entry reports a wrong argument before an abort, so the worker checks the arguments (a
915
1006
  // copy, never transferred: an aborted call leaves the image with the caller) without doing the work.
916
1007
  try {
917
- await invoke(name, [own(send(image)), ...args.map(own)], [], origin, {
1008
+ await invoke(name, [own(checked), ...args.map(own)], [], origin, {
918
1009
  check: true
919
1010
  });
920
1011
  } catch (error) {
@@ -924,12 +1015,7 @@ const makeWorker = (options, allowScript) => {
924
1015
  }
925
1016
  throw abortReason(signal);
926
1017
  }
927
- // The bare-image warning is decided here, on the caller's side and before a transfer can empty the
928
- // array, and given once the call succeeds: the thread checks the other arguments, and its own copy is
929
- // silenced (PRINCIPLES "Warnings").
930
- const warning = (0, _shared.bareImageWarning)(image);
931
- const byteLength = warning ? image.byteLength : 0;
932
- let sent = send(image);
1018
+ let sent = checked;
933
1019
  if (!ready()) {
934
1020
  sent = take(sent);
935
1021
  args = args.map(own);
@@ -938,21 +1024,10 @@ const makeWorker = (options, allowScript) => {
938
1024
  signal,
939
1025
  onProgress
940
1026
  });
941
- if (warning) {
942
- (0, _shared.warnOnce)(warning, byteLength);
943
- }
944
1027
  return mapped ? rebuild(image)(result) : result;
945
1028
  })();
946
1029
  };
947
1030
  }
948
- for (const name of otherFunctions) {
949
- instance[name] = (...args) => invoke(name, ready() ? args : args.map(own), [], new Error());
950
- }
951
- // 3.4.0's names for the functions that cluster an image. The old names are the same functions, and they still name the
952
- // call on the wire, so a worker script copied from an older version still understands it.
953
- instance.buildClustering = instance.getClustering;
954
- instance.buildPalette = instance.getPalette;
955
- instance.buildSwatches = instance.getSwatches;
956
1031
  instance.init = initArgs => {
957
1032
  const origin = new Error();
958
1033
  let checked;
@@ -981,7 +1056,7 @@ const makeWorker = (options, allowScript) => {
981
1056
  const looksLikeImage = value => value !== null && typeof value === 'object' && ((0, _shared.isUint8Array)(value) || (0, _shared.isUint8ClampedArray)(value) || (0, _shared.isImageData)(value) || 'data' in value);
982
1057
  // Builds the handle object for what the worker keeps under `id`: `kind` is 'image' (from `cluster`: an image and its
983
1058
  // clustering) or 'clustering' (from `load`: a clustering alone). `output` turns a mapped result back into the type of the image given.
984
- const makeHandle = (id, kind, output) => {
1059
+ const makeHandle = (id, kind, output, shape) => {
985
1060
  let released = false;
986
1061
  // Every method goes through `use`, which refers to `handle`, so a method kept after the handle itself is dropped
987
1062
  // keeps it alive and it is not reclaimed while still in use.
@@ -992,13 +1067,36 @@ const makeWorker = (options, allowScript) => {
992
1067
  return invoke(method, [id, ...args], [], new Error(), controls);
993
1068
  };
994
1069
  // Calls with mapping options, whose signal and progress callback stay on this side (see takeControls).
995
- const withControls = (method, leading, mapOptions) => {
1070
+ // `lead` is what comes first: k or a palette, checked before the options, as in the main entry. `keys` are the options the
1071
+ // method takes, and `shape` the image of this handle (see imageShape).
1072
+ const withControls = (method, leading, mapOptions, keys, lead) => {
996
1073
  let taken;
997
1074
  try {
998
- taken = takeControls(mapOptions);
1075
+ if (lead === 'palette') {
1076
+ (0, _shared.checkPalette)(leading[0]);
1077
+ } else {
1078
+ (0, _shared.checkK)(leading[0]);
1079
+ }
1080
+ taken = takeControls(mapOptions, keys, shape);
999
1081
  } catch (error) {
1000
1082
  return Promise.reject(error);
1001
1083
  }
1084
+ // A palette with no colours is wrong only if the image has pixels to map to it, which the thread knows (this side keeps
1085
+ // the image's size only). So with a signal already aborted, the thread checks the call, as the functions do, and the abort
1086
+ // is reported when that finds nothing wrong.
1087
+ if (lead === 'palette' && leading[0].length === 0 && taken.signal && taken.signal.aborted) {
1088
+ const aborted = taken.signal;
1089
+ return use(method, [...leading, taken.options], {
1090
+ check: true
1091
+ }).then(() => {
1092
+ throw abortReason(aborted);
1093
+ }, error => {
1094
+ if ((0, _shared.isCodedError)(error) && error.argument !== undefined) {
1095
+ throw error;
1096
+ }
1097
+ throw abortReason(aborted);
1098
+ });
1099
+ }
1002
1100
  return use(method, [...leading, taken.options], {
1003
1101
  signal: taken.signal,
1004
1102
  onProgress: taken.onProgress
@@ -1006,29 +1104,34 @@ const makeWorker = (options, allowScript) => {
1006
1104
  };
1007
1105
  // The cuts take no options (the handle's clustering already says how it was made): one passed anyway is an error,
1008
1106
  // as in the main entry, rather than silently ignored.
1009
- const plain = (method, name, args, extra) => extra.some(value => value !== undefined) ? Promise.reject((0, _shared.fail)('invalid-argument', `Invalid arguments: handle.${name} takes no options. To map pixels with options, use handle.quantize.`, 'options')) : use(method, args);
1107
+ const plain = (method, name, args, extra) => {
1108
+ // k first, then the options that aren't taken, as the main entry's cuts check them
1109
+ try {
1110
+ if (args.length > 0) {
1111
+ (0, _shared.checkK)(args[0]);
1112
+ }
1113
+ } catch (error) {
1114
+ return Promise.reject(error);
1115
+ }
1116
+ return extra.some(value => value !== undefined) ? Promise.reject((0, _shared.fail)('invalid-argument', `Invalid arguments: handle.${name} takes no options. To map pixels with options, use handle.quantize.`, 'options')) : use(method, args);
1117
+ };
1010
1118
  // An image where k belongs is a mix-up between the two kinds of handle: say so, rather than "k must be an integer".
1011
1119
  const imageAsK = (name, k) => looksLikeImage(k) ? Promise.reject((0, _shared.fail)('invalid-argument', `Invalid k: this handle holds an image (from worker.cluster) and maps it with ${name}(k); pass k, not an image. To map other images with a stored clustering, use worker.load(clustering).`, 'k')) : null;
1012
1120
  const handle = {
1013
1121
  getPalette: (k, ...extra) => plain('handleGetPalette', 'getPalette', [k], extra),
1014
1122
  getSwatches: (k, ...extra) => plain('handleGetSwatches', 'getSwatches', [k], extra),
1015
1123
  getClusteringInfo: (...extra) => plain('handleGetClusteringInfo', 'getClusteringInfo', [], extra),
1016
- // Takes the signal only: the main entry's chooseFrom takes no progress callback, so one given crosses as null for
1017
- // the thread to reject with the main entry's own error.
1018
- // That relies on the thread injecting a progress poster only for calls that have one (see `optionsIndex` in
1019
- // worker-thread.js): the null is then the only onProgress it sees, so its own option check rejects it.
1124
+ // Takes the signal only: the main entry's chooseFrom takes no progress callback, so one given is rejected here, by
1125
+ // the same check.
1020
1126
  chooseFrom: (palette, k, chooseOptions) => {
1021
1127
  let taken;
1022
1128
  try {
1023
- taken = takeControls(chooseOptions, false);
1129
+ (0, _shared.checkChoice)(palette, k);
1130
+ taken = takeControls(chooseOptions, ['colorSpace', 'signal']);
1024
1131
  } catch (error) {
1025
1132
  return Promise.reject(error);
1026
1133
  }
1027
- const sent = taken.onProgress !== undefined ? {
1028
- ...taken.options,
1029
- onProgress: null
1030
- } : taken.options;
1031
- return use('handleChooseFrom', [palette, k, sent], {
1134
+ return use('handleChooseFrom', [palette, k, taken.options], {
1032
1135
  signal: taken.signal
1033
1136
  });
1034
1137
  },
@@ -1056,15 +1159,15 @@ const makeWorker = (options, allowScript) => {
1056
1159
  if (kind === 'image') {
1057
1160
  Object.assign(handle, {
1058
1161
  getClustering: (...extra) => plain('handleGetClustering', 'getClustering', [], extra),
1059
- quantize: (k, mapOptions) => imageAsK('quantize', k) || (async () => output(await withControls('handleQuantize', [k], mapOptions)))(),
1060
- quantizeToIndices: (k, mapOptions) => imageAsK('quantizeToIndices', k) || withControls('handleQuantizeToIndices', [k], mapOptions),
1061
- quantizeWithPalette: async (palette, mapOptions) => output(await withControls('handleQuantizeWithPalette', [palette], mapOptions)),
1062
- quantizeToIndicesWithPalette: (palette, mapOptions) => withControls('handleQuantizeToIndicesWithPalette', [palette], mapOptions)
1162
+ quantize: (k, mapOptions) => imageAsK('quantize', k) || (async () => output(await withControls('handleQuantize', [k], mapOptions, _shared.mapOptions, 'k')))(),
1163
+ quantizeToIndices: (k, mapOptions) => imageAsK('quantizeToIndices', k) || withControls('handleQuantizeToIndices', [k], mapOptions, _shared.mapIndexOptions, 'k'),
1164
+ quantizeWithPalette: async (palette, mapOptions) => output(await withControls('handleQuantizeWithPalette', [palette], mapOptions, _shared.mapOptions, 'palette')),
1165
+ quantizeToIndicesWithPalette: (palette, mapOptions) => withControls('handleQuantizeToIndicesWithPalette', [palette], mapOptions, _shared.mapIndexOptions, 'palette')
1063
1166
  });
1064
1167
  }
1065
1168
  if (kind === 'clustering') {
1066
1169
  // The handle holds no image: each call maps the image it is given, and returns the type of that image.
1067
- const mapping = (name, method, mapped) => (image, k, mapOptions) => {
1170
+ const mapping = (name, method, mapped, keys) => (image, k, mapOptions) => {
1068
1171
  if (typeof image === 'number') {
1069
1172
  return Promise.reject((0, _shared.fail)('invalid-argument', "Invalid image: this handle holds a clustering, not an image (from worker.load); pass the image, then k.", 'image'));
1070
1173
  }
@@ -1073,15 +1176,21 @@ const makeWorker = (options, allowScript) => {
1073
1176
  if (released || !handle) {
1074
1177
  throw (0, _shared.fail)('invalid-handle', "Invalid handle: it was released.");
1075
1178
  }
1179
+ const bare = (0, _shared.bareImageError)(image);
1180
+ if (bare) {
1181
+ throw bare;
1182
+ }
1183
+ const checked = send(image);
1184
+ (0, _shared.checkK)(k);
1076
1185
  const {
1077
1186
  options,
1078
1187
  signal,
1079
1188
  onProgress
1080
- } = takeControls(mapOptions);
1189
+ } = takeControls(mapOptions, keys, imageShape(checked));
1081
1190
  if (signal && signal.aborted) {
1082
1191
  // As the functions on the worker do: a wrong argument is reported before the abort.
1083
1192
  try {
1084
- await invoke(method, [id, own(send(image)), k, options], [], origin, {
1193
+ await invoke(method, [id, own(checked), k, options], [], origin, {
1085
1194
  check: true
1086
1195
  });
1087
1196
  } catch (error) {
@@ -1091,9 +1200,7 @@ const makeWorker = (options, allowScript) => {
1091
1200
  }
1092
1201
  throw abortReason(signal);
1093
1202
  }
1094
- const warning = (0, _shared.bareImageWarning)(image);
1095
- const byteLength = warning ? image.byteLength : 0;
1096
- let sent = send(image);
1203
+ let sent = checked;
1097
1204
  const ahead = !ready();
1098
1205
  if (ahead) {
1099
1206
  sent = take(sent);
@@ -1102,15 +1209,12 @@ const makeWorker = (options, allowScript) => {
1102
1209
  signal,
1103
1210
  onProgress
1104
1211
  });
1105
- if (warning) {
1106
- (0, _shared.warnOnce)(warning, byteLength);
1107
- }
1108
1212
  return mapped ? rebuild(image)(result) : result;
1109
1213
  })();
1110
1214
  };
1111
1215
  Object.assign(handle, {
1112
- quantize: mapping('quantize', 'handleQuantizeImage', true),
1113
- quantizeToIndices: mapping('quantizeToIndices', 'handleQuantizeToIndicesImage', false)
1216
+ quantize: mapping('quantize', 'handleQuantizeImage', true, _shared.mapOptions),
1217
+ quantizeToIndices: mapping('quantizeToIndices', 'handleQuantizeToIndicesImage', false, _shared.mapIndexOptions)
1114
1218
  });
1115
1219
  }
1116
1220
  // `await using handle = await worker.cluster(image)` releases it at the end of the block.
@@ -1124,21 +1228,26 @@ const makeWorker = (options, allowScript) => {
1124
1228
  };
1125
1229
 
1126
1230
  // Clusters `image` and keeps it, with its clustering, in the worker.
1127
- instance.cluster = (image, clusterOptions) => {
1231
+ instance.cluster = (image, givenOptions) => {
1128
1232
  const origin = new Error();
1129
1233
  return (async () => {
1234
+ // The image is checked before the options and the abort, as the main entry does.
1235
+ const bare = (0, _shared.bareImageError)(image);
1236
+ if (bare) {
1237
+ throw bare;
1238
+ }
1239
+ const checked = send(image);
1240
+ const shape = imageShape(checked);
1130
1241
  const {
1131
1242
  options,
1132
1243
  signal,
1133
1244
  onProgress
1134
- } = takeControls(clusterOptions, false);
1245
+ } = takeControls(givenOptions, _shared.clusterOptions, shape);
1135
1246
  if (signal && signal.aborted) {
1136
1247
  throw abortReason(signal);
1137
1248
  }
1138
1249
  const id = nextHandle++;
1139
- const warning = (0, _shared.bareImageWarning)(image);
1140
- const byteLength = warning ? image.byteLength : 0;
1141
- const sent = ready() ? send(image) : take(send(image));
1250
+ const sent = ready() ? checked : take(checked);
1142
1251
  // Counted from before the call, so an abandoned worker isn't stopped between the call settling and the handle
1143
1252
  // existing (see `abandoned`).
1144
1253
  liveHandles++;
@@ -1157,10 +1266,13 @@ const makeWorker = (options, allowScript) => {
1157
1266
  }
1158
1267
  throw error;
1159
1268
  }
1160
- if (warning) {
1161
- (0, _shared.warnOnce)(warning, byteLength);
1162
- }
1163
- return makeHandle(id, 'image', rebuild(image));
1269
+ // The handle keeps the image's size, not its bytes (a transferred buffer is empty by now).
1270
+ return makeHandle(id, 'image', rebuild(image), {
1271
+ ...shape,
1272
+ data: {
1273
+ length: shape.data.length
1274
+ }
1275
+ });
1164
1276
  })();
1165
1277
  };
1166
1278
 
@@ -1246,29 +1358,16 @@ const init = (...args) => sharedWorker().init(...args);
1246
1358
  exports.init = init;
1247
1359
  const buildClustering = (...args) => sharedWorker().buildClustering(...args);
1248
1360
  exports.buildClustering = buildClustering;
1249
- const getClustering = exports.getClustering = buildClustering;
1250
1361
  const buildPalette = (...args) => sharedWorker().buildPalette(...args);
1251
1362
  exports.buildPalette = buildPalette;
1252
- const getPalette = exports.getPalette = buildPalette;
1253
- const getPaletteFromClustering = (...args) => sharedWorker().getPaletteFromClustering(...args);
1254
- exports.getPaletteFromClustering = getPaletteFromClustering;
1255
1363
  const buildSwatches = (...args) => sharedWorker().buildSwatches(...args);
1256
1364
  exports.buildSwatches = buildSwatches;
1257
- const getSwatches = exports.getSwatches = buildSwatches;
1258
- const getSwatchesFromClustering = (...args) => sharedWorker().getSwatchesFromClustering(...args);
1259
- exports.getSwatchesFromClustering = getSwatchesFromClustering;
1260
- const getClusteringInfo = (...args) => sharedWorker().getClusteringInfo(...args);
1261
- exports.getClusteringInfo = getClusteringInfo;
1262
1365
  const quantize = (...args) => sharedWorker().quantize(...args);
1263
1366
  exports.quantize = quantize;
1264
- const quantizeFromClustering = (...args) => sharedWorker().quantizeFromClustering(...args);
1265
- exports.quantizeFromClustering = quantizeFromClustering;
1266
1367
  const quantizeWithPalette = (...args) => sharedWorker().quantizeWithPalette(...args);
1267
1368
  exports.quantizeWithPalette = quantizeWithPalette;
1268
1369
  const quantizeToIndices = (...args) => sharedWorker().quantizeToIndices(...args);
1269
1370
  exports.quantizeToIndices = quantizeToIndices;
1270
- const quantizeToIndicesFromClustering = (...args) => sharedWorker().quantizeToIndicesFromClustering(...args);
1271
- exports.quantizeToIndicesFromClustering = quantizeToIndicesFromClustering;
1272
1371
  const quantizeToIndicesWithPalette = (...args) => sharedWorker().quantizeToIndicesWithPalette(...args);
1273
1372
  exports.quantizeToIndicesWithPalette = quantizeToIndicesWithPalette;
1274
1373
  // For file tracers (see scripts/patch-cjs.mjs); never called.