Nuxt/packages/kit/src/resolve.ts

153 lines
4.4 KiB
TypeScript
Raw Normal View History

import { existsSync, promises as fsp } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { basename, dirname, isAbsolute, join, normalize, resolve } from 'pathe'
import { globby } from 'globby'
import { resolvePath as _resolvePath } from 'mlly'
import { resolveAlias as _resolveAlias } from 'pathe/utils'
import { tryUseNuxt } from './context'
import { isIgnored } from './ignore'
2020-07-02 13:02:35 +00:00
export interface ResolvePathOptions {
/** Base for resolving paths from. Default is Nuxt rootDir. */
cwd?: string
/** An object of aliases. Default is Nuxt configured aliases. */
alias?: Record<string, string>
/** The file extensions to try. Default is Nuxt configured extensions. */
extensions?: string[]
2020-07-02 13:02:35 +00:00
}
/**
* Resolve full path to a file or directory respecting Nuxt alias and extensions options
*
* If path could not be resolved, normalized input path will be returned
*/
export async function resolvePath (path: string, opts: ResolvePathOptions = {}): Promise<string> {
// Always normalize input
const _path = path
path = normalize(path)
2021-04-15 18:49:29 +00:00
// Fast return if the path exists
if (isAbsolute(path) && existsSync(path) && !(await isDirectory(path))) {
return path
2020-07-02 13:02:35 +00:00
}
// Use current nuxt options
const nuxt = tryUseNuxt()
const cwd = opts.cwd || (nuxt ? nuxt.options.rootDir : process.cwd())
const extensions = opts.extensions || (nuxt ? nuxt.options.extensions : ['.ts', '.mjs', '.cjs', '.json'])
const modulesDir = nuxt ? nuxt.options.modulesDir : []
2020-07-02 13:02:35 +00:00
// Resolve aliases
path = resolveAlias(path)
2020-07-02 13:02:35 +00:00
// Resolve relative to cwd
if (!isAbsolute(path)) {
path = resolve(cwd, path)
}
// Check if resolvedPath is a file
let _isDir = false
if (existsSync(path)) {
_isDir = await isDirectory(path)
if (!_isDir) {
return path
}
2020-07-02 13:02:35 +00:00
}
// Check possible extensions
for (const ext of extensions) {
// path.[ext]
const pathWithExt = path + ext
if (existsSync(pathWithExt)) {
return pathWithExt
}
// path/index.[ext]
const pathWithIndex = join(path, 'index' + ext)
if (_isDir && existsSync(pathWithIndex)) {
return pathWithIndex
2020-07-02 13:02:35 +00:00
}
}
// Try to resolve as module id
const resolveModulePath = await _resolvePath(_path, { url: [cwd, ...modulesDir] }).catch(() => null)
if (resolveModulePath) {
return resolveModulePath
2020-07-02 13:02:35 +00:00
}
// Return normalized input
return path
2020-07-02 13:02:35 +00:00
}
/**
* Try to resolve first existing file in paths
*/
export async function findPath (paths: string | string[], opts?: ResolvePathOptions, pathType: 'file' | 'dir' = 'file'): Promise<string | null> {
if (!Array.isArray(paths)) {
paths = [paths]
}
for (const path of paths) {
const rPath = await resolvePath(path, opts)
if (await existsSensitive(rPath)) {
const _isDir = await isDirectory(rPath)
if (!pathType || (pathType === 'file' && !_isDir) || (pathType === 'dir' && _isDir)) {
return rPath
}
}
}
return null
}
2021-04-15 18:49:29 +00:00
/**
* Resolve path aliases respecting Nuxt alias options
2021-04-15 18:49:29 +00:00
*/
export function resolveAlias (path: string, alias?: Record<string, string>): string {
if (!alias) {
alias = tryUseNuxt()?.options.alias || {}
}
return _resolveAlias(path, alias)
2020-07-02 13:02:35 +00:00
}
export interface Resolver {
resolve (...path: string[]): string
resolvePath (path: string, opts?: ResolvePathOptions): Promise<string>
}
/**
* Create a relative resolver
*/
export function createResolver (base: string | URL): Resolver {
if (!base) {
throw new Error('`base` argument is missing for createResolver(base)!')
}
base = base.toString()
if (base.startsWith('file://')) {
base = dirname(fileURLToPath(base))
}
return {
resolve: (...path) => resolve(base as string, ...path),
resolvePath: (path, opts) => resolvePath(path, { cwd: base as string, ...opts })
}
}
// --- Internal ---
async function existsSensitive (path: string) {
if (!existsSync(path)) { return false }
const dirFiles = await fsp.readdir(dirname(path))
return dirFiles.includes(basename(path))
2020-07-02 13:02:35 +00:00
}
2023-01-19 13:20:53 +00:00
// Usage note: We assume path existence is already ensured
async function isDirectory (path: string) {
return (await fsp.lstat(path)).isDirectory()
}
export async function resolveFiles (path: string, pattern: string | string[], opts: { followSymbolicLinks?: boolean } = {}) {
const files = await globby(pattern, { cwd: path, followSymbolicLinks: opts.followSymbolicLinks ?? true })
return files.map(p => resolve(path, p)).filter(p => !isIgnored(p)).sort()
}