import { promisify } from "util";
import { getPorts as getPorts0 } from "portfinder";
import LRU from "lru-cache";
const getPortsUnsafe = promisify(getPorts0);
const cache = new LRU<number, true>({
ttl: 60000,
max: 10000,
});
export default async function getPorts(
n: number,
options: {
port?: number;
stopPort?: number;
} = {}
): Promise<number[]> {
const ports: number[] = [];
while (ports.length < n) {
for (const port of await getPortsUnsafe(n - ports.length, options)) {
if (!cache.has(port)) {
cache.set(port, true);
ports.push(port);
}
}
if (ports.length < n) {
options = { ...options, port: (options.port ?? 8000) + 1 };
}
}
return ports;
}