cursor-switch 1.0.6 → 1.0.8

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 (84) hide show
  1. package/README.md +76 -75
  2. package/SECURITY.md +22 -19
  3. package/bin/cswitch.js +31 -8
  4. package/dist/cli.d.ts +0 -4
  5. package/dist/cli.js +404 -225
  6. package/dist/core/account-store.d.ts +0 -7
  7. package/dist/core/account-store.js +22 -28
  8. package/dist/core/cdp-engine.d.ts +11 -49
  9. package/dist/core/cdp-engine.js +155 -110
  10. package/dist/core/config-store.d.ts +7 -6
  11. package/dist/core/config-store.js +33 -12
  12. package/dist/core/cursor-paths.d.ts +8 -18
  13. package/dist/core/cursor-paths.js +18 -37
  14. package/dist/core/dashboard-launcher.d.ts +2 -22
  15. package/dist/core/dashboard-launcher.js +10 -60
  16. package/dist/core/extract-client.d.ts +57 -0
  17. package/dist/core/extract-client.js +219 -0
  18. package/dist/core/extract-menu.d.ts +3 -0
  19. package/dist/core/extract-menu.js +360 -0
  20. package/dist/core/extract-service.d.ts +64 -0
  21. package/dist/core/extract-service.js +435 -0
  22. package/dist/core/fingerprint.d.ts +0 -4
  23. package/dist/core/fingerprint.js +0 -6
  24. package/dist/core/oauth-receiver.d.ts +1 -11
  25. package/dist/core/oauth-receiver.js +509 -527
  26. package/dist/core/official-api.d.ts +0 -17
  27. package/dist/core/official-api.js +4 -23
  28. package/dist/core/outlook-launcher.d.ts +0 -27
  29. package/dist/core/outlook-launcher.js +235 -261
  30. package/dist/core/process-manager.d.ts +0 -14
  31. package/dist/core/process-manager.js +7 -22
  32. package/dist/core/pure-login-service.d.ts +64 -28
  33. package/dist/core/pure-login-service.js +527 -346
  34. package/dist/core/refund-client.d.ts +0 -22
  35. package/dist/core/refund-client.js +7 -27
  36. package/dist/core/refund-service.d.ts +0 -16
  37. package/dist/core/refund-service.js +8 -34
  38. package/dist/core/safe-storage.d.ts +27 -0
  39. package/dist/core/safe-storage.js +284 -0
  40. package/dist/core/sqlite-bridge.d.ts +10 -11
  41. package/dist/core/sqlite-bridge.js +112 -47
  42. package/dist/core/storage-bridge.d.ts +14 -5
  43. package/dist/core/storage-bridge.js +84 -24
  44. package/dist/core/switch-orchestrator.d.ts +96 -0
  45. package/dist/core/switch-orchestrator.js +341 -0
  46. package/dist/core/token-exchange.d.ts +81 -0
  47. package/dist/core/token-exchange.js +275 -0
  48. package/dist/core/token-parser.d.ts +56 -20
  49. package/dist/core/token-parser.js +354 -43
  50. package/dist/core/update-checker.d.ts +1 -29
  51. package/dist/core/update-checker.js +28 -43
  52. package/dist/index.d.ts +1 -3
  53. package/dist/index.js +1 -3
  54. package/dist/menu.d.ts +0 -7
  55. package/dist/menu.js +445 -538
  56. package/dist/types.d.ts +12 -4
  57. package/dist/types.js +0 -4
  58. package/dist/utils/account-text-importer.d.ts +9 -0
  59. package/dist/utils/account-text-importer.js +96 -0
  60. package/dist/utils/browser-utils.d.ts +0 -24
  61. package/dist/utils/browser-utils.js +0 -57
  62. package/dist/utils/clipboard.d.ts +0 -4
  63. package/dist/utils/clipboard.js +0 -5
  64. package/dist/utils/credential-bundle-ui.d.ts +36 -0
  65. package/dist/utils/credential-bundle-ui.js +246 -0
  66. package/dist/utils/live-menu.d.ts +37 -9
  67. package/dist/utils/live-menu.js +510 -81
  68. package/dist/utils/plan-formatter.d.ts +0 -26
  69. package/dist/utils/plan-formatter.js +10 -44
  70. package/dist/utils/prompt-utils.d.ts +0 -18
  71. package/dist/utils/prompt-utils.js +0 -23
  72. package/dist/utils/proxy-bootstrap.d.ts +12 -0
  73. package/dist/utils/proxy-bootstrap.js +141 -0
  74. package/dist/utils/security.d.ts +2 -4
  75. package/dist/utils/security.js +36 -4
  76. package/dist/utils/table-renderer.d.ts +0 -4
  77. package/dist/utils/table-renderer.js +24 -8
  78. package/dist/utils/time-formatter.d.ts +0 -4
  79. package/dist/utils/time-formatter.js +0 -8
  80. package/dist/utils/token-preflight-ui.d.ts +28 -0
  81. package/dist/utils/token-preflight-ui.js +222 -0
  82. package/dist/utils/window-focus.d.ts +3 -0
  83. package/dist/utils/window-focus.js +106 -0
  84. package/package.json +12 -5
@@ -0,0 +1,222 @@
1
+ import boxen from 'boxen';
2
+ import chalk from 'chalk';
3
+ import { TokenParser } from '../core/token-parser.js';
4
+ import { buildOAuthAccountInfo, } from '../core/token-exchange.js';
5
+ import { OAuthReceiver } from '../core/oauth-receiver.js';
6
+ import { OfficialApiClient } from '../core/official-api.js';
7
+ import { generateMachineIds } from '../core/fingerprint.js';
8
+ import { PureLoginService } from '../core/pure-login-service.js';
9
+ import { quickSelect } from './live-menu.js';
10
+ import { safeConfirm, safeInput } from './prompt-utils.js';
11
+ export function printFactualTokenStatus(rawOrCleanToken, existingRefreshToken, workosSessionToken) {
12
+ const cls = TokenParser.classifyAccount({
13
+ token: rawOrCleanToken,
14
+ refresh_token: existingRefreshToken || undefined,
15
+ workos_cursor_session_token: workosSessionToken || undefined,
16
+ });
17
+ if (cls.credentialState === 'expired') {
18
+ console.log(boxen([
19
+ chalk.bold.red('⚠ 前置提醒:检测到该 Token 已超过 JWT 有效期且无可用客户端 Refresh Token'),
20
+ chalk.dim('────────────────────────────────────────────────'),
21
+ ` • 账号邮箱 : ${cls.email || cls.userId || '未知'}`,
22
+ ` • 建议操作 : 已过期凭据无法直接续期,请先通过 ${chalk.cyan('cswitch oauth')} 或 ${chalk.cyan('cswitch pure')} 重新获取 60 天客户端新票。`,
23
+ ].join('\n'), { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'red', borderStyle: 'round' }));
24
+ }
25
+ else if (cls.credentialState === 'web_only') {
26
+ const issuedLabel = cls.ageHours !== undefined ? TokenParser.formatAgeText(cls.ageHours) : '未知时间';
27
+ console.log(chalk.cyan(`ℹ 识别为网页端 (web) 会话凭据(签发于 ${issuedLabel},不含桌面端 refresh_token),可用于官网控制台 (dash) 与额度查询。`));
28
+ }
29
+ return cls;
30
+ }
31
+ export function printIngestUpgradeResult(res) {
32
+ if (res.status === 'web_only_skipped') {
33
+ console.log(boxen([
34
+ chalk.bold.yellow('! 凭据形态提示:当前录入的是网页端 Cookie(未包含桌面端双票)'),
35
+ chalk.dim('────────────────────────────────────────────────'),
36
+ ' • 可用功能 : 已完整保存 web 会话 Cookie,支持网页控制台 (cswitch dash) 与用量查询。',
37
+ ` • IDE 换号 : 如需稳定切入 Cursor 桌面端,请使用 ${chalk.cyan('cswitch oauth')} 或 ${chalk.cyan('cswitch pure')} 获取 60 天客户端双票。`,
38
+ ].join('\n'), { padding: { top: 0, bottom: 0, left: 1, right: 1 }, borderColor: 'yellow', borderStyle: 'round' }));
39
+ return;
40
+ }
41
+ if (res.status === 'expired') {
42
+ console.log(chalk.red(`✖ 该 Token 已超过 JWT 有效期 (${TokenParser.formatAgeText(res.classification.ageHours)}),无法自动续期,请重新登录取票。`));
43
+ }
44
+ }
45
+ export function renderPreflightBlockBox(issue, email) {
46
+ const lines = [
47
+ chalk.bold.red(`✖ 前置风控/时效拦截:${issue.title}`),
48
+ chalk.dim('────────────────────────────────────────────────'),
49
+ ];
50
+ if (email) {
51
+ lines.push(` • 目标账号 : ${chalk.bold.white(email)}`);
52
+ }
53
+ lines.push(` • 原因说明 : ${chalk.yellow(issue.reason)}`);
54
+ lines.push(` • 建议先做 : ${chalk.cyan(issue.recommendation)}`);
55
+ if (issue.kind === 'web_upgrade_failed') {
56
+ lines.push(' • 补充说明 : 原有 web 会话凭据仍可用于网页控制台 (dash) 或用量查询;仅在切入 Cursor 桌面端时需要可续期的客户端新票。');
57
+ }
58
+ lines.push(chalk.dim(' • 安全保障 : 目前尚未关闭 Cursor 或改动任何本地配置,可直接在下方选择就地取新票或安全取消。'));
59
+ console.log('\n' +
60
+ boxen(lines.join('\n'), {
61
+ padding: { top: 0, bottom: 0, left: 1, right: 1 },
62
+ borderColor: 'red',
63
+ borderStyle: 'round',
64
+ }) +
65
+ '\n');
66
+ }
67
+ export async function promptStaleSwitchConfirmation(issue, email, opts = {}) {
68
+ renderPreflightBlockBox(issue, email);
69
+ if (opts.force) {
70
+ console.log(chalk.yellow('! 已携带 --force 参数,跳过前置拦截并继续注入本地配置...\n'));
71
+ return true;
72
+ }
73
+ const interactive = opts.interactive ?? Boolean(process.stdin.isTTY);
74
+ if (!interactive) {
75
+ console.log(chalk.yellow('已自动中止切换(未改动本机 Cursor 状态)。请先获取新 Token,或追加 --force 强行写入。\n'));
76
+ return false;
77
+ }
78
+ const msg = '建议选 N 取消并先获取新 Token。是否仍要强行切入该旧 Token(可能会触发重登/二验)?';
79
+ if (opts.confirmFn) {
80
+ return opts.confirmFn(msg);
81
+ }
82
+ return safeConfirm({ message: msg, default: false });
83
+ }
84
+ function buildPureLoginPrefill(account) {
85
+ const email = (account.email || '').trim();
86
+ if (!email || !email.includes('@') || email.endsWith('@cursor.sh')) {
87
+ return undefined;
88
+ }
89
+ if (account.email_password && account.cursor_password) {
90
+ return `${email}----${account.email_password}----${account.cursor_password}`;
91
+ }
92
+ if (account.email_password) {
93
+ return `${email}----${account.email_password}`;
94
+ }
95
+ return email;
96
+ }
97
+ async function performBrowserOAuthHeal(account, store) {
98
+ const result = await OAuthReceiver.startOfficialOAuthFlow();
99
+ if (!result.success || !result.accessToken) {
100
+ if (result.message) {
101
+ console.log(chalk.yellow(`\n${result.message}\n`));
102
+ }
103
+ return null;
104
+ }
105
+ let email = result.email;
106
+ if (!email) {
107
+ const fallback = account.email && account.email.includes('@') && !account.email.endsWith('@cursor.sh')
108
+ ? account.email
109
+ : result.authId
110
+ ? `${result.authId.replace('auth0|', '')}@cursor.sh`
111
+ : `account_${Date.now().toString().slice(-6)}@cursor.sh`;
112
+ const inputEmail = await safeInput({
113
+ message: '未能自动解析到邮箱,请输入该账号的登录邮箱:',
114
+ default: fallback,
115
+ });
116
+ email = inputEmail || fallback;
117
+ }
118
+ process.stdout.write(chalk.grey('\n正在向 Cursor 官方同步用量与会员计划... '));
119
+ const usageRes = await OfficialApiClient.fetchUsage(result.accessToken);
120
+ const existing = store.getByEmail(email) || (email === account.email ? account : undefined);
121
+ const machineIds = existing?.machine_ids || generateMachineIds();
122
+ const built = buildOAuthAccountInfo({
123
+ email,
124
+ accessToken: result.accessToken,
125
+ refreshToken: result.refreshToken,
126
+ authId: result.authId,
127
+ usageRes,
128
+ existing,
129
+ machineIds,
130
+ });
131
+ const merged = {
132
+ ...(existing || {}),
133
+ ...built,
134
+ };
135
+ store.addOrUpdate(merged);
136
+ console.log(chalk.green(`✔ 已获取 ${email} 最新 60 天客户端新票\n`));
137
+ return merged;
138
+ }
139
+ async function performPureLoginHeal(account, ctx) {
140
+ const pureService = new PureLoginService();
141
+ return pureService.runInteractiveFlow(ctx.store, ctx.storage, ctx.sqlite, ctx.executablePath, {
142
+ prefilledInput: buildPureLoginPrefill(account),
143
+ skipSwitchPrompt: true,
144
+ });
145
+ }
146
+ export async function resolveStaleSwitchWithHealing(issue, account, ctx) {
147
+ renderPreflightBlockBox(issue, account.email);
148
+ if (ctx.force) {
149
+ console.log(chalk.yellow('! 已携带 --force 参数,跳过前置拦截并继续注入本地配置...\n'));
150
+ return { action: 'force' };
151
+ }
152
+ const interactive = ctx.interactive ?? Boolean(process.stdin.isTTY);
153
+ if (!interactive) {
154
+ console.log(chalk.yellow('已自动中止切换(未改动本机 Cursor 状态)。请先获取新 Token,或追加 --force 强行写入。\n'));
155
+ return { action: 'abort' };
156
+ }
157
+ const hasPureCreds = Boolean(account.email_password || account.cursor_password);
158
+ while (true) {
159
+ const choices = [];
160
+ if (hasPureCreds) {
161
+ choices.push({
162
+ name: '1. 一键纯净代登取 60 天新票并继续切号 (推荐·已存账号凭据)',
163
+ value: 'pure_relogin',
164
+ key: '1',
165
+ description: '复用本地保存的邮箱/账号凭据走纯净代登,取得 60 天客户端新票后继续切号',
166
+ });
167
+ }
168
+ const oauthKey = hasPureCreds ? '2' : '1';
169
+ choices.push({
170
+ name: `${oauthKey}. 立即浏览器 OAuth 授权取 60 天新票并继续切号${hasPureCreds ? '' : ' (推荐)'}`,
171
+ value: 'browser_oauth',
172
+ key: oauthKey,
173
+ description: '打开系统浏览器完成 Cursor 官方授权并同步 60 天客户端新票,完成后自动继续切号',
174
+ });
175
+ choices.push({
176
+ name: '0. 取消切号 (保持当前 Cursor 状态不变)',
177
+ value: 'abort',
178
+ key: '0',
179
+ description: '安全取消操作;原有 web 令牌仍会完整保留,不影响网页端查额度/控制台',
180
+ });
181
+ choices.push({
182
+ name: 'f. 强行写入当前旧凭据 (可能触发重登/二验)',
183
+ value: 'force',
184
+ key: 'f',
185
+ description: '忽略本次前置警告,强行将旧凭据写入 Cursor 本地配置',
186
+ });
187
+ const selected = ctx.selectActionFn
188
+ ? await ctx.selectActionFn(choices, '请选择就地处理方式')
189
+ : await quickSelect({
190
+ message: '请选择就地处理方式(可直接按数字键 1/2/0/f)',
191
+ choices,
192
+ pageSize: 8,
193
+ });
194
+ if (selected === 'abort' || selected === '__cancel__' || selected === '__back__') {
195
+ return { action: 'abort' };
196
+ }
197
+ if (selected === 'force') {
198
+ return { action: 'force' };
199
+ }
200
+ if (selected === 'pure_relogin') {
201
+ const healed = ctx.runPureReloginFn
202
+ ? await ctx.runPureReloginFn(account)
203
+ : await performPureLoginHeal(account, ctx);
204
+ if (healed) {
205
+ console.log(chalk.green(`\n✔ 已通过纯净代登取得 ${healed.email} 最新客户端凭据,正在继续完成切号...\n`));
206
+ return { action: 'replace_account', account: healed };
207
+ }
208
+ console.log(chalk.yellow('\n! 纯净代登未取回新凭据,请重新选择处理方式...\n'));
209
+ continue;
210
+ }
211
+ if (selected === 'browser_oauth') {
212
+ const healed = ctx.runBrowserOAuthFn
213
+ ? await ctx.runBrowserOAuthFn()
214
+ : await performBrowserOAuthHeal(account, ctx.store);
215
+ if (healed) {
216
+ console.log(chalk.green(`\n✔ 已通过浏览器 OAuth 取得 ${healed.email} 最新 60 天客户端凭据,正在继续完成切号...\n`));
217
+ return { action: 'replace_account', account: healed };
218
+ }
219
+ console.log(chalk.yellow('\n! 浏览器 OAuth 未取得新凭据,请重新选择处理方式...\n'));
220
+ }
221
+ }
222
+ }
@@ -0,0 +1,3 @@
1
+ export declare function extractLoopbackCdpPort(wsUrl: string): number | null;
2
+ export declare function buildWin32BrowserFocusScript(port: number, titleHint?: string): string;
3
+ export declare function bringOsBrowserWindowToFront(port: number, titleHint?: string): Promise<boolean>;
@@ -0,0 +1,106 @@
1
+ import { execFile } from 'node:child_process';
2
+ export function extractLoopbackCdpPort(wsUrl) {
3
+ try {
4
+ const parsed = new URL(wsUrl);
5
+ const host = parsed.hostname.toLowerCase();
6
+ if (host !== '127.0.0.1' && host !== 'localhost' && host !== '::1') {
7
+ return null;
8
+ }
9
+ const port = Number(parsed.port);
10
+ return Number.isInteger(port) && port > 0 && port <= 65535 ? port : null;
11
+ }
12
+ catch {
13
+ return null;
14
+ }
15
+ }
16
+ export function buildWin32BrowserFocusScript(port, titleHint = '') {
17
+ const safePort = Math.trunc(port);
18
+ const titleB64 = Buffer.from(titleHint.trim(), 'utf8').toString('base64');
19
+ return [
20
+ `$ProgressPreference = 'SilentlyContinue'`,
21
+ `Add-Type -TypeDefinition @'`,
22
+ `using System;`,
23
+ `using System.Collections.Generic;`,
24
+ `using System.Runtime.InteropServices;`,
25
+ `using System.Text;`,
26
+ `public static class CswitchWinFocus {`,
27
+ ` public delegate bool EnumProc(IntPtr hWnd, IntPtr lParam);`,
28
+ ` [DllImport("user32.dll")] public static extern bool EnumWindows(EnumProc lpEnumFunc, IntPtr lParam);`,
29
+ ` [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid);`,
30
+ ` [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hWnd);`,
31
+ ` [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr hWnd);`,
32
+ ` [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);`,
33
+ ` [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);`,
34
+ ` [DllImport("user32.dll")] public static extern bool BringWindowToTop(IntPtr hWnd);`,
35
+ ` [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd);`,
36
+ ` [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();`,
37
+ ` [DllImport("user32.dll")] public static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);`,
38
+ ` [DllImport("kernel32.dll")] public static extern uint GetCurrentThreadId();`,
39
+ ` [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetWindowText(IntPtr hWnd, StringBuilder sb, int maxCount);`,
40
+ ` [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetClassName(IntPtr hWnd, StringBuilder sb, int maxCount);`,
41
+ ` public static void RaiseWindow(IntPtr hWnd) {`,
42
+ ` if (hWnd == IntPtr.Zero) return;`,
43
+ ` if (IsIconic(hWnd)) { ShowWindow(hWnd, 9); }`,
44
+ ` // 先置顶再取消常驻置顶,突破 Windows 前台焦点锁定让被遮挡的 Chrome 真正弹到终端前面`,
45
+ ` const uint flags = 0x0001 | 0x0002 | 0x0040;`,
46
+ ` SetWindowPos(hWnd, new IntPtr(-1), 0, 0, 0, 0, flags);`,
47
+ ` SetWindowPos(hWnd, new IntPtr(-2), 0, 0, 0, 0, flags);`,
48
+ ` BringWindowToTop(hWnd);`,
49
+ ` IntPtr fg = GetForegroundWindow();`,
50
+ ` uint fgPid = 0;`,
51
+ ` uint fgThread = fg != IntPtr.Zero ? GetWindowThreadProcessId(fg, out fgPid) : 0;`,
52
+ ` uint curThread = GetCurrentThreadId();`,
53
+ ` uint targetPid = 0;`,
54
+ ` uint targetThread = GetWindowThreadProcessId(hWnd, out targetPid);`,
55
+ ` bool attachedFg = false;`,
56
+ ` bool attachedTarget = false;`,
57
+ ` try {`,
58
+ ` if (fgThread != 0 && fgThread != curThread) attachedFg = AttachThreadInput(curThread, fgThread, true);`,
59
+ ` if (targetThread != 0 && targetThread != curThread) attachedTarget = AttachThreadInput(curThread, targetThread, true);`,
60
+ ` SetForegroundWindow(hWnd);`,
61
+ ` BringWindowToTop(hWnd);`,
62
+ ` } finally {`,
63
+ ` if (attachedTarget) AttachThreadInput(curThread, targetThread, false);`,
64
+ ` if (attachedFg) AttachThreadInput(curThread, fgThread, false);`,
65
+ ` }`,
66
+ ` }`,
67
+ `}`,
68
+ `'@`,
69
+ `$portMarker = "--remote-debugging-port=${safePort}"`,
70
+ `$titleHint = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${titleB64}'))`,
71
+ `$targetPids = @(Get-CimInstance Win32_Process -Filter "Name='chrome.exe' OR Name='msedge.exe' OR Name='brave.exe'" -ErrorAction SilentlyContinue | Where-Object { $_.CommandLine -and $_.CommandLine.Contains($portMarker) -and -not $_.CommandLine.Contains('--type=') } | ForEach-Object { [uint32]$_.ProcessId })`,
72
+ `$byPid = New-Object System.Collections.Generic.List[IntPtr]`,
73
+ `$byTitle = New-Object System.Collections.Generic.List[IntPtr]`,
74
+ `[void][CswitchWinFocus]::EnumWindows({`,
75
+ ` param($h, $lp)`,
76
+ ` if (-not [CswitchWinFocus]::IsWindowVisible($h)) { return $true }`,
77
+ ` [uint32]$wp = 0`,
78
+ ` [void][CswitchWinFocus]::GetWindowThreadProcessId($h, [ref]$wp)`,
79
+ ` $sb = New-Object System.Text.StringBuilder 256`,
80
+ ` $cb = New-Object System.Text.StringBuilder 128`,
81
+ ` [void][CswitchWinFocus]::GetWindowText($h, $sb, 256)`,
82
+ ` [void][CswitchWinFocus]::GetClassName($h, $cb, 128)`,
83
+ ` $title = $sb.ToString()`,
84
+ ` $cls = $cb.ToString()`,
85
+ ` if ($targetPids -contains $wp -and $title.Length -gt 0) { $byPid.Add($h) }`,
86
+ ` elseif ($titleHint.Length -ge 4 -and $cls -eq 'Chrome_WidgetWin_1' -and $title.Contains($titleHint)) { $byTitle.Add($h) }`,
87
+ ` return $true`,
88
+ `}, [IntPtr]::Zero)`,
89
+ `$hits = if ($byPid.Count -gt 0) { $byPid } else { $byTitle }`,
90
+ `foreach ($h in $hits) { [CswitchWinFocus]::RaiseWindow($h) }`,
91
+ ].join('\n');
92
+ }
93
+ export function bringOsBrowserWindowToFront(port, titleHint = '') {
94
+ if (process.platform !== 'win32' ||
95
+ process.env.NODE_TEST_CONTEXT ||
96
+ !Number.isInteger(port) ||
97
+ port <= 0 ||
98
+ port > 65535) {
99
+ return Promise.resolve(false);
100
+ }
101
+ const script = buildWin32BrowserFocusScript(port, titleHint);
102
+ const encoded = Buffer.from(script, 'utf16le').toString('base64');
103
+ return new Promise((resolve) => {
104
+ execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-EncodedCommand', encoded], { timeout: 3000, windowsHide: true }, (err) => resolve(!err));
105
+ });
106
+ }
package/package.json CHANGED
@@ -1,11 +1,14 @@
1
1
  {
2
2
  "name": "cursor-switch",
3
- "version": "1.0.6",
3
+ "version": "1.0.8",
4
+ "private": false,
5
+ "edition": "public",
4
6
  "description": "极速、安全、纯本地运行的 Cursor IDE 多账号管理与防封虚拟机器指纹切换纯命令行工具",
5
7
  "author": "aozai",
6
8
  "license": "MIT",
7
9
  "type": "module",
8
10
  "main": "./dist/index.js",
11
+ "types": "./dist/index.d.ts",
9
12
  "bin": {
10
13
  "switch": "bin/cswitch.js",
11
14
  "cswitch": "bin/cswitch.js",
@@ -30,13 +33,16 @@
30
33
  "pure-cli"
31
34
  ],
32
35
  "engines": {
33
- "node": ">=18.0.0"
36
+ "node": ">=22.5.0"
34
37
  },
35
38
  "scripts": {
36
- "build": "tsc",
39
+ "clean": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\"",
40
+ "build": "npm run clean && tsc",
37
41
  "watch": "tsc --watch",
38
42
  "start": "node ./bin/cswitch.js",
39
- "prepublishOnly": "npm run build"
43
+ "test": "npm run build && node --test test/*.test.mjs",
44
+ "guard:publish": "node ./scripts/guard-publish.mjs",
45
+ "prepublishOnly": "npm run build && npm test && npm run guard:publish"
40
46
  },
41
47
  "dependencies": {
42
48
  "@inquirer/core": "^10.3.2",
@@ -45,7 +51,8 @@
45
51
  "chalk": "^5.4.1",
46
52
  "cli-table3": "^0.6.5",
47
53
  "commander": "^13.1.0",
48
- "open": "^10.1.0"
54
+ "open": "^10.1.0",
55
+ "undici": "^7.30.0"
49
56
  },
50
57
  "devDependencies": {
51
58
  "@types/node": "^24.0.0",