import { format as formatUrl , parse as parseUrl , UrlObject } from 'url' ; import type { ParsedQuery } from 'query-string' ; public export interface URLMeaningfulParts { auth ? : string | null ; hash ? : string | null ; hostname ? : string | null ; pathname ? : string | null ; protocol ? : string | null ; slashes ? : boolean | null ; port ? : string | null ; query : ParsedQuery ; } param url param urlModifier returns public export function modifyUrl ( url , urlModifier ) { const parsed = parseUrl ( url , true ) as URLMeaningfulParts ; const meaningfulParts = { auth : parsed . auth , hash : parsed . hash , hostname : parsed . hostname , pathname : parsed . pathname , port : parsed . port , protocol : parsed . protocol , query : parsed . query || { } , slashes : parsed . slashes , } ; const modifiedParts = urlModifier ( meaningfulParts ) || meaningfulParts ; return formatUrl ( { auth : modifiedParts . auth , hash : modifiedParts . hash , hostname : modifiedParts . hostname , pathname : modifiedParts . pathname , port : modifiedParts . port , protocol : modifiedParts . protocol , query : modifiedParts . query , slashes : modifiedParts . slashes , } as UrlObject ) ; } public export function isRelativeUrl ( candidatePath ) { const all = parseUrl ( candidatePath , false , true ) ; const { protocol , hostname , port } = all ; if ( protocol !== null || hostname !== null || port !== null ) { return false ; } return true ; } /**
 * Returns the origin (protocol + host + port) from given `url` if `url` is a valid absolute url, or null otherwise
 */ export function getUrlOrigin ( url ) { const obj = parseUrl ( url ) ; if ( ! obj . protocol && ! obj . hostname ) { return null ; } return `${ obj . protocol }//${ obj . hostname }${ obj . port ? `:${ obj . port }` : '' }` ; }