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.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +161 -0
  3. package/SECURITY.md +38 -0
  4. package/bin/cswitch.js +35 -0
  5. package/dist/cli.d.ts +6 -0
  6. package/dist/cli.js +850 -0
  7. package/dist/core/account-store.d.ts +25 -0
  8. package/dist/core/account-store.js +182 -0
  9. package/dist/core/cdp-engine.d.ts +75 -0
  10. package/dist/core/cdp-engine.js +320 -0
  11. package/dist/core/config-store.d.ts +38 -0
  12. package/dist/core/config-store.js +100 -0
  13. package/dist/core/cursor-paths.d.ts +22 -0
  14. package/dist/core/cursor-paths.js +287 -0
  15. package/dist/core/dashboard-launcher.d.ts +34 -0
  16. package/dist/core/dashboard-launcher.js +210 -0
  17. package/dist/core/fingerprint.d.ts +7 -0
  18. package/dist/core/fingerprint.js +34 -0
  19. package/dist/core/oauth-receiver.d.ts +31 -0
  20. package/dist/core/oauth-receiver.js +849 -0
  21. package/dist/core/official-api.d.ts +29 -0
  22. package/dist/core/official-api.js +205 -0
  23. package/dist/core/outlook-launcher.d.ts +54 -0
  24. package/dist/core/outlook-launcher.js +671 -0
  25. package/dist/core/process-manager.d.ts +25 -0
  26. package/dist/core/process-manager.js +133 -0
  27. package/dist/core/pure-login-service.d.ts +67 -0
  28. package/dist/core/pure-login-service.js +550 -0
  29. package/dist/core/refund-client.d.ts +102 -0
  30. package/dist/core/refund-client.js +221 -0
  31. package/dist/core/refund-service.d.ts +39 -0
  32. package/dist/core/refund-service.js +384 -0
  33. package/dist/core/sqlite-bridge.d.ts +23 -0
  34. package/dist/core/sqlite-bridge.js +207 -0
  35. package/dist/core/storage-bridge.d.ts +18 -0
  36. package/dist/core/storage-bridge.js +99 -0
  37. package/dist/core/token-parser.d.ts +35 -0
  38. package/dist/core/token-parser.js +106 -0
  39. package/dist/core/update-checker.d.ts +62 -0
  40. package/dist/core/update-checker.js +231 -0
  41. package/dist/index.d.ts +17 -0
  42. package/dist/index.js +17 -0
  43. package/dist/menu.d.ts +12 -0
  44. package/dist/menu.js +2201 -0
  45. package/dist/types.d.ts +60 -0
  46. package/dist/types.js +5 -0
  47. package/dist/utils/browser-utils.d.ts +31 -0
  48. package/dist/utils/browser-utils.js +283 -0
  49. package/dist/utils/clipboard.d.ts +5 -0
  50. package/dist/utils/clipboard.js +48 -0
  51. package/dist/utils/live-menu.d.ts +26 -0
  52. package/dist/utils/live-menu.js +169 -0
  53. package/dist/utils/plan-formatter.d.ts +30 -0
  54. package/dist/utils/plan-formatter.js +153 -0
  55. package/dist/utils/prompt-utils.d.ts +40 -0
  56. package/dist/utils/prompt-utils.js +105 -0
  57. package/dist/utils/security.d.ts +6 -0
  58. package/dist/utils/security.js +27 -0
  59. package/dist/utils/table-renderer.d.ts +7 -0
  60. package/dist/utils/table-renderer.js +88 -0
  61. package/dist/utils/time-formatter.d.ts +13 -0
  62. package/dist/utils/time-formatter.js +83 -0
  63. package/package.json +53 -0
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Cursor-Switch 数据模型与类型定义
3
+ * 100% 兼容 AoZai account_cache.json 数据结构
4
+ */
5
+ export interface MachineIds {
6
+ 'telemetry.devDeviceId': string;
7
+ 'telemetry.macMachineId': string;
8
+ 'telemetry.machineId': string;
9
+ 'telemetry.sqmId': string;
10
+ 'storage.serviceMachineId': string;
11
+ 'system.machineGuid'?: string;
12
+ 'system.sqmClientId'?: string;
13
+ }
14
+ export interface PlanUsage {
15
+ apiPercentUsed?: number;
16
+ autoPercentUsed?: number;
17
+ bonusSpend?: number | null;
18
+ includedSpend?: number | null;
19
+ limit?: number | null;
20
+ remaining?: number | null;
21
+ totalPercentUsed?: number;
22
+ totalSpend?: number | null;
23
+ }
24
+ export interface CurrentPeriodUsage {
25
+ billingCycleStart?: string;
26
+ billingCycleEnd?: string;
27
+ enabled?: boolean | null;
28
+ planUsage?: PlanUsage;
29
+ }
30
+ export interface AccountInfo {
31
+ email: string;
32
+ token: string;
33
+ refresh_token?: string | null;
34
+ workos_cursor_session_token?: string | null;
35
+ is_current?: boolean;
36
+ created_at?: string;
37
+ username?: string | null;
38
+ tags?: string[];
39
+ machine_ids?: MachineIds;
40
+ subscription_type?: string;
41
+ subscription_status?: string;
42
+ trial_days_remaining?: number;
43
+ usage_amount_cents?: number | null;
44
+ usage_fetched_at?: string;
45
+ current_period_usage?: CurrentPeriodUsage;
46
+ period_usage_fetched_at?: string;
47
+ email_password?: string;
48
+ cursor_password?: string;
49
+ }
50
+ export interface SwitchResult {
51
+ success: boolean;
52
+ message: string;
53
+ email: string;
54
+ details: string[];
55
+ }
56
+ export interface ResolvedCursorPaths {
57
+ storageJson: string;
58
+ sqliteDb: string;
59
+ executablePath?: string;
60
+ }
package/dist/types.js ADDED
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Cursor-Switch 数据模型与类型定义
3
+ * 100% 兼容 AoZai account_cache.json 数据结构
4
+ */
5
+ export {};
@@ -0,0 +1,31 @@
1
+ /**
2
+ * 全平台多浏览器适配与 URL 安全调起引擎
3
+ * 支持 Windows (Chrome/Edge/Brave/Firefox/Arc) / macOS (Safari/Chrome/Arc) / Linux (Firefox/Chromium)
4
+ * 支持 WSL 环境自动穿透、无头服务器 (SSH) 优雅降级与跨浏览器 Cookie 免密注入
5
+ */
6
+ /**
7
+ * 跨操作系统与环境安全打开浏览器 URL
8
+ * 具备 WSL 穿透与无头/SSH 降级容错机制
9
+ */
10
+ export declare function openBrowserUrl(url: string): Promise<boolean>;
11
+ /**
12
+ * 跨操作系统与环境以无痕/隐私窗口模式调起浏览器
13
+ * 确保打开一个全新的未登录实例,不携带历史 Cookie
14
+ */
15
+ export declare function openIncognitoBrowserUrl(url: string): Promise<boolean>;
16
+ /**
17
+ * 动态探测本地常见浏览器安装路径 (多盘符扫描)
18
+ */
19
+ export declare function findInstalledBrowsers(): {
20
+ name: string;
21
+ path: string;
22
+ }[];
23
+ /**
24
+ * 动态探测本地环境变量或当前目录中的免密脚本
25
+ */
26
+ export declare function findPythonDashboardScript(): string | null;
27
+ /**
28
+ * 生成全浏览器通用的 1 行 Console 免密注入 JavaScript 代码
29
+ * 适用于任何浏览器 (Chrome / Edge / Safari / Firefox / Arc / Brave 等)
30
+ */
31
+ export declare function getCookieInjectionSnippet(sessionToken: string): string;
@@ -0,0 +1,283 @@
1
+ /**
2
+ * 全平台多浏览器适配与 URL 安全调起引擎
3
+ * 支持 Windows (Chrome/Edge/Brave/Firefox/Arc) / macOS (Safari/Chrome/Arc) / Linux (Firefox/Chromium)
4
+ * 支持 WSL 环境自动穿透、无头服务器 (SSH) 优雅降级与跨浏览器 Cookie 免密注入
5
+ */
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import fs from 'node:fs';
9
+ import { spawn } from 'node:child_process';
10
+ import open from 'open';
11
+ /**
12
+ * 跨操作系统与环境安全打开浏览器 URL
13
+ * 具备 WSL 穿透与无头/SSH 降级容错机制
14
+ */
15
+ export async function openBrowserUrl(url) {
16
+ // 1. WSL (Windows Subsystem for Linux) 自动穿透调用宿主 Windows 浏览器
17
+ const isWsl = Boolean(process.env.WSL_DISTRO_NAME ||
18
+ process.env.WSL_INTEROP ||
19
+ (fs.existsSync('/proc/version') && fs.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft')));
20
+ if (isWsl) {
21
+ try {
22
+ // 优先尝试 wslview,若无则调用 cmd.exe 穿透
23
+ const child = spawn('wslview', [url], { stdio: 'ignore' });
24
+ child.on('error', () => {
25
+ try {
26
+ spawn('/mnt/c/Windows/System32/cmd.exe', ['/c', 'start', '""', url], { stdio: 'ignore' }).unref();
27
+ }
28
+ catch { }
29
+ });
30
+ child.unref();
31
+ return true;
32
+ }
33
+ catch { }
34
+ }
35
+ // 2. 调起系统默认浏览器 (使用 open 模块)
36
+ try {
37
+ const cp = await open(url);
38
+ if (cp && typeof cp.unref === 'function') {
39
+ cp.unref();
40
+ }
41
+ return true;
42
+ }
43
+ catch { }
44
+ // 3. 降级原生 Shell 命令调起
45
+ try {
46
+ const platform = process.platform;
47
+ if (platform === 'win32') {
48
+ spawn('cmd.exe', ['/c', 'start', '""', url], { detached: true, stdio: 'ignore' }).unref();
49
+ return true;
50
+ }
51
+ else if (platform === 'darwin') {
52
+ spawn('open', [url], { detached: true, stdio: 'ignore' }).unref();
53
+ return true;
54
+ }
55
+ else {
56
+ spawn('xdg-open', [url], { detached: true, stdio: 'ignore' }).unref();
57
+ return true;
58
+ }
59
+ }
60
+ catch { }
61
+ return false;
62
+ }
63
+ /**
64
+ * 跨操作系统与环境以无痕/隐私窗口模式调起浏览器
65
+ * 确保打开一个全新的未登录实例,不携带历史 Cookie
66
+ */
67
+ export async function openIncognitoBrowserUrl(url) {
68
+ const platform = process.platform;
69
+ const isWsl = Boolean(process.env.WSL_DISTRO_NAME ||
70
+ process.env.WSL_INTEROP ||
71
+ (fs.existsSync('/proc/version') && fs.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft')));
72
+ // 1. WSL 环境穿透宿主 Windows 浏览器无痕窗口
73
+ if (isWsl) {
74
+ try {
75
+ spawn('/mnt/c/Windows/System32/cmd.exe', ['/c', 'start', '""', 'chrome', '--incognito', `"${url}"`], { stdio: 'ignore' }).unref();
76
+ return true;
77
+ }
78
+ catch { }
79
+ try {
80
+ spawn('/mnt/c/Windows/System32/cmd.exe', ['/c', 'start', '""', 'msedge', '--inprivate', `"${url}"`], { stdio: 'ignore' }).unref();
81
+ return true;
82
+ }
83
+ catch { }
84
+ }
85
+ // 2. Windows 平台
86
+ if (platform === 'win32') {
87
+ const installed = findInstalledBrowsers();
88
+ // 优先尝试 Google Chrome
89
+ const chrome = installed.find((b) => b.name.includes('Chrome'));
90
+ if (chrome && fs.existsSync(chrome.path)) {
91
+ try {
92
+ const cp = spawn(chrome.path, ['--incognito', url], { detached: true, stdio: 'ignore' });
93
+ cp.unref();
94
+ return true;
95
+ }
96
+ catch { }
97
+ }
98
+ // 次选 Microsoft Edge
99
+ const edge = installed.find((b) => b.name.includes('Edge'));
100
+ if (edge && fs.existsSync(edge.path)) {
101
+ try {
102
+ const cp = spawn(edge.path, ['--inprivate', url], { detached: true, stdio: 'ignore' });
103
+ cp.unref();
104
+ return true;
105
+ }
106
+ catch { }
107
+ }
108
+ // Brave
109
+ const brave = installed.find((b) => b.name.includes('Brave'));
110
+ if (brave && fs.existsSync(brave.path)) {
111
+ try {
112
+ const cp = spawn(brave.path, ['--incognito', url], { detached: true, stdio: 'ignore' });
113
+ cp.unref();
114
+ return true;
115
+ }
116
+ catch { }
117
+ }
118
+ // Firefox
119
+ const firefox = installed.find((b) => b.name.includes('Firefox'));
120
+ if (firefox && fs.existsSync(firefox.path)) {
121
+ try {
122
+ const cp = spawn(firefox.path, ['-private-window', url], { detached: true, stdio: 'ignore' });
123
+ cp.unref();
124
+ return true;
125
+ }
126
+ catch { }
127
+ }
128
+ // 降级尝试系统命令唤起
129
+ try {
130
+ spawn('cmd.exe', ['/c', 'start', '""', 'chrome', '--incognito', `"${url}"`], { detached: true, stdio: 'ignore', windowsVerbatimArguments: true }).unref();
131
+ return true;
132
+ }
133
+ catch { }
134
+ try {
135
+ spawn('cmd.exe', ['/c', 'start', '""', 'msedge', '--inprivate', `"${url}"`], { detached: true, stdio: 'ignore', windowsVerbatimArguments: true }).unref();
136
+ return true;
137
+ }
138
+ catch { }
139
+ }
140
+ else if (platform === 'darwin') {
141
+ // macOS
142
+ try {
143
+ spawn('open', ['-na', 'Google Chrome', '--args', '--incognito', url], { detached: true, stdio: 'ignore' }).unref();
144
+ return true;
145
+ }
146
+ catch { }
147
+ try {
148
+ spawn('open', ['-na', 'Microsoft Edge', '--args', '--inprivate', url], { detached: true, stdio: 'ignore' }).unref();
149
+ return true;
150
+ }
151
+ catch { }
152
+ try {
153
+ spawn('open', ['-na', 'Firefox', '--args', '-private-window', url], { detached: true, stdio: 'ignore' }).unref();
154
+ return true;
155
+ }
156
+ catch { }
157
+ }
158
+ else {
159
+ // Linux
160
+ const linuxAttempts = [
161
+ { cmd: 'google-chrome', args: ['--incognito', url] },
162
+ { cmd: 'microsoft-edge', args: ['--inprivate', url] },
163
+ { cmd: 'brave-browser', args: ['--incognito', url] },
164
+ { cmd: 'firefox', args: ['-private-window', url] },
165
+ { cmd: 'chromium-browser', args: ['--incognito', url] },
166
+ ];
167
+ for (const attempt of linuxAttempts) {
168
+ try {
169
+ const cp = spawn(attempt.cmd, attempt.args, { detached: true, stdio: 'ignore' });
170
+ cp.unref();
171
+ return true;
172
+ }
173
+ catch { }
174
+ }
175
+ }
176
+ // 终极降级: 使用标准浏览器打开
177
+ return openBrowserUrl(url);
178
+ }
179
+ /**
180
+ * 动态探测本地常见浏览器安装路径 (多盘符扫描)
181
+ */
182
+ export function findInstalledBrowsers() {
183
+ const platform = process.platform;
184
+ const browsers = [];
185
+ if (platform === 'win32') {
186
+ const drives = ['C', 'D', 'E', 'F', 'G', 'H'];
187
+ const candidates = [
188
+ { name: 'Google Chrome', rel: 'Program Files\\Google\\Chrome\\Application\\chrome.exe' },
189
+ { name: 'Google Chrome (x86)', rel: 'Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe' },
190
+ { name: 'Microsoft Edge', rel: 'Program Files\\Microsoft\\Edge\\Application\\msedge.exe' },
191
+ { name: 'Microsoft Edge (x86)', rel: 'Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe' },
192
+ { name: 'Brave Browser', rel: 'Program Files\\BraveSoftware\\Brave-Browser\\Application\\brave.exe' },
193
+ { name: 'Brave Browser (x86)', rel: 'Program Files (x86)\\BraveSoftware\\Brave-Browser\\Application\\brave.exe' },
194
+ { name: 'Mozilla Firefox', rel: 'Program Files\\Mozilla Firefox\\firefox.exe' },
195
+ { name: 'Mozilla Firefox (x86)', rel: 'Program Files (x86)\\Mozilla Firefox\\firefox.exe' },
196
+ ];
197
+ for (const d of drives) {
198
+ const root = `${d}:\\`;
199
+ if (!fs.existsSync(root))
200
+ continue;
201
+ for (const cand of candidates) {
202
+ const full = path.join(root, cand.rel);
203
+ if (fs.existsSync(full) && !browsers.some((b) => b.path === full)) {
204
+ browsers.push({ name: cand.name, path: full });
205
+ }
206
+ }
207
+ }
208
+ // LocalAppData 目录 (针对用户态免提权安装的 Chrome / Arc)
209
+ const localAppData = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
210
+ const localCandidates = [
211
+ { name: 'Google Chrome (User)', full: path.join(localAppData, 'Google', 'Chrome', 'Application', 'chrome.exe') },
212
+ { name: 'Microsoft Edge (User)', full: path.join(localAppData, 'Microsoft', 'Edge', 'Application', 'msedge.exe') },
213
+ { name: 'Brave Browser (User)', full: path.join(localAppData, 'BraveSoftware', 'Brave-Browser', 'Application', 'brave.exe') },
214
+ { name: 'Arc Browser', full: path.join(localAppData, 'Programs', 'Arc', 'Arc.exe') },
215
+ { name: 'Mozilla Firefox (User)', full: path.join(localAppData, 'Mozilla Firefox', 'firefox.exe') },
216
+ ];
217
+ for (const cand of localCandidates) {
218
+ if (fs.existsSync(cand.full) && !browsers.some((b) => b.path === cand.full)) {
219
+ browsers.push({ name: cand.name, path: cand.full });
220
+ }
221
+ }
222
+ }
223
+ else if (platform === 'darwin') {
224
+ const macCandidates = [
225
+ { name: 'Safari', full: '/Applications/Safari.app/Contents/MacOS/Safari' },
226
+ { name: 'Google Chrome', full: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' },
227
+ { name: 'Microsoft Edge', full: '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge' },
228
+ { name: 'Arc Browser', full: '/Applications/Arc.app/Contents/MacOS/Arc' },
229
+ { name: 'Brave Browser', full: '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser' },
230
+ { name: 'Mozilla Firefox', full: '/Applications/Firefox.app/Contents/MacOS/Firefox' },
231
+ ];
232
+ for (const cand of macCandidates) {
233
+ if (fs.existsSync(cand.full)) {
234
+ browsers.push({ name: cand.name, path: cand.full });
235
+ }
236
+ }
237
+ }
238
+ else {
239
+ // Linux
240
+ const linuxBinaries = [
241
+ { name: 'Google Chrome', bin: '/usr/bin/google-chrome' },
242
+ { name: 'Chromium', bin: '/usr/bin/chromium-browser' },
243
+ { name: 'Microsoft Edge', bin: '/usr/bin/microsoft-edge' },
244
+ { name: 'Brave Browser', bin: '/usr/bin/brave-browser' },
245
+ { name: 'Mozilla Firefox', bin: '/usr/bin/firefox' },
246
+ ];
247
+ for (const cand of linuxBinaries) {
248
+ if (fs.existsSync(cand.bin)) {
249
+ browsers.push({ name: cand.name, path: cand.bin });
250
+ }
251
+ }
252
+ }
253
+ return browsers;
254
+ }
255
+ /**
256
+ * 动态探测本地环境变量或当前目录中的免密脚本
257
+ */
258
+ export function findPythonDashboardScript() {
259
+ const envScript = process.env.CURSOR_DASHBOARD_SCRIPT;
260
+ if (envScript && fs.existsSync(envScript)) {
261
+ return envScript;
262
+ }
263
+ const cwd = process.cwd();
264
+ const candidates = [
265
+ path.join(cwd, 'scripts', 'open_cursor_dashboard.cmd'),
266
+ path.join(cwd, 'scripts', 'open_cursor_dashboard.py'),
267
+ path.join(os.homedir(), '.cursor-switch', 'scripts', 'open_cursor_dashboard.py'),
268
+ ];
269
+ for (const cand of candidates) {
270
+ if (fs.existsSync(cand)) {
271
+ return cand;
272
+ }
273
+ }
274
+ return null;
275
+ }
276
+ /**
277
+ * 生成全浏览器通用的 1 行 Console 免密注入 JavaScript 代码
278
+ * 适用于任何浏览器 (Chrome / Edge / Safari / Firefox / Arc / Brave 等)
279
+ */
280
+ export function getCookieInjectionSnippet(sessionToken) {
281
+ const token = sessionToken.trim().replace(/["\r\n]/g, '');
282
+ return `document.cookie="WorkosCursorSessionToken=${token};domain=.cursor.com;path=/;max-age=31536000;secure";location.reload();`;
283
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * 跨操作系统零依赖系统剪贴板拷贝工具
3
+ * 原生支持 Windows (clip.exe), macOS (pbcopy), Linux (wl-copy / xclip)
4
+ */
5
+ export declare function copyToClipboard(text: string): Promise<boolean>;
@@ -0,0 +1,48 @@
1
+ /**
2
+ * 跨操作系统零依赖系统剪贴板拷贝工具
3
+ * 原生支持 Windows (clip.exe), macOS (pbcopy), Linux (wl-copy / xclip)
4
+ */
5
+ import { spawn } from 'node:child_process';
6
+ export function copyToClipboard(text) {
7
+ return new Promise((resolve) => {
8
+ let cmd = '';
9
+ let args = [];
10
+ if (process.platform === 'win32') {
11
+ cmd = 'clip.exe';
12
+ args = [];
13
+ }
14
+ else if (process.platform === 'darwin') {
15
+ cmd = 'pbcopy';
16
+ args = [];
17
+ }
18
+ else {
19
+ // Linux: 优先测试 Wayland wl-copy,否则回退到 xclip / xsel
20
+ if (process.env.WAYLAND_DISPLAY) {
21
+ cmd = 'wl-copy';
22
+ args = [];
23
+ }
24
+ else {
25
+ cmd = 'xclip';
26
+ args = ['-selection', 'clipboard'];
27
+ }
28
+ }
29
+ try {
30
+ const child = spawn(cmd, args, { stdio: ['pipe', 'ignore', 'ignore'] });
31
+ let hasError = false;
32
+ child.on('error', () => {
33
+ hasError = true;
34
+ resolve(false);
35
+ });
36
+ child.on('close', (code) => {
37
+ if (!hasError) {
38
+ resolve(code === 0);
39
+ }
40
+ });
41
+ child.stdin.write(text);
42
+ child.stdin.end();
43
+ }
44
+ catch {
45
+ resolve(false);
46
+ }
47
+ });
48
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * 现代终端极速响应式交互菜单引擎 (Live & Quick TUI Engine)
3
+ * 支持:
4
+ * 1. 单键瞬发直达 (按 0, 1, 2, s, q, Esc 键无需按回车直接触发秒选)
5
+ * 2. 方向键平滑巡览与动态说明 (↑↓ 移动光标,↵ 回车确认)
6
+ * 3. 毫秒级无闪烁响应式时钟 (主界面 HUD 每秒平滑走字)
7
+ */
8
+ import { Separator } from '@inquirer/core';
9
+ export interface QuickMenuChoice {
10
+ name: string;
11
+ value: string;
12
+ description?: string;
13
+ key?: string;
14
+ disabled?: boolean | string;
15
+ }
16
+ export interface QuickMenuConfig {
17
+ getHeader?: () => string;
18
+ header?: string;
19
+ message?: string;
20
+ choices: Array<QuickMenuChoice | Separator>;
21
+ pageSize?: number;
22
+ tickIntervalMs?: number;
23
+ }
24
+ export declare const quickSelect: import("@inquirer/type").Prompt<string, QuickMenuConfig>;
25
+ export declare const liveMenu: import("@inquirer/type").Prompt<string, QuickMenuConfig>;
26
+ export { Separator };
@@ -0,0 +1,169 @@
1
+ /**
2
+ * 现代终端极速响应式交互菜单引擎 (Live & Quick TUI Engine)
3
+ * 支持:
4
+ * 1. 单键瞬发直达 (按 0, 1, 2, s, q, Esc 键无需按回车直接触发秒选)
5
+ * 2. 方向键平滑巡览与动态说明 (↑↓ 移动光标,↵ 回车确认)
6
+ * 3. 毫秒级无闪烁响应式时钟 (主界面 HUD 每秒平滑走字)
7
+ */
8
+ import { createPrompt, useState, useEffect, useKeypress, usePagination, Separator, isUpKey, isDownKey, isEnterKey, } from '@inquirer/core';
9
+ import chalk from 'chalk';
10
+ export const quickSelect = createPrompt((config, done) => {
11
+ const { pageSize = 12, tickIntervalMs = 0 } = config;
12
+ const [, setTick] = useState(0);
13
+ const [status, setStatus] = useState('idle');
14
+ // 如果配置了定时刷新,每秒触发一次虚拟 Diff 重绘 (零闪烁实时走字)
15
+ useEffect(() => {
16
+ if (!tickIntervalMs || tickIntervalMs <= 0)
17
+ return;
18
+ let tickCount = 0;
19
+ const timer = setInterval(() => {
20
+ tickCount++;
21
+ setTick(tickCount);
22
+ }, tickIntervalMs);
23
+ return () => clearInterval(timer);
24
+ }, []);
25
+ const items = config.choices;
26
+ const isSelectable = (item) => !Separator.isSeparator(item) && !item?.disabled;
27
+ const selectableIndices = [];
28
+ items.forEach((item, idx) => {
29
+ if (isSelectable(item)) {
30
+ selectableIndices.push(idx);
31
+ }
32
+ });
33
+ const [active, setActive] = useState(selectableIndices[0] ?? 0);
34
+ const selectedChoice = items[active];
35
+ // 核心终端防护:确保无论上一界面以何种形式退出,此处均 100% 激活 rawMode 且流正常,彻底杜绝 Windows 方向键假死
36
+ useEffect(() => {
37
+ if (process.stdin.isTTY) {
38
+ if (!process.stdin.isRaw) {
39
+ try {
40
+ process.stdin.setRawMode(true);
41
+ }
42
+ catch { }
43
+ }
44
+ try {
45
+ process.stdin.resume();
46
+ }
47
+ catch { }
48
+ }
49
+ }, []);
50
+ useKeypress((key, rl) => {
51
+ if (status !== 'idle')
52
+ return;
53
+ // 1. Ctrl+C 紧急强退:无论任何时候按 Ctrl+C,100% 恢复光标并瞬间退回终端 Shell
54
+ if (key.ctrl && key.name === 'c') {
55
+ process.stdout.write('\x1b[?25h\n');
56
+ process.exit(0);
57
+ }
58
+ // 2. 回车键确认当前选定项
59
+ if (isEnterKey(key)) {
60
+ if (selectedChoice && isSelectable(selectedChoice)) {
61
+ setStatus('done');
62
+ done(selectedChoice.value);
63
+ }
64
+ return;
65
+ }
66
+ // 3. Escape 键取消当前操作,返回上一级或主菜单
67
+ if (key.name === 'escape') {
68
+ const backItem = items.find((item) => isSelectable(item) &&
69
+ (item.value === 'back' ||
70
+ item.value === '__back__' ||
71
+ item.value === 'exit' ||
72
+ item.value === '__cancel__'));
73
+ if (backItem && isSelectable(backItem)) {
74
+ setStatus('done');
75
+ done(backItem.value);
76
+ return;
77
+ }
78
+ // 无明确返回项时默认安全返回 '__back__',绝不抛出 ExitPromptError 误判为 SIGINT
79
+ setStatus('done');
80
+ done('__back__');
81
+ return;
82
+ }
83
+ // 4. 方向键导航 (支持 ↑↓ 和 vim 的 j/k)
84
+ if (isUpKey(key) || isDownKey(key) || key.name === 'k' || key.name === 'j') {
85
+ const isUp = isUpKey(key) || key.name === 'k';
86
+ const offset = isUp ? -1 : 1;
87
+ let next = active;
88
+ do {
89
+ next = (next + offset + items.length) % items.length;
90
+ } while (!isSelectable(items[next]));
91
+ setActive(next);
92
+ return;
93
+ }
94
+ // 5. 单键瞬发直达:支持数字键 0-9、字符键 s (搜索)、q (退出/返回)
95
+ const char = key.name ? key.name.toLowerCase() : '';
96
+ if (char) {
97
+ // 快捷退出/返回: 按 q 直接触发返回项
98
+ if (char === 'q') {
99
+ const backItem = items.find((item) => isSelectable(item) &&
100
+ (item.value === 'back' ||
101
+ item.value === '__back__' ||
102
+ item.value === 'exit' ||
103
+ item.value === '__cancel__'));
104
+ if (backItem && isSelectable(backItem)) {
105
+ setStatus('done');
106
+ done(backItem.value);
107
+ return;
108
+ }
109
+ }
110
+ // 匹配以该按键开头或指定 key 的选项
111
+ const matchIdx = items.findIndex((item) => {
112
+ if (!isSelectable(item))
113
+ return false;
114
+ if (item.key && item.key.toLowerCase() === char)
115
+ return true;
116
+ // 过滤颜色控制字符后比对前缀
117
+ const cleanName = item.name.replace(/\x1b\[[0-9;]*m/g, '').trim();
118
+ return (cleanName.startsWith(`${char}.`) ||
119
+ cleanName.startsWith(`${char} `) ||
120
+ cleanName.startsWith(`${char}·`) ||
121
+ cleanName.startsWith(`${char}、`));
122
+ });
123
+ if (matchIdx !== -1) {
124
+ const target = items[matchIdx];
125
+ setActive(matchIdx);
126
+ // 单键瞬发执行!无需再按回车
127
+ setStatus('done');
128
+ done(target.value);
129
+ return;
130
+ }
131
+ }
132
+ });
133
+ const page = usePagination({
134
+ items,
135
+ active,
136
+ renderItem({ item, isActive }) {
137
+ if (Separator.isSeparator(item)) {
138
+ return ` ${chalk.dim('────────────────────────────────')}`;
139
+ }
140
+ const choice = item;
141
+ if (isActive) {
142
+ return ` ${chalk.cyan.bold('❯')} ${chalk.bold.white(choice.name)}`;
143
+ }
144
+ return ` ${chalk.white(choice.name)}`;
145
+ },
146
+ pageSize,
147
+ loop: true,
148
+ });
149
+ if (status === 'done') {
150
+ return '\x1b[?25h';
151
+ }
152
+ const headerText = config.getHeader
153
+ ? config.getHeader()
154
+ : config.header
155
+ ? config.header
156
+ : '';
157
+ const promptMessage = config.message
158
+ ? `\n ${chalk.cyan('●')} ${chalk.bold.white(config.message)}\n`
159
+ : '\n';
160
+ const descText = selectedChoice?.description
161
+ ? `\n ${chalk.dim('›')} ${chalk.cyan(selectedChoice.description)}`
162
+ : '\n';
163
+ const helpTip = `\n ${chalk.dim('[↑↓] 移动 [↵] 确认 [数字/按键] 单键瞬发 [Esc/q] 返回 [Ctrl+C] 退出')}`;
164
+ const content = `${headerText}${promptMessage}${page}${descText}${helpTip}\x1b[?25l`;
165
+ return content;
166
+ });
167
+ // 兼容别名导出
168
+ export const liveMenu = quickSelect;
169
+ export { Separator };
@@ -0,0 +1,30 @@
1
+ /**
2
+ * 会员计划名称官方规范化映射工具
3
+ * 输出 Cursor 官方英文标准等级名称 (Free / Pro / Pro+ / Ultra / Team / Enterprise / Expired 等)
4
+ *
5
+ * 官方全档位体系矩阵:
6
+ * 👑 Ultra → Ultra
7
+ * ⚡ Pro+ → Pro+
8
+ * ⚡ Pro → Pro
9
+ * 👥 Team → Team
10
+ * 🏢 Enterprise → Enterprise
11
+ * 🎓 Student → Student
12
+ * 🎁 Trial → Trial
13
+ * 🆓 Free → Free
14
+ * ⚠️ Past Due → Past Due
15
+ * ❌ Expired → Expired
16
+ */
17
+ export type PlanTier = 'ultra' | 'pro_plus' | 'pro' | 'team' | 'enterprise' | 'student' | 'trial' | 'free' | 'past_due' | 'token_expired';
18
+ /**
19
+ * 将原始计划字符串解析为规范的标准档位
20
+ */
21
+ export declare function parsePlanTier(rawPlan?: string | null): PlanTier;
22
+ /**
23
+ * 会员计划名称格式化工具
24
+ * 输出 Cursor 官方英文规范等级名称 (Pro / Pro+ / Ultra / Team / Enterprise / Free 等)
25
+ */
26
+ export declare function formatPlanName(rawPlan?: string | null, trialDays?: number | null): string;
27
+ /**
28
+ * 具有专业色彩阶梯的终端高亮格式化
29
+ */
30
+ export declare function formatPlanBadge(rawPlan?: string | null, trialDays?: number | null): string;