@blazediff/core-native 6.0.1 → 7.0.0

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 CHANGED
@@ -49,9 +49,9 @@ Pre-built binaries are included via platform-specific packages:
49
49
 
50
50
  ## API
51
51
 
52
- ### compare(base, comparison, diffOutput, options?)
52
+ ### diff(a, b, options?)
53
53
 
54
- Compare two images from file paths or encoded `Uint8Array`/`Buffer` inputs and optionally generate a diff image. Both inputs must use the same input type. Format is auto-detected from the file extension or encoded bytes.
54
+ Compare two images and optionally draw the diff. `options` is `@blazediff/core`'s `DiffOptions`, with a wider `output`.
55
55
 
56
56
  <table>
57
57
  <tr>
@@ -60,44 +60,18 @@ Compare two images from file paths or encoded `Uint8Array`/`Buffer` inputs and o
60
60
  <th width="500">Description</th>
61
61
  </tr>
62
62
  <tr>
63
- <td><code>base</code></td>
64
- <td>string | Uint8Array</td>
65
- <td>Base/expected image path or encoded bytes</td>
66
- </tr>
67
- <tr>
68
- <td><code>comparison</code></td>
69
- <td>string | Uint8Array</td>
70
- <td>Comparison/actual image path or encoded bytes</td>
71
- </tr>
72
- <tr>
73
- <td><code>diffOutput</code></td>
74
- <td>string</td>
75
- <td>Path where the diff image will be saved</td>
63
+ <td><code>a</code>, <code>b</code></td>
64
+ <td>string | Uint8Array | Image</td>
65
+ <td>A file path, encoded PNG, JPEG or QOI bytes (a <code>Buffer</code> works), or raw RGBA pixels <code>{ data, width, height }</code>. The two sides can use different kinds</td>
76
66
  </tr>
77
67
  <tr>
78
68
  <td><code>options</code></td>
79
- <td>BlazeDiffOptions</td>
69
+ <td>NativeDiffOptions</td>
80
70
  <td>Comparison options (optional)</td>
81
71
  </tr>
82
72
  </table>
83
73
 
84
- <strong>Returns:</strong> `Promise<BlazeDiffResult>`
85
-
86
- #### Encoded Buffer Inputs
87
-
88
- ```typescript
89
- import { readFile } from "node:fs/promises";
90
- import { compare } from "@blazediff/core-native";
91
-
92
- const [expected, actual] = await Promise.all([
93
- readFile("expected.png"),
94
- readFile("actual.png"),
95
- ]);
96
-
97
- const result = await compare(expected, actual, "diff.png");
98
- ```
99
-
100
- The native binding borrows the existing `Buffer` or `Uint8Array` backing memory for the synchronous call. The encoded bytes are not copied into Rust, so the same JavaScript buffers can be reused across comparisons. Decoding still allocates native RGBA pixel buffers.
74
+ <strong>Returns:</strong> `Promise<NativeDiffResult>`
101
75
 
102
76
  <table>
103
77
  <tr>
@@ -107,77 +81,106 @@ The native binding borrows the existing `Buffer` or `Uint8Array` backing memory
107
81
  <th width="500">Description</th>
108
82
  </tr>
109
83
  <tr>
110
- <td><code>metric</code></td>
111
- <td>"pixel" | "ssim" | "ms-ssim" | "hitchhikers-ssim"</td>
112
- <td>"pixel"</td>
113
- <td>Comparison metric. <code>pixel</code> reports which pixels changed; the rest report a pooled similarity <code>score</code> in 0-1</td>
84
+ <td><code>threshold</code></td>
85
+ <td>number</td>
86
+ <td>0.1</td>
87
+ <td>Color difference threshold (0-1). Lower is stricter</td>
114
88
  </tr>
115
89
  <tr>
116
- <td><code>minScore</code></td>
117
- <td>number</td>
118
- <td>1</td>
119
- <td>Score at or above which the ssim metrics call two images identical</td>
90
+ <td><code>antialiasing</code></td>
91
+ <td>boolean</td>
92
+ <td>true</td>
93
+ <td>Detect anti-aliased pixels and leave them out of the count</td>
120
94
  </tr>
121
95
  <tr>
122
- <td><code>ssimWindowSize</code></td>
123
- <td>number</td>
124
- <td>11</td>
125
- <td>Local window size for the ssim metrics</td>
96
+ <td><code>metric</code></td>
97
+ <td>"yiq" | "oklab"</td>
98
+ <td>"yiq"</td>
99
+ <td>Color difference metric. <code>oklab</code> gives the same counts as pixelmatch 8</td>
126
100
  </tr>
127
101
  <tr>
128
- <td><code>threshold</code></td>
129
- <td>number</td>
130
- <td>0.1</td>
131
- <td>Color difference threshold (0.0-1.0). Lower = more strict. Pixel metric only</td>
102
+ <td><code>mask</code></td>
103
+ <td>Uint8Array</td>
104
+ <td>-</td>
105
+ <td>One byte per pixel (width × height). Non-zero pixels are skipped. Needs the N-API binding</td>
132
106
  </tr>
133
107
  <tr>
134
- <td><code>antialiasing</code></td>
135
- <td>boolean</td>
136
- <td>false</td>
137
- <td>Enable anti-aliasing detection to exclude AA pixels from diff count</td>
108
+ <td><code>window</code></td>
109
+ <td>number</td>
110
+ <td>-</td>
111
+ <td>Also report the N×N window with the most diff pixels</td>
138
112
  </tr>
139
113
  <tr>
140
- <td><code>diffMask</code></td>
141
- <td>boolean</td>
142
- <td>false</td>
143
- <td>Output only differences with transparent background</td>
114
+ <td><code>output</code></td>
115
+ <td>string | Image | { path, compression?, quality? }</td>
116
+ <td>-</td>
117
+ <td>Where to draw the diff: a file (PNG compression 0-9, JPEG quality 1-100), or an <code>Image</code> filled in place. A file is not written when the images are identical. An <code>Image</code> is always filled</td>
144
118
  </tr>
145
119
  <tr>
146
- <td><code>diffColorAlt</code></td>
147
- <td>[number, number, number]</td>
148
- <td>diff color</td>
149
- <td>Alternative RGB color for darkening differences</td>
120
+ <td><code>render</code></td>
121
+ <td>{ alpha?, diffColor?, diffColorAlt?, aaColor?, background? }</td>
122
+ <td>-</td>
123
+ <td>Output styling. <code>background: "transparent"</code> draws the diff alone</td>
150
124
  </tr>
151
125
  </table>
152
126
 
153
127
  ### Result Types
154
128
 
155
129
  ```typescript
156
- type BlazeDiffResult =
157
- | { match: true }
158
- | { match: false; reason: "layout-diff" }
159
- | { match: false; reason: "pixel-diff"; diffCount: number; diffPercentage: number }
160
- | { match: false; reason: "file-not-exists"; file: string };
130
+ type NativeDiffResult =
131
+ | {
132
+ kind: "compared";
133
+ count: number;
134
+ percentage: number;
135
+ identical: boolean;
136
+ /** Top-left corner and count of the busiest window, when `window` is set. */
137
+ window?: { x: number; y: number; count: number };
138
+ }
139
+ | { kind: "dimension-mismatch"; a: Size; b: Size }
140
+ | { kind: "io-error"; path?: string; message: string };
161
141
  ```
162
142
 
143
+ Invalid options or buffers throw a `BlazeDiffError` (re-exported from `@blazediff/core`) with a `code`: `invalid-image`, `invalid-output`, `invalid-mask` or `invalid-option`.
144
+
145
+ #### Encoded Buffer Inputs
146
+
147
+ ```typescript
148
+ import { readFile } from "node:fs/promises";
149
+ import { diff } from "@blazediff/core-native";
150
+
151
+ const [expected, actual] = await Promise.all([
152
+ readFile("expected.png"),
153
+ readFile("actual.png"),
154
+ ]);
155
+
156
+ const result = await diff(expected, actual, { output: "diff.png" });
157
+ ```
158
+
159
+ The native binding borrows the existing `Buffer` or `Uint8Array` backing memory for the synchronous call. The encoded bytes are not copied into Rust, so the same JavaScript buffers can be reused across comparisons. Decoding still allocates native RGBA pixel buffers.
160
+
161
+ #### CLI fallback
162
+
163
+ If the N-API binding cannot load, `diff` runs the bundled `blazediff` CLI. The fallback takes path inputs and a path output only, and no `mask`. Anything else throws.
164
+
163
165
  ## Usage
164
166
 
165
167
  ### Programmatic API
166
168
 
167
169
  ```typescript
168
- import { compare } from '@blazediff/core-native';
170
+ import { diff } from '@blazediff/core-native';
169
171
 
170
- const result = await compare('expected.png', 'actual.png', 'diff.png', {
172
+ const result = await diff('expected.png', 'actual.png', {
173
+ output: 'diff.png',
171
174
  threshold: 0.1,
172
- antialiasing: true,
173
175
  });
174
176
 
175
- if (result.match) {
176
- console.log('Images are identical!');
177
- } else if (result.reason === 'pixel-diff') {
178
- console.log(`${result.diffCount} pixels differ (${result.diffPercentage.toFixed(2)}%)`);
179
- } else if (result.reason === 'layout-diff') {
177
+ if (result.kind === 'compared') {
178
+ if (result.identical) console.log('Images are identical!');
179
+ else console.log(`${result.count} pixels differ (${result.percentage.toFixed(2)}%)`);
180
+ } else if (result.kind === 'dimension-mismatch') {
180
181
  console.log('Images have different dimensions');
182
+ } else {
183
+ console.log(`Could not read ${result.path}: ${result.message}`);
181
184
  }
182
185
  ```
183
186
 
@@ -201,58 +204,58 @@ console.log(`Severity: ${result.severity}, ${result.diffPercentage.toFixed(2)}%
201
204
 
202
205
  ```bash
203
206
  # Compare two PNG images
204
- npx blazediff expected.png actual.png diff.png
207
+ npx blazediff expected.png actual.png -o diff.png
205
208
 
206
209
  # Compare two JPEG images
207
- npx blazediff expected.jpg actual.jpg diff.jpg
208
-
209
- # Compare two QOI images
210
- npx blazediff expected.qoi actual.qoi diff.qoi
210
+ npx blazediff expected.jpg actual.jpg -o diff.jpg
211
211
 
212
212
  # Mixed formats (PNG input, QOI output - recommended for smallest diff files)
213
- npx blazediff expected.png actual.png diff.qoi
213
+ npx blazediff expected.png actual.png -o diff.qoi
214
214
 
215
215
  # With options
216
- npx blazediff expected.png actual.png diff.png --threshold 0.05 --antialiasing
216
+ npx blazediff expected.png actual.png -o diff.png --threshold 0.05 --no-antialiasing
217
217
 
218
- # Score structural similarity instead of counting pixels, and pass at 0.99
219
- npx blazediff expected.png actual.png ssim-map.png --metric ssim --min-score 0.99
218
+ # pixelmatch 8 metric, a mask, and the busiest 16×16 window
219
+ npx blazediff expected.png actual.png --metric oklab --mask mask.png --window 16
220
220
 
221
221
  # With higher PNG compression (smaller output file, slower)
222
- npx blazediff expected.png actual.png diff.png -c 6
223
-
224
- # With JPEG quality setting
225
- npx blazediff expected.jpg actual.jpg diff.jpg -q 85
222
+ npx blazediff expected.png actual.png -o diff.png -c 6
226
223
 
227
224
  # Output as JSON
228
- npx blazediff expected.png actual.png diff.png --output-format json
225
+ npx blazediff expected.png actual.png --json
229
226
  ```
230
227
 
231
228
  ### CLI Options
232
229
 
233
230
  ```
234
- Usage: blazediff [OPTIONS] <IMAGE1> <IMAGE2> [OUTPUT]
231
+ Usage: blazediff [OPTIONS] <A> <B>
235
232
 
236
233
  Arguments:
237
- <IMAGE1> First image path (PNG, JPEG, or QOI)
238
- <IMAGE2> Second image path (PNG, JPEG, or QOI)
239
- [OUTPUT] Output diff image path (optional, format detected from extension)
234
+ <A> First image path (PNG, JPEG, or QOI)
235
+ <B> Second image path (PNG, JPEG, or QOI)
240
236
 
241
237
  Options:
242
- --metric <METRIC> pixel, ssim, ms-ssim or hitchhikers-ssim [default: pixel]
243
- --min-score <SCORE> Score at or above which the ssim metrics call images identical [default: 1.0]
244
- --ssim-window-size <N> Local window size for the ssim metrics [default: 11]
245
- -t, --threshold <THRESHOLD> Color difference threshold (0.0-1.0) [default: 0.1]
246
- -a, --antialiasing Enable anti-aliasing detection
247
- --diff-mask Output only differences (transparent background)
248
- --diff-color-alt <R,G,B> Alternative RGB color for darkening differences
249
- -c, --compression <LEVEL> PNG compression level (0-9, 0=fastest, 9=smallest) [default: 0]
250
- -q, --quality <QUALITY> JPEG quality (1-100) [default: 90]
251
- --output-format <FORMAT> Output format (json or text) [default: json]
252
- -h, --help Print help
253
- -V, --version Print version
238
+ -o, --output <OUTPUT> Write the diff image (only when the images differ)
239
+ -t, --threshold <THRESHOLD> Color difference threshold (0.0-1.0) [default: 0.1]
240
+ --antialiasing Detect anti-aliased pixels and leave them out of the count (default)
241
+ --no-antialiasing Count anti-aliased pixels as differences
242
+ --metric <METRIC> Color difference metric: yiq or oklab (pixelmatch 8) [default: yiq]
243
+ --mask <MASK> Image the size of the inputs; its non-black pixels are skipped
244
+ --window <WINDOW> Also report the N×N window with the most diff pixels
245
+ -a, --alpha <ALPHA> Opacity of the faded background (0.0-1.0) [default: 0.1]
246
+ --diff-color <R,G,B> RGB color for differing pixels
247
+ --diff-color-alt <R,G,B> RGB color for pixels that get darker in the second image
248
+ --aa-color <R,G,B> RGB color for anti-aliased pixels
249
+ --background <BACKGROUND> faded or transparent [default: faded]
250
+ -c, --compression <COMPRESSION> PNG compression level (0-9, 0=fastest, 9=smallest) [default: 0]
251
+ -q, --quality <QUALITY> JPEG quality (1-100) [default: 90]
252
+ --json Print the result as JSON
253
+ -h, --help Print help
254
+ -V, --version Print version
254
255
  ```
255
256
 
257
+ With `--json`, the result object prints to stdout and an error such as `{"kind":"io-error","path":"...","message":"..."}` prints to stderr.
258
+
256
259
  ### Supported Formats
257
260
 
258
261
  | Format | Extensions | Notes |
@@ -268,7 +271,7 @@ Input images can be mixed formats (e.g., compare PNG to JPEG). Output format is
268
271
  ### Exit Codes
269
272
 
270
273
  - `0` - Images are identical
271
- - `1` - Images differ (includes layout/size mismatch)
274
+ - `1` - Images differ, or their dimensions do not match
272
275
  - `2` - Error (file not found, invalid format, etc.)
273
276
 
274
277
  ## Performance
package/dist/index.d.ts CHANGED
@@ -1,61 +1,45 @@
1
- interface BlazeDiffOptions {
2
- /** Color difference threshold (0.0-1.0). Lower = more strict. Default: 0.1 */
3
- threshold?: number;
4
- /** Enable anti-aliasing detection to exclude AA pixels from diff count */
5
- antialiasing?: boolean;
6
- /** Output only differences with transparent background */
7
- diffMask?: boolean;
8
- /** Alternative RGB color for darkening differences. Default: diff color */
9
- diffColorAlt?: [number, number, number];
10
- /** PNG compression level (0-9, 0=fastest/largest, 9=slowest/smallest) */
1
+ import { Image, DiffOptions, DiffResult } from '@blazediff/core';
2
+ export { BlazeDiffError, DiffOptions, DiffResult, Image } from '@blazediff/core';
3
+
4
+ /** A file path, encoded PNG, JPEG or QOI bytes, or raw RGBA pixels. */
5
+ type NativeInput = Image | string | Uint8Array;
6
+ /** Raw pixels drawn in place, a file path, or a file path with encoder settings. */
7
+ type NativeOutput = Image | string | {
8
+ path: string;
9
+ /** PNG compression level (0-9, 0=fastest/largest). Default: 0 */
11
10
  compression?: number;
12
11
  /** JPEG quality (1-100). Default: 90 */
13
12
  quality?: number;
14
- }
15
- /** File path or encoded PNG, JPEG, or QOI bytes. */
16
- type BlazeDiffInput = string | Uint8Array;
17
- type BlazeDiffResult = {
18
- match: true;
19
- } | {
20
- match: false;
21
- reason: "layout-diff";
22
- } | {
23
- match: false;
24
- reason: "pixel-diff";
25
- /** Differing pixels. */
26
- diffCount: number;
27
- diffPercentage: number;
28
- } | {
29
- match: false;
30
- reason: "file-not-exists";
31
- file: string;
13
+ };
14
+ type NativeDiffOptions = Omit<DiffOptions, "output"> & {
15
+ /** Draw the diff here. A file is only written when the images differ. */
16
+ output?: NativeOutput;
17
+ };
18
+ type NativeDiffResult = DiffResult | {
19
+ kind: "io-error";
20
+ path?: string;
21
+ message: string;
32
22
  };
33
23
  /**
34
- * Compare two encoded images (PNG, JPEG, or QOI) and optionally generate a diff image.
24
+ * Compares two images with the native Rust engine.
35
25
  *
36
- * Inputs must both be file paths or both be encoded byte arrays. Node.js Buffer
37
- * values are Uint8Array instances and can be passed directly.
26
+ * Inputs may be file paths, encoded PNG, JPEG or QOI bytes (a Node.js Buffer
27
+ * works), or raw RGBA `Image`s, mixed freely. Uses the N-API binding when it
28
+ * loads; otherwise falls back to the `blazediff` CLI, which supports path
29
+ * inputs, a path output and no mask.
38
30
  *
39
- * Uses native N-API bindings when available for ~10-100x better performance
40
- * on small images (no process spawn overhead). Path inputs fall back to
41
- * execFile if native bindings are unavailable.
31
+ * Unreadable inputs return `kind: "io-error"`; invalid options throw a
32
+ * {@link BlazeDiffError}.
42
33
  *
43
34
  * @example
44
35
  * ```ts
45
- * // With file paths and diff output
46
- * const result = await compare('expected.png', 'actual.png', 'diff.png');
47
- *
48
- * // With encoded image buffers
49
- * const result = await compare(expectedPngBuffer, actualPngBuffer);
50
- *
51
- * if (result.match) {
52
- * console.log('Images identical');
53
- * } else if (result.reason === 'pixel-diff') {
54
- * console.log(`${result.diffCount} pixels differ`);
36
+ * const result = await diff("expected.png", "actual.png", { output: "diff.png" });
37
+ * if (result.kind === "compared" && !result.identical) {
38
+ * console.log(`${result.count} pixels differ`);
55
39
  * }
56
40
  * ```
57
41
  */
58
- declare function compare(base: BlazeDiffInput, comparison: BlazeDiffInput, diffOutput?: string, options?: BlazeDiffOptions): Promise<BlazeDiffResult>;
42
+ declare function diff(a: NativeInput, b: NativeInput, options?: NativeDiffOptions): Promise<NativeDiffResult>;
59
43
  /** Get the path to the blazediff binary for direct CLI usage. */
60
44
  declare function getBinaryPath(): string;
61
45
  /**
@@ -64,4 +48,4 @@ declare function getBinaryPath(): string;
64
48
  */
65
49
  declare function hasNativeBinding(): boolean;
66
50
 
67
- export { type BlazeDiffInput, type BlazeDiffOptions, type BlazeDiffResult, compare, getBinaryPath, hasNativeBinding };
51
+ export { type NativeDiffOptions, type NativeDiffResult, type NativeInput, type NativeOutput, diff, getBinaryPath, hasNativeBinding };
package/dist/index.js CHANGED
@@ -30,7 +30,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
- compare: () => compare,
33
+ BlazeDiffError: () => import_core2.BlazeDiffError,
34
+ diff: () => diff,
34
35
  getBinaryPath: () => getBinaryPath,
35
36
  hasNativeBinding: () => hasNativeBinding
36
37
  });
@@ -48,18 +49,9 @@ var import_node_os = __toESM(require("os"));
48
49
  var import_node_path = __toESM(require("path"));
49
50
  var import_node_url = require("url");
50
51
  var import_node_util = require("util");
52
+ var import_core = require("@blazediff/core");
53
+ var import_core2 = require("@blazediff/core");
51
54
  var execFileAsync = (0, import_node_util.promisify)(import_node_child_process.execFile);
52
- function validateRgb(color) {
53
- if (!color) return void 0;
54
- if (color.length !== 3 || color.some(
55
- (channel) => !Number.isInteger(channel) || channel < 0 || channel > 255
56
- )) {
57
- throw new RangeError(
58
- "diffColorAlt must contain three integer RGB channels"
59
- );
60
- }
61
- return color;
62
- }
63
55
  var PLATFORM_PACKAGES = {
64
56
  "darwin-arm64": {
65
57
  packageName: "@blazediff/core-native-darwin-arm64",
@@ -103,7 +95,7 @@ function tryLoadNativeBinding() {
103
95
  try {
104
96
  const require2 = (0, import_node_module.createRequire)(importMetaUrl);
105
97
  const binding = require2(platformInfo.packageName);
106
- if (typeof binding?.compare === "function") {
98
+ if (typeof binding?.diff === "function") {
107
99
  nativeBinding = binding;
108
100
  return binding;
109
101
  }
@@ -120,7 +112,7 @@ function tryLoadNativeBinding() {
120
112
  if ((0, import_node_fs.existsSync)(nodePath)) {
121
113
  const require2 = (0, import_node_module.createRequire)(importMetaUrl);
122
114
  const binding = require2(nodePath);
123
- if (typeof binding?.compare === "function") {
115
+ if (typeof binding?.diff === "function") {
124
116
  nativeBinding = binding;
125
117
  return binding;
126
118
  }
@@ -129,30 +121,6 @@ function tryLoadNativeBinding() {
129
121
  }
130
122
  return null;
131
123
  }
132
- function convertNapiResult(result) {
133
- if (result.matchResult) {
134
- return { match: true };
135
- }
136
- if (result.reason === "layout-diff") {
137
- return { match: false, reason: "layout-diff" };
138
- }
139
- return {
140
- match: false,
141
- reason: "pixel-diff",
142
- diffCount: result.diffCount ?? 0,
143
- diffPercentage: result.diffPercentage ?? 0
144
- };
145
- }
146
- function convertToNapiOptions(options) {
147
- return {
148
- threshold: options?.threshold,
149
- antialiasing: options?.antialiasing,
150
- diffMask: options?.diffMask,
151
- diffColorAlt: validateRgb(options?.diffColorAlt),
152
- compression: options?.compression,
153
- quality: options?.quality
154
- };
155
- }
156
124
  function resolveBinaryPath() {
157
125
  const platform = import_node_os.default.platform();
158
126
  const arch = import_node_os.default.arch();
@@ -197,114 +165,149 @@ function getBinaryPathInternal() {
197
165
  }
198
166
  return cachedBinaryPath;
199
167
  }
200
- function buildArgs(diffOutput, options) {
168
+ function isBytes(value) {
169
+ return ArrayBuffer.isView(value) && value.BYTES_PER_ELEMENT === 1;
170
+ }
171
+ function asBytes(data) {
172
+ return data instanceof Uint8Array ? data : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
173
+ }
174
+ function toNapiOptions(options) {
175
+ (0, import_core.assertOptions)(options);
176
+ const { threshold, antialiasing, metric, mask, window, render } = options;
177
+ return {
178
+ threshold,
179
+ antialiasing,
180
+ metric,
181
+ mask: mask && asBytes(mask),
182
+ // Floored to >= 1 like @blazediff/core; the binding clamps to the image size.
183
+ window: window === void 0 || !Number.isFinite(window) ? void 0 : Math.max(1, Math.floor(window)),
184
+ render
185
+ };
186
+ }
187
+ function toNapiInput(input, name) {
188
+ if (typeof input === "string") return { path: input };
189
+ if (isBytes(input)) return { encoded: asBytes(input) };
190
+ (0, import_core.assertImage)(input, name, "invalid-image");
191
+ return {
192
+ image: {
193
+ data: asBytes(input.data),
194
+ width: input.width,
195
+ height: input.height
196
+ }
197
+ };
198
+ }
199
+ function toNapiOutput(output) {
200
+ if (output === void 0) return null;
201
+ if (typeof output === "string") return { path: output };
202
+ if ("path" in output) return output;
203
+ (0, import_core.assertImage)(output, "output", "invalid-output");
204
+ return { image: asBytes(output.data) };
205
+ }
206
+ function errorCode(message) {
207
+ if (/mask/i.test(message)) return "invalid-mask";
208
+ if (/^output/.test(message)) return "invalid-output";
209
+ if (/^[ab][.:]|data size/i.test(message)) return "invalid-image";
210
+ return "invalid-option";
211
+ }
212
+ function fromNapiResult(result) {
213
+ switch (result.kind) {
214
+ case "dimension-mismatch":
215
+ return {
216
+ kind: "dimension-mismatch",
217
+ a: result.a,
218
+ b: result.b
219
+ };
220
+ case "io-error":
221
+ return {
222
+ kind: "io-error",
223
+ ...result.path !== void 0 && result.path !== null && { path: result.path },
224
+ message: result.message ?? ""
225
+ };
226
+ default:
227
+ return {
228
+ kind: "compared",
229
+ count: result.count ?? 0,
230
+ percentage: result.percentage ?? 0,
231
+ identical: result.identical ?? false,
232
+ ...result.window && { window: result.window }
233
+ };
234
+ }
235
+ }
236
+ function buildArgs(output, options) {
201
237
  const args = [];
202
- if (diffOutput) args.push(diffOutput);
203
- args.push("--output-format=json");
204
- if (!options) return args;
205
- if (options.threshold !== void 0)
206
- args.push(`--threshold=${options.threshold}`);
207
- if (options.antialiasing) args.push("--antialiasing");
208
- if (options.diffMask) args.push("--diff-mask");
209
- const diffColorAlt = validateRgb(options.diffColorAlt);
210
- if (diffColorAlt) args.push(`--diff-color-alt=${diffColorAlt.join(",")}`);
211
- if (options.compression !== void 0)
212
- args.push(`--compression=${options.compression}`);
213
- if (options.quality !== void 0) args.push(`--quality=${options.quality}`);
238
+ if (output) args.push("--output", output);
239
+ args.push("--json");
240
+ const { threshold, antialiasing, metric, window, render } = options;
241
+ if (threshold !== void 0) args.push("--threshold", String(threshold));
242
+ if (antialiasing === false) args.push("--no-antialiasing");
243
+ if (metric) args.push("--metric", metric);
244
+ if (window !== void 0) args.push("--window", String(window));
245
+ if (render?.alpha !== void 0) args.push("--alpha", String(render.alpha));
246
+ if (render?.diffColor) args.push("--diff-color", render.diffColor.join(","));
247
+ if (render?.diffColorAlt)
248
+ args.push("--diff-color-alt", render.diffColorAlt.join(","));
249
+ if (render?.aaColor) args.push("--aa-color", render.aaColor.join(","));
250
+ if (render?.background) args.push("--background", render.background);
214
251
  return args;
215
252
  }
216
- function parseJsonOutput(text) {
253
+ function parseJson(text) {
217
254
  try {
218
- return JSON.parse(text);
255
+ return JSON.parse(text ?? "");
219
256
  } catch {
220
257
  return null;
221
258
  }
222
259
  }
223
- function detectMissingFile(error, basePath, comparePath) {
224
- if (!/Failed to load images:.*(?:No such file|not found)/i.test(error)) {
225
- return null;
226
- }
227
- if (error.includes(basePath)) return basePath;
228
- if (error.includes(comparePath)) return comparePath;
229
- return basePath;
230
- }
231
- async function execFileCompare(basePath, comparePath, diffOutput, options) {
232
- const binaryPath = getBinaryPathInternal();
233
- const args = [basePath, comparePath, ...buildArgs(diffOutput, options)];
260
+ async function execFileDiff(a, b, output, options) {
261
+ const args = [a, b, ...buildArgs(output?.path, options)];
262
+ if (output?.compression !== void 0)
263
+ args.push("--compression", String(output.compression));
264
+ if (output?.quality !== void 0)
265
+ args.push("--quality", String(output.quality));
266
+ let stdout;
234
267
  try {
235
- await execFileAsync(binaryPath, args);
236
- return { match: true };
268
+ ({ stdout } = await execFileAsync(getBinaryPathInternal(), args));
237
269
  } catch (err) {
238
- const { code, stdout, stderr } = err;
239
- const output = stdout || stderr || "";
240
- if (code === 1) {
241
- const json = parseJsonOutput(output);
242
- if (json?.error?.includes("Layout differs")) {
243
- return { match: false, reason: "layout-diff" };
244
- }
245
- if (json) {
246
- return {
247
- match: false,
248
- reason: "pixel-diff",
249
- diffCount: json.diffCount,
250
- diffPercentage: json.diffPercentage
251
- };
252
- }
253
- if (output.includes("Layout differs")) {
254
- return { match: false, reason: "layout-diff" };
255
- }
256
- }
257
- if (code === 2) {
258
- const missingFile = detectMissingFile(output, basePath, comparePath);
259
- if (missingFile) {
260
- return { match: false, reason: "file-not-exists", file: missingFile };
261
- }
270
+ const failure = err;
271
+ if (failure.code !== 1) {
272
+ const json2 = parseJson(failure.stderr);
273
+ if (json2?.kind === "io-error") return fromNapiResult(json2);
274
+ throw new Error(
275
+ json2?.message ?? (failure.stderr || `blazediff exited with code ${failure.code}`)
276
+ );
262
277
  }
263
- throw new Error(output || `blazediff exited with code ${code}`);
278
+ stdout = failure.stdout;
264
279
  }
280
+ const json = parseJson(stdout);
281
+ if (!json) throw new Error(`blazediff printed invalid JSON: ${stdout}`);
282
+ return fromNapiResult(json);
265
283
  }
266
- async function compare(base, comparison, diffOutput, options) {
267
- const baseIsPath = typeof base === "string";
268
- const comparisonIsPath = typeof comparison === "string";
269
- if (baseIsPath !== comparisonIsPath) {
270
- throw new TypeError(
271
- "Image inputs must both be file paths or both be encoded byte arrays"
272
- );
273
- }
284
+ async function diff(a, b, options = {}) {
285
+ const napiOptions = toNapiOptions(options);
286
+ const napiA = toNapiInput(a, "a");
287
+ const napiB = toNapiInput(b, "b");
288
+ const napiOutput = toNapiOutput(options.output);
274
289
  const binding = tryLoadNativeBinding();
275
290
  if (binding) {
276
291
  try {
277
- const result = baseIsPath && comparisonIsPath ? binding.compare(
278
- base,
279
- comparison,
280
- diffOutput ?? null,
281
- convertToNapiOptions(options)
282
- ) : binding.compareBuffers(
283
- base,
284
- comparison,
285
- diffOutput ?? null,
286
- convertToNapiOptions(options)
292
+ return fromNapiResult(
293
+ binding.diff(napiA, napiB, napiOutput, napiOptions)
287
294
  );
288
- return convertNapiResult(result);
289
295
  } catch (err) {
290
- if (baseIsPath && comparisonIsPath) {
291
- const message = err instanceof Error ? err.message : String(err);
292
- const missingFile = detectMissingFile(message, base, comparison);
293
- if (missingFile) {
294
- return {
295
- match: false,
296
- reason: "file-not-exists",
297
- file: missingFile
298
- };
299
- }
300
- }
296
+ const { code, message } = err;
297
+ if (code === "InvalidArg" && message)
298
+ throw new import_core.BlazeDiffError(errorCode(message), message);
301
299
  throw err;
302
300
  }
303
301
  }
304
- if (!baseIsPath || !comparisonIsPath) {
305
- throw new Error("Encoded image inputs require the native N-API binding");
306
- }
307
- return execFileCompare(base, comparison, diffOutput, options);
302
+ if (napiA.path === void 0 || napiB.path === void 0)
303
+ throw new Error(
304
+ "Encoded and raw image inputs require the native N-API binding"
305
+ );
306
+ if (napiOutput?.image)
307
+ throw new Error("An Image output requires the native N-API binding");
308
+ if (napiOptions.mask)
309
+ throw new Error("mask requires the native N-API binding");
310
+ return execFileDiff(napiA.path, napiB.path, napiOutput, napiOptions);
308
311
  }
309
312
  function getBinaryPath() {
310
313
  return getBinaryPathInternal();
@@ -314,7 +317,8 @@ function hasNativeBinding() {
314
317
  }
315
318
  // Annotate the CommonJS export names for ESM import in node:
316
319
  0 && (module.exports = {
317
- compare,
320
+ BlazeDiffError,
321
+ diff,
318
322
  getBinaryPath,
319
323
  hasNativeBinding
320
324
  });
package/dist/index.mjs CHANGED
@@ -6,18 +6,13 @@ import os from "os";
6
6
  import path from "path";
7
7
  import { fileURLToPath } from "url";
8
8
  import { promisify } from "util";
9
+ import {
10
+ assertImage,
11
+ assertOptions,
12
+ BlazeDiffError
13
+ } from "@blazediff/core";
14
+ import { BlazeDiffError as BlazeDiffError2 } from "@blazediff/core";
9
15
  var execFileAsync = promisify(execFile);
10
- function validateRgb(color) {
11
- if (!color) return void 0;
12
- if (color.length !== 3 || color.some(
13
- (channel) => !Number.isInteger(channel) || channel < 0 || channel > 255
14
- )) {
15
- throw new RangeError(
16
- "diffColorAlt must contain three integer RGB channels"
17
- );
18
- }
19
- return color;
20
- }
21
16
  var PLATFORM_PACKAGES = {
22
17
  "darwin-arm64": {
23
18
  packageName: "@blazediff/core-native-darwin-arm64",
@@ -61,7 +56,7 @@ function tryLoadNativeBinding() {
61
56
  try {
62
57
  const require2 = createRequire(import.meta.url);
63
58
  const binding = require2(platformInfo.packageName);
64
- if (typeof binding?.compare === "function") {
59
+ if (typeof binding?.diff === "function") {
65
60
  nativeBinding = binding;
66
61
  return binding;
67
62
  }
@@ -78,7 +73,7 @@ function tryLoadNativeBinding() {
78
73
  if (existsSync(nodePath)) {
79
74
  const require2 = createRequire(import.meta.url);
80
75
  const binding = require2(nodePath);
81
- if (typeof binding?.compare === "function") {
76
+ if (typeof binding?.diff === "function") {
82
77
  nativeBinding = binding;
83
78
  return binding;
84
79
  }
@@ -87,30 +82,6 @@ function tryLoadNativeBinding() {
87
82
  }
88
83
  return null;
89
84
  }
90
- function convertNapiResult(result) {
91
- if (result.matchResult) {
92
- return { match: true };
93
- }
94
- if (result.reason === "layout-diff") {
95
- return { match: false, reason: "layout-diff" };
96
- }
97
- return {
98
- match: false,
99
- reason: "pixel-diff",
100
- diffCount: result.diffCount ?? 0,
101
- diffPercentage: result.diffPercentage ?? 0
102
- };
103
- }
104
- function convertToNapiOptions(options) {
105
- return {
106
- threshold: options?.threshold,
107
- antialiasing: options?.antialiasing,
108
- diffMask: options?.diffMask,
109
- diffColorAlt: validateRgb(options?.diffColorAlt),
110
- compression: options?.compression,
111
- quality: options?.quality
112
- };
113
- }
114
85
  function resolveBinaryPath() {
115
86
  const platform = os.platform();
116
87
  const arch = os.arch();
@@ -155,114 +126,149 @@ function getBinaryPathInternal() {
155
126
  }
156
127
  return cachedBinaryPath;
157
128
  }
158
- function buildArgs(diffOutput, options) {
129
+ function isBytes(value) {
130
+ return ArrayBuffer.isView(value) && value.BYTES_PER_ELEMENT === 1;
131
+ }
132
+ function asBytes(data) {
133
+ return data instanceof Uint8Array ? data : new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
134
+ }
135
+ function toNapiOptions(options) {
136
+ assertOptions(options);
137
+ const { threshold, antialiasing, metric, mask, window, render } = options;
138
+ return {
139
+ threshold,
140
+ antialiasing,
141
+ metric,
142
+ mask: mask && asBytes(mask),
143
+ // Floored to >= 1 like @blazediff/core; the binding clamps to the image size.
144
+ window: window === void 0 || !Number.isFinite(window) ? void 0 : Math.max(1, Math.floor(window)),
145
+ render
146
+ };
147
+ }
148
+ function toNapiInput(input, name) {
149
+ if (typeof input === "string") return { path: input };
150
+ if (isBytes(input)) return { encoded: asBytes(input) };
151
+ assertImage(input, name, "invalid-image");
152
+ return {
153
+ image: {
154
+ data: asBytes(input.data),
155
+ width: input.width,
156
+ height: input.height
157
+ }
158
+ };
159
+ }
160
+ function toNapiOutput(output) {
161
+ if (output === void 0) return null;
162
+ if (typeof output === "string") return { path: output };
163
+ if ("path" in output) return output;
164
+ assertImage(output, "output", "invalid-output");
165
+ return { image: asBytes(output.data) };
166
+ }
167
+ function errorCode(message) {
168
+ if (/mask/i.test(message)) return "invalid-mask";
169
+ if (/^output/.test(message)) return "invalid-output";
170
+ if (/^[ab][.:]|data size/i.test(message)) return "invalid-image";
171
+ return "invalid-option";
172
+ }
173
+ function fromNapiResult(result) {
174
+ switch (result.kind) {
175
+ case "dimension-mismatch":
176
+ return {
177
+ kind: "dimension-mismatch",
178
+ a: result.a,
179
+ b: result.b
180
+ };
181
+ case "io-error":
182
+ return {
183
+ kind: "io-error",
184
+ ...result.path !== void 0 && result.path !== null && { path: result.path },
185
+ message: result.message ?? ""
186
+ };
187
+ default:
188
+ return {
189
+ kind: "compared",
190
+ count: result.count ?? 0,
191
+ percentage: result.percentage ?? 0,
192
+ identical: result.identical ?? false,
193
+ ...result.window && { window: result.window }
194
+ };
195
+ }
196
+ }
197
+ function buildArgs(output, options) {
159
198
  const args = [];
160
- if (diffOutput) args.push(diffOutput);
161
- args.push("--output-format=json");
162
- if (!options) return args;
163
- if (options.threshold !== void 0)
164
- args.push(`--threshold=${options.threshold}`);
165
- if (options.antialiasing) args.push("--antialiasing");
166
- if (options.diffMask) args.push("--diff-mask");
167
- const diffColorAlt = validateRgb(options.diffColorAlt);
168
- if (diffColorAlt) args.push(`--diff-color-alt=${diffColorAlt.join(",")}`);
169
- if (options.compression !== void 0)
170
- args.push(`--compression=${options.compression}`);
171
- if (options.quality !== void 0) args.push(`--quality=${options.quality}`);
199
+ if (output) args.push("--output", output);
200
+ args.push("--json");
201
+ const { threshold, antialiasing, metric, window, render } = options;
202
+ if (threshold !== void 0) args.push("--threshold", String(threshold));
203
+ if (antialiasing === false) args.push("--no-antialiasing");
204
+ if (metric) args.push("--metric", metric);
205
+ if (window !== void 0) args.push("--window", String(window));
206
+ if (render?.alpha !== void 0) args.push("--alpha", String(render.alpha));
207
+ if (render?.diffColor) args.push("--diff-color", render.diffColor.join(","));
208
+ if (render?.diffColorAlt)
209
+ args.push("--diff-color-alt", render.diffColorAlt.join(","));
210
+ if (render?.aaColor) args.push("--aa-color", render.aaColor.join(","));
211
+ if (render?.background) args.push("--background", render.background);
172
212
  return args;
173
213
  }
174
- function parseJsonOutput(text) {
214
+ function parseJson(text) {
175
215
  try {
176
- return JSON.parse(text);
216
+ return JSON.parse(text ?? "");
177
217
  } catch {
178
218
  return null;
179
219
  }
180
220
  }
181
- function detectMissingFile(error, basePath, comparePath) {
182
- if (!/Failed to load images:.*(?:No such file|not found)/i.test(error)) {
183
- return null;
184
- }
185
- if (error.includes(basePath)) return basePath;
186
- if (error.includes(comparePath)) return comparePath;
187
- return basePath;
188
- }
189
- async function execFileCompare(basePath, comparePath, diffOutput, options) {
190
- const binaryPath = getBinaryPathInternal();
191
- const args = [basePath, comparePath, ...buildArgs(diffOutput, options)];
221
+ async function execFileDiff(a, b, output, options) {
222
+ const args = [a, b, ...buildArgs(output?.path, options)];
223
+ if (output?.compression !== void 0)
224
+ args.push("--compression", String(output.compression));
225
+ if (output?.quality !== void 0)
226
+ args.push("--quality", String(output.quality));
227
+ let stdout;
192
228
  try {
193
- await execFileAsync(binaryPath, args);
194
- return { match: true };
229
+ ({ stdout } = await execFileAsync(getBinaryPathInternal(), args));
195
230
  } catch (err) {
196
- const { code, stdout, stderr } = err;
197
- const output = stdout || stderr || "";
198
- if (code === 1) {
199
- const json = parseJsonOutput(output);
200
- if (json?.error?.includes("Layout differs")) {
201
- return { match: false, reason: "layout-diff" };
202
- }
203
- if (json) {
204
- return {
205
- match: false,
206
- reason: "pixel-diff",
207
- diffCount: json.diffCount,
208
- diffPercentage: json.diffPercentage
209
- };
210
- }
211
- if (output.includes("Layout differs")) {
212
- return { match: false, reason: "layout-diff" };
213
- }
214
- }
215
- if (code === 2) {
216
- const missingFile = detectMissingFile(output, basePath, comparePath);
217
- if (missingFile) {
218
- return { match: false, reason: "file-not-exists", file: missingFile };
219
- }
231
+ const failure = err;
232
+ if (failure.code !== 1) {
233
+ const json2 = parseJson(failure.stderr);
234
+ if (json2?.kind === "io-error") return fromNapiResult(json2);
235
+ throw new Error(
236
+ json2?.message ?? (failure.stderr || `blazediff exited with code ${failure.code}`)
237
+ );
220
238
  }
221
- throw new Error(output || `blazediff exited with code ${code}`);
239
+ stdout = failure.stdout;
222
240
  }
241
+ const json = parseJson(stdout);
242
+ if (!json) throw new Error(`blazediff printed invalid JSON: ${stdout}`);
243
+ return fromNapiResult(json);
223
244
  }
224
- async function compare(base, comparison, diffOutput, options) {
225
- const baseIsPath = typeof base === "string";
226
- const comparisonIsPath = typeof comparison === "string";
227
- if (baseIsPath !== comparisonIsPath) {
228
- throw new TypeError(
229
- "Image inputs must both be file paths or both be encoded byte arrays"
230
- );
231
- }
245
+ async function diff(a, b, options = {}) {
246
+ const napiOptions = toNapiOptions(options);
247
+ const napiA = toNapiInput(a, "a");
248
+ const napiB = toNapiInput(b, "b");
249
+ const napiOutput = toNapiOutput(options.output);
232
250
  const binding = tryLoadNativeBinding();
233
251
  if (binding) {
234
252
  try {
235
- const result = baseIsPath && comparisonIsPath ? binding.compare(
236
- base,
237
- comparison,
238
- diffOutput ?? null,
239
- convertToNapiOptions(options)
240
- ) : binding.compareBuffers(
241
- base,
242
- comparison,
243
- diffOutput ?? null,
244
- convertToNapiOptions(options)
253
+ return fromNapiResult(
254
+ binding.diff(napiA, napiB, napiOutput, napiOptions)
245
255
  );
246
- return convertNapiResult(result);
247
256
  } catch (err) {
248
- if (baseIsPath && comparisonIsPath) {
249
- const message = err instanceof Error ? err.message : String(err);
250
- const missingFile = detectMissingFile(message, base, comparison);
251
- if (missingFile) {
252
- return {
253
- match: false,
254
- reason: "file-not-exists",
255
- file: missingFile
256
- };
257
- }
258
- }
257
+ const { code, message } = err;
258
+ if (code === "InvalidArg" && message)
259
+ throw new BlazeDiffError(errorCode(message), message);
259
260
  throw err;
260
261
  }
261
262
  }
262
- if (!baseIsPath || !comparisonIsPath) {
263
- throw new Error("Encoded image inputs require the native N-API binding");
264
- }
265
- return execFileCompare(base, comparison, diffOutput, options);
263
+ if (napiA.path === void 0 || napiB.path === void 0)
264
+ throw new Error(
265
+ "Encoded and raw image inputs require the native N-API binding"
266
+ );
267
+ if (napiOutput?.image)
268
+ throw new Error("An Image output requires the native N-API binding");
269
+ if (napiOptions.mask)
270
+ throw new Error("mask requires the native N-API binding");
271
+ return execFileDiff(napiA.path, napiB.path, napiOutput, napiOptions);
266
272
  }
267
273
  function getBinaryPath() {
268
274
  return getBinaryPathInternal();
@@ -271,7 +277,8 @@ function hasNativeBinding() {
271
277
  return tryLoadNativeBinding() !== null;
272
278
  }
273
279
  export {
274
- compare,
280
+ BlazeDiffError2 as BlazeDiffError,
281
+ diff,
275
282
  getBinaryPath,
276
283
  hasNativeBinding
277
284
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blazediff/core-native",
3
- "version": "6.0.1",
3
+ "version": "7.0.0",
4
4
  "description": "Native Rust binaries for blazediff - the fastest image diff in the world",
5
5
  "private": false,
6
6
  "publishConfig": {
@@ -19,13 +19,16 @@
19
19
  "files": [
20
20
  "dist"
21
21
  ],
22
+ "dependencies": {
23
+ "@blazediff/core": "2.0.0"
24
+ },
22
25
  "optionalDependencies": {
23
- "@blazediff/core-native-darwin-arm64": "6.0.1",
24
- "@blazediff/core-native-darwin-x64": "6.0.1",
25
- "@blazediff/core-native-linux-arm64": "6.0.1",
26
- "@blazediff/core-native-linux-x64": "6.0.1",
27
- "@blazediff/core-native-win32-arm64": "6.0.1",
28
- "@blazediff/core-native-win32-x64": "6.0.1"
26
+ "@blazediff/core-native-darwin-arm64": "7.0.0",
27
+ "@blazediff/core-native-darwin-x64": "7.0.0",
28
+ "@blazediff/core-native-linux-arm64": "7.0.0",
29
+ "@blazediff/core-native-linux-x64": "7.0.0",
30
+ "@blazediff/core-native-win32-arm64": "7.0.0",
31
+ "@blazediff/core-native-win32-x64": "7.0.0"
29
32
  },
30
33
  "keywords": [
31
34
  "image",
@@ -50,8 +53,7 @@
50
53
  "pngjs": "^7.0.0",
51
54
  "tsup": "8.5.0",
52
55
  "typescript": "5.9.2",
53
- "vitest": "^3.2.4",
54
- "@blazediff/core": "1.10.0"
56
+ "vitest": "^3.2.4"
55
57
  },
56
58
  "scripts": {
57
59
  "typecheck": "tsc --noEmit",