UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

249 lines (248 loc) • 9.04 kB
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs"; import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs"; import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs"; import { t as escapeRegExp } from "./regexp-dj3rRPbj.mjs"; import { t as PLUGIN_SOURCE_CAPTURE_PREFIX } from "./plugin-source-capture-path-Dr3_vipZ.mjs"; import Module, { createRequire } from "node:module"; import fs from "node:fs"; import { fileURLToPath, pathToFileURL } from "node:url"; import path from "node:path"; //#region src/plugins/native-module-require.ts /** Bun's native plugin resolver remains the owner even when Node hooks are available. */ function useNodeModuleHooks() { return !process.versions.bun && typeof Module.registerHooks === "function"; } const PLUGIN_SOURCE_MODULE_EXTENSIONS = [ ".ts", ".tsx", ".mts", ".cts", ".mtsx", ".ctsx" ]; function isPluginSourceModulePath(e) { return PLUGIN_SOURCE_MODULE_EXTENSIONS.includes(path.extname(e).toLowerCase()); } const nativeModuleLoadFailures = /* @__PURE__ */ new Map(); const moduleWithResolver = Module; const bunRuntimeOnResolveProbe = resolveGlobalSingleton(Symbol.for("openclaw.bunRuntimeOnResolveProbe"), () => ({ tested: false, supported: false })); /** Whether Bun can redirect runtime-computed specifiers through public onResolve hooks. */ function supportsBunRuntimeOnResolveTargets() { if (bunRuntimeOnResolveProbe.tested) return bunRuntimeOnResolveProbe.supported; bunRuntimeOnResolveProbe.tested = true; const e = globalThis.Bun; if (!e?.resolveSync) return false; const t = "openclaw-bun-runtime-onresolve-probe"; const n = fileURLToPath(import.meta.url); let r = false; try { e.plugin({ name: t, setup(e) { e.onResolve({ filter: /^openclaw-bun-runtime-onresolve-probe$/u, namespace: "file" }, () => { r = true; return { path: n, namespace: "file" }; }); } }); bunRuntimeOnResolveProbe.supported = e.resolveSync(t, path.dirname(n)) === n && r; } catch { bunRuntimeOnResolveProbe.supported = false; } return bunRuntimeOnResolveProbe.supported; } const capturedModuleResolvers = resolveGlobalSingleton(Symbol.for("openclaw.capturedModuleResolvers"), () => ({ installed: false, loaderInstalled: false, resolving: false, owners: /* @__PURE__ */ new Set() })); function resolveCapturedPluginModule(e) { if (capturedModuleResolvers.resolving) return; capturedModuleResolvers.resolving = true; try { for (const t of capturedModuleResolvers.owners) { const n = e(t); if (n) return n; } } finally { capturedModuleResolvers.resolving = false; } } function installCapturedPluginModuleResolver(e) { if (e) { e.plugin({ name: "openclaw-plugin-source-capture", setup(t) { const n = new RegExp(`^(?!${escapeRegExp(e.main)}(?![\\s\\S]))`); t.onResolve({ filter: n, namespace: "file" }, ({ path: e, importer: t, kind: n }) => { const r = resolveCapturedPluginModule((r) => r.prepare(e, t, n)); return r ? { path: r, namespace: "file" } : void 0; }); } }); return; } const t = moduleWithResolver["_resolveFilename"]; moduleWithResolver["_resolveFilename"] = (e, n, r, i) => { const a = n?.filename; return (a ? resolveCapturedPluginModule((o) => o.resolve(e, a, () => t(e, n, r, i))) : void 0) ?? t(e, n, r, i); }; } function installCapturedPluginModuleLoader(e) { e.plugin({ name: "openclaw-plugin-source-jsx", setup(e) { e.onLoad({ filter: new RegExp(`${PLUGIN_SOURCE_CAPTURE_PREFIX}[^/\\\\]+[/\\\\].*\\.[cm]?[jt]sx$`, "u"), namespace: "file" }, ({ path: e }) => resolveCapturedPluginModule((t) => t.load?.(e)) ?? { contents: fs.readFileSync(e, "utf8"), loader: e.toLowerCase().endsWith(".jsx") ? "jsx" : "tsx" }); } }); } /** Captured parents retain their resolver while their instance's consumers drain. */ function registerCapturedPluginModuleResolver(e) { const t = globalThis.Bun; if (!capturedModuleResolvers.installed) { installCapturedPluginModuleResolver(t); capturedModuleResolvers.installed = true; } if (e.load && t && !capturedModuleResolvers.loaderInstalled) { installCapturedPluginModuleLoader(t); capturedModuleResolvers.loaderInstalled = true; } capturedModuleResolvers.owners.add(e); return () => { capturedModuleResolvers.owners.delete(e); }; } /** True for file extensions Node can load through the native JS module loader. */ function isJavaScriptModulePath(e) { return [ ".js", ".mjs", ".cjs" ].includes(path.extname(e).toLowerCase()); } function resolvePluginLoaderTryNative(e, t) { const n = [ ".js", ".mjs", ".cjs", ".json" ].includes(path.extname(e).trim().toLowerCase()); if (e.replace(/\\/g, "/").includes("/dist/extensions/")) return n; return n || t?.preferBuiltDist === true && e.includes(`${path.sep}dist${path.sep}`); } function isMissingTargetModuleError(e, t) { if (e.code !== "MODULE_NOT_FOUND" || typeof e.message !== "string") return false; const n = e.message.split("\n", 1)[0] ?? ""; return n.includes(`'${t}'`) || n.includes(`"${t}"`); } function isSourceTransformFallbackError(e, t) { if (!e || typeof e !== "object" || !("code" in e)) return false; const n = e.code; return n === "ERR_REQUIRE_ESM" || n === "ERR_REQUIRE_ASYNC_MODULE" || n === "ERR_REQUIRE_ESM_RACE_CONDITION" || n === "ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX" || n === "ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING" || n === "ERR_UNKNOWN_FILE_EXTENSION" || isMissingTargetModuleError(e, t); } /** Attempts native require before falling back to source transform paths. */ function tryNativeRequireJavaScriptModule(e, t = {}) { const n = toNativeRequirePath(e); const r = Boolean(process.versions.bun) && isPluginSourceModulePath(n); if (!isJavaScriptModulePath(n) && !r) return { ok: false }; return tryNativeRequireModule(e, t); } /** Loads prepared host aliases, including source SDK paths supported by the runtime. */ function tryNativeRequireModule(e, t = {}) { const n = toNativeRequirePath(e); const r = createRequire(import.meta.url); if (isPluginSourceModulePath(n) && !process.features.typescript && typeof r.extensions?.[path.extname(n)] !== "function") return { ok: false }; let i; try { i = withNativeRequireAliases(t.aliasMap, () => r.resolve(n)); const e = withNativeRequireAliases(t.aliasMap, () => r(n)); nativeModuleLoadFailures.delete(i); return { ok: true, moduleExport: e }; } catch (e) { const r = e && typeof e === "object" ? Reflect.get(e, "code") : void 0; if (i !== void 0 && nativeModuleLoadFailures.has(i) && (r === "ERR_REQUIRE_ESM_RACE_CONDITION" || r === "ERR_INTERNAL_ASSERTION")) throw nativeModuleLoadFailures.get(i); if (isSourceTransformFallbackError(e, n) || i === void 0 && t.fallbackOnMissingDependency === true && (r === "MODULE_NOT_FOUND" || r === "ERR_MODULE_NOT_FOUND")) return { ok: false }; if (i !== void 0) nativeModuleLoadFailures.set(i, e); throw e; } } /** Explicit public-library invalidation refreshes the current path synchronously. */ function clearPluginModuleRequireCache(e, t) { const n = createRequire(import.meta.url); const r = /* @__PURE__ */ new Set(); const clear = (e) => { if (r.has(e) || !isPathInside(t, e)) return; r.add(e); for (const t of n.cache[e]?.children ?? []) clear(t.id); delete n.cache[e]; }; clear(e); } function toNativeRequirePath(e) { try { return /^file:\/\//iu.test(e) ? fileURLToPath(e) : e; } catch { return e; } } /** Runs a native require block with temporary CJS/ESM alias hooks and restores both afterward. */ function withNativeRequireAliases(e, t) { if (!e || !moduleWithResolver["_resolveFilename"]) return t(); const n = typeof e === "function" ? e : (t) => e[t]; const r = moduleWithResolver["_resolveFilename"]; const i = useNodeModuleHooks() ? Module.registerHooks({ resolve(e, t, r) { const i = t.parentURL?.startsWith("file:") ? fileURLToPath(t.parentURL) : void 0; const a = n(e, i); if (a) return { shortCircuit: true, url: pathToFileURL(a).href }; try { return r(e, t); } catch (n) { if (i && isPluginSourceModulePath(i) && e.startsWith(".") && /\.[cm]?js$/u.test(e) && hasErrnoCode(n, "ERR_MODULE_NOT_FOUND")) { const n = new URL(e.replace(/\.([cm]?)js$/u, ".$1ts"), t.parentURL); if (fs.existsSync(fileURLToPath(n))) return r(n.href, t); } throw n; } } }) : void 0; moduleWithResolver["_resolveFilename"] = ((e, t, i, a) => { const o = n(e, t?.filename); if (o) return path.normalize(o); return r(e, t, i, a); }); try { return t(); } finally { moduleWithResolver["_resolveFilename"] = r; i?.deregister(); } } //#endregion export { registerCapturedPluginModuleResolver as a, tryNativeRequireJavaScriptModule as c, isPluginSourceModulePath as i, tryNativeRequireModule as l, clearPluginModuleRequireCache as n, resolvePluginLoaderTryNative as o, isJavaScriptModulePath as r, supportsBunRuntimeOnResolveTargets as s, PLUGIN_SOURCE_MODULE_EXTENSIONS as t, useNodeModuleHooks as u };