"use strict" ;
const defaultValue = require ( "default-value" ) ;
const url = require ( "url" ) ;
const ValidationError = require ( "@validatem/error" ) ;
const isString = require ( "@validatem/is-string" ) ;
module . exports = function ( options = { } ) {
let parse = defaultValue ( options . parse , true ) ;
let protocols = options . protocols ;
if ( Array . isArray ( options ) ) { // keep compatibility with <=0.2.0
protocols = options ;
options = { } ;
}
if ( protocols != null && ! Array . isArray ( protocols ) ) {
throw new Error ( ` Permitted protocol list must be an array ` ) ;
}
let protocolSet = ( protocols != null )
? new Set ( protocols . map ( ( protocol ) => protocol . toLowerCase ( ) ) )
: null ;
return [
isString ,
function isURL ( value ) {
let parsed = url . parse ( value ) ;
let slashes = ( parsed . slashes === true )
? "//"
: "" ;
let parsedProtocol = ( parsed . protocol != null )
? parsed . protocol + slashes
: null ;
if ( parsedProtocol == null ) {
return new ValidationError ( "Must be a valid URL" , { code : "validatem.is-url.invalid-url" } ) ;
} else if ( protocolSet != null && ! protocolSet . has ( parsedProtocol . toLowerCase ( ) ) ) {
let validProtocolList = protocols
. map ( ( protocol ) => protocol . toUpperCase ( ) )
. join ( ", " ) ;
return new ValidationError ( ` Must be a URL with one of the following protocols: ${ validProtocolList } - but got ${ parsedProtocol . toUpperCase ( ) } instead ` , { code : "validatem.is-url.wrong-protocol" } ) ;
} else {
if ( parse ) {
return parsed ;
} else {
return value ;
}
}
}
] ;
} ;