okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
64b48c0d0
main
1/** Ports the host listens on: a free one for the helpers, and a plain sentence when the main one cannot be taken. */ 2import net from 'node:net' ; 3 4/** Why a listen failed, in words a person can act on (Windows keeps whole ranges for Hyper-V, WSL and Docker). */ 5export function listenProblem ( error , port , host = '127.0.0.1' , platform = process . platform ) { 6const code = error ?. code ; 7if ( code === 'EADDRINUSE' ) return `Port ${ port } is already in use. Strata may already be running; close it or the other program, or start Strata with another port (STRATA_PORT).` ; 8if ( code === 'EACCES' && platform !== 'win32' ) return `This system does not let Strata use port ${ port } . On Linux and macOS, ports below 1024 need administrator rights. Start Strata with another port (STRATA_PORT), for example 8801.` ; 9if ( code === 'EACCES' ) return `Windows or a firewall does not let Strata use port ${ port } . Hyper-V, WSL and Docker keep ranges of ports for themselves (see "netsh int ipv4 show excludedportrange protocol=tcp"). Start Strata with another port (STRATA_PORT), for example 8801.` ; 10if ( code === 'EADDRNOTAVAIL' ) return ` ${ host } is not an address of this computer, so Strata cannot listen on it. Check STRATA_BIND.` ; 11return `Strata cannot listen on ${ host } : ${ port } ( ${ error ?. message ?? code } ).` ; 12} 13 14function tryListen ( port , host ) { 15return new Promise ( resolve => { 16const probe = net . createServer (); 17probe . once ( 'error' , () => resolve ( null )); 18probe . listen ( port , host , () => { const got = probe . address (). port ; probe . close (() => resolve ( got )); }); 19}); 20} 21 22/** `preferred` when it can be taken, else the next free port above it (up to `tries` of them), else any free port. Never throws. */ 23export async function findFreePort ( preferred , host = '127.0.0.1' , { skip= [], tries= 20 } = {}) { 24for ( let offset = 0 ; offset < tries ; offset ++ ) { 25const port = preferred + offset ; 26if ( port > 65535 || skip . includes ( port )) continue ; 27const got = await tryListen ( port , host ); 28if ( got ) return got ; 29} 30return ( await tryListen ( 0 , host )) ?? preferred ; 31}