forked from openclaw/openclaw
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
401 lines (357 loc) 路 10.5 KB
/
Copy pathutils.ts
File metadata and controls
401 lines (357 loc) 路 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { resolveOAuthDir } from "./config/paths.js";
import { logVerbose, shouldLogVerbose } from "./globals.js";
import {
expandHomePrefix,
resolveEffectiveHomeDir,
resolveRequiredHomeDir,
} from "./infra/home-dir.js";
export async function ensureDir(dir: string) {
await fs.promises.mkdir(dir, { recursive: true });
}
/**
* Check if a file or directory exists at the given path.
*/
export async function pathExists(targetPath: string): Promise<boolean> {
try {
await fs.promises.access(targetPath);
return true;
} catch {
return false;
}
}
export function clampNumber(value: number, min: number, max: number): number {
return Math.max(min, Math.min(max, value));
}
export function clampInt(value: number, min: number, max: number): number {
return clampNumber(Math.floor(value), min, max);
}
/** Alias for clampNumber (shorter, more common name) */
export const clamp = clampNumber;
/**
* Escapes special regex characters in a string so it can be used in a RegExp constructor.
*/
export function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
/**
* Safely parse JSON, returning null on error instead of throwing.
*/
export function safeParseJson<T>(raw: string): T | null {
try {
return JSON.parse(raw) as T;
} catch {
return null;
}
}
/**
* Type guard for plain objects (not arrays, null, Date, RegExp, etc.).
* Uses Object.prototype.toString for maximum safety.
*/
export function isPlainObject(value: unknown): value is Record<string, unknown> {
return (
typeof value === "object" &&
value !== null &&
!Array.isArray(value) &&
Object.prototype.toString.call(value) === "[object Object]"
);
}
/**
* Type guard for Record<string, unknown> (less strict than isPlainObject).
* Accepts any non-null object that isn't an array.
*/
export function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
export type WebChannel = "web";
export function assertWebChannel(input: string): asserts input is WebChannel {
if (input !== "web") {
throw new Error("Web channel must be 'web'");
}
}
export function normalizePath(p: string): string {
if (!p.startsWith("/")) {
return `/${p}`;
}
return p;
}
export function withWhatsAppPrefix(number: string): string {
return number.startsWith("whatsapp:") ? number : `whatsapp:${number}`;
}
export function normalizeE164(number: string): string {
const withoutPrefix = number.replace(/^whatsapp:/, "").trim();
const digits = withoutPrefix.replace(/[^\d+]/g, "");
if (digits.startsWith("+")) {
return `+${digits.slice(1)}`;
}
return `+${digits}`;
}
/**
* "Self-chat mode" heuristic (single phone): the gateway is logged in as the owner's own WhatsApp account,
* and `channels.whatsapp.allowFrom` includes that same number. Used to avoid side-effects that make no sense when the
* "bot" and the human are the same WhatsApp identity (e.g. auto read receipts, @mention JID triggers).
*/
export function isSelfChatMode(
selfE164: string | null | undefined,
allowFrom?: Array<string | number> | null,
): boolean {
if (!selfE164) {
return false;
}
if (!Array.isArray(allowFrom) || allowFrom.length === 0) {
return false;
}
const normalizedSelf = normalizeE164(selfE164);
return allowFrom.some((n) => {
if (n === "*") {
return false;
}
try {
return normalizeE164(String(n)) === normalizedSelf;
} catch {
return false;
}
});
}
export function toWhatsappJid(number: string): string {
const withoutPrefix = number.replace(/^whatsapp:/, "").trim();
if (withoutPrefix.includes("@")) {
return withoutPrefix;
}
const e164 = normalizeE164(withoutPrefix);
const digits = e164.replace(/\D/g, "");
return `${digits}@s.whatsapp.net`;
}
export type JidToE164Options = {
authDir?: string;
lidMappingDirs?: string[];
logMissing?: boolean;
};
type LidLookup = {
getPNForLID?: (jid: string) => Promise<string | null>;
};
function resolveLidMappingDirs(opts?: JidToE164Options): string[] {
const dirs = new Set<string>();
const addDir = (dir?: string | null) => {
if (!dir) {
return;
}
dirs.add(resolveUserPath(dir));
};
addDir(opts?.authDir);
for (const dir of opts?.lidMappingDirs ?? []) {
addDir(dir);
}
addDir(resolveOAuthDir());
addDir(path.join(CONFIG_DIR, "credentials"));
return [...dirs];
}
function readLidReverseMapping(lid: string, opts?: JidToE164Options): string | null {
const mappingFilename = `lid-mapping-${lid}_reverse.json`;
const mappingDirs = resolveLidMappingDirs(opts);
for (const dir of mappingDirs) {
const mappingPath = path.join(dir, mappingFilename);
try {
const data = fs.readFileSync(mappingPath, "utf8");
const phone = JSON.parse(data) as string | number | null;
if (phone === null || phone === undefined) {
continue;
}
return normalizeE164(String(phone));
} catch {
// Try the next location.
}
}
return null;
}
export function jidToE164(jid: string, opts?: JidToE164Options): string | null {
// Convert a WhatsApp JID (with optional device suffix, e.g. 1234:1@s.whatsapp.net) back to +1234.
const match = jid.match(/^(\d+)(?::\d+)?@(s\.whatsapp\.net|hosted)$/);
if (match) {
const digits = match[1];
return `+${digits}`;
}
// Support @lid format (WhatsApp Linked ID) - look up reverse mapping
const lidMatch = jid.match(/^(\d+)(?::\d+)?@(lid|hosted\.lid)$/);
if (lidMatch) {
const lid = lidMatch[1];
const phone = readLidReverseMapping(lid, opts);
if (phone) {
return phone;
}
const shouldLog = opts?.logMissing ?? shouldLogVerbose();
if (shouldLog) {
logVerbose(`LID mapping not found for ${lid}; skipping inbound message`);
}
}
return null;
}
export async function resolveJidToE164(
jid: string | null | undefined,
opts?: JidToE164Options & { lidLookup?: LidLookup },
): Promise<string | null> {
if (!jid) {
return null;
}
const direct = jidToE164(jid, opts);
if (direct) {
return direct;
}
if (!/(@lid|@hosted\.lid)$/.test(jid)) {
return null;
}
if (!opts?.lidLookup?.getPNForLID) {
return null;
}
try {
const pnJid = await opts.lidLookup.getPNForLID(jid);
if (!pnJid) {
return null;
}
return jidToE164(pnJid, opts);
} catch (err) {
if (shouldLogVerbose()) {
logVerbose(`LID mapping lookup failed for ${jid}: ${String(err)}`);
}
return null;
}
}
export function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function isHighSurrogate(codeUnit: number): boolean {
return codeUnit >= 0xd800 && codeUnit <= 0xdbff;
}
function isLowSurrogate(codeUnit: number): boolean {
return codeUnit >= 0xdc00 && codeUnit <= 0xdfff;
}
export function sliceUtf16Safe(input: string, start: number, end?: number): string {
const len = input.length;
let from = start < 0 ? Math.max(len + start, 0) : Math.min(start, len);
let to = end === undefined ? len : end < 0 ? Math.max(len + end, 0) : Math.min(end, len);
if (to < from) {
const tmp = from;
from = to;
to = tmp;
}
if (from > 0 && from < len) {
const codeUnit = input.charCodeAt(from);
if (isLowSurrogate(codeUnit) && isHighSurrogate(input.charCodeAt(from - 1))) {
from += 1;
}
}
if (to > 0 && to < len) {
const codeUnit = input.charCodeAt(to - 1);
if (isHighSurrogate(codeUnit) && isLowSurrogate(input.charCodeAt(to))) {
to -= 1;
}
}
return input.slice(from, to);
}
export function truncateUtf16Safe(input: string, maxLen: number): string {
const limit = Math.max(0, Math.floor(maxLen));
if (input.length <= limit) {
return input;
}
return sliceUtf16Safe(input, 0, limit);
}
export function resolveUserPath(input: string): string {
const trimmed = input.trim();
if (!trimmed) {
return trimmed;
}
if (trimmed.startsWith("~")) {
const expanded = expandHomePrefix(trimmed, {
home: resolveRequiredHomeDir(process.env, os.homedir),
env: process.env,
homedir: os.homedir,
});
return path.resolve(expanded);
}
return path.resolve(trimmed);
}
export function resolveConfigDir(
env: NodeJS.ProcessEnv = process.env,
homedir: () => string = os.homedir,
): string {
const override = env.OPENCLAW_STATE_DIR?.trim() || env.CLAWDBOT_STATE_DIR?.trim();
if (override) {
return resolveUserPath(override);
}
const newDir = path.join(resolveRequiredHomeDir(env, homedir), ".openclaw");
try {
const hasNew = fs.existsSync(newDir);
if (hasNew) {
return newDir;
}
} catch {
// best-effort
}
return newDir;
}
export function resolveHomeDir(): string | undefined {
return resolveEffectiveHomeDir(process.env, os.homedir);
}
function resolveHomeDisplayPrefix(): { home: string; prefix: string } | undefined {
const home = resolveHomeDir();
if (!home) {
return undefined;
}
const explicitHome = process.env.OPENCLAW_HOME?.trim();
if (explicitHome) {
return { home, prefix: "$OPENCLAW_HOME" };
}
return { home, prefix: "~" };
}
export function shortenHomePath(input: string): string {
if (!input) {
return input;
}
const display = resolveHomeDisplayPrefix();
if (!display) {
return input;
}
const { home, prefix } = display;
if (input === home) {
return prefix;
}
if (input.startsWith(`${home}/`) || input.startsWith(`${home}\\`)) {
return `${prefix}${input.slice(home.length)}`;
}
return input;
}
export function shortenHomeInString(input: string): string {
if (!input) {
return input;
}
const display = resolveHomeDisplayPrefix();
if (!display) {
return input;
}
return input.split(display.home).join(display.prefix);
}
export function displayPath(input: string): string {
return shortenHomePath(input);
}
export function displayString(input: string): string {
return shortenHomeInString(input);
}
export function formatTerminalLink(
label: string,
url: string,
opts?: { fallback?: string; force?: boolean },
): string {
const esc = "\u001b";
const safeLabel = label.replaceAll(esc, "");
const safeUrl = url.replaceAll(esc, "");
const allow =
opts?.force === true ? true : opts?.force === false ? false : Boolean(process.stdout.isTTY);
if (!allow) {
return opts?.fallback ?? `${safeLabel} (${safeUrl})`;
}
return `\u001b]8;;${safeUrl}\u0007${safeLabel}\u001b]8;;\u0007`;
}
// Configuration root; can be overridden via OPENCLAW_STATE_DIR.
export const CONFIG_DIR = resolveConfigDir();