forked from somersby10ml/win-claude-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrunner.js
More file actions
463 lines (390 loc) · 15.5 KB
/
Copy pathrunner.js
File metadata and controls
463 lines (390 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
#!/usr/bin/env node
import { execSync, spawn } from 'child_process';
import path from 'path';
import fs from 'fs';
import { syncBuiltinESMExports, createRequire } from 'module';
import os from 'os';
(async () => {
const originalMethods = {
error: console.error.bind(console),
warn: console.warn.bind(console),
log: console.log.bind(console)
};
const originalConsole = {
error: (...args) => originalMethods.error('[win-claude-code]', ...args),
warn: (...args) => originalMethods.warn('[win-claude-code]', ...args),
log: (...args) => originalMethods.log('[win-claude-code]', ...args)
};
let gitBashPath = null;
async function main() {
const npmGlobalRoot = await getNpmGlobalRoot();
const claudePath = path.join(npmGlobalRoot, '@anthropic-ai', 'claude-code');
const packageInstalled = fs.existsSync(path.join(claudePath, 'package.json'));
if (!packageInstalled) {
originalConsole.error('Claude Code package is not installed globally. Please run "npm install -g @anthropic-ai/claude-code --ignore-scripts"');
return;
}
const cliPath = path.join(claudePath, 'cli.js');
if (!fs.existsSync(cliPath)) {
originalConsole.error('CLI script is not found. Please ensure it is installed correctly.');
return;
}
gitBashPath = findGitBashPath();
if (!gitBashPath) {
originalConsole.warn('Git Bash not found - Unix commands (grep, find, awk, sed) will not be available');
originalConsole.warn('To enable Unix commands, install Git for Windows: https://git-scm.com/download/win');
originalConsole.warn('After installation, restart your terminal and run win-claude-code again');
}
hook();
await import(`file://${cliPath}`).catch(err => {
originalConsole.error('Error importing CLI script:', err);
});
}
const hook = () => {
// Claude IDE Lock File Path Conversion Hook
// Converts POSIX paths to Windows paths for IDE compatibility
// Transforms /mnt/c/path to C:\path format in workspaceFolders
try {
const originalReadFileSync = fs.readFileSync;
fs.readFileSync = function (path, options) {
const result = originalReadFileSync.apply(this, arguments);
const fileName = String(path).toString();
const isClaudeIdeLockFile = /\.claude[\\\/]ide[\\\/]\d+\.lock$/i.test(fileName);
if (isClaudeIdeLockFile) {
try {
const jsonContent = JSON.parse(result.toString());
if (jsonContent && Array.isArray(jsonContent.workspaceFolders)) {
jsonContent.workspaceFolders = jsonContent.workspaceFolders.map(folder => {
if (typeof folder === 'string') {
if (folder.startsWith('/mnt/')) {
// Remove /mnt/ prefix
const withoutMnt = folder.substring(5);
// Check if drive letter exists
if (withoutMnt.length > 0) {
// Convert drive letter to uppercase and add colon
const driveLetter = withoutMnt[0].toUpperCase();
const restPath = withoutMnt.substring(1);
// Convert to Windows path format (C:\path)
return driveLetter + ':' + restPath.replace(/\//g, '\\');
}
}
// Handle existing Windows paths - ensure drive letter is uppercase
else if (/^[a-zA-Z]:[\\\/]/.test(folder)) {
const driveLetter = folder[0].toUpperCase();
const restPath = folder.substring(1);
// Ensure consistent backslash separators and uppercase drive
return driveLetter + restPath.replace(/\//g, '\\');
}
}
return folder;
});
const modifiedResult = JSON.stringify(jsonContent);
if (result instanceof Buffer) {
return Buffer.from(modifiedResult);
} else {
return modifiedResult;
}
}
} catch (error) {
// Silently continue with original result if JSON parsing fails
}
}
return result;
};
} catch (error) {
}
// Hook execFile to intercept cursor extension commands
// Prevents actual IDE from launching and returns extension list from filesystem
try {
// TODO: what is `cursor --force --install-extension C:\Users\admin\AppData\Local\nvm\v22.11.0\node_modules\@anthropic-ai\claude-code\vendor\claude-code.vsix`?
// TODO: It looks like you're forcing the extension to install, but think about how you want to handle it in the future.
const require = createRequire(import.meta.url);
const childProcess = require('child_process');
const originalExecFile = childProcess.execFile;
// Custom execFile hook that intercepts IDE extension commands
const hookedExecFile = function (file, args, options, callback) {
// Handle parameter variations exactly like original execFile
let actualArgs = args;
let actualOptions = options;
let actualCallback = callback;
// execFile(file, callback)
if (typeof args === 'function') {
actualCallback = args;
actualArgs = undefined;
actualOptions = undefined;
}
// execFile(file, args, callback)
else if (typeof options === 'function') {
actualCallback = options;
actualOptions = undefined;
}
// Only intercept if we have valid args array and it contains --list-extensions
const isCursorExtensionListCommand = (
file === 'cursor' &&
Array.isArray(actualArgs) &&
actualArgs.includes('--list-extensions')
);
if (isCursorExtensionListCommand) {
// Check if --show-versions flag is present
const includeVersion = actualArgs.includes('--show-versions');
// Get extension list using our function for Cursor
const extensionList = getIdeExtensionList('.cursor', includeVersion);
const stdout = extensionList.join('\n');
const stderr = '';
// Call callback asynchronously to simulate real execFile behavior
if (typeof actualCallback === 'function') {
process.nextTick(() => {
actualCallback(null, stdout, stderr);
});
}
// Return a mock child process object
return {
pid: process.pid,
stdout: { on: () => { }, pipe: () => { } },
stderr: { on: () => { }, pipe: () => { } },
on: () => { },
kill: () => { }
};
}
// For non-extension commands, call original execFile with exact same parameters
// Preserve original parameter structure
if (typeof args === 'function') {
return originalExecFile.call(this, file, args);
} else if (typeof options === 'function') {
return originalExecFile.call(this, file, args, options);
} else {
return originalExecFile.call(this, file, args, options, callback);
}
};
// Replace the execFile method
childProcess.execFile = hookedExecFile;
} catch (error) {
originalConsole.error('[EXECFILE HOOK] Failed to hook execFile method:', error.message);
}
// F2 Key Hook (originally Shift + Tab, changed for Windows compatibility)
// plan mode or auto-accept mode
const originalStdin = process.stdin;
const fakeStdin = Object.create(originalStdin);
fakeStdin.read = function (...args) {
const result = originalStdin.read.apply(originalStdin, args);
if (result && result.toString().includes('\x1b[[B')) {
return Buffer.from('\x1b[Z');
}
return result;
};
Object.defineProperty(process, 'stdin', {
value: fakeStdin,
writable: false,
configurable: false
});
const originalAccessSync = fs.accessSync;
fs.accessSync = function (...args) {
if (args.length >= 2 && typeof args[0] === 'string' && args[0].includes('/bin/bash') && args[1] === 1) {
return true;
}
return originalAccessSync.apply(this, args);
};
const originalTmpdir = os.tmpdir;
os.tmpdir = function () {
const windowsTmpPath = originalTmpdir.call(this);
const unixTmpPath = windowsToPosix(windowsTmpPath);
return unixTmpPath;
};
// const originalLstat = fs.lstat;
// fs.lstat = function (path, options, callback) {
// console.log('[lstat]', path);
// if (typeof options === 'function') {
// callback = options;
// options = {};
// }
// const posixPath = windowsToPosix(path);
// return originalLstat.call(this, posixPath, options, callback);
// };
// const originalLstatSync = fs.lstatSync;
// fs.lstatSync = function (path, options) {
// console.log('[lstatSync]', path);
// const posixPath = windowsToPosix(path);
// return originalLstatSync.call(this, posixPath, options);
// };
// // realpath 후킹 - Windows 경로를 POSIX 경로로 변환 후 호출
// const originalRealpath = fs.realpath;
// fs.realpath = function (path, options, callback) {
// console.log('[realpath]', path);
// if (typeof options === 'function') {
// callback = options;
// options = {};
// }
// const posixPath = windowsToPosix(path);
// return originalRealpath.call(this, posixPath, options, callback);
// };
// const originalRealpathSync = fs.realpathSync;
// fs.realpathSync = function (path, options) {
// console.log('[realpathSync]', path);
// const posixPath = windowsToPosix(path);
// return originalRealpathSync.call(this, posixPath, options);
// };
// const originalJoin = path.join;
// path.join = function (...args) {
// console.log(args);
// const result = originalJoin.apply(this, args);
// return windowsToPosix(result);
// };
// const originalResolve = path.resolve;
// path.resolve = function (...args) {
// console.log(args);
// const result = originalResolve.apply(this, args);
// return windowsToPosix(result);
// };
if (gitBashPath) {
const originalSpawn = spawn;
const spawnHook = function (command, args = [], options = {}) {
try {
if (command === '/bin/bash') {
command = gitBashPath;
}
return originalSpawn.call(this, command, args, options);
}
catch (error) {
originalConsole.error('spawn error:', error);
throw error;
}
};
// Replace spawn function
try {
// Replace spawn in CommonJS modules (using createRequire)
const require = createRequire(import.meta.url);
const childProcess = require('child_process');
if (childProcess && childProcess.spawn) {
childProcess.spawn = spawnHook;
}
// Also register spawn in global (so other code can use it)
if (typeof global !== 'undefined') {
global.spawn = spawnHook;
}
} catch (e) {
originalConsole.warn('Could not hook spawn function:', e.message);
}
}
// think about this...
// process.env.SHELL = 'bash';
// try {
// const require = createRequire(import.meta.url); // import createRequire from 'module'
// const nodeFs = require('fs');
// if (nodeFs && nodeFs.accessSync) {
// nodeFs.accessSync = function (...args) {
// return true;
// };
// }
// } catch (e) {
// originalConsole.error('[win-cursor] Could not patch Node.js fs module');
// }
// try {
// Object.defineProperty(fs, 'accessSync', {
// value: function (...args) {
// return true;
// },
// writable: false,
// configurable: true
// });
// } catch (e) {
// originalConsole.error('[win-cursor] Could not override fs.accessSync with defineProperty');
// }
try {
syncBuiltinESMExports();
} catch (e) {
// Silently ignore sync errors - not critical for operation
}
}
// Automatically add Git Bash path
const findGitBashPath = () => {
const possibleGitPaths = [
`C:/Program Files/Git/usr/bin/bash.exe`,
`C:/Program Files (x86)/Git/usr/bin/bash.exe`,
];
for (const gitPath of possibleGitPaths) {
if (fs.existsSync(gitPath)) {
return gitPath;
}
}
return false;
};
const windowsToPosix = (path) => {
return path
.replace(/\\/g, '/') // \ → /
.replace(/^([A-Z]):/i, '/$1') // C: → /c
.toLowerCase() // 소문자로
.replace(/^\/[a-z]/, match => match.toLowerCase());
}
const getNpmGlobalRoot = () => {
try {
const result = execSync('npm root -g', {
encoding: 'utf8',
timeout: 10000 // 10 seconds timeout
});
const rootPath = result.trim();
if (!rootPath) {
throw new Error('npm root -g returned empty result');
}
return rootPath;
} catch (error) {
if (error.code === 'ENOENT') {
throw new Error('npm command not found. Please ensure npm is installed and available in PATH');
}
if (error.signal === 'SIGTERM') {
throw new Error('npm root -g command timed out');
}
throw new Error(`Failed to get npm global root: ${error.message}`);
}
}
/**
* Reads installed IDE extensions from filesystem instead of launching the IDE
* @param {string} ideDirectory - IDE directory name (default: '.cursor')
* @param {boolean} includeVersion - Whether to include version in format 'id@version' (default: false)
* @returns {string[]} Array of extension IDs or extension IDs with versions
* @throws Returns empty array on any error (file not found, parse error, etc.)
*/
const getIdeExtensionList = (ideDirectory = '.cursor', includeVersion = false) => {
try {
// Construct %USERPROFILE%/{ideDirectory}/extensions/extensions.json path
const homeDir = os.homedir();
const extensionsJsonPath = path.join(homeDir, ideDirectory, 'extensions', 'extensions.json');
// Check if file exists
if (!fs.existsSync(extensionsJsonPath)) {
return [];
}
// Read file and parse JSON
const fileContent = fs.readFileSync(extensionsJsonPath, 'utf8');
const extensionsData = JSON.parse(fileContent);
// Check if it's an array
if (!Array.isArray(extensionsData)) {
return [];
}
// Extract extension list
const extensionList = [];
for (const extension of extensionsData) {
// Check identifier.id and version properties
if (extension &&
extension.identifier &&
extension.identifier.id &&
extension.version) {
const extensionId = extension.identifier.id;
const extensionVersion = extension.version;
if (includeVersion === true) {
// When includeVersion = true: return extension ID@version format
extensionList.push(`${extensionId}@${extensionVersion}`);
} else {
// When includeVersion = false: return extension ID only
extensionList.push(extensionId);
}
}
}
return extensionList;
} catch (error) {
// Return empty array if file reading or parsing error occurs
return [];
}
}
main().catch(err => {
originalConsole.error('Error in main function:', err);
});
})();