openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
278 lines (277 loc) • 9.52 kB
JavaScript
import { l as resolveRuntimeScriptEnv } from "./cli-invocation-ZSPsKRWa.mjs";
import { n as tryProcessCwd } from "./safe-cwd-CZqaxroH.mjs";
import { b as uniqueStrings } from "./string-normalization-DLmfYZXI.mjs";
import { r as resolveSafeChildProcessInvocation } from "./windows-command-BgNYMnai.mjs";
import { t as resolveNpmCommand } from "./npm-command-kcBVU3OP.mjs";
import fs from "node:fs";
import path from "node:path";
import os from "node:os";
import { spawnSync } from "node:child_process";
import { safeStatSync } from "@openclaw/fs-safe/path";
//#region src/infra/update-network-budget.ts
const UPDATE_NETWORK_TIMEOUT_MS = 3e5;
//#endregion
//#region src/infra/npm-install-env.ts
const NPM_CONFIG_SCRIPT_SHELL_KEYS = ["NPM_CONFIG_SCRIPT_SHELL", "npm_config_script_shell"];
const NPM_CONFIG_KEYS_TO_RESET = /* @__PURE__ */ new Set([
"npm_config_allow_scripts",
"npm_config_cache",
"npm_config_dry_run",
"npm_config_global",
"npm_config_include_workspace_root",
"npm_config_ignore_scripts",
"npm_config_location",
"npm_config_legacy_peer_deps",
"npm_config_prefix",
"npm_config_strict_peer_deps",
"npm_config_workspace",
"npm_config_workspaces"
]);
const NPM_FRESHNESS_BYPASS_KEYS = [
"NPM_CONFIG_BEFORE",
"npm_config_before",
"NPM_CONFIG_MIN_RELEASE_AGE",
"npm_config_min_release_age",
"NPM_CONFIG_MIN-RELEASE-AGE",
"npm_config_min-release-age"
];
const NPM_CONFIG_PATH_PROBE_PARENT_ENV_KEYS = [
"PATH",
"Path",
"PATHEXT",
"SystemRoot",
"ComSpec"
];
const NPM_GLOBAL_CONFIG_PATH_CACHE = /* @__PURE__ */ new Map();
const NPM_GLOBAL_CONFIG_PATH_CACHE_ENV_KEYS = [
...NPM_CONFIG_PATH_PROBE_PARENT_ENV_KEYS,
"NPM_CONFIG_GLOBALCONFIG",
"npm_config_globalconfig",
"NPM_CONFIG_PREFIX",
"npm_config_prefix",
"NPM_CONFIG_USERCONFIG",
"npm_config_userconfig",
"HOME",
"PREFIX",
"USERPROFILE"
];
function resolveEnvPath(e, t) {
const n = e[`NPM_CONFIG_${t}`]?.trim() || e[`npm_config_${t.toLowerCase()}`]?.trim();
return n ? resolveNpmConfigPath(n, e) : null;
}
function resolveHomeNpmrc(e) {
const t = e.HOME?.trim() || e.USERPROFILE?.trim() || os.homedir();
return path.join(t, ".npmrc");
}
function replaceNpmEnvRefs(e, t) {
return e.replace(/(?<!\\)(\\*)\$\{([^${}?]+)(\?)?\}/gu, (e, n, r, i) => {
const a = i === "?" ? "" : `\${${r}}`;
const o = t[r] !== void 0 ? t[r] : a;
if (n.length % 2) return e.slice((n.length + 1) / 2);
return `${n.slice(n.length / 2)}${o}`;
});
}
function resolveNpmConfigPath(e, t) {
const n = replaceNpmEnvRefs(e, t);
const r = t.HOME?.trim() || t.USERPROFILE?.trim() || os.homedir();
return (process.platform === "win32" ? /^~(\/|\\)/u : /^~\//u).test(n) && r ? path.resolve(r, n.slice(2)) : path.resolve(n);
}
function createNpmConfigPathProbeEnv(e, t) {
const n = { ...e };
for (const e of NPM_FRESHNESS_BYPASS_KEYS) delete n[e];
for (const e of NPM_CONFIG_PATH_PROBE_PARENT_ENV_KEYS) if (n[e] == null && process.env[e] != null) n[e] = process.env[e];
if (t.npmConfigPrefix) n.npm_config_prefix = t.npmConfigPrefix;
return n;
}
function runNpmConfigProbe(e) {
const t = resolveRuntimeScriptEnv(e.env);
const n = resolveSafeChildProcessInvocation({
argv: resolveNpmCommand(e.args),
cwd: e.cwd,
env: t
});
const r = spawnSync(n.command, n.args, {
cwd: e.cwd,
encoding: "utf-8",
env: t,
stdio: [
"ignore",
"pipe",
"ignore"
],
timeout: e.timeoutMs,
windowsHide: n.windowsHide,
windowsVerbatimArguments: n.windowsVerbatimArguments
});
if (r.error) throw r.error;
if (r.status !== 0) throw new Error(`npm config check exited with status ${r.status ?? "unknown"}`);
return r.stdout;
}
function readNpmGlobalConfigPath(e, t) {
const n = resolveScopedGlobalNpmrc(t);
if (n) return n;
const r = resolveEnvPath(e, "GLOBALCONFIG");
if (r) return r;
const i = resolveEnvPath(e, "PREFIX");
if (i) return path.join(i, "etc", "npmrc");
const a = buildNpmGlobalConfigPathCacheKey(e, t);
if (NPM_GLOBAL_CONFIG_PATH_CACHE.has(a)) return NPM_GLOBAL_CONFIG_PATH_CACHE.get(a) ?? null;
try {
const n = runNpmConfigProbe({
args: [
"config",
"get",
"globalconfig"
],
env: createNpmConfigPathProbeEnv(e, t),
timeoutMs: 2e3
}).trim();
const r = n && n !== "null" && n !== "undefined" ? n : null;
NPM_GLOBAL_CONFIG_PATH_CACHE.set(a, r);
return r;
} catch {
NPM_GLOBAL_CONFIG_PATH_CACHE.set(a, null);
return null;
}
}
function buildNpmGlobalConfigPathCacheKey(e, t) {
const n = resolveNpmConfigFiles(e, t);
return JSON.stringify({
cwd: t.npmConfigCwd?.trim() || tryProcessCwd() || "",
prefix: t.npmConfigPrefix?.trim() ?? "",
env: Object.fromEntries(NPM_GLOBAL_CONFIG_PATH_CACHE_ENV_KEYS.map((t) => [t, e[t] ?? process.env[t] ?? ""])),
configFiles: n.map((e) => {
const t = safeStatSync(e);
return {
path: e,
signature: t ? `${t.mtimeMs}:${t.size}` : "missing"
};
})
});
}
function resolveScopedProjectNpmrc(e) {
const t = e.npmConfigCwd?.trim() || tryProcessCwd();
return t ? path.join(t, ".npmrc") : null;
}
function resolveScopedGlobalNpmrc(e) {
const t = e.npmConfigPrefix?.trim();
return t ? path.join(t, "etc", "npmrc") : null;
}
function resolveNpmConfigFiles(e, t, n = false) {
const r = [
resolveScopedProjectNpmrc(t),
resolveEnvPath(e, "USERCONFIG") ?? resolveHomeNpmrc(e),
resolveEnvPath(e, "GLOBALCONFIG"),
resolveScopedGlobalNpmrc(t),
...n ? [readNpmGlobalConfigPath(e, t)] : []
];
return uniqueStrings(r.filter((e) => Boolean(e)));
}
function hasNpmrcConfigKey(e, t) {
try {
const n = fs.readFileSync(e, "utf-8");
const r = t.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
return new RegExp(`^\\s*${r}\\s*=`, "imu").test(n);
} catch {
return false;
}
}
function hasNpmEnvConfigKey(e, t) {
return Object.entries(e).some(([e, n]) => {
if (!/^npm_config_/iu.test(e) || !n?.trim()) return false;
return e.slice(11).replace(/(?!^)_/gu, "-").toLowerCase() === t;
});
}
/** Finds keys npm resolves from explicit config layers rather than built-in defaults. */
function findExplicitNpmConfigKeys(e, t, n = {}) {
const r = new Set(t.filter((t) => hasNpmEnvConfigKey(e, t)));
const i = t.filter((e) => !r.has(e));
if (i.length === 0) return r;
const a = n.npmConfigCwd?.trim() || tryProcessCwd() || void 0;
const o = createNpmConfigPathProbeEnv(e, n);
try {
const e = runNpmConfigProbe({
args: [
"config",
"list",
"--location=project",
"--json=false",
"--long=false"
],
cwd: a,
env: o,
timeoutMs: 5e3
});
const t = e.split(/^; "publishConfig" from /mu, 1)[0] ?? e;
for (const e of i) {
const n = e.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
if (new RegExp(`^${n}\\s*=`, "mu").test(t)) r.add(e);
}
} catch {
for (const e of i) r.add(e);
}
return r;
}
function resolveNpmFreshnessBypassMode(e, t) {
if (process.platform === "win32") return "before";
const hasRawKey = (n) => resolveNpmConfigFiles(e, t, true).some((e) => hasNpmrcConfigKey(e, n));
if (hasRawKey("min-release-age")) return "min-release-age";
return hasRawKey("before") ? "before" : "min-release-age";
}
/**
* Builds npm args that bypass host freshness policies for OpenClaw-managed installs.
* Existing npmrc policy decides whether `before` or `min-release-age` is safer.
*/
function createNpmFreshnessBypassArgs(e = process.env, t = /* @__PURE__ */ new Date(), n = {}) {
if (resolveNpmFreshnessBypassMode(e, n) === "min-release-age") return ["--min-release-age=0"];
return [`--before=${t.toISOString()}`];
}
function applyNpmFreshnessBypassEnv(e, t = /* @__PURE__ */ new Date(), n = {}) {
const r = resolveNpmFreshnessBypassMode(e, n) === "before" ? t.toISOString() : void 0;
for (const t of NPM_FRESHNESS_BYPASS_KEYS) {
if (process.platform === "win32" && t.includes("-")) {
delete e[t];
continue;
}
e[t] = "";
}
if (r !== void 0) e.npm_config_before = r;
else e.npm_config_min_release_age = "0";
}
/**
* Creates npm env for project-local installs, clearing global/workspace config
* and adding fetch, freshness, cache, and POSIX script-shell defaults.
*/
function createNpmProjectInstallEnv(e, t = {}) {
const n = resolveRuntimeScriptEnv(e);
for (const e of Object.keys(n)) if (NPM_CONFIG_KEYS_TO_RESET.has(e.toLowerCase())) delete n[e];
for (const [e, t] of Object.entries({
npm_config_fetch_retries: "5",
npm_config_fetch_retry_maxtimeout: "120000",
npm_config_fetch_retry_mintimeout: "10000",
npm_config_fetch_timeout: String(UPDATE_NETWORK_TIMEOUT_MS)
})) if (!Object.entries(n).some(([t, n]) => t.toLowerCase() === e && n !== void 0)) n[e] = t;
const r = {
...n,
npm_config_dry_run: "false",
npm_config_global: "false",
npm_config_location: "project",
npm_config_package_lock: "false",
npm_config_save: "false",
...t.cacheDir ? { npm_config_cache: t.cacheDir } : {}
};
applyNpmFreshnessBypassEnv(r, /* @__PURE__ */ new Date(), t);
applyPosixNpmScriptShellEnv(r);
return r;
}
/** Sets npm's script-shell env only when the caller has not configured one. */
function applyPosixNpmScriptShellEnv(e) {
if (NPM_CONFIG_SCRIPT_SHELL_KEYS.some((t) => Boolean(e[t]?.trim())) || process.platform === "win32") return;
if (fs.existsSync("/bin/sh")) e.NPM_CONFIG_SCRIPT_SHELL = "/bin/sh";
else {
const t = e.SHELL?.trim();
if (t && path.isAbsolute(t) && fs.existsSync(t)) e.NPM_CONFIG_SCRIPT_SHELL = t;
}
}
//#endregion
export { findExplicitNpmConfigKeys as a, createNpmProjectInstallEnv as i, applyPosixNpmScriptShellEnv as n, UPDATE_NETWORK_TIMEOUT_MS as o, createNpmFreshnessBypassArgs as r, applyNpmFreshnessBypassEnv as t };