import type { Filter , Request } from './types' ; import * as isGlob from 'is-glob' ; import * as micromatch from 'micromatch' ; import * as url from 'url' ; import { ERRORS } from './errors' ; export function match ( context , uri , req ) { if ( isStringPath ( context as string ) ) { return matchSingleStringPath ( context as string , uri ) ; } if ( isGlobPath ( context as string ) ) { return matchSingleGlobPath ( context as string [ ] , uri ) ; } if ( Array . isArray ( context ) ) { if ( context . every ( isStringPath ) ) { return matchMultiPath ( context , uri ) ; } if ( context . every ( isGlobPath ) ) { return matchMultiGlobPath ( context as string [ ] , uri ) ; } throw new Error ( ERRORS . ERR_CONTEXT_MATCHER_INVALID_ARRAY ) ; } if ( typeof context === 'function' ) { const pathname = getUrlPathName ( uri ) ; return context ( pathname , req ) ; } throw new Error ( ERRORS . ERR_CONTEXT_MATCHER_GENERIC ) ; } param { String } context param { String } uri return { Boolean } function matchSingleStringPath ( context , uri ) { const pathname = getUrlPathName ( uri ) ; return pathname . indexOf ( context ) === 0 ; } function matchSingleGlobPath ( pattern , uri ) { const pathname = getUrlPathName ( uri ) ; const matches = micromatch ( [ pathname ] , pattern ) ; return matches && matches . length > 0 ; } function matchMultiGlobPath ( patternList , uri ) { return matchSingleGlobPath ( patternList , uri ) ; } param { String } contextList param { String } uri return { Boolean } function matchMultiPath ( contextList , uri ) { let isMultiPath = false ; for ( const context of contextList ) { if ( matchSingleStringPath ( context , uri ) ) { isMultiPath = true ; break ; } } return isMultiPath ; } param { String } uri return { String } function getUrlPathName ( uri ) { return uri && url . parse ( uri ) . pathname ; } function isStringPath ( context ) { return typeof context === 'string' && ! isGlob ( context ) ; } function isGlobPath ( context ) { return isGlob ( context ) ; }