tt-help-cli-ycl 1.3.25 → 1.3.27

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.
Files changed (59) hide show
  1. package/README.md +17 -17
  2. package/cli.js +9 -9
  3. package/package.json +47 -47
  4. package/scripts/run-explore copy.bat +68 -68
  5. package/scripts/run-explore.bat +68 -68
  6. package/scripts/run-explore.ps1 +81 -81
  7. package/scripts/run-explore.sh +73 -73
  8. package/scripts/test-captcha-lib.mjs +68 -0
  9. package/scripts/test-captcha.mjs +81 -0
  10. package/scripts/test-incognito-lib.mjs +36 -0
  11. package/scripts/test-login-state.mjs +128 -0
  12. package/scripts/test-safe-click.mjs +45 -0
  13. package/src/cli/attach.js +180 -180
  14. package/src/cli/auto.js +240 -186
  15. package/src/cli/config.js +152 -152
  16. package/src/cli/explore.js +464 -296
  17. package/src/cli/info.js +88 -88
  18. package/src/cli/progress.js +111 -111
  19. package/src/cli/refresh.js +216 -216
  20. package/src/cli/scrape.js +47 -47
  21. package/src/cli/utils.js +18 -18
  22. package/src/cli/videos.js +41 -41
  23. package/src/cli/watch.js +31 -31
  24. package/src/lib/api-interceptor.js +182 -191
  25. package/src/lib/args.js +551 -551
  26. package/src/lib/browser/anti-detect.js +23 -23
  27. package/src/lib/browser/cdp.js +236 -236
  28. package/src/lib/browser/health-checker.js +54 -6
  29. package/src/lib/browser/launch.js +43 -43
  30. package/src/lib/browser/page.js +156 -156
  31. package/src/lib/constants.js +206 -206
  32. package/src/lib/delay.js +54 -54
  33. package/src/lib/explore-fetch.js +118 -118
  34. package/src/lib/fetcher.js +45 -45
  35. package/src/lib/filter.js +66 -66
  36. package/src/lib/io.js +54 -54
  37. package/src/lib/output.js +80 -80
  38. package/src/lib/page-error-detector.js +105 -71
  39. package/src/lib/parse-ssr.mjs +69 -69
  40. package/src/lib/parser.js +47 -47
  41. package/src/lib/retry.js +45 -45
  42. package/src/lib/scrape.js +89 -89
  43. package/src/lib/tiktok-scraper.mjs +194 -194
  44. package/src/lib/url.js +52 -52
  45. package/src/main.js +44 -44
  46. package/src/results/user-videos-bar.lar.lar.moeta.json +37 -0
  47. package/src/scraper/auto-core.js +203 -203
  48. package/src/scraper/core.js +211 -211
  49. package/src/scraper/explore-core.js +167 -198
  50. package/src/scraper/modules/captcha-handler.js +114 -114
  51. package/src/scraper/modules/comment-extractor.js +74 -74
  52. package/src/scraper/modules/follow-extractor.js +118 -118
  53. package/src/scraper/modules/guess-extractor.js +51 -51
  54. package/src/scraper/modules/page-helpers.js +48 -48
  55. package/src/scraper/refresh-core.js +179 -179
  56. package/src/videos/core.js +125 -101
  57. package/src/watch/data-store.js +828 -828
  58. package/src/watch/public/index.html +753 -753
  59. package/src/watch/server.js +705 -705
@@ -1,23 +1,23 @@
1
- export function getAntiDetectScript() {
2
- return () => {
3
- Object.defineProperty(navigator, 'webdriver', { get: () => false });
4
-
5
- if (!window.chrome) {
6
- window.chrome = { runtime: {} };
7
- }
8
-
9
- const originalQuery = window.navigator.permissions.query;
10
- window.navigator.permissions.query = (params) =>
11
- params.name === 'notifications'
12
- ? Promise.resolve({ state: Notification.permission })
13
- : originalQuery(params);
14
-
15
- Object.defineProperty(navigator, 'languages', {
16
- get: () => ['en-US', 'en'],
17
- });
18
-
19
- Object.defineProperty(navigator, 'plugins', {
20
- get: () => [1, 2, 3, 4, 5],
21
- });
22
- };
23
- }
1
+ export function getAntiDetectScript() {
2
+ return () => {
3
+ Object.defineProperty(navigator, 'webdriver', { get: () => false });
4
+
5
+ if (!window.chrome) {
6
+ window.chrome = { runtime: {} };
7
+ }
8
+
9
+ const originalQuery = window.navigator.permissions.query;
10
+ window.navigator.permissions.query = (params) =>
11
+ params.name === 'notifications'
12
+ ? Promise.resolve({ state: Notification.permission })
13
+ : originalQuery(params);
14
+
15
+ Object.defineProperty(navigator, 'languages', {
16
+ get: () => ['en-US', 'en'],
17
+ });
18
+
19
+ Object.defineProperty(navigator, 'plugins', {
20
+ get: () => [1, 2, 3, 4, 5],
21
+ });
22
+ };
23
+ }
@@ -1,237 +1,237 @@
1
- import { exec } from 'child_process';
2
- import { execSync } from 'child_process';
3
- import fs from 'fs';
4
- import http from 'http';
5
- import os from 'os';
6
- import path from 'path';
7
- import { chromium } from 'playwright';
8
-
9
- const DEFAULT_CDP_PORT = 9222;
10
- const DEFAULT_USER_DATA_DIR = path.join(os.homedir(), 'Library', 'Application Support', 'Microsoft Edge For Testing');
11
-
12
- function getEdgePath() {
13
- const platform = os.platform();
14
- if (platform === 'darwin') return '"Microsoft Edge"';
15
- if (platform === 'win32') return 'msedge.exe';
16
- return 'msedge';
17
- }
18
-
19
- function isEdgeRunning() {
20
- return new Promise(resolve => {
21
- const platform = os.platform();
22
- let command;
23
- if (platform === 'darwin') {
24
- command = 'ps aux | grep -q "[M]icrosoft Edge.app/Contents/MacOS/Microsoft Edge" 2>/dev/null';
25
- } else if (platform === 'win32') {
26
- command = 'tasklist /FI "IMAGENAME eq msedge.exe" 2>nul | findstr /I msedge';
27
- } else {
28
- command = 'pgrep -f msedge > /dev/null 2>&1';
29
- }
30
- exec(command, (err) => resolve(!err));
31
- });
32
- }
33
-
34
- function checkCDPPort(port) {
35
- return new Promise(resolve => {
36
- const req = http.get(`http://127.0.0.1:${port}/json`, res => {
37
- res.on('data', () => {});
38
- res.on('end', () => resolve(res.statusCode === 200));
39
- });
40
- req.on('error', () => resolve(false));
41
- req.setTimeout(3000, () => { resolve(false); req.destroy(); });
42
- });
43
- }
44
-
45
- function checkEdgeArgs() {
46
- return new Promise(resolve => {
47
- const platform = os.platform();
48
- let command;
49
- if (platform === 'darwin') {
50
- command = 'ps aux | grep "[M]icrosoft Edge" | grep -v "Helper\\|crashpad" | grep "user-data-dir"';
51
- } else if (platform === 'win32') {
52
- command = 'wmic process where "name like \\"%msedge%\\"" get commandline | findstr "user-data-dir"';
53
- } else {
54
- command = 'ps aux | grep "[m]sedge" | grep -v "Helper\\|crashpad" | grep "user-data-dir"';
55
- }
56
- exec(command, (err, stdout) => resolve(!err && stdout.trim().length > 0));
57
- });
58
- }
59
-
60
- function killEdgeProcesses(targetDir) {
61
- return new Promise(resolve => {
62
- const platform = os.platform();
63
- let command;
64
- if (platform === 'darwin') {
65
- if (targetDir) {
66
- let pids = '';
67
- try {
68
- // ps aux 输出中 --user-data-dir= 后面没有引号
69
- // 用路径精确匹配,结尾加空格或行尾避免子串误杀
70
- const escapedDir = targetDir.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
71
- pids = execSync(
72
- `ps aux | grep "[M]icrosoft Edge" | grep -v "Helper\\|crashpad" | grep -E -- '--user-data-dir=${escapedDir}($|[^A-Za-z0-9_])' | awk '{print $2}'`
73
- ).toString().trim();
74
- } catch (e) {
75
- pids = '';
76
- }
77
- if (pids) {
78
- command = `kill -9 ${pids} 2>/dev/null; rm -f ~/Library/Caches/Microsoft\\ Edge/Singleton*; true`;
79
- } else {
80
- command = 'true';
81
- }
82
- } else {
83
- command = 'killall -9 "Microsoft Edge" 2>/dev/null; rm -f ~/Library/Caches/Microsoft\\ Edge/Singleton*; true';
84
- }
85
- } else if (platform === 'win32') {
86
- if (targetDir) {
87
- try {
88
- const ps1Path = path.join(os.tmpdir(), `kill-edge-${Date.now()}.ps1`);
89
- const escapedDir = targetDir.replace(/'/g, "''");
90
- const ps1Content = `$procs = Get-CimInstance Win32_Process -Filter "Name='msedge.exe'" 2>$null; ` +
91
- `$count = 0; ` +
92
- `foreach ($p in $procs) { ` +
93
- ` if ($p.CommandLine -and $p.CommandLine -like "*${escapedDir}*") { ` +
94
- ` Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue; ` +
95
- ` $count++ ` +
96
- ` } ` +
97
- `}; ` +
98
- `Get-ChildItem "$env:LOCALAPPDATA\\Microsoft\\Edge\\Singleton*" -ErrorAction SilentlyContinue | Remove-Item -Force; ` +
99
- `Write-Output $count`;
100
- fs.writeFileSync(ps1Path, ps1Content);
101
- const result = execSync(
102
- `powershell.exe -ExecutionPolicy Bypass -File "${ps1Path}"`
103
- ).toString().trim();
104
- fs.unlinkSync(ps1Path);
105
- command = 'exit 0';
106
- } catch {
107
- command = 'taskkill /F /IM msedge.exe 2>nul || exit 0';
108
- }
109
- } else {
110
- command = 'taskkill /F /IM msedge.exe 2>nul || exit 0';
111
- }
1
+ import { exec } from 'child_process';
2
+ import { execSync } from 'child_process';
3
+ import fs from 'fs';
4
+ import http from 'http';
5
+ import os from 'os';
6
+ import path from 'path';
7
+ import { chromium } from 'playwright';
8
+
9
+ const DEFAULT_CDP_PORT = 9222;
10
+ const DEFAULT_USER_DATA_DIR = path.join(os.homedir(), 'Library', 'Application Support', 'Microsoft Edge For Testing');
11
+
12
+ function getEdgePath() {
13
+ const platform = os.platform();
14
+ if (platform === 'darwin') return '"Microsoft Edge"';
15
+ if (platform === 'win32') return 'msedge.exe';
16
+ return 'msedge';
17
+ }
18
+
19
+ function isEdgeRunning() {
20
+ return new Promise(resolve => {
21
+ const platform = os.platform();
22
+ let command;
23
+ if (platform === 'darwin') {
24
+ command = 'ps aux | grep -q "[M]icrosoft Edge.app/Contents/MacOS/Microsoft Edge" 2>/dev/null';
25
+ } else if (platform === 'win32') {
26
+ command = 'tasklist /FI "IMAGENAME eq msedge.exe" 2>nul | findstr /I msedge';
112
27
  } else {
113
- if (targetDir) {
114
- const escapedDir = targetDir.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
115
- command = `ps aux | grep msedge | grep -v Helper | grep -E -- '--user-data-dir=${escapedDir}($|[^A-Za-z0-9_])' | awk '{print $2}' | xargs -r kill -9 2>/dev/null; true`;
116
- } else {
117
- command = 'pkill -9 -f msedge 2>/dev/null; true';
118
- }
119
- }
120
- exec(command, () => resolve());
121
- });
122
- }
123
-
124
- function launchEdgeWithCDP(port, userDataDir) {
125
- return new Promise((resolve, reject) => {
126
- const platform = os.platform();
127
- const edgePath = getEdgePath();
128
- let command;
129
-
130
- const extraArgs = [
131
- `--remote-debugging-port=${port}`,
132
- `--user-data-dir="${userDataDir}"`,
133
- '--disable-blink-features=AutomationControlled',
134
- '--no-first-run',
135
- '--no-default-browser-check',
136
- '--password-store=basic',
137
- '--disable-background-mode',
138
- '--disable-component-update',
139
- '--disable-crash-reporter',
140
- '--disable-breakpad',
141
- '--disable-background-networking',
142
- '--disable-sync',
143
- ].join(' ');
144
-
145
- if (platform === 'darwin') {
146
- command = `open -a ${edgePath} --new --args ${extraArgs}`;
147
- } else if (platform === 'win32') {
148
- command = `start msedge ${extraArgs}`;
149
- } else {
150
- command = `msedge ${extraArgs} &`;
151
- }
152
-
153
- exec(command, (err) => {
154
- if (err) reject(new Error(`启动 Edge 浏览器失败: ${err.message}`));
155
- else resolve();
156
- });
157
- });
158
- }
159
-
160
- async function waitForCDP(port, timeout = 30000, interval = 1000) {
161
- const start = Date.now();
162
- while (Date.now() - start < timeout) {
163
- const ready = await checkCDPPort(port);
164
- if (ready) return true;
165
- await new Promise(r => setTimeout(r, interval));
166
- }
167
- return false;
168
- }
169
-
170
- export { killEdgeProcesses };
171
-
172
- export async function ensureBrowserReady(options = {}) {
173
- const port = options.port || DEFAULT_CDP_PORT;
174
- const userDataDir = options.userDataDir || DEFAULT_USER_DATA_DIR;
175
- const isCustom = port !== DEFAULT_CDP_PORT || !!options.userDataDir;
176
-
177
- const isReady = await checkCDPPort(port);
178
- let needLaunch = !isReady;
179
-
180
- if (!needLaunch) {
181
- if (!isCustom) {
182
- const edgeArgsValid = await checkEdgeArgs();
183
- if (!edgeArgsValid) {
184
- console.error(`Edge 已运行但启动参数不完整,正在重启端口 ${port}...`);
185
- await killEdgeProcesses(userDataDir);
186
- await new Promise(r => setTimeout(r, 3000));
187
- needLaunch = true;
188
- }
189
- }
190
- }
191
-
192
- if (needLaunch) {
193
- if (isCustom) {
194
- console.error(`CDP 端口 ${port} 未就绪,正在启动 Edge 浏览器...`);
195
- } else {
196
- const edgeRunning = await isEdgeRunning();
197
- if (edgeRunning) {
198
- console.error(`Edge 已运行但 CDP 端口 ${port} 未启用,正在重启...`);
199
- await killEdgeProcesses(userDataDir);
200
- await new Promise(r => setTimeout(r, 3000));
201
- } else {
202
- console.error(`CDP 端口 ${port} 未就绪,正在启动 Edge 浏览器...`);
203
- }
204
- }
205
- await launchEdgeWithCDP(port, userDataDir);
206
-
207
- console.error('等待浏览器启动...');
208
- const launched = await waitForCDP(port);
209
- if (!launched) {
210
- throw new Error(
211
- `等待 CDP 端口 ${port} 超时。请确认 Edge 浏览器已安装,\n` +
212
- `或手动启动: Microsoft Edge --remote-debugging-port=${port} [参见 cdp.js extraArgs]`
213
- );
214
- }
215
- console.error('浏览器启动成功');
216
- }
217
-
218
- const browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`);
219
- return browser;
220
- }
221
-
222
- export async function switchAccount(oldAccount, newAccount) {
223
- console.error(`\n[账户切换] 从端口 ${oldAccount.port} -> ${newAccount.port}`);
224
-
225
- await killEdgeProcesses(oldAccount.userDataDir);
226
- await new Promise(r => setTimeout(r, 3000));
227
-
228
- const newCdpOptions = {};
229
- newCdpOptions.port = newAccount.port;
230
- newCdpOptions.userDataDir = newAccount.userDataDir;
231
-
232
- const browser = await ensureBrowserReady(newCdpOptions);
233
-
234
- await new Promise(r => setTimeout(r, 10000));
235
-
236
- return browser;
237
- }
28
+ command = 'pgrep -f msedge > /dev/null 2>&1';
29
+ }
30
+ exec(command, (err) => resolve(!err));
31
+ });
32
+ }
33
+
34
+ function checkCDPPort(port) {
35
+ return new Promise(resolve => {
36
+ const req = http.get(`http://127.0.0.1:${port}/json`, res => {
37
+ res.on('data', () => {});
38
+ res.on('end', () => resolve(res.statusCode === 200));
39
+ });
40
+ req.on('error', () => resolve(false));
41
+ req.setTimeout(3000, () => { resolve(false); req.destroy(); });
42
+ });
43
+ }
44
+
45
+ function checkEdgeArgs() {
46
+ return new Promise(resolve => {
47
+ const platform = os.platform();
48
+ let command;
49
+ if (platform === 'darwin') {
50
+ command = 'ps aux | grep "[M]icrosoft Edge" | grep -v "Helper\\|crashpad" | grep "user-data-dir"';
51
+ } else if (platform === 'win32') {
52
+ command = 'wmic process where "name like \\"%msedge%\\"" get commandline | findstr "user-data-dir"';
53
+ } else {
54
+ command = 'ps aux | grep "[m]sedge" | grep -v "Helper\\|crashpad" | grep "user-data-dir"';
55
+ }
56
+ exec(command, (err, stdout) => resolve(!err && stdout.trim().length > 0));
57
+ });
58
+ }
59
+
60
+ function killEdgeProcesses(targetDir) {
61
+ return new Promise(resolve => {
62
+ const platform = os.platform();
63
+ let command;
64
+ if (platform === 'darwin') {
65
+ if (targetDir) {
66
+ let pids = '';
67
+ try {
68
+ // ps aux 输出中 --user-data-dir= 后面没有引号
69
+ // 用路径精确匹配,结尾加空格或行尾避免子串误杀
70
+ const escapedDir = targetDir.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
71
+ pids = execSync(
72
+ `ps aux | grep "[M]icrosoft Edge" | grep -v "Helper\\|crashpad" | grep -E -- '--user-data-dir=${escapedDir}($|[^A-Za-z0-9_])' | awk '{print $2}'`
73
+ ).toString().trim();
74
+ } catch (e) {
75
+ pids = '';
76
+ }
77
+ if (pids) {
78
+ command = `kill -9 ${pids} 2>/dev/null; rm -f ~/Library/Caches/Microsoft\\ Edge/Singleton*; true`;
79
+ } else {
80
+ command = 'true';
81
+ }
82
+ } else {
83
+ command = 'killall -9 "Microsoft Edge" 2>/dev/null; rm -f ~/Library/Caches/Microsoft\\ Edge/Singleton*; true';
84
+ }
85
+ } else if (platform === 'win32') {
86
+ if (targetDir) {
87
+ try {
88
+ const ps1Path = path.join(os.tmpdir(), `kill-edge-${Date.now()}.ps1`);
89
+ const escapedDir = targetDir.replace(/'/g, "''");
90
+ const ps1Content = `$procs = Get-CimInstance Win32_Process -Filter "Name='msedge.exe'" 2>$null; ` +
91
+ `$count = 0; ` +
92
+ `foreach ($p in $procs) { ` +
93
+ ` if ($p.CommandLine -and $p.CommandLine -like "*${escapedDir}*") { ` +
94
+ ` Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue; ` +
95
+ ` $count++ ` +
96
+ ` } ` +
97
+ `}; ` +
98
+ `Get-ChildItem "$env:LOCALAPPDATA\\Microsoft\\Edge\\Singleton*" -ErrorAction SilentlyContinue | Remove-Item -Force; ` +
99
+ `Write-Output $count`;
100
+ fs.writeFileSync(ps1Path, ps1Content);
101
+ const result = execSync(
102
+ `powershell.exe -ExecutionPolicy Bypass -File "${ps1Path}"`
103
+ ).toString().trim();
104
+ fs.unlinkSync(ps1Path);
105
+ command = 'exit 0';
106
+ } catch {
107
+ command = 'taskkill /F /IM msedge.exe 2>nul || exit 0';
108
+ }
109
+ } else {
110
+ command = 'taskkill /F /IM msedge.exe 2>nul || exit 0';
111
+ }
112
+ } else {
113
+ if (targetDir) {
114
+ const escapedDir = targetDir.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
115
+ command = `ps aux | grep msedge | grep -v Helper | grep -E -- '--user-data-dir=${escapedDir}($|[^A-Za-z0-9_])' | awk '{print $2}' | xargs -r kill -9 2>/dev/null; true`;
116
+ } else {
117
+ command = 'pkill -9 -f msedge 2>/dev/null; true';
118
+ }
119
+ }
120
+ exec(command, () => resolve());
121
+ });
122
+ }
123
+
124
+ function launchEdgeWithCDP(port, userDataDir) {
125
+ return new Promise((resolve, reject) => {
126
+ const platform = os.platform();
127
+ const edgePath = getEdgePath();
128
+ let command;
129
+
130
+ const extraArgs = [
131
+ `--remote-debugging-port=${port}`,
132
+ `--user-data-dir="${userDataDir}"`,
133
+ '--disable-blink-features=AutomationControlled',
134
+ '--no-first-run',
135
+ '--no-default-browser-check',
136
+ '--password-store=basic',
137
+ '--disable-background-mode',
138
+ '--disable-component-update',
139
+ '--disable-crash-reporter',
140
+ '--disable-breakpad',
141
+ '--disable-background-networking',
142
+ '--disable-sync',
143
+ ].join(' ');
144
+
145
+ if (platform === 'darwin') {
146
+ command = `open -a ${edgePath} --new --args ${extraArgs}`;
147
+ } else if (platform === 'win32') {
148
+ command = `start msedge ${extraArgs}`;
149
+ } else {
150
+ command = `msedge ${extraArgs} &`;
151
+ }
152
+
153
+ exec(command, (err) => {
154
+ if (err) reject(new Error(`启动 Edge 浏览器失败: ${err.message}`));
155
+ else resolve();
156
+ });
157
+ });
158
+ }
159
+
160
+ async function waitForCDP(port, timeout = 30000, interval = 1000) {
161
+ const start = Date.now();
162
+ while (Date.now() - start < timeout) {
163
+ const ready = await checkCDPPort(port);
164
+ if (ready) return true;
165
+ await new Promise(r => setTimeout(r, interval));
166
+ }
167
+ return false;
168
+ }
169
+
170
+ export { killEdgeProcesses };
171
+
172
+ export async function ensureBrowserReady(options = {}) {
173
+ const port = options.port || DEFAULT_CDP_PORT;
174
+ const userDataDir = options.userDataDir || DEFAULT_USER_DATA_DIR;
175
+ const isCustom = port !== DEFAULT_CDP_PORT || !!options.userDataDir;
176
+
177
+ const isReady = await checkCDPPort(port);
178
+ let needLaunch = !isReady;
179
+
180
+ if (!needLaunch) {
181
+ if (!isCustom) {
182
+ const edgeArgsValid = await checkEdgeArgs();
183
+ if (!edgeArgsValid) {
184
+ console.error(`Edge 已运行但启动参数不完整,正在重启端口 ${port}...`);
185
+ await killEdgeProcesses(userDataDir);
186
+ await new Promise(r => setTimeout(r, 3000));
187
+ needLaunch = true;
188
+ }
189
+ }
190
+ }
191
+
192
+ if (needLaunch) {
193
+ if (isCustom) {
194
+ console.error(`CDP 端口 ${port} 未就绪,正在启动 Edge 浏览器...`);
195
+ } else {
196
+ const edgeRunning = await isEdgeRunning();
197
+ if (edgeRunning) {
198
+ console.error(`Edge 已运行但 CDP 端口 ${port} 未启用,正在重启...`);
199
+ await killEdgeProcesses(userDataDir);
200
+ await new Promise(r => setTimeout(r, 3000));
201
+ } else {
202
+ console.error(`CDP 端口 ${port} 未就绪,正在启动 Edge 浏览器...`);
203
+ }
204
+ }
205
+ await launchEdgeWithCDP(port, userDataDir);
206
+
207
+ console.error('等待浏览器启动...');
208
+ const launched = await waitForCDP(port);
209
+ if (!launched) {
210
+ throw new Error(
211
+ `等待 CDP 端口 ${port} 超时。请确认 Edge 浏览器已安装,\n` +
212
+ `或手动启动: Microsoft Edge --remote-debugging-port=${port} [参见 cdp.js extraArgs]`
213
+ );
214
+ }
215
+ console.error('浏览器启动成功');
216
+ }
217
+
218
+ const browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`);
219
+ return browser;
220
+ }
221
+
222
+ export async function switchAccount(oldAccount, newAccount) {
223
+ console.error(`\n[账户切换] 从端口 ${oldAccount.port} -> ${newAccount.port}`);
224
+
225
+ await killEdgeProcesses(oldAccount.userDataDir);
226
+ await new Promise(r => setTimeout(r, 3000));
227
+
228
+ const newCdpOptions = {};
229
+ newCdpOptions.port = newAccount.port;
230
+ newCdpOptions.userDataDir = newAccount.userDataDir;
231
+
232
+ const browser = await ensureBrowserReady(newCdpOptions);
233
+
234
+ await new Promise(r => setTimeout(r, 10000));
235
+
236
+ return browser;
237
+ }
@@ -1,10 +1,11 @@
1
- import os from 'os';
2
- import path from 'path';
1
+ import os from "os";
2
+ import path from "path";
3
+ import { execSync } from "child_process";
3
4
 
4
5
  const TOTAL_ACCOUNTS = 10;
5
6
  const BASE_PORT = 9222;
6
7
  const MEMORY_THRESHOLD = 0.9;
7
- const ROTATE_INTERVAL_MS = 2 * 60 * 60 * 1000;
8
+ const ROTATE_INTERVAL_MS = 1 * 60 * 60 * 1000; // 1小时
8
9
 
9
10
  class HealthChecker {
10
11
  constructor() {
@@ -16,7 +17,10 @@ class HealthChecker {
16
17
  port,
17
18
  profile,
18
19
  userDataDir: path.join(
19
- os.homedir(), 'Library', 'Application Support', `Microsoft Edge For Testing_${profile}`
20
+ os.homedir(),
21
+ "Library",
22
+ "Application Support",
23
+ `Microsoft Edge For Testing_${profile}`,
20
24
  ),
21
25
  });
22
26
  }
@@ -30,11 +34,47 @@ class HealthChecker {
30
34
 
31
35
  getNextAccount() {
32
36
  this.currentIndex = (this.currentIndex + 1) % TOTAL_ACCOUNTS;
37
+ this.startTime = Date.now(); // 切换后重置运行时间
33
38
  return this.accounts[this.currentIndex];
34
39
  }
35
40
 
36
41
  check() {
37
- const memUsage = (1 - os.freemem() / os.totalmem());
42
+ let memUsage;
43
+ const platform = os.platform();
44
+
45
+ if (platform === "darwin") {
46
+ // macOS 上 os.freemem() 不包含 inactive 内存,导致虚高
47
+ // 使用 vm_stat 获取准确数据
48
+ try {
49
+ const vmStat = execSync("vm_stat", { encoding: "utf-8" });
50
+ const parsePages = (line) => {
51
+ const match = line.match(/Pages (\w+(?:\s+\w+)*):\s+(\d+)/);
52
+ return match ? parseInt(match[2], 10) : 0;
53
+ };
54
+ const lines = vmStat.trim().split("\n");
55
+ const pageSize = 16384;
56
+ const active = parsePages(
57
+ lines.find((l) => l.includes("active")) || "",
58
+ );
59
+ const wired = parsePages(
60
+ lines.find((l) => l.includes("wired down")) || "",
61
+ );
62
+ const compressor = parsePages(
63
+ lines.find((l) => l.includes("occupied by compressor")) || "",
64
+ );
65
+ const total = os.totalmem();
66
+ const used = (active + wired + compressor) * pageSize;
67
+ memUsage = used / total;
68
+ } catch {
69
+ // 降级:使用估算
70
+ const total = os.totalmem();
71
+ const free = os.freemem();
72
+ const inactiveEstimate = total * 0.35;
73
+ memUsage = 1 - (free + inactiveEstimate) / total;
74
+ }
75
+ } else {
76
+ memUsage = 1 - os.freemem() / os.totalmem();
77
+ }
38
78
  const memPercent = (memUsage * 100).toFixed(1);
39
79
 
40
80
  if (memUsage >= MEMORY_THRESHOLD) {
@@ -47,7 +87,15 @@ class HealthChecker {
47
87
  return { shouldSwitch: true, reason: `运行 ${mins} 分钟` };
48
88
  }
49
89
 
50
- return { shouldSwitch: false };
90
+ // 计算预计切换时间
91
+ const remainingMs = ROTATE_INTERVAL_MS - elapsed;
92
+ const remainingMins = Math.round(remainingMs / 60000);
93
+ const memHeadroom = ((MEMORY_THRESHOLD - memUsage) * 100).toFixed(1);
94
+
95
+ return {
96
+ shouldSwitch: false,
97
+ info: `内存 ${memPercent}% (余量 ${memHeadroom}%) | 定时轮换 ${remainingMins} 分钟后`,
98
+ };
51
99
  }
52
100
  }
53
101