import * as path from "path" ; import * as Filesystem from "./filesystem" ; import * as MappingEntry from "./mapping-entry" ; import * as TryPath from "./try-path" ; /**
 * Function that can match a path
 */ export interface MatchPath { ( requestedModule , readJson ? , fileExists ? , extensions ? ) : string | undefined ; } param absoluteBaseUrl param paths param mainFields param addMatchAll returns export function createMatchPath ( absoluteBaseUrl , paths , mainFields = [ "main" ] , addMatchAll = true ) { const absolutePaths = MappingEntry . getAbsoluteMappingEntries ( absoluteBaseUrl , paths , addMatchAll ) ; return ( requestedModule , readJson ? , fileExists ? , extensions ? ) => matchFromAbsolutePaths ( absolutePaths , requestedModule , readJson , fileExists , extensions , mainFields ) ; } param absolutePathMappings param requestedModule param readJson param fileExists param extensions param mainFields returns export function matchFromAbsolutePaths ( absolutePathMappings , requestedModule , readJson = Filesystem . readJsonFromDiskSync , fileExists = Filesystem . fileExistsSync , extensions = Object . keys ( require . extensions ) , mainFields = [ "main" ] ) { const tryPaths = TryPath . getPathsToTry ( extensions , absolutePathMappings , requestedModule ) ; if ( ! tryPaths ) { return undefined ; } return findFirstExistingPath ( tryPaths , readJson , fileExists , mainFields ) ; } function findFirstExistingMainFieldMappedFile ( packageJson , mainFields , packageJsonPath , fileExists ) { for ( let index = 0 ; index < mainFields . length ; index ++ ) { const mainFieldName = mainFields [ index ] ; const candidateMapping = packageJson [ mainFieldName ] ; if ( candidateMapping && typeof candidateMapping === "string" ) { const candidateFilePath = path . join ( path . dirname ( packageJsonPath ) , candidateMapping ) ; if ( fileExists ( candidateFilePath ) ) { return candidateFilePath ; } } } return undefined ; } function findFirstExistingPath ( tryPaths , readJson = Filesystem . readJsonFromDiskSync , fileExists , mainFields = [ "main" ] ) { for ( const tryPath of tryPaths ) { if ( tryPath . type === "file" || tryPath . type === "extension" || tryPath . type === "index" ) { if ( fileExists ( tryPath . path ) ) { return TryPath . getStrippedPath ( tryPath ) ; } } else if ( tryPath . type === "package" ) { const packageJson = readJson ( tryPath . path ) ; if ( packageJson ) { const mainFieldMappedFile = findFirstExistingMainFieldMappedFile ( packageJson , mainFields , tryPath . path , fileExists ) ; if ( mainFieldMappedFile ) { return Filesystem . removeExtension ( mainFieldMappedFile ) ; } } } else { TryPath . exhaustiveTypeException ( tryPath . type ) ; } } return undefined ; }