Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

fix(mitm): lazy-load undici in upstreamTrust so tests can import (R4 #2)

diegosouzapw1a0aca9b9422
diff --git a/src/mitm/upstreamTrust.ts b/src/mitm/upstreamTrust.ts
index 1837abaf9c..cc4fe0db5c 100644
--- a/src/mitm/upstreamTrust.ts
+++ b/src/mitm/upstreamTrust.ts
@@ -6,12 +6,19 @@
* Source: plano 11 §4.7 (origin: llm-interceptor --upstream-ca-cert)
* Hard Rule #12: error message is a safe literal — no stack trace exposed.
*/
-import { Agent, setGlobalDispatcher } from "undici";
import { readFileSync, existsSync } from "node:fs";
+import { createRequire } from "node:module";
/**
* Configure undici's global dispatcher to trust a custom CA certificate.
*
+ * `undici` is loaded lazily (only when a CA is actually being configured) so
+ * that merely importing this module — which happens transitively from every
+ * MITM handler via `base.ts` — does not eagerly pull in undici's full index.
+ * That keeps the module importable in test/toolchain environments where the
+ * installed undici may be incompatible with the running Node version, and
+ * avoids loading a heavy dependency for the common no-CA path.
+ *
* @param pemPath - Absolute path to the PEM file. If undefined/empty, no-op.
* @throws {Error} With a safe error message (no stack trace) if pemPath is set
* but the file does not exist.
@@ -27,5 +34,7 @@ export function configureUpstreamCa(pemPath?: string): void {
}
const ca = readFileSync(pemPath, "utf8");
+ const require = createRequire(import.meta.url);
+ const { Agent, setGlobalDispatcher } = require("undici") as typeof import("undici");
setGlobalDispatcher(new Agent({ connect: { ca } }));
}