feat: auto-rebuild native modules on Node.js version mismatch
When Node.js is updated, native modules like better-sqlite3 can become incompatible due to NODE_MODULE_VERSION differences. This change adds automatic detection and rebuild capability: - Add native-module-helper.js utility for detecting version errors - Lazy-load better-sqlite3 to catch import errors at runtime - Automatically run npm rebuild when version mismatch is detected - Clear require cache and retry loading after successful rebuild - Provide clear instructions if automatic rebuild fails Fixes the issue where users running via npx encounter module errors after updating Node.js.
This commit is contained in:
136
src/utils/native-module-helper.js
Normal file
136
src/utils/native-module-helper.js
Normal file
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* Native Module Helper
|
||||
* Detects and auto-rebuilds native Node.js modules when they become
|
||||
* incompatible after a Node.js version update.
|
||||
*/
|
||||
|
||||
import { execSync } from 'child_process';
|
||||
import { dirname, join } from 'path';
|
||||
import { existsSync } from 'fs';
|
||||
import { createRequire } from 'module';
|
||||
import { logger } from './logger.js';
|
||||
|
||||
/**
|
||||
* Check if an error is a NODE_MODULE_VERSION mismatch error
|
||||
* @param {Error} error - The error to check
|
||||
* @returns {boolean} True if it's a version mismatch error
|
||||
*/
|
||||
export function isModuleVersionError(error) {
|
||||
const message = error?.message || '';
|
||||
return message.includes('NODE_MODULE_VERSION') &&
|
||||
message.includes('was compiled against a different Node.js version');
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the module path from a NODE_MODULE_VERSION error message
|
||||
* @param {Error} error - The error containing the module path
|
||||
* @returns {string|null} The path to the .node file, or null if not found
|
||||
*/
|
||||
export function extractModulePath(error) {
|
||||
const message = error?.message || '';
|
||||
// Match pattern like: "The module '/path/to/module.node'"
|
||||
const match = message.match(/The module '([^']+\.node)'/);
|
||||
return match ? match[1] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the package root directory from a .node file path
|
||||
* @param {string} nodeFilePath - Path to the .node file
|
||||
* @returns {string|null} Path to the package root, or null if not found
|
||||
*/
|
||||
export function findPackageRoot(nodeFilePath) {
|
||||
// Walk up from the .node file to find package.json
|
||||
let dir = dirname(nodeFilePath);
|
||||
while (dir && dir !== '/') {
|
||||
const packageJsonPath = join(dir, 'package.json');
|
||||
if (existsSync(packageJsonPath)) {
|
||||
return dir;
|
||||
}
|
||||
dir = dirname(dir);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to rebuild a native module
|
||||
* @param {string} packagePath - Path to the package root directory
|
||||
* @returns {boolean} True if rebuild succeeded, false otherwise
|
||||
*/
|
||||
export function rebuildModule(packagePath) {
|
||||
try {
|
||||
logger.info(`[NativeModule] Rebuilding native module at: ${packagePath}`);
|
||||
|
||||
// Run npm rebuild in the package directory
|
||||
execSync('npm rebuild', {
|
||||
cwd: packagePath,
|
||||
stdio: 'pipe', // Capture output instead of printing
|
||||
timeout: 120000 // 2 minute timeout
|
||||
});
|
||||
|
||||
logger.success('[NativeModule] Rebuild completed successfully');
|
||||
return true;
|
||||
} catch (error) {
|
||||
logger.error(`[NativeModule] Rebuild failed: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to auto-rebuild a native module from an error
|
||||
* @param {Error} error - The NODE_MODULE_VERSION error
|
||||
* @returns {boolean} True if rebuild succeeded, false otherwise
|
||||
*/
|
||||
export function attemptAutoRebuild(error) {
|
||||
const nodePath = extractModulePath(error);
|
||||
if (!nodePath) {
|
||||
logger.error('[NativeModule] Could not extract module path from error');
|
||||
return false;
|
||||
}
|
||||
|
||||
const packagePath = findPackageRoot(nodePath);
|
||||
if (!packagePath) {
|
||||
logger.error('[NativeModule] Could not find package root');
|
||||
return false;
|
||||
}
|
||||
|
||||
logger.warn('[NativeModule] Native module version mismatch detected');
|
||||
logger.info('[NativeModule] Attempting automatic rebuild...');
|
||||
|
||||
return rebuildModule(packagePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the require cache for a module to force re-import
|
||||
* This is needed after rebuilding a native module
|
||||
* @param {string} moduleName - The module name (e.g., 'better-sqlite3')
|
||||
*/
|
||||
export function clearModuleCache(moduleName) {
|
||||
const require = createRequire(import.meta.url);
|
||||
try {
|
||||
const resolved = require.resolve(moduleName);
|
||||
// Clear the main module and its dependencies
|
||||
const mod = require.cache[resolved];
|
||||
if (mod) {
|
||||
// Remove from parent's children array
|
||||
if (mod.parent) {
|
||||
const idx = mod.parent.children.indexOf(mod);
|
||||
if (idx !== -1) {
|
||||
mod.parent.children.splice(idx, 1);
|
||||
}
|
||||
}
|
||||
// Delete from cache
|
||||
delete require.cache[resolved];
|
||||
}
|
||||
} catch {
|
||||
// Module might not be in cache, that's okay
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
isModuleVersionError,
|
||||
extractModulePath,
|
||||
findPackageRoot,
|
||||
rebuildModule,
|
||||
attemptAutoRebuild,
|
||||
clearModuleCache
|
||||
};
|
||||
Reference in New Issue
Block a user