remcode
Version:
Turn your AI assistant into a codebase expert. Intelligent code analysis, semantic search, and software engineering guidance through MCP integration.
89 lines (88 loc) • 3.25 kB
JavaScript
/**
* Port Management Utilities
*
* Handles smart port selection with auto-increment and availability checking
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PortManager = void 0;
const net_1 = require("net");
const chalk_1 = __importDefault(require("chalk"));
const logger_1 = require("./logger");
const logger = (0, logger_1.getLogger)('PortManager');
/**
* Port Manager class for handling port selection
*/
class PortManager {
/**
* Check if a port is available
*/
static async isPortAvailable(port) {
// Check both IPv4 and IPv6
const ipv4Available = await this.checkPortOnInterface(port, '127.0.0.1');
const ipv6Available = await this.checkPortOnInterface(port, '::1');
return ipv4Available && ipv6Available;
}
/**
* Check if a port is available on a specific interface
*/
static async checkPortOnInterface(port, host) {
return new Promise((resolve) => {
const server = (0, net_1.createServer)();
server.listen(port, host, () => {
server.close(() => {
resolve(true);
});
});
server.on('error', () => {
resolve(false);
});
});
}
/**
* Find an available port starting from the preferred port
*/
static async findAvailablePort(preferredPort, maxAttempts = 10) {
let currentPort = preferredPort;
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const available = await this.isPortAvailable(currentPort);
if (available) {
return {
port: currentPort,
available: true,
autoSelected: attempt > 0
};
}
logger.info(`Port ${currentPort} is busy, trying ${currentPort + 1}`);
currentPort++;
}
return {
port: preferredPort,
available: false
};
}
/**
* Get an available port with user-friendly messaging
*/
static async getAvailablePort(preferredPort) {
console.log(chalk_1.default.gray(`🔍 Checking port availability...`));
const result = await this.findAvailablePort(preferredPort);
if (!result.available) {
console.log(chalk_1.default.red(`❌ Could not find an available port after ${preferredPort + 9}`));
console.log(chalk_1.default.yellow(`💡 Try specifying a different port: --port ${preferredPort + 100}`));
throw new Error(`No available ports found starting from ${preferredPort}`);
}
if (result.autoSelected) {
console.log(chalk_1.default.yellow(`⚠ Port ${preferredPort} was busy`));
console.log(chalk_1.default.green(`✅ Auto-selected available port: ${result.port}`));
}
else {
console.log(chalk_1.default.green(`✅ Port ${result.port} is available`));
}
return result.port;
}
}
exports.PortManager = PortManager;
;