diff --git a/src/index.js b/src/index.js index 12ea2b6..57a3f5e 100755 --- a/src/index.js +++ b/src/index.js @@ -438,25 +438,44 @@ Prototype REPL - https://github.com/nodejs/repl } } -const child = spawn(process.execPath, [ - '--inspect-publish-uid=http', - ...process.execArgv, - require.resolve('./stub.js'), - ...process.argv, -], { - cwd: process.cwd(), - windowsHide: true, -}); - -child.stdout.on('data', (data) => { - process.stdout.write(data); -}); - -child.stderr.on('data', (data) => { - const s = data.toString(); - if (s.startsWith('__DEBUGGER_URL__')) { - start(s.split(' ')[1]); - } else if (s !== 'Debugger attached.\n') { - process.stderr.write(data); - } -}); +const net = require('net'); + +function findAvailablePort(startPort = 9229) { + return new Promise((resolve, reject) => { + const server = net.createServer(); + server.listen(startPort, '127.0.0.1', () => { + const port = server.address().port; + server.close(() => resolve(port)); + }); + server.on('error', (err) => { + if (err.code === 'EADDRINUSE') { + resolve(findAvailablePort(startPort + 1)); + } else { + reject(err); + } + }); + }); +} + +findAvailablePort().then(port => { + const child = spawn(process.execPath, [ + `--inspect=${port}`, + `--inspect-publish-uid=http`, + require.resolve('./stub.js'), + ...process.argv, + ], { + cwd: process.cwd(), + windowsHide: true, + }); + child.stdout.on('data', (data) => { + process.stdout.write(data); + }); + child.stderr.on('data', (data) => { + const s = data.toString(); + if (s.startsWith('__DEBUGGER_URL__')) { + start(s.split(' ')[1]); + } else if (s !== 'Debugger attached.\n') { + process.stderr.write(data); + } + }); +}); \ No newline at end of file diff --git a/src/stub.js b/src/stub.js index a7c8866..ceefe84 100644 --- a/src/stub.js +++ b/src/stub.js @@ -5,7 +5,22 @@ const path = require('path'); const inspector = require('inspector'); const util = require('util'); -inspector.open(0, true); +// Handle inspector.open() API differences across Node.js versions +if (!inspector.url()) { + try { + // Try Node.js v24+ API (host, port) + inspector.open(9229, '127.0.0.1'); + } catch (err) { + // Fall back to Node.js v20 and below API (fd, host, port) + try { + inspector.open(0, 'localhost', 9229); + } catch (fallbackErr) { + // If both fail, continue without debugger + console.error('Failed to open inspector:', fallbackErr.message); + } + } +} + process.stderr.write(`__DEBUGGER_URL__ ${inspector.url()}`); if (process.platform !== 'win32') {