@rosepetal/node-red-contrib-image-tools 1.6.3 → 1.7.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.
Files changed (60) hide show
  1. package/.claude/rules/node-implementation-template.md +1 -1
  2. package/README.md +2 -0
  3. package/node-red-contrib-image-tools/lib/bmp-decode.js +18 -68
  4. package/node-red-contrib-image-tools/lib/cpp-bridge.js +202 -104
  5. package/node-red-contrib-image-tools/lib/node-utils.js +78 -78
  6. package/node-red-contrib-image-tools/nodes/blend/add-bbs.html +11 -4
  7. package/node-red-contrib-image-tools/nodes/blend/add-mask.html +11 -4
  8. package/node-red-contrib-image-tools/nodes/blend/add-masks.html +11 -4
  9. package/node-red-contrib-image-tools/nodes/blend/blend.html +11 -4
  10. package/node-red-contrib-image-tools/nodes/io/folder-in.js +98 -46
  11. package/node-red-contrib-image-tools/nodes/io/image-in.js +3 -4
  12. package/node-red-contrib-image-tools/nodes/io/image-out.html +11 -4
  13. package/node-red-contrib-image-tools/nodes/io/image-out.js +93 -146
  14. package/node-red-contrib-image-tools/nodes/mix/advanced-mosaic.html +11 -4
  15. package/node-red-contrib-image-tools/nodes/mix/concat.html +11 -4
  16. package/node-red-contrib-image-tools/nodes/mix/mosaic.html +11 -4
  17. package/node-red-contrib-image-tools/nodes/specialized/cropBB.js +3 -3
  18. package/node-red-contrib-image-tools/nodes/specialized/heat-diff.js +3 -3
  19. package/node-red-contrib-image-tools/nodes/specialized/image-align.html +3 -2
  20. package/node-red-contrib-image-tools/nodes/specialized/image-align.js +3 -3
  21. package/node-red-contrib-image-tools/nodes/transform/color-convert.js +3 -3
  22. package/node-red-contrib-image-tools/nodes/transform/crop.html +11 -4
  23. package/node-red-contrib-image-tools/nodes/transform/crop.js +3 -3
  24. package/node-red-contrib-image-tools/nodes/transform/filter.html +11 -4
  25. package/node-red-contrib-image-tools/nodes/transform/filter.js +3 -3
  26. package/node-red-contrib-image-tools/nodes/transform/padding.html +11 -4
  27. package/node-red-contrib-image-tools/nodes/transform/padding.js +3 -3
  28. package/node-red-contrib-image-tools/nodes/transform/resize.html +3 -3
  29. package/node-red-contrib-image-tools/nodes/transform/resize.js +3 -3
  30. package/node-red-contrib-image-tools/nodes/transform/rotate.html +11 -4
  31. package/node-red-contrib-image-tools/nodes/transform/rotate.js +3 -3
  32. package/npm/darwin-arm64/package.json +1 -1
  33. package/npm/darwin-x64/package.json +1 -1
  34. package/npm/linux-arm64/package.json +1 -1
  35. package/npm/linux-x64/package.json +1 -1
  36. package/npm/linuxmusl-x64/package.json +1 -1
  37. package/npm/win32-x64/package.json +1 -1
  38. package/package.json +6 -6
  39. package/rosepetal-image-engine/binding.gyp +2 -1
  40. package/rosepetal-image-engine/src/add-bbs.cpp +123 -123
  41. package/rosepetal-image-engine/src/add-mask.cpp +30 -15
  42. package/rosepetal-image-engine/src/add-masks.cpp +145 -102
  43. package/rosepetal-image-engine/src/advanced-mosaic.cpp +200 -129
  44. package/rosepetal-image-engine/src/blend.cpp +34 -20
  45. package/rosepetal-image-engine/src/codec.cpp +157 -0
  46. package/rosepetal-image-engine/src/color-convert.cpp +22 -19
  47. package/rosepetal-image-engine/src/concat.cpp +38 -43
  48. package/rosepetal-image-engine/src/crop.cpp +23 -26
  49. package/rosepetal-image-engine/src/draw.cpp +33 -10
  50. package/rosepetal-image-engine/src/filter.cpp +22 -26
  51. package/rosepetal-image-engine/src/heat-diff.cpp +31 -8
  52. package/rosepetal-image-engine/src/image-align.cpp +36 -32
  53. package/rosepetal-image-engine/src/main.cpp +4 -0
  54. package/rosepetal-image-engine/src/mosaic.cpp +31 -40
  55. package/rosepetal-image-engine/src/padding.cpp +30 -29
  56. package/rosepetal-image-engine/src/resize.cpp +20 -25
  57. package/rosepetal-image-engine/src/rotate.cpp +22 -23
  58. package/rosepetal-image-engine/src/utils.h +243 -144
  59. package/scripts/dual-register.js +32 -25
  60. package/scripts/sync-version.js +58 -41
@@ -122,4 +122,4 @@ These are the names doc-writer is allowed to reference in Examples:
122
122
  - `handleNodeErrorWithPassthrough`, `handleValidationErrorWithPassthrough` — error path
123
123
  - `recordPerformanceMetrics` — sets `msg.performance.rpimage.<key>`
124
124
  - `debugImageDisplay` — emits the editor preview via `RED.comms.publish('debug-image', …)`
125
- - `rawToJpeg`, `encodeWebpAdvanced` — Sharp-based encoders
125
+ - `rawToJpeg`, `encodeWebpAdvanced` — Sharp-based encoders (BGR/BGRA inputs are converted natively via `toSharpRaw`)
package/README.md CHANGED
@@ -80,6 +80,7 @@ cd ~/.node-red && npm install /path/to/node-red-contrib-image-tools
80
80
  - **Parallel processing** for array operations
81
81
  - **Memory efficient** with optimized algorithms
82
82
  - **Async operations** with real-time performance timing
83
+ - **Never blocks the event loop**: decoding, processing and encoding (including BMP and colour-space swaps) all run on the libuv thread pool; the JavaScript layer only validates and routes messages
83
84
 
84
85
  ### Image Data Format
85
86
  ```javascript
@@ -133,6 +134,7 @@ rosepetal-image-engine/ # C++ processing engine
133
134
  - Process **arrays when possible** for parallel execution
134
135
  - Choose **appropriate output formats** for your destination
135
136
  - Monitor **node status displays** for timing information
137
+ - Under heavy concurrency, raise the libuv thread pool (default 4 threads, shared with `sharp` and file I/O) before starting Node-RED, e.g. `UV_THREADPOOL_SIZE=8 node-red`
136
138
 
137
139
  ## 🤝 Contributing
138
140
 
@@ -1,79 +1,29 @@
1
1
  /**
2
- * @file Pure-JS BMP decoder for uncompressed BI_RGB files (8/24/32-bit).
3
- * Read-side counterpart of encodeBmpRaw in image-out; Sharp cannot read BMP.
2
+ * @file BMP support for the image-in / folder-in nodes.
3
+ * Sharp cannot read BMP, so BMP files are decoded by the native engine
4
+ * (OpenCV, on the libuv thread pool) instead of a pure-JS pixel loop that
5
+ * would block the Node-RED event loop.
4
6
  * @author Rosepetal
5
7
  */
6
8
 
9
+ const Cpp = require('./cpp-bridge.js');
10
+
7
11
  function isBmp(buf) {
8
12
  return Buffer.isBuffer(buf) && buf.length >= 2 && buf[0] === 0x42 && buf[1] === 0x4D;
9
13
  }
10
14
 
11
- // Decodes a BMP buffer to the toolkit's raw image object.
12
- // Supports 8-bit palette, 24-bit and 32-bit uncompressed, top-down and bottom-up.
13
- function decodeBmp(buf) {
14
- if (!isBmp(buf) || buf.length < 54) throw new Error('Invalid BMP file');
15
-
16
- const pixelOffset = buf.readUInt32LE(10);
17
- const infoSize = buf.readUInt32LE(14);
18
- if (infoSize < 40) throw new Error(`Unsupported BMP header (size ${infoSize})`);
19
-
20
- const width = buf.readInt32LE(18);
21
- const rawHeight = buf.readInt32LE(22);
22
- const bpp = buf.readUInt16LE(28);
23
- const compression = buf.readUInt32LE(30);
24
-
25
- const topDown = rawHeight < 0;
26
- const height = Math.abs(rawHeight);
27
- if (width <= 0 || height === 0) throw new Error('Invalid BMP dimensions');
28
- if (compression !== 0) throw new Error(`Unsupported BMP compression ${compression} (only uncompressed BI_RGB)`);
29
- if (bpp !== 8 && bpp !== 24 && bpp !== 32) throw new Error(`Unsupported BMP bit depth ${bpp} (only 8/24/32)`);
30
-
31
- const srcStride = (width * (bpp / 8) + 3) & ~3;
32
- if (pixelOffset + srcStride * height > buf.length) throw new Error('Corrupt BMP: pixel data truncated');
33
-
34
- // 8-bit files carry a BGRA palette; an all-gray palette maps to a GRAY image
35
- let palette = null;
36
- let grayPalette = false;
37
- if (bpp === 8) {
38
- const colors = buf.readUInt32LE(46) || 256;
39
- const palOffset = 14 + infoSize;
40
- if (palOffset + colors * 4 > buf.length) throw new Error('Corrupt BMP: palette truncated');
41
- palette = [];
42
- grayPalette = true;
43
- for (let i = 0; i < colors; i++) {
44
- const b = buf[palOffset + i * 4], g = buf[palOffset + i * 4 + 1], r = buf[palOffset + i * 4 + 2];
45
- if (r !== g || g !== b) grayPalette = false;
46
- palette.push([r, g, b]);
47
- }
48
- }
49
-
50
- const channels = bpp === 32 ? 4 : (bpp === 24 || !grayPalette) ? 3 : 1;
51
- const colorSpace = channels === 4 ? 'RGBA' : channels === 3 ? 'RGB' : 'GRAY';
52
- const out = Buffer.alloc(width * height * channels);
53
-
54
- for (let y = 0; y < height; y++) {
55
- const srcRow = pixelOffset + (topDown ? y : height - 1 - y) * srcStride;
56
- const dstRow = y * width * channels;
57
- if (bpp === 8) {
58
- for (let x = 0; x < width; x++) {
59
- const entry = palette[buf[srcRow + x]] || [0, 0, 0];
60
- if (channels === 1) {
61
- out[dstRow + x] = entry[0];
62
- } else {
63
- const d = dstRow + x * 3;
64
- out[d] = entry[0]; out[d + 1] = entry[1]; out[d + 2] = entry[2];
65
- }
66
- }
67
- } else {
68
- for (let x = 0; x < width; x++) {
69
- const s = srcRow + x * (bpp / 8), d = dstRow + x * channels;
70
- out[d] = buf[s + 2]; out[d + 1] = buf[s + 1]; out[d + 2] = buf[s]; // BGR → RGB
71
- if (channels === 4) out[d + 3] = buf[s + 3];
72
- }
73
- }
74
- }
75
-
76
- return { data: out, width, height, channels, colorSpace, dtype: 'uint8' };
15
+ /**
16
+ * Decodes a BMP buffer to the toolkit's raw image object.
17
+ * Supports every uncompressed / RLE BMP variant OpenCV handles (1/4/8-bit
18
+ * palette, 16/24/32-bit). Grayscale palettes yield a GRAY image, colour
19
+ * palettes and 24-bit files yield RGB, 32-bit files yield RGBA.
20
+ * @param {Buffer} buf
21
+ * @returns {Promise<{data: Buffer, width: number, height: number, channels: number, colorSpace: string, dtype: string}>}
22
+ */
23
+ async function decodeBmp(buf) {
24
+ if (!isBmp(buf)) throw new Error('Invalid BMP file');
25
+ const { image } = await Cpp.decode(buf);
26
+ return image;
77
27
  }
78
28
 
79
29
  module.exports = { isBmp, decodeBmp };
@@ -3,120 +3,186 @@
3
3
  * Follows Sharp's pattern for platform-specific binary loading.
4
4
  *
5
5
  * Loading order:
6
- * 1. Try platform-specific package (@rosepetal/node-red-contrib-image-tools-{platform})
7
- * 2. Fallback to local build (development mode)
8
- * 3. Fallback to node-gyp rebuild if build tools available
6
+ * 1. Local build (development / install.sh)
7
+ * 2. Platform-specific package (@rosepetal/node-red-contrib-image-tools-{platform})
8
+ * 3. node-gyp rebuild if build tools + OpenCV are available
9
9
  * 4. Error with helpful message
10
+ *
11
+ * Everything here is asynchronous: the probing uses fs.promises, child
12
+ * processes are spawned with the async child_process API, and the addon is
13
+ * resolved lazily through a single cached promise. The only synchronous step
14
+ * left is `require()` of the `.node` file itself (dlopen has no async form in
15
+ * Node.js); it takes a few milliseconds and happens once per process.
16
+ *
17
+ * The exported object has the same shape as before: one async function per
18
+ * native operation (`resize`, `rotate`, … `decode`, `encode`). Callers keep
19
+ * doing `await Cpp.resize(...)`.
10
20
  */
11
21
  const util = require('util');
12
22
  const path = require('path');
13
23
  const fs = require('fs');
24
+ const { execFile, spawn } = require('child_process');
14
25
 
15
- /**
16
- * Detect the current platform identifier
17
- * @returns {string} Platform identifier (e.g., 'linux-x64', 'darwin-arm64', 'linuxmusl-x64')
18
- */
19
- function detectPlatform() {
20
- const platform = process.platform;
21
- const arch = process.arch;
26
+ const fsp = fs.promises;
27
+ const execFileAsync = util.promisify(execFile);
22
28
 
23
- let platformId = `${platform}-${arch}`;
29
+ /** Public API of the native addon (mirrors rosepetal-image-engine/src/main.cpp). */
30
+ const FUNCTION_NAMES = [
31
+ 'resize', 'rotate', 'crop', 'concat', 'padding', 'filter',
32
+ 'mosaic', 'advancedMosaic', 'blend', 'addMask', 'addMasks', 'addBBs',
33
+ 'imageAlign', 'draw', 'colorConvert', 'heatDiff',
34
+ 'decode', 'encode'
35
+ ];
24
36
 
25
- // On Linux, distinguish between glibc and musl (Alpine)
26
- if (platform === 'linux') {
27
- const isMusl = detectMusl();
28
- platformId = isMusl ? `linuxmusl-${arch}` : `linux-${arch}`;
29
- }
37
+ const SUPPORTED_PLATFORMS = [
38
+ 'linux-x64', 'linux-arm64',
39
+ 'linuxmusl-x64',
40
+ 'darwin-x64', 'darwin-arm64'
41
+ ];
30
42
 
31
- return platformId;
43
+ async function pathExists(p) {
44
+ try {
45
+ await fsp.access(p);
46
+ return true;
47
+ } catch {
48
+ return false;
49
+ }
32
50
  }
33
51
 
34
52
  /**
35
53
  * Detect if running on musl libc (Alpine Linux, etc.)
36
- * @returns {boolean} True if musl libc detected
54
+ * @returns {Promise<boolean>} True if musl libc detected
37
55
  */
38
- function detectMusl() {
56
+ async function detectMusl() {
39
57
  try {
40
- // Method 1: Check for Alpine release file
41
- if (fs.existsSync('/etc/alpine-release')) {
42
- return true;
43
- }
58
+ // Method 1: Alpine release file
59
+ if (await pathExists('/etc/alpine-release')) return true;
44
60
 
45
- // Method 2: Check for musl loader
46
- if (fs.existsSync('/lib/ld-musl-x86_64.so.1') ||
47
- fs.existsSync('/lib/ld-musl-aarch64.so.1')) {
61
+ // Method 2: musl loader
62
+ if (await pathExists('/lib/ld-musl-x86_64.so.1') ||
63
+ await pathExists('/lib/ld-musl-aarch64.so.1')) {
48
64
  return true;
49
65
  }
50
66
 
51
- // Method 3: Check ldd output
52
- const { execSync } = require('child_process');
53
- const lddOutput = execSync('ldd --version 2>&1 || true', {
54
- encoding: 'utf8',
55
- timeout: 5000
56
- });
57
- if (lddOutput.toLowerCase().includes('musl')) {
58
- return true;
67
+ // Method 3: ldd output (async subprocess, never blocks the event loop)
68
+ try {
69
+ const { stdout, stderr } = await execFileAsync('ldd', ['--version'], {
70
+ encoding: 'utf8',
71
+ timeout: 5000
72
+ });
73
+ return `${stdout}\n${stderr}`.toLowerCase().includes('musl');
74
+ } catch (err) {
75
+ // ldd exits non-zero on some libcs; its output is still useful
76
+ const out = `${err && err.stdout ? err.stdout : ''}\n${err && err.stderr ? err.stderr : ''}`;
77
+ return out.toLowerCase().includes('musl');
59
78
  }
60
-
61
- return false;
62
79
  } catch {
63
80
  return false;
64
81
  }
65
82
  }
66
83
 
67
84
  /**
68
- * Try to load the addon from the platform-specific npm package
85
+ * Detect the current platform identifier
86
+ * @returns {Promise<string>} Platform identifier (e.g., 'linux-x64', 'darwin-arm64', 'linuxmusl-x64')
87
+ */
88
+ async function detectPlatform() {
89
+ const platform = process.platform;
90
+ const arch = process.arch;
91
+
92
+ // On Linux, distinguish between glibc and musl (Alpine)
93
+ if (platform === 'linux') {
94
+ const isMusl = await detectMusl();
95
+ return isMusl ? `linuxmusl-${arch}` : `linux-${arch}`;
96
+ }
97
+
98
+ return `${platform}-${arch}`;
99
+ }
100
+
101
+ /**
102
+ * Try to load the addon from the platform-specific npm package.
103
+ * The node_modules lookup dirs come from `require.resolve.paths()` (pure
104
+ * computation, no I/O); existence is probed with fs.promises.
69
105
  * @param {string} platformId - Platform identifier
70
- * @returns {object|null} The loaded addon or null
106
+ * @returns {Promise<object|null>} The loaded addon or null
71
107
  */
72
- function tryLoadFromPackage(platformId) {
108
+ async function tryLoadFromPackage(platformId) {
73
109
  const packageName = `@rosepetal/node-red-contrib-image-tools-${platformId}`;
110
+ const searchDirs = require.resolve.paths(packageName) || [];
74
111
 
75
- try {
76
- // Try to resolve and load the platform-specific package
77
- const addonPath = require.resolve(`${packageName}/lib/addon.node`);
78
- return require(addonPath);
79
- } catch (err) {
80
- // Package not installed or not found
81
- return null;
112
+ for (const dir of searchDirs) {
113
+ const addonPath = path.join(dir, packageName, 'lib', 'addon.node');
114
+ if (await pathExists(addonPath)) {
115
+ try {
116
+ return require(addonPath);
117
+ } catch {
118
+ // Broken package (wrong ABI, partial install, ...) — keep looking
119
+ }
120
+ }
82
121
  }
122
+ return null;
83
123
  }
84
124
 
85
125
  /**
86
126
  * Try to load the addon from local build (development mode)
87
- * @returns {object|null} The loaded addon or null
127
+ * @returns {Promise<object|null>} The loaded addon or null
88
128
  */
89
- function tryLoadFromLocalBuild() {
129
+ async function tryLoadFromLocalBuild() {
90
130
  const localPaths = [
91
131
  // From node-red-contrib-image-tools/lib/ -> rosepetal-image-engine/build/
92
132
  path.join(__dirname, '../../rosepetal-image-engine/build/Release/addon.node'),
93
133
  // Alternative path structure
94
134
  path.join(__dirname, '../../../rosepetal-image-engine/build/Release/addon.node'),
95
- // Direct sibling
96
- path.resolve(__dirname, '../../rosepetal-image-engine/build/Release/addon.node'),
97
135
  ];
98
136
 
99
137
  for (const addonPath of localPaths) {
100
- try {
101
- if (fs.existsSync(addonPath)) {
138
+ if (await pathExists(addonPath)) {
139
+ try {
102
140
  return require(addonPath);
141
+ } catch {
142
+ // Continue to next path
103
143
  }
104
- } catch {
105
- // Continue to next path
106
144
  }
107
145
  }
108
146
 
109
147
  return null;
110
148
  }
111
149
 
150
+ /**
151
+ * Spawn a command asynchronously with inherited stdio and a timeout.
152
+ * @returns {Promise<void>} resolves on exit code 0, rejects otherwise
153
+ */
154
+ function spawnAsync(cmd, args, { cwd, timeout }) {
155
+ return new Promise((resolve, reject) => {
156
+ const child = spawn(cmd, args, { cwd, stdio: 'inherit' });
157
+ let settled = false;
158
+ const timer = setTimeout(() => {
159
+ if (settled) return;
160
+ settled = true;
161
+ child.kill('SIGTERM');
162
+ reject(new Error(`"${cmd} ${args.join(' ')}" timed out after ${timeout} ms`));
163
+ }, timeout);
164
+ child.on('error', (err) => {
165
+ if (settled) return;
166
+ settled = true;
167
+ clearTimeout(timer);
168
+ reject(err);
169
+ });
170
+ child.on('exit', (code, signal) => {
171
+ if (settled) return;
172
+ settled = true;
173
+ clearTimeout(timer);
174
+ if (code === 0) resolve();
175
+ else reject(new Error(`"${cmd} ${args.join(' ')}" exited with ${signal || code}`));
176
+ });
177
+ });
178
+ }
179
+
112
180
  /**
113
181
  * Try to build the addon using node-gyp (fallback for systems with build tools)
114
- * @returns {object|null} The loaded addon or null
182
+ * @returns {Promise<object|null>} The loaded addon or null
115
183
  */
116
- function tryBuildFromSource() {
184
+ async function tryBuildFromSource() {
117
185
  try {
118
- const { execSync } = require('child_process');
119
-
120
186
  // Find the rosepetal-image-engine directory
121
187
  const enginePaths = [
122
188
  path.join(__dirname, '../../rosepetal-image-engine'),
@@ -125,7 +191,7 @@ function tryBuildFromSource() {
125
191
 
126
192
  let engineDir = null;
127
193
  for (const p of enginePaths) {
128
- if (fs.existsSync(path.join(p, 'binding.gyp'))) {
194
+ if (await pathExists(path.join(p, 'binding.gyp'))) {
129
195
  engineDir = p;
130
196
  break;
131
197
  }
@@ -137,24 +203,22 @@ function tryBuildFromSource() {
137
203
 
138
204
  // Check if OpenCV is available via pkg-config
139
205
  try {
140
- execSync('pkg-config --exists opencv4', { encoding: 'utf8', timeout: 5000 });
206
+ await execFileAsync('pkg-config', ['--exists', 'opencv4'], { timeout: 5000 });
141
207
  } catch {
142
208
  // OpenCV not available, can't build from source
143
209
  return null;
144
210
  }
145
211
 
146
- // Try to build
212
+ // Try to build (async subprocess; Node-RED keeps serving meanwhile)
147
213
  console.log('rosepetal-image-engine: Pre-built binary not found, attempting to build from source...');
148
- execSync('npm run rebuild', {
214
+ await spawnAsync('npm', ['run', 'rebuild'], {
149
215
  cwd: engineDir,
150
- encoding: 'utf8',
151
- stdio: 'inherit',
152
216
  timeout: 300000 // 5 minutes
153
217
  });
154
218
 
155
219
  // Try to load the freshly built addon
156
220
  const addonPath = path.join(engineDir, 'build/Release/addon.node');
157
- if (fs.existsSync(addonPath)) {
221
+ if (await pathExists(addonPath)) {
158
222
  return require(addonPath);
159
223
  }
160
224
 
@@ -167,58 +231,92 @@ function tryBuildFromSource() {
167
231
 
168
232
  /**
169
233
  * Load the native addon with platform detection and fallback
170
- * @returns {object} The loaded addon
234
+ * @returns {Promise<object>} The loaded (promisified) addon
171
235
  * @throws {Error} If no addon could be loaded
172
236
  */
173
- function loadAddon() {
174
- const platformId = detectPlatform();
175
-
237
+ async function loadAddon() {
176
238
  // 1. Try local build first (development / install.sh)
177
- let addon = tryLoadFromLocalBuild();
178
- if (addon) {
179
- return addon;
180
- }
239
+ let addon = await tryLoadFromLocalBuild();
181
240
 
182
241
  // 2. Try platform-specific package (npm install without build tools)
183
- addon = tryLoadFromPackage(platformId);
184
- if (addon) {
185
- return addon;
242
+ if (!addon) {
243
+ const platformId = await detectPlatform();
244
+ addon = await tryLoadFromPackage(platformId);
245
+
246
+ // 3. Try building from source (fallback)
247
+ if (!addon) {
248
+ addon = await tryBuildFromSource();
249
+ }
250
+
251
+ // 4. Provide helpful error message
252
+ if (!addon) {
253
+ throw new Error(
254
+ `Could not load the rosepetal-image-engine native addon.\n\n` +
255
+ `Detected platform: ${platformId}\n` +
256
+ `Supported platforms: ${SUPPORTED_PLATFORMS.join(', ')}\n\n` +
257
+ `Possible solutions:\n` +
258
+ `1. Reinstall the package: npm install @rosepetal/node-red-contrib-image-tools\n` +
259
+ `2. If your platform is supported, ensure you're using a recent npm version (npm >= 9)\n` +
260
+ `3. For unsupported platforms or development:\n` +
261
+ ` - Install OpenCV 4.x and build tools\n` +
262
+ ` - Run: cd rosepetal-image-engine && npm run rebuild\n`
263
+ );
264
+ }
186
265
  }
187
266
 
188
- // 3. Try building from source (fallback)
189
- addon = tryBuildFromSource();
190
- if (addon) {
191
- return addon;
267
+ // Promisify every native (callback-style) function
268
+ const promisified = {};
269
+ for (const key of Object.keys(addon)) {
270
+ if (typeof addon[key] === 'function') {
271
+ promisified[key] = util.promisify(addon[key]);
272
+ }
192
273
  }
193
274
 
194
- // 4. Provide helpful error message
195
- const supportedPlatforms = [
196
- 'linux-x64', 'linux-arm64',
197
- 'linuxmusl-x64',
198
- 'darwin-x64', 'darwin-arm64'
199
- ];
275
+ const missing = FUNCTION_NAMES.filter((name) => typeof promisified[name] !== 'function');
276
+ if (missing.length > 0) {
277
+ console.warn(
278
+ `rosepetal-image-engine: the loaded native addon does not export ${missing.join(', ')}. ` +
279
+ `It was built from an older source tree; rebuild it (cd rosepetal-image-engine && npm run rebuild) ` +
280
+ `or update the platform package.`
281
+ );
282
+ }
200
283
 
201
- throw new Error(
202
- `Could not load the rosepetal-image-engine native addon.\n\n` +
203
- `Detected platform: ${platformId}\n` +
204
- `Supported platforms: ${supportedPlatforms.join(', ')}\n\n` +
205
- `Possible solutions:\n` +
206
- `1. Reinstall the package: npm install @rosepetal/node-red-contrib-image-tools\n` +
207
- `2. If your platform is supported, ensure you're using a recent npm version (npm >= 9)\n` +
208
- `3. For unsupported platforms or development:\n` +
209
- ` - Install OpenCV 4.x and build tools\n` +
210
- ` - Run: cd rosepetal-image-engine && npm run rebuild\n`
211
- );
284
+ return promisified;
212
285
  }
213
286
 
214
- // Load and promisify the addon
215
- const addon = loadAddon();
216
- const promisifiedAddon = {};
287
+ // Single cached load. Kicked off eagerly (without blocking) so missing-addon
288
+ // diagnostics show up at startup; every call awaits the same promise.
289
+ let addonPromise = null;
217
290
 
218
- for (const key in addon) {
219
- if (typeof addon[key] === 'function') {
220
- promisifiedAddon[key] = util.promisify(addon[key]);
291
+ function getAddon() {
292
+ if (!addonPromise) {
293
+ addonPromise = loadAddon();
294
+ // Avoid an unhandled-rejection warning: callers get the error when they await.
295
+ addonPromise.catch((err) => {
296
+ console.error(`rosepetal-image-engine: ${err.message}`);
297
+ });
221
298
  }
299
+ return addonPromise;
300
+ }
301
+
302
+ getAddon();
303
+
304
+ const bridge = {};
305
+ for (const name of FUNCTION_NAMES) {
306
+ bridge[name] = async function (...args) {
307
+ const addon = await getAddon();
308
+ const fn = addon[name];
309
+ if (typeof fn !== 'function') {
310
+ throw new Error(
311
+ `rosepetal-image-engine: native function "${name}" is not available in the loaded addon. ` +
312
+ `Rebuild the native module (cd rosepetal-image-engine && npm run rebuild) or update the platform package.`
313
+ );
314
+ }
315
+ return fn(...args);
316
+ };
222
317
  }
223
318
 
224
- module.exports = promisifiedAddon;
319
+ /** Resolves once the native addon is loaded (or rejects with the load error). */
320
+ bridge.ready = () => getAddon().then(() => undefined);
321
+
322
+ module.exports = bridge;