openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
407 lines (406 loc) • 15.9 kB
JavaScript
import path from "node:path";
import { isNotFoundPathError, isPathInside as isPathInside$1, normalizeWindowsPathForComparison as normalizeWindowsPathForComparison$1 } from "@openclaw/fs-safe/path";
import os from "node:os";
//#region src/shared/global-singleton.ts
/**
* Process-local singleton helpers for registries, caches, and SDK-visible shared state.
* Keys must be symbols so unrelated modules cannot collide on `globalThis` property names.
*/
const GLOBAL_SINGLETON_RESETS_KEY = Symbol.for("openclaw.globalSingletonLifecycleResets");
function resolveGlobalSingletonResetRegistry() {
const e = globalThis;
const t = e[GLOBAL_SINGLETON_RESETS_KEY];
if (t instanceof Map) return t;
const n = /* @__PURE__ */ new Map();
e[GLOBAL_SINGLETON_RESETS_KEY] = n;
return n;
}
/** Observe an existing owner's state without initializing it or registering cleanup. */
function readGlobalSingleton(e) {
const t = globalThis;
return Object.hasOwn(t, e) ? t[e] : void 0;
}
/** Resolves a process-local singleton for caches and registries that tolerate helper lookup. */
function resolveGlobalSingleton(e, t, n, r = "close-and-restart") {
const i = globalThis;
let a;
if (Object.hasOwn(i, e)) a = i[e];
else {
a = t();
i[e] = a;
}
if (n) resolveGlobalSingletonResetRegistry().set(e, {
lifecycle: r,
reset: () => n(a)
});
return a;
}
/** Resolves a process-local Map singleton for keyed caches backed by globalThis. */
function resolveGlobalMap(e, t, n) {
return resolveGlobalSingleton(e, () => /* @__PURE__ */ new Map(), typeof t === "string" ? (e) => e.clear() : t, typeof t === "string" ? t : n);
}
/** Resolves a lifecycle-owned process-local Set singleton. */
function resolveGlobalSet(e, t) {
return resolveGlobalSingleton(e, () => /* @__PURE__ */ new Set(), (e) => e.clear(), t);
}
//#endregion
//#region packages/normalization-core/src/string-coerce.ts
/** Trims string input and returns null for non-strings or empty strings. */
function normalizeNullableString(e) {
if (typeof e !== "string") return null;
const t = e.trim();
return t ? t : null;
}
/** Trims string input and returns undefined for non-strings or empty strings. */
function normalizeOptionalString(e) {
return normalizeNullableString(e) ?? void 0;
}
/** Lowercases a normalized optional string. */
function normalizeOptionalLowercaseString(e) {
return normalizeOptionalString(e)?.toLowerCase();
}
/** Lowercases a normalized string or returns an empty string when absent. */
function normalizeLowercaseStringOrEmpty(e) {
return normalizeOptionalLowercaseString(e) ?? "";
}
/** Type guard for strings that remain non-empty after trimming. */
function hasNonEmptyString(e) {
return normalizeOptionalString(e) !== void 0;
}
//#endregion
//#region packages/normalization-core/src/number-coercion.ts
function asFiniteNumber(e) {
return typeof e === "number" && Number.isFinite(e) ? e : void 0;
}
function asPositiveFiniteNumber(e) {
const t = asFiniteNumber(e);
return t && t > 0 ? t : void 0;
}
/** Floors positive finite input; fractions below one become zero. */
function floorPositiveFiniteNumber(e) {
const t = asPositiveFiniteNumber(e);
return t === void 0 ? void 0 : Math.floor(t);
}
function asNonNegativeFiniteNumber(e) {
const t = asFiniteNumber(e);
return t && t < 0 ? void 0 : t;
}
/** Returns a finite number only when it satisfies the supplied inclusive/exclusive bounds. */
function asFiniteNumberInRange(e, t) {
const n = asFiniteNumber(e);
if (n === void 0) return;
if (t.min !== void 0) {
if (t.minExclusive ? n <= t.min : n < t.min) return;
}
if (t.max !== void 0) {
if (t.maxExclusive ? n >= t.max : n > t.max) return;
}
return n;
}
/** Returns a safe integer only when it satisfies the supplied inclusive bounds. */
function asSafeIntegerInRange(e, t) {
if (typeof e !== "number" || !Number.isSafeInteger(e)) return;
if (t.min !== void 0 && e < t.min) return;
if (t.max !== void 0 && e > t.max) return;
return e;
}
/** Parses only safe integer numbers or base-10 integer strings. */
function parseStrictInteger(e) {
if (typeof e === "number") return Number.isSafeInteger(e) ? e : void 0;
const t = normalizeOptionalString(e);
if (!t || !/^[+-]?\d+$/.test(t)) return;
const n = Number(t);
return Number.isSafeInteger(n) ? n : void 0;
}
function asPositiveSafeInteger(e) {
return typeof e === "number" && Number.isSafeInteger(e) && e > 0 ? e : void 0;
}
function asPositiveInteger(e) {
return typeof e === "number" && Number.isInteger(e) && e > 0 ? e : void 0;
}
function asNonNegativeInteger(e) {
return typeof e === "number" && Number.isInteger(e) && e >= 0 ? e : void 0;
}
/** Conservative upper bound for Node timer delays. */
const MAX_TIMER_TIMEOUT_MS = 2147e6;
/** Timer bound expressed in whole seconds for env/config inputs. */
const MAX_TIMER_TIMEOUT_SECONDS = Math.floor(MAX_TIMER_TIMEOUT_MS / 1e3);
/** Largest timestamp accepted by JavaScript Date. */
const MAX_DATE_TIMESTAMP_MS = 864e13;
function asDateTimestampMs(e) {
return asFiniteNumberInRange(e, {
min: -864e13,
max: MAX_DATE_TIMESTAMP_MS
});
}
/** Parses Date-valid timestamp strings using JavaScript date-string semantics. */
function parseDateStringTimestampMs(e) {
return typeof e === "string" ? asDateTimestampMs(Date.parse(e)) : void 0;
}
/** Clamps finite millisecond values into the Node-safe timer range. */
function clampTimerTimeoutMs(e, t = 1) {
const n = asFiniteNumber(e);
if (n === void 0) return;
return Math.min(Math.max(Math.floor(n), Math.max(1, Math.floor(t))), MAX_TIMER_TIMEOUT_MS);
}
/** Clamps positive finite millisecond values into the Node-safe timer range. */
function clampPositiveTimerTimeoutMs(e) {
const t = asFiniteNumber(e);
if (t === void 0 || t <= 0) return;
return clampTimerTimeoutMs(t);
}
/** Resolves a positive timer timeout or falls back through safe timer clamping. */
function resolvePositiveTimerTimeoutMs(e, t) {
return clampPositiveTimerTimeoutMs(e) ?? resolveTimerTimeoutMs(t, 1);
}
/** Resolves arbitrary timeout input with fallback and minimum timer bounds. */
function resolveTimerTimeoutMs(e, t, n = 1) {
const r = asFiniteNumber(e) ?? asFiniteNumber(t);
const i = Math.max(0, Math.floor(n));
if (r === void 0) return i;
return Math.min(Math.max(Math.floor(r), i), MAX_TIMER_TIMEOUT_MS);
}
/** Resolves an integer option from finite numeric input or fallback, then clamps bounds. */
function resolveIntegerOption(e, t, n = {}) {
const r = asFiniteNumber(e) ?? t;
const i = Math.floor(r);
const a = n.min === void 0 ? i : Math.max(n.min, i);
return n.max === void 0 ? a : Math.min(n.max, a);
}
/** Resolves an optional integer option, returning undefined for non-finite input. */
function resolveOptionalIntegerOption(e, t = {}) {
if (typeof e !== "number" || !Number.isFinite(e)) return;
return resolveIntegerOption(e, e, t);
}
function resolveNonNegativeIntegerOption(e, t) {
return resolveIntegerOption(e, t, { min: 0 });
}
function parseStrictPositiveInteger(e) {
const t = parseStrictInteger(e);
return t !== void 0 && t > 0 ? t : void 0;
}
function parseStrictNonNegativeInteger(e) {
const t = parseStrictInteger(e);
return t !== void 0 && t >= 0 ? t : void 0;
}
//#endregion
//#region packages/normalization-core/src/home-dir.ts
function normalizeHomeDirValue(e) {
const t = e?.trim();
return t && t !== "undefined" && t !== "null" ? t : void 0;
}
function normalizeSafe(e) {
try {
return normalizeHomeDirValue(e());
} catch {
return;
}
}
function resolveTermuxHome(e) {
const t = normalizeHomeDirValue(e.PREFIX);
if (!t || !normalizeHomeDirValue(e.ANDROID_DATA)) return;
if (!/(?:^|\/)com\.termux\/files\/usr\/?$/u.test(t.replace(/\\/gu, "/"))) return;
return path.resolve(t, "..", "home");
}
function resolveRawOsHomeDir(e, t) {
return normalizeHomeDirValue(e.HOME) ?? normalizeHomeDirValue(e.USERPROFILE) ?? resolveTermuxHome(e) ?? normalizeSafe(t);
}
function resolveOsHomeDir(e = process.env, t = os.homedir) {
const n = resolveRawOsHomeDir(e, t);
return n ? path.resolve(n) : void 0;
}
function resolveEffectiveHomeDir(e = process.env, t = os.homedir, n) {
const r = normalizeHomeDirValue(e.OPENCLAW_HOME);
if (!r) return resolveOsHomeDir(e, t);
if (r === "~" || r.startsWith("~/") || r.startsWith("~\\")) {
const i = resolveRawOsHomeDir(e, t);
if (!i) return n?.preserveUnresolvedTilde ? path.resolve(r) : void 0;
return path.resolve(r.replace(/^~(?=$|[\\/])/, () => i));
}
return path.resolve(r);
}
//#endregion
//#region src/infra/safe-cwd.ts
function tryProcessCwd() {
try {
return process.cwd();
} catch {
return;
}
}
//#endregion
//#region src/infra/home-dir.ts
function getUserPathBaseDirectory() {
return resolveGlobalSingleton(Symbol.for("openclaw.userPathBaseDirectory"), () => {
const { AsyncLocalStorage: e } = process.getBuiltinModule("async_hooks");
return new e();
});
}
/** Resolves the effective home or falls back to cwd when no home source exists. */
function resolveRequiredHomeDir(e = process.env, t = os.homedir) {
const n = resolveEffectiveHomeDir(e, t) ?? tryProcessCwd();
if (n) return path.resolve(n);
throw new Error("Unable to resolve an OpenClaw home: set OPENCLAW_HOME, HOME, or USERPROFILE, or run from an existing directory.");
}
/** Resolves the OS home or falls back to cwd when no OS home source exists. */
function resolveRequiredOsHomeDir(e = process.env, t = os.homedir) {
const n = resolveOsHomeDir(e, t) ?? tryProcessCwd();
if (n) return path.resolve(n);
throw new Error("Unable to resolve an OS home: set HOME or USERPROFILE, or run from an existing directory.");
}
/** Expands leading `~`, `~/`, or `~\` with the effective home when one is known. */
function expandHomePrefix(e, t) {
if (!e.startsWith("~")) return e;
const n = normalizeHomeDirValue(t?.home) ?? resolveEffectiveHomeDir(t?.env ?? process.env, t?.homedir ?? os.homedir);
if (!n) return e;
return e.replace(/^~(?=$|[\\/])/, () => n);
}
function resolveAgainstUserBase(e) {
const t = getUserPathBaseDirectory().getStore();
return t ? path.resolve(t, e) : path.resolve(e);
}
function resolvePathWithHome(e, t, n, r = resolveAgainstUserBase) {
const i = e.trim();
if (!i) return i;
return r(i.startsWith("~") ? expandHomePrefix(i, {
home: n(t?.env ?? process.env, t?.homedir ?? os.homedir),
env: t?.env,
homedir: t?.homedir
}) : i);
}
/** Resolves a user-supplied path after trimming and expanding against the effective home. */
function resolveHomeRelativePath(e, t) {
return resolvePathWithHome(e, t, resolveRequiredHomeDir);
}
/** Resolves a user path against the effective home, preserving an empty input. */
function resolveUserPath(e, t = process.env, n = os.homedir) {
if (!e) return "";
return resolveHomeRelativePath(e, {
env: t,
homedir: n
});
}
//#endregion
//#region src/cli/profile-utils.ts
const PROFILE_NAME_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/i;
function isValidProfileName(e) {
return PROFILE_NAME_RE.test(e);
}
function normalizeProfileName(e) {
const t = e?.trim();
if (!t) return null;
if (normalizeLowercaseStringOrEmpty(t) === "default") return null;
if (!isValidProfileName(t)) return null;
return t;
}
/** Resolve the canonical home-scoped state root for a validated CLI profile. */
function resolveProfileStateDir(e, t, n) {
const r = e.trim();
if (!isValidProfileName(r)) throw new Error(`Invalid profile name: ${JSON.stringify(e)}`);
const i = normalizeLowercaseStringOrEmpty(r) === "default" ? "" : `-${r}`;
return path.join(resolveRequiredHomeDir(t, n), `.openclaw${i}`);
}
//#endregion
//#region src/infra/lru-cache.ts
/** Process-local LRU storage; callers own freshness and lifecycle. */
var LruCache = class {
#e;
#t;
#n;
#r = /* @__PURE__ */ new Map();
#i = 0;
constructor(e, t) {
this.#e = Number.isFinite(e) && e > 0 ? Math.max(1, Math.floor(e)) : 1;
this.#t = t?.maxBytes ?? Number.POSITIVE_INFINITY;
this.#n = t?.sizeOf;
}
get size() {
return this.#r.size;
}
clear() {
this.#r.clear();
this.#i = 0;
}
keys() {
return this.#r.keys();
}
delete(e) {
if (!this.#r.has(e)) return false;
this.#i -= this.#n?.(this.#r.get(e)) ?? 0;
return this.#r.delete(e);
}
deleteValue(e) {
for (const [t, n] of this.#r) if (n === e) this.delete(t);
}
/** Reads without promoting a value whose revalidation is still pending. */
peek(e) {
return this.#r.get(e);
}
/** Returns a cached value and refreshes its recency when present. */
get(e) {
if (!this.#r.has(e)) return;
const t = this.#r.get(e);
this.#r.delete(e);
this.#r.set(e, t);
return t;
}
/** Stores a value as the newest entry and evicts oldest entries past capacity. */
set(e, t) {
this.delete(e);
this.#r.set(e, t);
this.#i += this.#n?.(t) ?? 0;
for (const e of this.#r.keys()) {
if (this.#r.size <= this.#e && this.#i <= this.#t) break;
this.delete(e);
}
}
};
//#endregion
//#region src/config/state-dir.ts
const absoluteStateDirs = new LruCache(64);
function resolveNewStateDir(e = resolveRequiredHomeDir) {
return path.join(e(), ".openclaw");
}
/**
* State directory for mutable data (sessions, logs, caches).
* Can be overridden via OPENCLAW_STATE_DIR.
* Default: ~/.openclaw, or ~/.openclaw-<profile> for a named profile.
*/
function resolveStateDir(e = process.env, t = os.homedir) {
const n = e.OPENCLAW_STATE_DIR?.trim();
if (n && process.platform !== "win32" && path.isAbsolute(n)) {
const e = absoluteStateDirs.peek(n);
if (e !== void 0) return e;
const t = path.resolve(n);
absoluteStateDirs.set(n, t);
return t;
}
if (n) return resolveHomeRelativePath(n, {
env: e,
homedir: t
});
return resolveStateDirFromHome(e, () => resolveRequiredHomeDir(e, t));
}
/** Select a default state directory from the caller's already resolved home. */
function resolveStateDirFromHome(e, t) {
const n = normalizeProfileName(e.OPENCLAW_PROFILE);
return n ? resolveProfileStateDir(n, e, t) : resolveNewStateDir(t);
}
//#endregion
//#region src/infra/path-guards.ts
/**
* Normalize a Windows path for boundary math whose result is handed back to callers.
*
* Unlike `normalizeWindowsPathForComparison`, this preserves case: `path.win32.relative`
* already matches roots case-insensitively, so lowercasing only corrupts the returned
* relative path — and callers create files from it on a case-preserving filesystem.
* Extended-length prefix stripping stays, or `\\?\`-prefixed inputs read as boundary escapes.
*/
function normalizeWindowsPathPreservingCase(e) {
const t = path.win32.normalize(e);
if (!t.startsWith("\\\\?\\")) return t;
const n = t.slice(4);
return n.toUpperCase().startsWith("UNC\\") ? `\\\\${n.slice(4)}` : n;
}
//#endregion
export { parseStrictPositiveInteger as A, normalizeOptionalString as B, asPositiveInteger as C, floorPositiveFiniteNumber as D, clampPositiveTimerTimeoutMs as E, resolveTimerTimeoutMs as F, resolveGlobalMap as H, hasNonEmptyString as I, normalizeLowercaseStringOrEmpty as L, resolveNonNegativeIntegerOption as M, resolveOptionalIntegerOption as N, parseDateStringTimestampMs as O, resolvePositiveTimerTimeoutMs as P, normalizeNullableString as R, asPositiveFiniteNumber as S, asSafeIntegerInRange as T, resolveGlobalSet as U, readGlobalSingleton as V, resolveGlobalSingleton as W, MAX_DATE_TIMESTAMP_MS as _, resolveStateDir as a, asNonNegativeFiniteNumber as b, resolveProfileStateDir as c, resolveRequiredHomeDir as d, resolveRequiredOsHomeDir as f, resolveEffectiveHomeDir as g, normalizeHomeDirValue as h, normalizeWindowsPathPreservingCase as i, resolveIntegerOption as j, parseStrictNonNegativeInteger as k, expandHomePrefix as l, tryProcessCwd as m, isPathInside$1 as n, LruCache as o, resolveUserPath as p, normalizeWindowsPathForComparison$1 as r, normalizeProfileName as s, isNotFoundPathError as t, resolveHomeRelativePath as u, MAX_TIMER_TIMEOUT_MS as v, asPositiveSafeInteger as w, asNonNegativeInteger as x, asFiniteNumber as y, normalizeOptionalLowercaseString as z };