agglomerative-clustering 3.0.0-beta.4 → 3.0.0-beta.5

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/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  import createWasmModule from './clustering.js';
2
- import { version, fail, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, imageHint, latestVersion, readHeader, checkPalette, isDetached, imageDataLike } from "./shared.mjs";
2
+ import { version, fail, colorSpaces, colorSpaceName, isUint8Array, isUint8ClampedArray, isArrayBufferLike, isOptionsObject, snapshot, isPalette, isClustering, markPalette, markClustering, imageHint, latestVersion, readHeader, checkPalette, isDetached, imageDataLike, isImageData } from "./shared.mjs";
3
3
 
4
4
  // The library's version, the stored-data format version, and the Palette and Clustering types (see shared.js).
5
- export { version, Palette, Clustering } from "./shared.mjs";
5
+ export { version, Palette, Clustering, errorCodes, isCodedError } from "./shared.mjs";
6
6
  // The version of stored data (clusterings) this build writes. It reads this one and format 2 (see readHeader). Unlike
7
7
  // `version`, it changes only when the stored format does, so a 3.x release that keeps the format keeps this number.
8
8
  export const formatVersion = latestVersion;
@@ -11,8 +11,6 @@ export const formatVersion = latestVersion;
11
11
  // canvas, a WebAssembly.Module compiled by a bundler's runtime (Next.js Edge's `import wasm from '…wasm?module'`), a URL
12
12
  // from a vm context. A tag can be faked, but only on purpose, and the value is then used as what it claims to be.
13
13
  const tagOf = value => Object.prototype.toString.call(value);
14
- // (`instanceof` is kept too, for implementations without the tag, such as node-canvas's ImageData.)
15
- const isImageData = value => typeof value === 'object' && value !== null && (typeof ImageData !== 'undefined' && value instanceof ImageData || tagOf(value) === '[object ImageData]');
16
14
  const isWasmModule = value => typeof value === 'object' && value !== null && (typeof WebAssembly !== 'undefined' && value instanceof WebAssembly.Module || tagOf(value) === '[object WebAssembly.Module]');
17
15
  const isURL = value => typeof value === 'object' && value !== null && (typeof URL !== 'undefined' && value instanceof URL || tagOf(value) === '[object URL]');
18
16
  const codes = {
@@ -105,18 +103,34 @@ const wasmLoadFailed = (cause, given) => {
105
103
  // Where an explicit init({ wasm }) URL or path pointed, to name in the message.
106
104
  const where = typeof given === 'string' ? ` (${given})` : '';
107
105
  let advice;
108
- if (/Content.Security.Policy|wasm-eval|unsafe-eval|CompileError: .*(disallowed|refused)/i.test(text)) {
106
+ if (/Content.Security.Policy|blocked by CSP|wasm-eval|unsafe-eval|CompileError: .*(disallowed|refused)/i.test(text)) {
109
107
  // Chrome's message names 'wasm-eval', which Chrome rejects in an extension's manifest; 'wasm-unsafe-eval' is the one.
110
- advice = "A Content-Security-Policy blocks compiling WebAssembly: add 'wasm-unsafe-eval' to its script-src (in a browser extension, to content_security_policy.extension_pages in the manifest).";
108
+ // Which policy applies depends on where the module is compiled: a worker started from a blob: URL (the worker entry
109
+ // does that for a script from another origin, a content script's included) follows the page's.
110
+ advice = "A Content-Security-Policy blocks compiling WebAssembly: add 'wasm-unsafe-eval' to the script-src of the policy that applies. That is the page's for a page and for the worker entry's worker (also when started from a content script, whose worker follows the page's policy); for a browser extension's own pages, offscreen document and service worker, it is content_security_policy.extension_pages in the manifest.";
111
111
  } else if (!hasSimd()) {
112
112
  advice = "This engine has no WebAssembly SIMD, which the module needs (Chrome and Edge 91, Firefox 89, Safari 16.4, Node 16.4 or newer).";
113
+ } else if (/magic (word|number)|BufferSource argument is empty|wasm validation error: at offset [0-4]:/i.test(text)) {
114
+ // What a 404 page, or a server's fallback HTML page, looks like once it has been compiled as WebAssembly.
115
+ if (given === true) {
116
+ reason = `the bytes given to init({ wasm }) are not a WebAssembly module (${reason})`;
117
+ advice = "Pass this package's clustering.wasm: its bytes, its URL or path, or the module compiled from it.";
118
+ } else {
119
+ reason = `the file loaded as clustering.wasm${where} is not WebAssembly (${reason}): most likely an error page (a 404) or a fallback HTML page served in its place`;
120
+ advice = given ? "Check that URL or path: it must be this package's clustering.wasm, served with the application/wasm type." : "Check that clustering.wasm is served next to the script or emitted by your bundler (open its URL in the browser), or say where it is with init({ wasm }).";
121
+ }
113
122
  } else if (/XMLHttpRequest is not defined|both async and sync fetching|failed to fetch|NetworkError|404|ENOENT/i.test(text)) {
114
123
  reason = given ? `the .wasm file could not be fetched${where}` : 'the .wasm file could not be fetched (the package looks for clustering.wasm next to its script)';
115
- advice = given ? "Check that URL or path: it must be this package's clustering.wasm, served (not a 404) with the application/wasm type." : "Check that clustering.wasm is served next to the script or emitted by your bundler, or say where it is with init({ wasm }).";
124
+ const blocked = " If it is there, something may block the request: a Content-Security-Policy's connect-src, or, in a browser extension's content script, a clustering.wasm not listed in web_accessible_resources (the browser's console names the URL).";
125
+ advice = given ? `Check that URL or path: it must be this package's clustering.wasm, served (not a 404) with the application/wasm type.${blocked}` : `Check that clustering.wasm is served next to the script or emitted by your bundler, or say where it is with init({ wasm }).${blocked}`;
116
126
  } else if (given) {
117
127
  advice = `Check what init({ wasm }) was given${where}: it must be this package's clustering.wasm (its URL or path, its bytes, or the module compiled from it).`;
118
128
  } else if (isNodeLike) {
119
- advice = "If the package was bundled into a server build (Next.js and others), the bundler may have moved or renamed clustering.wasm: leave the package out of the bundle (in Next.js, serverExternalPackages: ['agglomerative-clustering']) or give the module with init({ wasm }).";
129
+ // The glue's `new URL('clustering.wasm', import.meta.url)`, with import.meta emptied by a CommonJS bundle.
130
+ if (/Invalid URL/i.test(reason)) {
131
+ reason = "the package doesn't know where clustering.wasm is (bundled into CommonJS, it has lost its own URL)";
132
+ }
133
+ advice = "If the package was bundled (a server build, a CommonJS bundle from esbuild or Rollup, a plugin's single file), the bundler moved clustering.wasm or dropped what tells the package where it is, and the package's own copy wasn't found from the working directory either: leave the package out of the bundle (mark it external; in Next.js, serverExternalPackages: ['agglomerative-clustering']), or say where the file is with init({ wasm: path }) or give its bytes.";
120
134
  } else {
121
135
  advice = "Check that clustering.wasm is served next to the script (not a 404, and with the application/wasm type) and allowed by the page's Content-Security-Policy, or say where it is with init({ wasm }).";
122
136
  }
@@ -182,6 +196,35 @@ const packagedWasm = async () => {
182
196
  return readFile(file);
183
197
  };
184
198
 
199
+ // In Node, init({ wasm }) given a path or a file: URL reads the file here and hands the glue its bytes. The glue reads files
200
+ // itself only when it knows it runs in Node, which it tells from import.meta.url; in a server build bundled into CommonJS
201
+ // (esbuild, Rollup, a VS Code or Obsidian plugin) that is gone, so it would try to fetch the path as if in a browser.
202
+ // Anything else (an http(s) URL, bytes, a module) is left as it is. Returns null when the option is not a file.
203
+ const nodeWasmFile = async wasm => {
204
+ if (!isNodeLike) {
205
+ return null;
206
+ }
207
+ const text = typeof wasm === 'string' ? wasm : isURL(wasm) ? wasm.href : null;
208
+ if (text === null) {
209
+ return null;
210
+ }
211
+ const isFileUrl = /^file:/i.test(text);
212
+ // A string with a scheme (http:, data:, blob:) is a URL; a Windows drive letter (C:\) is a path.
213
+ if (!isFileUrl && /^[a-z][a-z0-9+.-]+:/i.test(text) && !/^[a-z]:[\\/]/i.test(text)) {
214
+ return null;
215
+ }
216
+ const {
217
+ readFile
218
+ } = await import(/* webpackIgnore: true */ /* @vite-ignore */['node', 'fs/promises'].join(':'));
219
+ if (!isFileUrl) {
220
+ return readFile(text);
221
+ }
222
+ const {
223
+ fileURLToPath
224
+ } = await import(/* webpackIgnore: true */ /* @vite-ignore */['node', 'url'].join(':'));
225
+ return readFile(fileURLToPath(text));
226
+ };
227
+
185
228
  // The module loads once: concurrent calls share one load, and a load that fails is forgotten, so it can be retried.
186
229
  let loading = null;
187
230
 
@@ -210,7 +253,8 @@ const acquire = async options => {
210
253
  loading = (async () => {
211
254
  let instance;
212
255
  try {
213
- instance = await instantiate(wasm);
256
+ const file = await nodeWasmFile(wasm);
257
+ instance = await instantiate(file === null ? wasm : file);
214
258
  } catch (error) {
215
259
  // In Node, a bundler that rewrote the glue's `new URL('clustering.wasm', import.meta.url)` (a Next.js server
216
260
  // build, say) leaves it pointing at a file that isn't there. The package's own copy is then looked for the
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.version = exports.snapshot = exports.revive = exports.readHeader = exports.markPalette = exports.markClustering = exports.mark = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isDetached = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageDataLike = exports.formatVersion = exports.fail = exports.colorSpaces = exports.colorSpaceName = exports.checkPalette = void 0;
9
+ exports.version = exports.snapshot = exports.revive = exports.readHeader = exports.markPalette = exports.markClustering = exports.mark = exports.latestVersion = exports.isUint8ClampedArray = exports.isUint8Array = exports.isPalette = exports.isOptionsObject = exports.isImageData = exports.isDetached = exports.isCodedError = exports.isClustering = exports.isArrayBufferLike = exports.imageHint = exports.imageDataLike = exports.formatVersion = exports.fail = exports.errorCodes = exports.colorSpaces = exports.colorSpaceName = exports.checkPalette = 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 = '3.0.0-beta.4';
16
+ const version = exports.version = '3.0.0-beta.5';
17
17
  const colorSpaces = exports.colorSpaces = {
18
18
  'rgb': 0,
19
19
  'oklab': 1
@@ -26,7 +26,15 @@ const colorSpaceName = code => code === 1 ? 'oklab' : 'rgb';
26
26
  // 'worker-terminated', 'worker-failed' and 'invalid-handle'. When the error is about one argument, `argument` names it
27
27
  // for programs (the message is for people): 'image', 'k', 'clustering', 'palette', 'options', or 'options.<key>' for
28
28
  // one option.
29
+ // Every code `fail` gives, for programs that branch on them or forward them (a wrapper package, an IPC bridge).
29
30
  exports.colorSpaceName = colorSpaceName;
31
+ const errorCodes = exports.errorCodes = Object.freeze(['invalid-argument', 'invalid-clustering', 'unsupported-version', 'out-of-memory', 'wasm-load-failed', 'worker-terminated', 'worker-failed', 'invalid-handle']);
32
+
33
+ // Whether `value` is one of this library's errors: an error (or, after crossing Electron's IPC or a postMessage, a plain
34
+ // object) with a string message and one of `errorCodes`. Checking `code` alone isn't enough: Node's own errors have a
35
+ // `code` too ('ENOENT'), and an abort rejects with the signal's reason, which has none.
36
+ const isCodedError = value => value !== null && typeof value === 'object' && typeof value.message === 'string' && typeof value.code === 'string' && errorCodes.includes(value.code);
37
+ exports.isCodedError = isCodedError;
30
38
  const fail = (code, message, argument) => Object.assign(new Error(message), argument === undefined ? {
31
39
  code
32
40
  } : {
@@ -59,10 +67,16 @@ const isDetached = view => {
59
67
  }
60
68
  };
61
69
 
70
+ // An ImageData: checked by tag as well as `instanceof`, so one from another realm (an iframe's canvas) is recognised, and by
71
+ // its class's name with the shape of one, for implementations that have neither the tag nor the global (node-canvas under
72
+ // jsdom, skia-canvas, whose tag is plain [object Object]).
73
+ exports.isDetached = isDetached;
74
+ const isImageData = value => typeof value === 'object' && value !== null && (typeof ImageData !== 'undefined' && value instanceof ImageData || tag(value) === '[object ImageData]' || typeof value.constructor === 'function' && value.constructor.name === 'ImageData' && isUint8ClampedArray(value.data) && Number.isInteger(value.width) && Number.isInteger(value.height));
75
+
62
76
  // An ImageData like `like`, with these pixels: made with `like`'s own class where it has one, so an ImageData from another
63
77
  // implementation (node-canvas, in Node or under jsdom) comes back as one that implementation accepts, and where there is
64
78
  // no global ImageData at all. The colour space is kept ('display-p3' canvases), since the pixels are still in it.
65
- exports.isDetached = isDetached;
79
+ exports.isImageData = isImageData;
66
80
  const imageDataLike = (like, pixels) => {
67
81
  const {
68
82
  width,
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 = '3.0.0-beta.4';
7
+ export const version = '3.0.0-beta.5';
8
8
  export const colorSpaces = {
9
9
  'rgb': 0,
10
10
  'oklab': 1
@@ -17,6 +17,13 @@ export const colorSpaceName = code => code === 1 ? 'oklab' : 'rgb';
17
17
  // 'worker-terminated', 'worker-failed' and 'invalid-handle'. When the error is about one argument, `argument` names it
18
18
  // for programs (the message is for people): 'image', 'k', 'clustering', 'palette', 'options', or 'options.<key>' for
19
19
  // one option.
20
+ // Every code `fail` gives, for programs that branch on them or forward them (a wrapper package, an IPC bridge).
21
+ export const errorCodes = Object.freeze(['invalid-argument', 'invalid-clustering', 'unsupported-version', 'out-of-memory', 'wasm-load-failed', 'worker-terminated', 'worker-failed', 'invalid-handle']);
22
+
23
+ // Whether `value` is one of this library's errors: an error (or, after crossing Electron's IPC or a postMessage, a plain
24
+ // object) with a string message and one of `errorCodes`. Checking `code` alone isn't enough: Node's own errors have a
25
+ // `code` too ('ENOENT'), and an abort rejects with the signal's reason, which has none.
26
+ export const isCodedError = value => value !== null && typeof value === 'object' && typeof value.message === 'string' && typeof value.code === 'string' && errorCodes.includes(value.code);
20
27
  export const fail = (code, message, argument) => Object.assign(new Error(message), argument === undefined ? {
21
28
  code
22
29
  } : {
@@ -45,6 +52,11 @@ export const isDetached = view => {
45
52
  }
46
53
  };
47
54
 
55
+ // An ImageData: checked by tag as well as `instanceof`, so one from another realm (an iframe's canvas) is recognised, and by
56
+ // its class's name with the shape of one, for implementations that have neither the tag nor the global (node-canvas under
57
+ // jsdom, skia-canvas, whose tag is plain [object Object]).
58
+ export const isImageData = value => typeof value === 'object' && value !== null && (typeof ImageData !== 'undefined' && value instanceof ImageData || tag(value) === '[object ImageData]' || typeof value.constructor === 'function' && value.constructor.name === 'ImageData' && isUint8ClampedArray(value.data) && Number.isInteger(value.width) && Number.isInteger(value.height));
59
+
48
60
  // An ImageData like `like`, with these pixels: made with `like`'s own class where it has one, so an ImageData from another
49
61
  // implementation (node-canvas, in Node or under jsdom) comes back as one that implementation accepts, and where there is
50
62
  // no global ImageData at all. The colour space is kept ('display-p3' canvases), since the pixels are still in it.