qwenproxy-cli 1.0.0 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +14 -14
- package/README.md +906 -906
- package/bin/qwenproxy.js +5 -1
- package/package.json +77 -78
- package/src/api/error-classifier.ts +159 -159
- package/src/api/error-helpers.ts +118 -118
- package/src/api/models.ts +261 -261
- package/src/api/server.ts +860 -859
- package/src/cache/memory-cache.ts +385 -385
- package/src/clean-cache.ts +204 -204
- package/src/core/account-concurrency.ts +671 -671
- package/src/core/account-manager.ts +301 -297
- package/src/core/account-priority.ts +163 -163
- package/src/core/accounts.ts +186 -186
- package/src/core/config.ts +383 -383
- package/src/core/crypto-utils.ts +79 -79
- package/src/core/database.ts +276 -276
- package/src/core/errors.ts +118 -118
- package/src/core/logger.ts +269 -269
- package/src/core/memory-usage.ts +84 -84
- package/src/core/metrics.ts +291 -291
- package/src/core/model-alias.ts +77 -77
- package/src/core/model-registry.ts +544 -544
- package/src/core/mutex.ts +119 -119
- package/src/core/paths.ts +199 -199
- package/src/core/prompt-limits.ts +214 -214
- package/src/core/reasoning-effort.ts +102 -102
- package/src/core/stream-registry.ts +96 -96
- package/src/core/waf-isolation.ts +117 -117
- package/src/core/watchdog.ts +195 -195
- package/src/delete-chats.ts +23 -23
- package/src/index.ts +65 -64
- package/src/login.ts +147 -147
- package/src/reset-cooldowns.ts +11 -11
- package/src/routes/anthropic/index.ts +355 -355
- package/src/routes/anthropic/translate.ts +522 -522
- package/src/routes/anthropic/types.ts +154 -154
- package/src/routes/anthropic/validation.ts +144 -144
- package/src/routes/chat/account.ts +1817 -1817
- package/src/routes/chat/context.ts +241 -241
- package/src/routes/chat/errors.ts +85 -85
- package/src/routes/chat/helpers.ts +268 -268
- package/src/routes/chat/index.ts +618 -618
- package/src/routes/chat/media.ts +285 -285
- package/src/routes/chat/retry-policy.ts +754 -754
- package/src/routes/chat/stop.ts +98 -98
- package/src/routes/chat/streaming.ts +2710 -2710
- package/src/routes/chat/validation.ts +526 -526
- package/src/routes/chat.ts +2 -2
- package/src/routes/completions.ts +290 -290
- package/src/routes/images.ts +139 -139
- package/src/routes/responses/adapter.ts +503 -503
- package/src/routes/responses/index.ts +405 -405
- package/src/routes/responses/state.ts +230 -230
- package/src/routes/responses/streaming.ts +528 -528
- package/src/routes/responses/types.ts +285 -285
- package/src/routes/responses/validation.ts +202 -202
- package/src/routes/upload.ts +731 -731
- package/src/routes/videos.ts +214 -214
- package/src/services/auth-playwright.ts +173 -173
- package/src/services/captcha-coordinator.ts +161 -161
- package/src/services/captcha-solver.ts +553 -553
- package/src/services/chat-cleanup.ts +80 -80
- package/src/services/context-meter.ts +317 -317
- package/src/services/fingerprint.ts +242 -242
- package/src/services/human-behavior.ts +173 -173
- package/src/services/media-generation.ts +1748 -1748
- package/src/services/playwright.ts +2878 -2800
- package/src/services/qwen-chat-pool.ts +345 -345
- package/src/services/qwen-errors.ts +133 -133
- package/src/services/qwen-headers.ts +79 -79
- package/src/services/qwen-thread-state.ts +393 -393
- package/src/services/qwen-url.ts +19 -19
- package/src/services/qwen.ts +3126 -3126
- package/src/services/session-keeper.ts +88 -88
- package/src/services/token-estimation-metrics.ts +118 -118
- package/src/sync/claude-code.ts +75 -75
- package/src/sync/codex.ts +123 -123
- package/src/sync/index.ts +362 -362
- package/src/sync/omp.ts +105 -105
- package/src/sync/opencode.ts +214 -214
- package/src/sync/types.ts +53 -53
- package/src/sync/utils.ts +27 -27
- package/src/sync-clients.ts +189 -189
- package/src/tools/instructions.ts +137 -137
- package/src/tools/manifest.ts +81 -81
- package/src/tools/parser.ts +2989 -2989
- package/src/tools/toolcall-tags.ts +142 -142
- package/src/tui/app.ts +259 -264
- package/src/tui/index.ts +61 -61
- package/src/tui/markdown.ts +258 -258
- package/src/tui/proxy-client.ts +331 -326
- package/src/tui/screen.ts +294 -278
- package/src/tui/server-manager.ts +270 -270
- package/src/tui/theme.ts +432 -432
- package/src/tui/types.ts +33 -33
- package/src/tui/views/accounts-view.ts +656 -656
- package/src/tui/views/chat-view.ts +1018 -823
- package/src/tui/views/logs-view.ts +479 -413
- package/src/tui/views/status-view.ts +204 -204
- package/src/tui/views/storage-view.ts +304 -291
- package/src/tui/views/sync-view.ts +409 -409
- package/src/types/ali-oss.d.ts +32 -32
- package/src/update-cli.ts +121 -0
- package/src/utils/context-truncation.ts +84 -84
- package/src/utils/json.ts +380 -380
- package/src/utils/session-id.ts +37 -37
- package/src/utils/tool-call-guard.ts +84 -84
- package/src/utils/types.ts +109 -109
package/src/core/mutex.ts
CHANGED
|
@@ -1,119 +1,119 @@
|
|
|
1
|
-
import { logger } from "./logger.js";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Maximum time a mutex can be held before it's considered leaked and
|
|
5
|
-
* force-released. Overridable via MUTEX_MAX_HOLD_MS for tests.
|
|
6
|
-
*/
|
|
7
|
-
const MAX_HOLD_MS = (() => {
|
|
8
|
-
const parsed = parseInt(process.env.MUTEX_MAX_HOLD_MS ?? "", 10);
|
|
9
|
-
return Number.isFinite(parsed) && parsed > 0 ? parsed : 120_000;
|
|
10
|
-
})();
|
|
11
|
-
|
|
12
|
-
export class Mutex {
|
|
13
|
-
private queue: Array<{ waiter: () => void; enqueuedAt: number; key: string }> = [];
|
|
14
|
-
private locked = false;
|
|
15
|
-
private lockedAt = 0;
|
|
16
|
-
private lockedByKey = "";
|
|
17
|
-
|
|
18
|
-
constructor(
|
|
19
|
-
public readonly name: string = "unnamed",
|
|
20
|
-
private readonly maxHoldMs: number = MAX_HOLD_MS,
|
|
21
|
-
) {}
|
|
22
|
-
|
|
23
|
-
async acquire(timeoutMs = 300_000, key = ""): Promise<() => void> {
|
|
24
|
-
// Stale detection: force-release if held beyond the hold limit
|
|
25
|
-
// (leaked lock). The chat lock uses a longer hold so a legitimate
|
|
26
|
-
// long generation (2-3 min with huge contexts) is not force-released
|
|
27
|
-
// mid-stream; the page/init locks keep the shorter safety net so a
|
|
28
|
-
// stuck browser op releases the account back to the pool faster.
|
|
29
|
-
const holdLimitMs = this.maxHoldMs;
|
|
30
|
-
if (this.locked && Date.now() - this.lockedAt > holdLimitMs) {
|
|
31
|
-
const heldFor = Date.now() - this.lockedAt;
|
|
32
|
-
logger.warn(
|
|
33
|
-
`[Mutex:${this.name}] Force-releasing stale lock | heldBy=${this.lockedByKey} | heldFor=${heldFor}ms | limit=${holdLimitMs}ms`,
|
|
34
|
-
);
|
|
35
|
-
this.locked = false;
|
|
36
|
-
this.lockedAt = 0;
|
|
37
|
-
this.lockedByKey = "";
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
if (!this.locked) {
|
|
41
|
-
this.locked = true;
|
|
42
|
-
this.lockedAt = Date.now();
|
|
43
|
-
this.lockedByKey = key;
|
|
44
|
-
return this.createRelease();
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
const enqueuedAt = Date.now();
|
|
48
|
-
const logKey = key || "anon";
|
|
49
|
-
if (logger.isLevelEnabled("debug")) {
|
|
50
|
-
logger.debug(`[Mutex:${this.name}] enqueue key=${logKey} queue=${this.queue.length + 1} heldBy=${this.lockedByKey || "unknown"} heldFor=${Date.now() - this.lockedAt}ms`);
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
return new Promise<() => void>((resolve, reject) => {
|
|
54
|
-
const waiter = () => {
|
|
55
|
-
clearTimeout(timer);
|
|
56
|
-
this.lockedByKey = logKey;
|
|
57
|
-
this.lockedAt = Date.now();
|
|
58
|
-
resolve(this.createRelease());
|
|
59
|
-
};
|
|
60
|
-
const timer = setTimeout(() => {
|
|
61
|
-
const index = this.queue.findIndex((e) => e.waiter === waiter);
|
|
62
|
-
if (index !== -1) this.queue.splice(index, 1);
|
|
63
|
-
const heldFor = Date.now() - this.lockedAt;
|
|
64
|
-
logger.warn(`[Mutex:${this.name}] TIMEOUT key=${logKey} waited=${timeoutMs}ms heldBy=${this.lockedByKey || "unknown"} heldFor=${heldFor}ms queueLeft=${this.queue.length}`);
|
|
65
|
-
reject(new Error(`Mutex[${this.name}] acquire timeout after ${timeoutMs}ms (held by ${this.lockedByKey || "unknown"} for ${heldFor}ms)`));
|
|
66
|
-
}, timeoutMs);
|
|
67
|
-
this.queue.push({ waiter, enqueuedAt, key: logKey });
|
|
68
|
-
});
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
async withLock<T>(fn: () => Promise<T> | T, timeoutMs?: number): Promise<T> {
|
|
72
|
-
const release = await this.acquire(timeoutMs);
|
|
73
|
-
try {
|
|
74
|
-
return await fn();
|
|
75
|
-
} finally {
|
|
76
|
-
release();
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
private createRelease(): () => void {
|
|
81
|
-
let released = false;
|
|
82
|
-
return () => {
|
|
83
|
-
if (released) return;
|
|
84
|
-
released = true;
|
|
85
|
-
this.release();
|
|
86
|
-
};
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
private release(): void {
|
|
90
|
-
const next = this.queue.shift();
|
|
91
|
-
if (next) {
|
|
92
|
-
const waitTime = Date.now() - next.enqueuedAt;
|
|
93
|
-
if (waitTime > 1_000 && logger.isLevelEnabled("debug")) {
|
|
94
|
-
logger.debug(`[Mutex:${this.name}] dequeued key=${next.key} waited=${waitTime}ms`);
|
|
95
|
-
}
|
|
96
|
-
next.waiter();
|
|
97
|
-
return;
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
this.locked = false;
|
|
101
|
-
this.lockedAt = 0;
|
|
102
|
-
this.lockedByKey = "";
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
/** Returns true if the mutex is not locked and has no waiting queue. */
|
|
106
|
-
isIdle(): boolean {
|
|
107
|
-
return !this.locked && this.queue.length === 0;
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
/** Returns diagnostic info about the current lock state. */
|
|
111
|
-
state(): { locked: boolean; heldBy: string; heldForMs: number; queueLength: number } {
|
|
112
|
-
return {
|
|
113
|
-
locked: this.locked,
|
|
114
|
-
heldBy: this.lockedByKey,
|
|
115
|
-
heldForMs: this.locked ? Date.now() - this.lockedAt : 0,
|
|
116
|
-
queueLength: this.queue.length,
|
|
117
|
-
};
|
|
118
|
-
}
|
|
119
|
-
}
|
|
1
|
+
import { logger } from "./logger.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Maximum time a mutex can be held before it's considered leaked and
|
|
5
|
+
* force-released. Overridable via MUTEX_MAX_HOLD_MS for tests.
|
|
6
|
+
*/
|
|
7
|
+
const MAX_HOLD_MS = (() => {
|
|
8
|
+
const parsed = parseInt(process.env.MUTEX_MAX_HOLD_MS ?? "", 10);
|
|
9
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : 120_000;
|
|
10
|
+
})();
|
|
11
|
+
|
|
12
|
+
export class Mutex {
|
|
13
|
+
private queue: Array<{ waiter: () => void; enqueuedAt: number; key: string }> = [];
|
|
14
|
+
private locked = false;
|
|
15
|
+
private lockedAt = 0;
|
|
16
|
+
private lockedByKey = "";
|
|
17
|
+
|
|
18
|
+
constructor(
|
|
19
|
+
public readonly name: string = "unnamed",
|
|
20
|
+
private readonly maxHoldMs: number = MAX_HOLD_MS,
|
|
21
|
+
) {}
|
|
22
|
+
|
|
23
|
+
async acquire(timeoutMs = 300_000, key = ""): Promise<() => void> {
|
|
24
|
+
// Stale detection: force-release if held beyond the hold limit
|
|
25
|
+
// (leaked lock). The chat lock uses a longer hold so a legitimate
|
|
26
|
+
// long generation (2-3 min with huge contexts) is not force-released
|
|
27
|
+
// mid-stream; the page/init locks keep the shorter safety net so a
|
|
28
|
+
// stuck browser op releases the account back to the pool faster.
|
|
29
|
+
const holdLimitMs = this.maxHoldMs;
|
|
30
|
+
if (this.locked && Date.now() - this.lockedAt > holdLimitMs) {
|
|
31
|
+
const heldFor = Date.now() - this.lockedAt;
|
|
32
|
+
logger.warn(
|
|
33
|
+
`[Mutex:${this.name}] Force-releasing stale lock | heldBy=${this.lockedByKey} | heldFor=${heldFor}ms | limit=${holdLimitMs}ms`,
|
|
34
|
+
);
|
|
35
|
+
this.locked = false;
|
|
36
|
+
this.lockedAt = 0;
|
|
37
|
+
this.lockedByKey = "";
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (!this.locked) {
|
|
41
|
+
this.locked = true;
|
|
42
|
+
this.lockedAt = Date.now();
|
|
43
|
+
this.lockedByKey = key;
|
|
44
|
+
return this.createRelease();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const enqueuedAt = Date.now();
|
|
48
|
+
const logKey = key || "anon";
|
|
49
|
+
if (logger.isLevelEnabled("debug")) {
|
|
50
|
+
logger.debug(`[Mutex:${this.name}] enqueue key=${logKey} queue=${this.queue.length + 1} heldBy=${this.lockedByKey || "unknown"} heldFor=${Date.now() - this.lockedAt}ms`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return new Promise<() => void>((resolve, reject) => {
|
|
54
|
+
const waiter = () => {
|
|
55
|
+
clearTimeout(timer);
|
|
56
|
+
this.lockedByKey = logKey;
|
|
57
|
+
this.lockedAt = Date.now();
|
|
58
|
+
resolve(this.createRelease());
|
|
59
|
+
};
|
|
60
|
+
const timer = setTimeout(() => {
|
|
61
|
+
const index = this.queue.findIndex((e) => e.waiter === waiter);
|
|
62
|
+
if (index !== -1) this.queue.splice(index, 1);
|
|
63
|
+
const heldFor = Date.now() - this.lockedAt;
|
|
64
|
+
logger.warn(`[Mutex:${this.name}] TIMEOUT key=${logKey} waited=${timeoutMs}ms heldBy=${this.lockedByKey || "unknown"} heldFor=${heldFor}ms queueLeft=${this.queue.length}`);
|
|
65
|
+
reject(new Error(`Mutex[${this.name}] acquire timeout after ${timeoutMs}ms (held by ${this.lockedByKey || "unknown"} for ${heldFor}ms)`));
|
|
66
|
+
}, timeoutMs);
|
|
67
|
+
this.queue.push({ waiter, enqueuedAt, key: logKey });
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async withLock<T>(fn: () => Promise<T> | T, timeoutMs?: number): Promise<T> {
|
|
72
|
+
const release = await this.acquire(timeoutMs);
|
|
73
|
+
try {
|
|
74
|
+
return await fn();
|
|
75
|
+
} finally {
|
|
76
|
+
release();
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
private createRelease(): () => void {
|
|
81
|
+
let released = false;
|
|
82
|
+
return () => {
|
|
83
|
+
if (released) return;
|
|
84
|
+
released = true;
|
|
85
|
+
this.release();
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
private release(): void {
|
|
90
|
+
const next = this.queue.shift();
|
|
91
|
+
if (next) {
|
|
92
|
+
const waitTime = Date.now() - next.enqueuedAt;
|
|
93
|
+
if (waitTime > 1_000 && logger.isLevelEnabled("debug")) {
|
|
94
|
+
logger.debug(`[Mutex:${this.name}] dequeued key=${next.key} waited=${waitTime}ms`);
|
|
95
|
+
}
|
|
96
|
+
next.waiter();
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
this.locked = false;
|
|
101
|
+
this.lockedAt = 0;
|
|
102
|
+
this.lockedByKey = "";
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Returns true if the mutex is not locked and has no waiting queue. */
|
|
106
|
+
isIdle(): boolean {
|
|
107
|
+
return !this.locked && this.queue.length === 0;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Returns diagnostic info about the current lock state. */
|
|
111
|
+
state(): { locked: boolean; heldBy: string; heldForMs: number; queueLength: number } {
|
|
112
|
+
return {
|
|
113
|
+
locked: this.locked,
|
|
114
|
+
heldBy: this.lockedByKey,
|
|
115
|
+
heldForMs: this.locked ? Date.now() - this.lockedAt : 0,
|
|
116
|
+
queueLength: this.queue.length,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
}
|
package/src/core/paths.ts
CHANGED
|
@@ -1,199 +1,199 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* QwenProxy - Unified Cross-Platform Storage & Path Resolution Engine
|
|
3
|
-
*
|
|
4
|
-
* Provides resilient, OS-standard persistent data paths for:
|
|
5
|
-
* - SQLite Database & WAL logs
|
|
6
|
-
* - AES-256-GCM Master Encryption Key
|
|
7
|
-
* - Chromium persistent browser profiles (cookies & session storage)
|
|
8
|
-
* - Account priority & AI client sync caches
|
|
9
|
-
*
|
|
10
|
-
* Guarantees zero data loss on package reinstall/update across npm, pnpm, bun, and yarn.
|
|
11
|
-
*/
|
|
12
|
-
|
|
13
|
-
import fs from "node:fs";
|
|
14
|
-
import path from "node:path";
|
|
15
|
-
import os from "node:os";
|
|
16
|
-
|
|
17
|
-
export interface ResolveDataDirOptions {
|
|
18
|
-
envDataDir?: string;
|
|
19
|
-
isNodeTest?: boolean;
|
|
20
|
-
localDataExists?: boolean;
|
|
21
|
-
platform?: NodeJS.Platform;
|
|
22
|
-
appData?: string;
|
|
23
|
-
homeDir?: string;
|
|
24
|
-
xdgDataHome?: string;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* Checks if the current process is running as a unit/mock test.
|
|
29
|
-
*/
|
|
30
|
-
export function isRunningUnderNodeTest(): boolean {
|
|
31
|
-
return process.argv.some(
|
|
32
|
-
(arg) =>
|
|
33
|
-
arg === "--test" ||
|
|
34
|
-
arg.includes("src/tests/") ||
|
|
35
|
-
arg.includes("src\\tests\\"),
|
|
36
|
-
);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* Computes the canonical global user data directory according to OS conventions:
|
|
41
|
-
* - Windows: %APPDATA%\qwenproxy
|
|
42
|
-
* - macOS: ~/Library/Application Support/qwenproxy
|
|
43
|
-
* - Linux: $XDG_DATA_HOME/qwenproxy or ~/.local/share/qwenproxy
|
|
44
|
-
*/
|
|
45
|
-
export function getOsGlobalDataDir(options?: {
|
|
46
|
-
platform?: NodeJS.Platform;
|
|
47
|
-
appData?: string;
|
|
48
|
-
homeDir?: string;
|
|
49
|
-
xdgDataHome?: string;
|
|
50
|
-
}): string {
|
|
51
|
-
const currentPlatform = options?.platform || process.platform;
|
|
52
|
-
const home = options?.homeDir || os.homedir();
|
|
53
|
-
|
|
54
|
-
if (currentPlatform === "win32") {
|
|
55
|
-
const winPath = path.win32 || path;
|
|
56
|
-
const appData =
|
|
57
|
-
options?.appData ||
|
|
58
|
-
process.env.APPDATA ||
|
|
59
|
-
winPath.join(home, "AppData", "Roaming");
|
|
60
|
-
return winPath.join(appData, "qwenproxy");
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
if (currentPlatform === "darwin") {
|
|
64
|
-
return path.join(home, "Library", "Application Support", "qwenproxy");
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
// Linux / BSD / POSIX
|
|
68
|
-
const xdgDataHome =
|
|
69
|
-
options?.xdgDataHome ||
|
|
70
|
-
process.env.XDG_DATA_HOME ||
|
|
71
|
-
path.join(home, ".local", "share");
|
|
72
|
-
return path.join(xdgDataHome, "qwenproxy");
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
/**
|
|
76
|
-
* Resolves the active data directory based on environment, testing state,
|
|
77
|
-
* local checkout presence, or the persistent global OS user directory.
|
|
78
|
-
*/
|
|
79
|
-
export function resolveDataDir(options?: ResolveDataDirOptions): string {
|
|
80
|
-
// 1. Explicit environment variable override takes top precedence
|
|
81
|
-
const envDir = options?.envDataDir ?? process.env.QWEN_DATA_DIR;
|
|
82
|
-
if (envDir && envDir.trim().length > 0) {
|
|
83
|
-
return path.resolve(envDir.trim());
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
// 2. Automated test isolation
|
|
87
|
-
const isTest = options?.isNodeTest ?? isRunningUnderNodeTest();
|
|
88
|
-
if (isTest) {
|
|
89
|
-
if (options?.localDataExists === false) {
|
|
90
|
-
return path.resolve("data-test");
|
|
91
|
-
}
|
|
92
|
-
if (fs.existsSync(path.resolve("data"))) {
|
|
93
|
-
return path.resolve("data");
|
|
94
|
-
}
|
|
95
|
-
return path.resolve("data-test");
|
|
96
|
-
}
|
|
97
|
-
// 3. Local repository checkout (development mode)
|
|
98
|
-
const localDir = path.resolve("data");
|
|
99
|
-
const localExists =
|
|
100
|
-
options?.localDataExists ??
|
|
101
|
-
(fs.existsSync(path.join(localDir, "db", "qwenproxy.db")) ||
|
|
102
|
-
fs.existsSync(localDir));
|
|
103
|
-
|
|
104
|
-
if (localExists) {
|
|
105
|
-
return localDir;
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
// 4. Global OS user directory (npm/pnpm/bun/yarn global mode)
|
|
109
|
-
return getOsGlobalDataDir({
|
|
110
|
-
platform: options?.platform,
|
|
111
|
-
appData: options?.appData,
|
|
112
|
-
homeDir: options?.homeDir,
|
|
113
|
-
xdgDataHome: options?.xdgDataHome,
|
|
114
|
-
});
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
/**
|
|
118
|
-
* Returns the active root data directory.
|
|
119
|
-
*/
|
|
120
|
-
export function getDataDir(): string {
|
|
121
|
-
return resolveDataDir();
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/**
|
|
125
|
-
* Directory for SQLite database and encryption key.
|
|
126
|
-
*/
|
|
127
|
-
export function getDbDir(customDataDir?: string): string {
|
|
128
|
-
return path.join(customDataDir || getDataDir(), "db");
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
/**
|
|
132
|
-
* Absolute path to the SQLite database file.
|
|
133
|
-
*/
|
|
134
|
-
export function getDbPath(customDataDir?: string): string {
|
|
135
|
-
return path.join(getDbDir(customDataDir), "qwenproxy.db");
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
/**
|
|
139
|
-
* Absolute path to the master AES-256 encryption key.
|
|
140
|
-
*/
|
|
141
|
-
export function getEncryptionKeyPath(customDataDir?: string): string {
|
|
142
|
-
return path.join(getDbDir(customDataDir), ".encryption_key");
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
/**
|
|
146
|
-
* Directory for persistent Chromium browser profiles.
|
|
147
|
-
*/
|
|
148
|
-
export function getProfilesDir(customDataDir?: string): string {
|
|
149
|
-
return path.join(customDataDir || getDataDir(), "qwen_profiles");
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
/**
|
|
153
|
-
* Path to a specific account's Chromium profile directory.
|
|
154
|
-
*/
|
|
155
|
-
export function getAccountProfilePath(accountId: string, customDataDir?: string): string {
|
|
156
|
-
return path.join(getProfilesDir(customDataDir), accountId);
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
/**
|
|
160
|
-
* Path to account priority persistence file.
|
|
161
|
-
*/
|
|
162
|
-
export function getAccountPriorityPath(customDataDir?: string): string {
|
|
163
|
-
return path.join(customDataDir || getDataDir(), "account-priority.json");
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
/**
|
|
167
|
-
* Path to AI coding clients synchronization state file.
|
|
168
|
-
*/
|
|
169
|
-
export function getSyncStatePath(customDataDir?: string): string {
|
|
170
|
-
return path.join(customDataDir || getDataDir(), "sync-state.json");
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
/**
|
|
174
|
-
* Path to user configuration .env file (either local or in global data dir).
|
|
175
|
-
*/
|
|
176
|
-
export function getEnvFilePath(customDataDir?: string): string {
|
|
177
|
-
const localEnv = path.resolve(".env");
|
|
178
|
-
if (fs.existsSync(localEnv)) {
|
|
179
|
-
return localEnv;
|
|
180
|
-
}
|
|
181
|
-
return path.join(customDataDir || getDataDir(), ".env");
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
/**
|
|
185
|
-
* Ensures all standard directories exist on disk with proper recursive creation.
|
|
186
|
-
*/
|
|
187
|
-
export function ensureDataDirs(targetDataDir?: string): void {
|
|
188
|
-
const root = targetDataDir || getDataDir();
|
|
189
|
-
const dbDir = getDbDir(root);
|
|
190
|
-
const profilesDir = getProfilesDir(root);
|
|
191
|
-
|
|
192
|
-
try {
|
|
193
|
-
if (!fs.existsSync(root)) fs.mkdirSync(root, { recursive: true });
|
|
194
|
-
if (!fs.existsSync(dbDir)) fs.mkdirSync(dbDir, { recursive: true });
|
|
195
|
-
if (!fs.existsSync(profilesDir)) fs.mkdirSync(profilesDir, { recursive: true });
|
|
196
|
-
} catch (err: any) {
|
|
197
|
-
console.error(`[Paths] Error ensuring data directories at ${root}:`, err?.message || String(err));
|
|
198
|
-
}
|
|
199
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* QwenProxy - Unified Cross-Platform Storage & Path Resolution Engine
|
|
3
|
+
*
|
|
4
|
+
* Provides resilient, OS-standard persistent data paths for:
|
|
5
|
+
* - SQLite Database & WAL logs
|
|
6
|
+
* - AES-256-GCM Master Encryption Key
|
|
7
|
+
* - Chromium persistent browser profiles (cookies & session storage)
|
|
8
|
+
* - Account priority & AI client sync caches
|
|
9
|
+
*
|
|
10
|
+
* Guarantees zero data loss on package reinstall/update across npm, pnpm, bun, and yarn.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import fs from "node:fs";
|
|
14
|
+
import path from "node:path";
|
|
15
|
+
import os from "node:os";
|
|
16
|
+
|
|
17
|
+
export interface ResolveDataDirOptions {
|
|
18
|
+
envDataDir?: string;
|
|
19
|
+
isNodeTest?: boolean;
|
|
20
|
+
localDataExists?: boolean;
|
|
21
|
+
platform?: NodeJS.Platform;
|
|
22
|
+
appData?: string;
|
|
23
|
+
homeDir?: string;
|
|
24
|
+
xdgDataHome?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Checks if the current process is running as a unit/mock test.
|
|
29
|
+
*/
|
|
30
|
+
export function isRunningUnderNodeTest(): boolean {
|
|
31
|
+
return process.argv.some(
|
|
32
|
+
(arg) =>
|
|
33
|
+
arg === "--test" ||
|
|
34
|
+
arg.includes("src/tests/") ||
|
|
35
|
+
arg.includes("src\\tests\\"),
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Computes the canonical global user data directory according to OS conventions:
|
|
41
|
+
* - Windows: %APPDATA%\qwenproxy
|
|
42
|
+
* - macOS: ~/Library/Application Support/qwenproxy
|
|
43
|
+
* - Linux: $XDG_DATA_HOME/qwenproxy or ~/.local/share/qwenproxy
|
|
44
|
+
*/
|
|
45
|
+
export function getOsGlobalDataDir(options?: {
|
|
46
|
+
platform?: NodeJS.Platform;
|
|
47
|
+
appData?: string;
|
|
48
|
+
homeDir?: string;
|
|
49
|
+
xdgDataHome?: string;
|
|
50
|
+
}): string {
|
|
51
|
+
const currentPlatform = options?.platform || process.platform;
|
|
52
|
+
const home = options?.homeDir || os.homedir();
|
|
53
|
+
|
|
54
|
+
if (currentPlatform === "win32") {
|
|
55
|
+
const winPath = path.win32 || path;
|
|
56
|
+
const appData =
|
|
57
|
+
options?.appData ||
|
|
58
|
+
process.env.APPDATA ||
|
|
59
|
+
winPath.join(home, "AppData", "Roaming");
|
|
60
|
+
return winPath.join(appData, "qwenproxy");
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
if (currentPlatform === "darwin") {
|
|
64
|
+
return path.join(home, "Library", "Application Support", "qwenproxy");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Linux / BSD / POSIX
|
|
68
|
+
const xdgDataHome =
|
|
69
|
+
options?.xdgDataHome ||
|
|
70
|
+
process.env.XDG_DATA_HOME ||
|
|
71
|
+
path.join(home, ".local", "share");
|
|
72
|
+
return path.join(xdgDataHome, "qwenproxy");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Resolves the active data directory based on environment, testing state,
|
|
77
|
+
* local checkout presence, or the persistent global OS user directory.
|
|
78
|
+
*/
|
|
79
|
+
export function resolveDataDir(options?: ResolveDataDirOptions): string {
|
|
80
|
+
// 1. Explicit environment variable override takes top precedence
|
|
81
|
+
const envDir = options?.envDataDir ?? process.env.QWEN_DATA_DIR;
|
|
82
|
+
if (envDir && envDir.trim().length > 0) {
|
|
83
|
+
return path.resolve(envDir.trim());
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// 2. Automated test isolation
|
|
87
|
+
const isTest = options?.isNodeTest ?? isRunningUnderNodeTest();
|
|
88
|
+
if (isTest) {
|
|
89
|
+
if (options?.localDataExists === false) {
|
|
90
|
+
return path.resolve("data-test");
|
|
91
|
+
}
|
|
92
|
+
if (fs.existsSync(path.resolve("data"))) {
|
|
93
|
+
return path.resolve("data");
|
|
94
|
+
}
|
|
95
|
+
return path.resolve("data-test");
|
|
96
|
+
}
|
|
97
|
+
// 3. Local repository checkout (development mode)
|
|
98
|
+
const localDir = path.resolve("data");
|
|
99
|
+
const localExists =
|
|
100
|
+
options?.localDataExists ??
|
|
101
|
+
(fs.existsSync(path.join(localDir, "db", "qwenproxy.db")) ||
|
|
102
|
+
fs.existsSync(localDir));
|
|
103
|
+
|
|
104
|
+
if (localExists) {
|
|
105
|
+
return localDir;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// 4. Global OS user directory (npm/pnpm/bun/yarn global mode)
|
|
109
|
+
return getOsGlobalDataDir({
|
|
110
|
+
platform: options?.platform,
|
|
111
|
+
appData: options?.appData,
|
|
112
|
+
homeDir: options?.homeDir,
|
|
113
|
+
xdgDataHome: options?.xdgDataHome,
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Returns the active root data directory.
|
|
119
|
+
*/
|
|
120
|
+
export function getDataDir(): string {
|
|
121
|
+
return resolveDataDir();
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Directory for SQLite database and encryption key.
|
|
126
|
+
*/
|
|
127
|
+
export function getDbDir(customDataDir?: string): string {
|
|
128
|
+
return path.join(customDataDir || getDataDir(), "db");
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Absolute path to the SQLite database file.
|
|
133
|
+
*/
|
|
134
|
+
export function getDbPath(customDataDir?: string): string {
|
|
135
|
+
return path.join(getDbDir(customDataDir), "qwenproxy.db");
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Absolute path to the master AES-256 encryption key.
|
|
140
|
+
*/
|
|
141
|
+
export function getEncryptionKeyPath(customDataDir?: string): string {
|
|
142
|
+
return path.join(getDbDir(customDataDir), ".encryption_key");
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Directory for persistent Chromium browser profiles.
|
|
147
|
+
*/
|
|
148
|
+
export function getProfilesDir(customDataDir?: string): string {
|
|
149
|
+
return path.join(customDataDir || getDataDir(), "qwen_profiles");
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Path to a specific account's Chromium profile directory.
|
|
154
|
+
*/
|
|
155
|
+
export function getAccountProfilePath(accountId: string, customDataDir?: string): string {
|
|
156
|
+
return path.join(getProfilesDir(customDataDir), accountId);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Path to account priority persistence file.
|
|
161
|
+
*/
|
|
162
|
+
export function getAccountPriorityPath(customDataDir?: string): string {
|
|
163
|
+
return path.join(customDataDir || getDataDir(), "account-priority.json");
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Path to AI coding clients synchronization state file.
|
|
168
|
+
*/
|
|
169
|
+
export function getSyncStatePath(customDataDir?: string): string {
|
|
170
|
+
return path.join(customDataDir || getDataDir(), "sync-state.json");
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Path to user configuration .env file (either local or in global data dir).
|
|
175
|
+
*/
|
|
176
|
+
export function getEnvFilePath(customDataDir?: string): string {
|
|
177
|
+
const localEnv = path.resolve(".env");
|
|
178
|
+
if (fs.existsSync(localEnv)) {
|
|
179
|
+
return localEnv;
|
|
180
|
+
}
|
|
181
|
+
return path.join(customDataDir || getDataDir(), ".env");
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Ensures all standard directories exist on disk with proper recursive creation.
|
|
186
|
+
*/
|
|
187
|
+
export function ensureDataDirs(targetDataDir?: string): void {
|
|
188
|
+
const root = targetDataDir || getDataDir();
|
|
189
|
+
const dbDir = getDbDir(root);
|
|
190
|
+
const profilesDir = getProfilesDir(root);
|
|
191
|
+
|
|
192
|
+
try {
|
|
193
|
+
if (!fs.existsSync(root)) fs.mkdirSync(root, { recursive: true });
|
|
194
|
+
if (!fs.existsSync(dbDir)) fs.mkdirSync(dbDir, { recursive: true });
|
|
195
|
+
if (!fs.existsSync(profilesDir)) fs.mkdirSync(profilesDir, { recursive: true });
|
|
196
|
+
} catch (err: any) {
|
|
197
|
+
console.error(`[Paths] Error ensuring data directories at ${root}:`, err?.message || String(err));
|
|
198
|
+
}
|
|
199
|
+
}
|