cursor-switch 1.0.0
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 +21 -0
- package/README.md +161 -0
- package/SECURITY.md +38 -0
- package/bin/cswitch.js +35 -0
- package/dist/cli.d.ts +6 -0
- package/dist/cli.js +850 -0
- package/dist/core/account-store.d.ts +25 -0
- package/dist/core/account-store.js +182 -0
- package/dist/core/cdp-engine.d.ts +75 -0
- package/dist/core/cdp-engine.js +320 -0
- package/dist/core/config-store.d.ts +38 -0
- package/dist/core/config-store.js +100 -0
- package/dist/core/cursor-paths.d.ts +22 -0
- package/dist/core/cursor-paths.js +287 -0
- package/dist/core/dashboard-launcher.d.ts +34 -0
- package/dist/core/dashboard-launcher.js +210 -0
- package/dist/core/fingerprint.d.ts +7 -0
- package/dist/core/fingerprint.js +34 -0
- package/dist/core/oauth-receiver.d.ts +31 -0
- package/dist/core/oauth-receiver.js +849 -0
- package/dist/core/official-api.d.ts +29 -0
- package/dist/core/official-api.js +205 -0
- package/dist/core/outlook-launcher.d.ts +54 -0
- package/dist/core/outlook-launcher.js +671 -0
- package/dist/core/process-manager.d.ts +25 -0
- package/dist/core/process-manager.js +133 -0
- package/dist/core/pure-login-service.d.ts +67 -0
- package/dist/core/pure-login-service.js +550 -0
- package/dist/core/refund-client.d.ts +102 -0
- package/dist/core/refund-client.js +221 -0
- package/dist/core/refund-service.d.ts +39 -0
- package/dist/core/refund-service.js +384 -0
- package/dist/core/sqlite-bridge.d.ts +23 -0
- package/dist/core/sqlite-bridge.js +207 -0
- package/dist/core/storage-bridge.d.ts +18 -0
- package/dist/core/storage-bridge.js +99 -0
- package/dist/core/token-parser.d.ts +35 -0
- package/dist/core/token-parser.js +106 -0
- package/dist/core/update-checker.d.ts +62 -0
- package/dist/core/update-checker.js +231 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +17 -0
- package/dist/menu.d.ts +12 -0
- package/dist/menu.js +2201 -0
- package/dist/types.d.ts +60 -0
- package/dist/types.js +5 -0
- package/dist/utils/browser-utils.d.ts +31 -0
- package/dist/utils/browser-utils.js +283 -0
- package/dist/utils/clipboard.d.ts +5 -0
- package/dist/utils/clipboard.js +48 -0
- package/dist/utils/live-menu.d.ts +26 -0
- package/dist/utils/live-menu.js +169 -0
- package/dist/utils/plan-formatter.d.ts +30 -0
- package/dist/utils/plan-formatter.js +153 -0
- package/dist/utils/prompt-utils.d.ts +40 -0
- package/dist/utils/prompt-utils.js +105 -0
- package/dist/utils/security.d.ts +6 -0
- package/dist/utils/security.js +27 -0
- package/dist/utils/table-renderer.d.ts +7 -0
- package/dist/utils/table-renderer.js +88 -0
- package/dist/utils/time-formatter.d.ts +13 -0
- package/dist/utils/time-formatter.js +83 -0
- package/package.json +53 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 本地账号安全持久化仓库 (100% Local-First)
|
|
3
|
+
* 支持 ~/.cursor-switch/accounts.json 独立管理,且能无缝兼容同步 AoZai 数据
|
|
4
|
+
*/
|
|
5
|
+
import type { AccountInfo } from '../types.js';
|
|
6
|
+
export declare class AccountStore {
|
|
7
|
+
private dataDir;
|
|
8
|
+
private filePath;
|
|
9
|
+
constructor(customPath?: string);
|
|
10
|
+
getDataDir(): string;
|
|
11
|
+
getFilePath(): string;
|
|
12
|
+
private ensureDir;
|
|
13
|
+
/**
|
|
14
|
+
* 自动探测并从外部备用目录导入历史数据
|
|
15
|
+
*/
|
|
16
|
+
autoDetectExternal(): string | null;
|
|
17
|
+
loadAll(): AccountInfo[];
|
|
18
|
+
saveAll(accounts: AccountInfo[]): void;
|
|
19
|
+
getByEmail(email: string): AccountInfo | undefined;
|
|
20
|
+
getByIndexOrEmail(identifier: string | number): AccountInfo | undefined;
|
|
21
|
+
getCurrentAccount(): AccountInfo | undefined;
|
|
22
|
+
addOrUpdate(account: AccountInfo): void;
|
|
23
|
+
remove(email: string): boolean;
|
|
24
|
+
markCurrent(email: string): void;
|
|
25
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 本地账号安全持久化仓库 (100% Local-First)
|
|
3
|
+
* 支持 ~/.cursor-switch/accounts.json 独立管理,且能无缝兼容同步 AoZai 数据
|
|
4
|
+
*/
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import { generateMachineIds } from './fingerprint.js';
|
|
9
|
+
export class AccountStore {
|
|
10
|
+
dataDir;
|
|
11
|
+
filePath;
|
|
12
|
+
constructor(customPath) {
|
|
13
|
+
if (customPath) {
|
|
14
|
+
this.filePath = customPath;
|
|
15
|
+
this.dataDir = path.dirname(customPath);
|
|
16
|
+
}
|
|
17
|
+
else {
|
|
18
|
+
this.dataDir = path.join(os.homedir(), '.cursor-switch');
|
|
19
|
+
this.filePath = path.join(this.dataDir, 'accounts.json');
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
getDataDir() {
|
|
23
|
+
return this.dataDir;
|
|
24
|
+
}
|
|
25
|
+
getFilePath() {
|
|
26
|
+
return this.filePath;
|
|
27
|
+
}
|
|
28
|
+
ensureDir() {
|
|
29
|
+
if (!fs.existsSync(this.dataDir)) {
|
|
30
|
+
fs.mkdirSync(this.dataDir, { recursive: true });
|
|
31
|
+
// 在 Unix/macOS 系统上设置严格的 700 权限(仅本人可读写)
|
|
32
|
+
if (process.platform !== 'win32') {
|
|
33
|
+
try {
|
|
34
|
+
fs.chmodSync(this.dataDir, 0o700);
|
|
35
|
+
}
|
|
36
|
+
catch { }
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* 自动探测并从外部备用目录导入历史数据
|
|
42
|
+
*/
|
|
43
|
+
autoDetectExternal() {
|
|
44
|
+
const candidates = [
|
|
45
|
+
path.join(os.homedir(), '.cursor_data', 'account_cache.json'),
|
|
46
|
+
path.join(os.homedir(), '.cursor-switch', 'backup', 'accounts.json'),
|
|
47
|
+
];
|
|
48
|
+
for (const cand of candidates) {
|
|
49
|
+
if (fs.existsSync(cand)) {
|
|
50
|
+
return cand;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
loadAll() {
|
|
56
|
+
this.ensureDir();
|
|
57
|
+
// 如果自己的 accounts.json 不存在,但检测到了 AoZai 的 account_cache.json,自动同步初始化
|
|
58
|
+
if (!fs.existsSync(this.filePath)) {
|
|
59
|
+
const ext = this.autoDetectExternal();
|
|
60
|
+
if (ext) {
|
|
61
|
+
try {
|
|
62
|
+
const content = fs.readFileSync(ext, 'utf8');
|
|
63
|
+
const extAccounts = JSON.parse(content);
|
|
64
|
+
this.saveAll(extAccounts);
|
|
65
|
+
return extAccounts;
|
|
66
|
+
}
|
|
67
|
+
catch { }
|
|
68
|
+
}
|
|
69
|
+
return [];
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
const content = fs.readFileSync(this.filePath, 'utf8');
|
|
73
|
+
const accounts = JSON.parse(content);
|
|
74
|
+
// 确保每个账号都有绑定的专属机器指纹
|
|
75
|
+
let modified = false;
|
|
76
|
+
for (const acc of accounts) {
|
|
77
|
+
if (!acc.machine_ids || !acc.machine_ids['telemetry.devDeviceId']) {
|
|
78
|
+
acc.machine_ids = generateMachineIds();
|
|
79
|
+
modified = true;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
if (modified) {
|
|
83
|
+
this.saveAll(accounts);
|
|
84
|
+
}
|
|
85
|
+
return accounts;
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return [];
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
saveAll(accounts) {
|
|
92
|
+
this.ensureDir();
|
|
93
|
+
const tmp = `${this.filePath}.tmp_${Date.now()}`;
|
|
94
|
+
const jsonStr = JSON.stringify(accounts, null, 2);
|
|
95
|
+
fs.writeFileSync(tmp, jsonStr, 'utf8');
|
|
96
|
+
fs.renameSync(tmp, this.filePath);
|
|
97
|
+
// 强化文件权限 600(非 Windows 平台)
|
|
98
|
+
if (process.platform !== 'win32') {
|
|
99
|
+
try {
|
|
100
|
+
fs.chmodSync(this.filePath, 0o600);
|
|
101
|
+
}
|
|
102
|
+
catch { }
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
getByEmail(email) {
|
|
106
|
+
const list = this.loadAll();
|
|
107
|
+
const query = email.trim().toLowerCase();
|
|
108
|
+
return list.find((a) => a.email.toLowerCase() === query);
|
|
109
|
+
}
|
|
110
|
+
getByIndexOrEmail(identifier) {
|
|
111
|
+
const list = this.loadAll();
|
|
112
|
+
if (typeof identifier === 'number' || /^\d+$/.test(String(identifier).trim())) {
|
|
113
|
+
const idx = Number(identifier) - 1; // 1-indexed to 0-indexed
|
|
114
|
+
return list[idx];
|
|
115
|
+
}
|
|
116
|
+
const query = String(identifier).trim().toLowerCase();
|
|
117
|
+
return list.find((a) => a.email.toLowerCase().includes(query) || (a.username && a.username.toLowerCase().includes(query)));
|
|
118
|
+
}
|
|
119
|
+
getCurrentAccount() {
|
|
120
|
+
const list = this.loadAll();
|
|
121
|
+
return list.find((a) => a.is_current);
|
|
122
|
+
}
|
|
123
|
+
addOrUpdate(account) {
|
|
124
|
+
const list = this.loadAll();
|
|
125
|
+
const idx = list.findIndex((a) => a.email.toLowerCase() === account.email.toLowerCase());
|
|
126
|
+
// 自动补齐专属硬件机器指纹
|
|
127
|
+
if (!account.machine_ids || !account.machine_ids['telemetry.devDeviceId']) {
|
|
128
|
+
account.machine_ids = generateMachineIds();
|
|
129
|
+
}
|
|
130
|
+
if (idx >= 0) {
|
|
131
|
+
// 保留原有机器码与创建时间
|
|
132
|
+
const existing = list[idx];
|
|
133
|
+
// 🛡️ 防御性订阅计划合并:绝不允许失败/离线时的 free 冲掉原有的团队商业版、Pro 等高价值订阅
|
|
134
|
+
let mergedSubscription = account.subscription_type;
|
|
135
|
+
const isExistingPaid = existing.subscription_type &&
|
|
136
|
+
existing.subscription_type !== 'free' &&
|
|
137
|
+
existing.subscription_type !== 'token_expired';
|
|
138
|
+
if (!mergedSubscription || mergedSubscription === 'free') {
|
|
139
|
+
if (isExistingPaid) {
|
|
140
|
+
mergedSubscription = existing.subscription_type;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
// 🛡️ 防御性计费周期合并:若新传入的为空,保留原有记录的到期时间与配额数据
|
|
144
|
+
const mergedUsage = account.current_period_usage || existing.current_period_usage;
|
|
145
|
+
list[idx] = {
|
|
146
|
+
...existing,
|
|
147
|
+
...account,
|
|
148
|
+
subscription_type: mergedSubscription || existing.subscription_type || 'free',
|
|
149
|
+
current_period_usage: mergedUsage,
|
|
150
|
+
machine_ids: account.machine_ids || existing.machine_ids,
|
|
151
|
+
created_at: existing.created_at || account.created_at,
|
|
152
|
+
username: account.username || existing.username,
|
|
153
|
+
workos_cursor_session_token: account.workos_cursor_session_token || existing.workos_cursor_session_token,
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
else {
|
|
157
|
+
if (!account.created_at) {
|
|
158
|
+
account.created_at = new Date().toISOString().replace('T', ' ').slice(0, 19);
|
|
159
|
+
}
|
|
160
|
+
list.push(account);
|
|
161
|
+
}
|
|
162
|
+
this.saveAll(list);
|
|
163
|
+
}
|
|
164
|
+
remove(email) {
|
|
165
|
+
const list = this.loadAll();
|
|
166
|
+
const beforeLen = list.length;
|
|
167
|
+
const filtered = list.filter((a) => a.email.toLowerCase() !== email.trim().toLowerCase());
|
|
168
|
+
if (filtered.length !== beforeLen) {
|
|
169
|
+
this.saveAll(filtered);
|
|
170
|
+
return true;
|
|
171
|
+
}
|
|
172
|
+
return false;
|
|
173
|
+
}
|
|
174
|
+
markCurrent(email) {
|
|
175
|
+
const list = this.loadAll();
|
|
176
|
+
const target = email.trim().toLowerCase();
|
|
177
|
+
for (const a of list) {
|
|
178
|
+
a.is_current = a.email.toLowerCase() === target;
|
|
179
|
+
}
|
|
180
|
+
this.saveAll(list);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 原生零依赖 Chrome DevTools Protocol (CDP) 控制引擎
|
|
3
|
+
* 基于 Node.js 内置 HTTP 与原生 WebSocket 构建,不依赖任何第三方包
|
|
4
|
+
* 兼容 Windows / macOS / Linux / WSL 各类操作系统
|
|
5
|
+
*/
|
|
6
|
+
export interface CdpTarget {
|
|
7
|
+
id: string;
|
|
8
|
+
type: string;
|
|
9
|
+
title: string;
|
|
10
|
+
url: string;
|
|
11
|
+
webSocketDebuggerUrl?: string;
|
|
12
|
+
}
|
|
13
|
+
export declare class CdpEngine {
|
|
14
|
+
private ws;
|
|
15
|
+
private messageId;
|
|
16
|
+
private responseHandlers;
|
|
17
|
+
private targetWsUrl;
|
|
18
|
+
constructor(targetWsUrl: string);
|
|
19
|
+
/**
|
|
20
|
+
* 动态分配一个本地可用随机空闲端口
|
|
21
|
+
*/
|
|
22
|
+
static getFreePort(): Promise<number>;
|
|
23
|
+
/**
|
|
24
|
+
* 等待并发现指定 CDP 端口上的有效页面 Target
|
|
25
|
+
*/
|
|
26
|
+
static waitForPageTarget(port: number, timeoutMs?: number): Promise<CdpTarget | null>;
|
|
27
|
+
/**
|
|
28
|
+
* 原生 HTTP GET 获取 JSON 数据
|
|
29
|
+
*/
|
|
30
|
+
private static fetchJson;
|
|
31
|
+
/**
|
|
32
|
+
* 连接到页面 WebSocket CDP 端口
|
|
33
|
+
*/
|
|
34
|
+
connect(timeoutMs?: number): Promise<void>;
|
|
35
|
+
/**
|
|
36
|
+
* 发送标准 CDP JSON-RPC 消息并等待响应
|
|
37
|
+
*/
|
|
38
|
+
send<T = any>(method: string, params?: Record<string, any>): Promise<T>;
|
|
39
|
+
/**
|
|
40
|
+
* 在页面全局执行 JavaScript 表达式并返回值
|
|
41
|
+
*/
|
|
42
|
+
evaluate<T = any>(expression: string): Promise<T | undefined>;
|
|
43
|
+
/**
|
|
44
|
+
* 激活并将浏览器窗口/标签页置顶到屏幕最前 (Bring to front)
|
|
45
|
+
*/
|
|
46
|
+
bringToFront(): Promise<void>;
|
|
47
|
+
/**
|
|
48
|
+
* 导航到指定 URL
|
|
49
|
+
*/
|
|
50
|
+
navigate(url: string): Promise<void>;
|
|
51
|
+
/**
|
|
52
|
+
* 获取当前页面 URL
|
|
53
|
+
*/
|
|
54
|
+
getCurrentUrl(): Promise<string>;
|
|
55
|
+
/**
|
|
56
|
+
* 获取页面 document.body.innerText
|
|
57
|
+
*/
|
|
58
|
+
getBodyText(): Promise<string>;
|
|
59
|
+
/**
|
|
60
|
+
* 触发输入框聚焦并填入文本 (兼具 CDP 原生键入流与 React/Vue/Knockout 状态同步,100% 兼容各类复杂前端)
|
|
61
|
+
*/
|
|
62
|
+
fillInput(selector: string, value: string): Promise<boolean>;
|
|
63
|
+
/**
|
|
64
|
+
* 点击匹配的元素 (结合 CDP 原生鼠标事件与 DOM 派发)
|
|
65
|
+
*/
|
|
66
|
+
click(selector: string): Promise<boolean>;
|
|
67
|
+
/**
|
|
68
|
+
* 使用原生 CDP 鼠标事件真实点击指定屏幕坐标 (具有真实 isTrusted 属性,兼容各类复杂前端框架与自定义组件)
|
|
69
|
+
*/
|
|
70
|
+
clickPoint(x: number, y: number): Promise<void>;
|
|
71
|
+
/**
|
|
72
|
+
* 优雅断开 CDP 连接,保持被托管的浏览器进程继续运行
|
|
73
|
+
*/
|
|
74
|
+
disconnect(): void;
|
|
75
|
+
}
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 原生零依赖 Chrome DevTools Protocol (CDP) 控制引擎
|
|
3
|
+
* 基于 Node.js 内置 HTTP 与原生 WebSocket 构建,不依赖任何第三方包
|
|
4
|
+
* 兼容 Windows / macOS / Linux / WSL 各类操作系统
|
|
5
|
+
*/
|
|
6
|
+
import http from 'node:http';
|
|
7
|
+
import net from 'node:net';
|
|
8
|
+
export class CdpEngine {
|
|
9
|
+
ws = null;
|
|
10
|
+
messageId = 1;
|
|
11
|
+
responseHandlers = new Map();
|
|
12
|
+
targetWsUrl;
|
|
13
|
+
constructor(targetWsUrl) {
|
|
14
|
+
this.targetWsUrl = targetWsUrl;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* 动态分配一个本地可用随机空闲端口
|
|
18
|
+
*/
|
|
19
|
+
static getFreePort() {
|
|
20
|
+
return new Promise((resolve, reject) => {
|
|
21
|
+
const server = net.createServer();
|
|
22
|
+
server.listen(0, '127.0.0.1', () => {
|
|
23
|
+
const address = server.address();
|
|
24
|
+
if (address && typeof address === 'object') {
|
|
25
|
+
const port = address.port;
|
|
26
|
+
server.close(() => resolve(port));
|
|
27
|
+
}
|
|
28
|
+
else {
|
|
29
|
+
server.close(() => reject(new Error('无法分配空闲端口')));
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
server.on('error', reject);
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* 等待并发现指定 CDP 端口上的有效页面 Target
|
|
37
|
+
*/
|
|
38
|
+
static async waitForPageTarget(port, timeoutMs = 15000) {
|
|
39
|
+
const deadline = Date.now() + timeoutMs;
|
|
40
|
+
while (Date.now() < deadline) {
|
|
41
|
+
try {
|
|
42
|
+
const targets = await this.fetchJson(`http://127.0.0.1:${port}/json/list`);
|
|
43
|
+
if (Array.isArray(targets) && targets.length > 0) {
|
|
44
|
+
// 优先寻找普通的 page 页面(排除扩展后台页 background_page 和浏览器内部 UI)
|
|
45
|
+
const page = targets.find((t) => t.type === 'page' &&
|
|
46
|
+
t.webSocketDebuggerUrl &&
|
|
47
|
+
!t.url.startsWith('chrome-extension://') &&
|
|
48
|
+
!t.url.startsWith('edge-extension://'));
|
|
49
|
+
if (page)
|
|
50
|
+
return page;
|
|
51
|
+
// 兜底任一 page 类型的 target
|
|
52
|
+
const anyPage = targets.find((t) => t.type === 'page' && t.webSocketDebuggerUrl);
|
|
53
|
+
if (anyPage)
|
|
54
|
+
return anyPage;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
// 浏览器尚未完全启动或端口未就绪,继续重试
|
|
59
|
+
}
|
|
60
|
+
await new Promise((r) => setTimeout(r, 250));
|
|
61
|
+
}
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* 原生 HTTP GET 获取 JSON 数据
|
|
66
|
+
*/
|
|
67
|
+
static fetchJson(url) {
|
|
68
|
+
return new Promise((resolve, reject) => {
|
|
69
|
+
http
|
|
70
|
+
.get(url, (res) => {
|
|
71
|
+
let data = '';
|
|
72
|
+
res.on('data', (chunk) => (data += chunk));
|
|
73
|
+
res.on('end', () => {
|
|
74
|
+
try {
|
|
75
|
+
resolve(JSON.parse(data));
|
|
76
|
+
}
|
|
77
|
+
catch (err) {
|
|
78
|
+
reject(err);
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
})
|
|
82
|
+
.on('error', reject);
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* 连接到页面 WebSocket CDP 端口
|
|
87
|
+
*/
|
|
88
|
+
async connect(timeoutMs = 10000) {
|
|
89
|
+
const WebSocketImpl = globalThis.WebSocket;
|
|
90
|
+
if (!WebSocketImpl) {
|
|
91
|
+
throw new Error('当前 Node.js 运行环境缺少原生 WebSocket 支持 (建议 Node >= 20)');
|
|
92
|
+
}
|
|
93
|
+
return new Promise((resolve, reject) => {
|
|
94
|
+
const timer = setTimeout(() => {
|
|
95
|
+
reject(new Error(`连接 CDP WebSocket 超时: ${this.targetWsUrl}`));
|
|
96
|
+
}, timeoutMs);
|
|
97
|
+
try {
|
|
98
|
+
this.ws = new WebSocketImpl(this.targetWsUrl);
|
|
99
|
+
this.ws.onopen = () => {
|
|
100
|
+
clearTimeout(timer);
|
|
101
|
+
resolve();
|
|
102
|
+
};
|
|
103
|
+
this.ws.onerror = (err) => {
|
|
104
|
+
clearTimeout(timer);
|
|
105
|
+
reject(err);
|
|
106
|
+
};
|
|
107
|
+
this.ws.onmessage = (event) => {
|
|
108
|
+
try {
|
|
109
|
+
const raw = typeof event.data === 'string' ? event.data : event.data.toString();
|
|
110
|
+
const msg = JSON.parse(raw);
|
|
111
|
+
if (msg.id && this.responseHandlers.has(msg.id)) {
|
|
112
|
+
const handler = this.responseHandlers.get(msg.id);
|
|
113
|
+
this.responseHandlers.delete(msg.id);
|
|
114
|
+
if (msg.error) {
|
|
115
|
+
handler(null, msg.error);
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
handler(msg.result);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
catch { }
|
|
123
|
+
};
|
|
124
|
+
this.ws.onclose = () => {
|
|
125
|
+
// 清空等待响应的处理器
|
|
126
|
+
for (const handler of this.responseHandlers.values()) {
|
|
127
|
+
handler(null, new Error('CDP 连接已关闭'));
|
|
128
|
+
}
|
|
129
|
+
this.responseHandlers.clear();
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
catch (e) {
|
|
133
|
+
clearTimeout(timer);
|
|
134
|
+
reject(e);
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* 发送标准 CDP JSON-RPC 消息并等待响应
|
|
140
|
+
*/
|
|
141
|
+
send(method, params = {}) {
|
|
142
|
+
if (!this.ws || this.ws.readyState !== 1) {
|
|
143
|
+
return Promise.reject(new Error('CDP WebSocket 未处于连接状态'));
|
|
144
|
+
}
|
|
145
|
+
const id = this.messageId++;
|
|
146
|
+
return new Promise((resolve, reject) => {
|
|
147
|
+
this.responseHandlers.set(id, (result, error) => {
|
|
148
|
+
if (error) {
|
|
149
|
+
reject(new Error(error.message || JSON.stringify(error)));
|
|
150
|
+
}
|
|
151
|
+
else {
|
|
152
|
+
resolve(result);
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
this.ws.send(JSON.stringify({ id, method, params }));
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* 在页面全局执行 JavaScript 表达式并返回值
|
|
160
|
+
*/
|
|
161
|
+
async evaluate(expression) {
|
|
162
|
+
try {
|
|
163
|
+
const res = await this.send('Runtime.evaluate', {
|
|
164
|
+
expression,
|
|
165
|
+
returnByValue: true,
|
|
166
|
+
awaitPromise: true,
|
|
167
|
+
});
|
|
168
|
+
return res?.result?.value;
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
return undefined;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* 激活并将浏览器窗口/标签页置顶到屏幕最前 (Bring to front)
|
|
176
|
+
*/
|
|
177
|
+
async bringToFront() {
|
|
178
|
+
try {
|
|
179
|
+
await this.send('Page.bringToFront');
|
|
180
|
+
}
|
|
181
|
+
catch { }
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* 导航到指定 URL
|
|
185
|
+
*/
|
|
186
|
+
async navigate(url) {
|
|
187
|
+
await this.send('Page.navigate', { url });
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* 获取当前页面 URL
|
|
191
|
+
*/
|
|
192
|
+
async getCurrentUrl() {
|
|
193
|
+
const url = await this.evaluate('window.location.href');
|
|
194
|
+
return url || '';
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* 获取页面 document.body.innerText
|
|
198
|
+
*/
|
|
199
|
+
async getBodyText() {
|
|
200
|
+
const text = await this.evaluate('document.body ? document.body.innerText : ""');
|
|
201
|
+
return text || '';
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* 触发输入框聚焦并填入文本 (兼具 CDP 原生键入流与 React/Vue/Knockout 状态同步,100% 兼容各类复杂前端)
|
|
205
|
+
*/
|
|
206
|
+
async fillInput(selector, value) {
|
|
207
|
+
// 1. 滚动居中并聚焦目标输入框 (兼容 position: fixed 弹窗)
|
|
208
|
+
const focused = await this.evaluate(`(() => {
|
|
209
|
+
const el = document.querySelector(${JSON.stringify(selector)});
|
|
210
|
+
if (!el || el.disabled) return false;
|
|
211
|
+
const r = el.getBoundingClientRect();
|
|
212
|
+
const style = window.getComputedStyle(el);
|
|
213
|
+
if (style.display === 'none' || style.visibility === 'hidden') return false;
|
|
214
|
+
if (r.width === 0 && r.height === 0 && el.getClientRects().length === 0) return false;
|
|
215
|
+
el.scrollIntoView({ block: 'center' });
|
|
216
|
+
el.focus();
|
|
217
|
+
if (typeof el.select === 'function') {
|
|
218
|
+
el.select();
|
|
219
|
+
}
|
|
220
|
+
return true;
|
|
221
|
+
})()`);
|
|
222
|
+
if (!focused)
|
|
223
|
+
return false;
|
|
224
|
+
// 2. 优先通过 CDP Input.insertText 真实键入,生成具有真实 isTrusted 与原生 Keyboard/Input 流
|
|
225
|
+
try {
|
|
226
|
+
await this.send('Input.insertText', { text: value });
|
|
227
|
+
}
|
|
228
|
+
catch { }
|
|
229
|
+
// 3. 辅助原生 Prototype Setter 与 input/change 事件兜底
|
|
230
|
+
await this.evaluate(`(() => {
|
|
231
|
+
const el = document.querySelector(${JSON.stringify(selector)});
|
|
232
|
+
if (!el) return false;
|
|
233
|
+
if (el.value !== ${JSON.stringify(value)}) {
|
|
234
|
+
try {
|
|
235
|
+
const nativeSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set;
|
|
236
|
+
if (nativeSetter) {
|
|
237
|
+
nativeSetter.call(el, ${JSON.stringify(value)});
|
|
238
|
+
} else {
|
|
239
|
+
el.value = ${JSON.stringify(value)};
|
|
240
|
+
}
|
|
241
|
+
} catch {
|
|
242
|
+
el.value = ${JSON.stringify(value)};
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
el.dispatchEvent(new Event('input', { bubbles: true }));
|
|
246
|
+
el.dispatchEvent(new Event('change', { bubbles: true }));
|
|
247
|
+
return true;
|
|
248
|
+
})()`);
|
|
249
|
+
return true;
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* 点击匹配的元素 (结合 CDP 原生鼠标事件与 DOM 派发)
|
|
253
|
+
*/
|
|
254
|
+
async click(selector) {
|
|
255
|
+
// 1. 获取目标元素当前屏幕绝对坐标 (支持 position: fixed Lightbox)
|
|
256
|
+
const point = await this.evaluate(`(() => {
|
|
257
|
+
const el = document.querySelector(${JSON.stringify(selector)});
|
|
258
|
+
if (!el || el.disabled) return null;
|
|
259
|
+
const style = window.getComputedStyle(el);
|
|
260
|
+
if (style.display === 'none' || style.visibility === 'hidden') return null;
|
|
261
|
+
el.scrollIntoView({ block: 'center' });
|
|
262
|
+
const r = el.getBoundingClientRect();
|
|
263
|
+
if (r.width <= 0 || r.height <= 0) return null;
|
|
264
|
+
return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
|
|
265
|
+
})()`);
|
|
266
|
+
if (point && typeof point.x === 'number' && typeof point.y === 'number') {
|
|
267
|
+
await this.clickPoint(point.x, point.y);
|
|
268
|
+
}
|
|
269
|
+
// 2. 页面内 DOM click 派发兜底
|
|
270
|
+
const clicked = await this.evaluate(`(() => {
|
|
271
|
+
const el = document.querySelector(${JSON.stringify(selector)});
|
|
272
|
+
if (!el || el.disabled) return false;
|
|
273
|
+
const style = window.getComputedStyle(el);
|
|
274
|
+
if (style.display === 'none' || style.visibility === 'hidden') return false;
|
|
275
|
+
el.click();
|
|
276
|
+
return true;
|
|
277
|
+
})()`);
|
|
278
|
+
return Boolean(point || clicked);
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* 使用原生 CDP 鼠标事件真实点击指定屏幕坐标 (具有真实 isTrusted 属性,兼容各类复杂前端框架与自定义组件)
|
|
282
|
+
*/
|
|
283
|
+
async clickPoint(x, y) {
|
|
284
|
+
try {
|
|
285
|
+
await this.send('Input.dispatchMouseEvent', {
|
|
286
|
+
type: 'mouseMoved',
|
|
287
|
+
x,
|
|
288
|
+
y,
|
|
289
|
+
});
|
|
290
|
+
await this.send('Input.dispatchMouseEvent', {
|
|
291
|
+
type: 'mousePressed',
|
|
292
|
+
x,
|
|
293
|
+
y,
|
|
294
|
+
button: 'left',
|
|
295
|
+
clickCount: 1,
|
|
296
|
+
});
|
|
297
|
+
await this.send('Input.dispatchMouseEvent', {
|
|
298
|
+
type: 'mouseReleased',
|
|
299
|
+
x,
|
|
300
|
+
y,
|
|
301
|
+
button: 'left',
|
|
302
|
+
clickCount: 1,
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
catch { }
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* 优雅断开 CDP 连接,保持被托管的浏览器进程继续运行
|
|
309
|
+
*/
|
|
310
|
+
disconnect() {
|
|
311
|
+
if (this.ws) {
|
|
312
|
+
try {
|
|
313
|
+
this.ws.close();
|
|
314
|
+
}
|
|
315
|
+
catch { }
|
|
316
|
+
this.ws = null;
|
|
317
|
+
}
|
|
318
|
+
this.responseHandlers.clear();
|
|
319
|
+
}
|
|
320
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 用户本地偏好配置仓库
|
|
3
|
+
* 存储路径: ~/.cursor-switch/config.json
|
|
4
|
+
* 用于记忆常用卡密、接口地址与个性化选项
|
|
5
|
+
*/
|
|
6
|
+
export interface AppConfig {
|
|
7
|
+
seat_card_code?: string;
|
|
8
|
+
token_card_code?: string;
|
|
9
|
+
seat_api_base?: string;
|
|
10
|
+
auto_restart_cursor?: boolean;
|
|
11
|
+
last_update_check?: number;
|
|
12
|
+
latest_version?: string;
|
|
13
|
+
custom_executable_path?: string;
|
|
14
|
+
custom_data_dir?: string;
|
|
15
|
+
}
|
|
16
|
+
export declare class ConfigStore {
|
|
17
|
+
private configDir;
|
|
18
|
+
private configPath;
|
|
19
|
+
constructor();
|
|
20
|
+
private ensureDir;
|
|
21
|
+
load(): AppConfig;
|
|
22
|
+
save(config: AppConfig): void;
|
|
23
|
+
getSeatCardCode(): string | null;
|
|
24
|
+
setSeatCardCode(code: string): void;
|
|
25
|
+
getTokenCardCode(): string | null;
|
|
26
|
+
setTokenCardCode(code: string): void;
|
|
27
|
+
getSeatApiBase(): string;
|
|
28
|
+
setSeatApiBase(url: string): void;
|
|
29
|
+
getUpdateCache(): {
|
|
30
|
+
lastCheck?: number;
|
|
31
|
+
latestVersion?: string;
|
|
32
|
+
};
|
|
33
|
+
setUpdateCache(latestVersion: string): void;
|
|
34
|
+
getCustomExecutablePath(): string | null;
|
|
35
|
+
setCustomExecutablePath(pathStr: string): void;
|
|
36
|
+
getCustomDataDir(): string | null;
|
|
37
|
+
setCustomDataDir(dirStr: string): void;
|
|
38
|
+
}
|