import url from 'url' ; import net from 'net' ; import address from 'address' ; import { env } from './env' ; export interface ServiceUrl { url : string ; port : number ; host : string ; } interface InternalServiceUrls { local : ServiceUrl ; network : ServiceUrl ; } export const DEFAULT_PORT = 3000 ; param port private const _findPort = async ( port ) => { return new Promise ( ( resolve , reject ) => { const server = net . createConnection ( { port } ) ; server . on ( 'connect' , ( ) => { server . end ( ) ; reject ( ) ; } ) . on ( 'error' , ( ) => resolve ( port ) ) ; } ) ; } ; param port export const getDefaultPort = ( port ? ) : number => { if ( port ) { const numeric = parseInt ( port , 10 ) ; if ( isNaN ( numeric ) ) { return DEFAULT_PORT ; } return numeric ; } return DEFAULT_PORT ; } ; param startPort export const findPort = async ( startPort = 3000 ) : Promise < number > => { try { await Promise . all ( [ _findPort ( startPort ) ] ) ; return startPort ; } catch ( e ) { return findPort ( startPort + 1 ) ; } } ; param port export const getLocalAndNetworkUrls = ( port ) : InternalServiceUrls => { const protocol = env . isHTTPS ( ) ? 'https' : 'http' ; const localUrl = url . format ( { protocol , port , hostname : 'localhost' , pathname : '/' , } ) ; const networkUrl = url . format ( { protocol , port , hostname : address . ip ( ) , pathname : '/' , } ) ; return { local : { url : localUrl , port , host : '0.0.0.0' , } , network : { url : networkUrl , port , host : address . ip ( ) , } , } ; } ; export default url ;