UNPKG

@bytebase/dbhub

Version:

Token-efficient database MCP server for PostgreSQL, MySQL, MariaDB, SQL Server, Oracle, ClickHouse, SQLite

75 lines (73 loc) • 2.73 kB
// src/utils/module-loader.ts var MISSING_MODULE_RE = /Cannot find (?:package|module) '([^']+)'/; function isDriverNotInstalled(err, driver) { if (!(err instanceof Error) || !("code" in err) || err.code !== "ERR_MODULE_NOT_FOUND") { return false; } const match = err.message.match(MISSING_MODULE_RE); if (!match) { return false; } const missingSpecifier = match[1]; return missingSpecifier === driver || missingSpecifier.startsWith(`${driver}/`); } function isModuleNotFound(err) { if (!(err instanceof Error) || !("code" in err)) { return false; } const code = err.code; return code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND"; } var skippedConnectors = []; function getNpxCacheDir(scriptPath) { if (!scriptPath) { return null; } const match = scriptPath.match(/^(.*[\\/]_npx)[\\/]/); return match ? match[1] : null; } function getMissingDriverHint(dsn, scriptPath = process.argv[1]) { const scheme = dsn.split("://", 1)[0].toLowerCase(); const skipped = skippedConnectors.find((c) => c.schemes.includes(scheme)); if (!skipped) { return null; } const cause = `The ${skipped.name} connector was skipped at startup because the package "${skipped.missing}" is not installed.`; const npxCacheDir = getNpxCacheDir(scriptPath); if (npxCacheDir) { return `${cause} DBHub is running from the npx cache, where some npm versions drop optional driver packages when upgrading a cached install. Delete the npx cache directory (${npxCacheDir}) and restart, or upgrade npm (npm install -g npm@latest).`; } return `${cause} Install it next to DBHub (for a global install: npm install -g ${skipped.missing}) and restart.`; } async function loadConnectors(connectorModules) { skippedConnectors.length = 0; await Promise.all( connectorModules.map(async ({ load, name, driver, schemes = [] }) => { try { await load(); } catch (err) { if (isDriverNotInstalled(err, driver)) { skippedConnectors.push({ name, missing: driver, schemes }); console.error( `Skipping ${name} connector: driver package "${driver}" not installed.` ); } else if (isModuleNotFound(err)) { const msg = err instanceof Error ? err.message : String(err); const match = msg.match(MISSING_MODULE_RE); const missing = match ? match[1] : "unknown"; skippedConnectors.push({ name, missing, schemes }); console.error( `Skipping ${name} connector: required dependency "${missing}" not installed.` ); } else { throw err; } } }) ); } export { isDriverNotInstalled, getMissingDriverHint, loadConnectors };