UNPKG

astro

Version:

Astro is a modern site builder with web best practices, performance, and DX front-of-mind.

68 lines (67 loc) • 2.69 kB
import { fileURLToPath } from "node:url"; import { commonAncestorPath } from "common-ancestor-path"; import { appendExtension, appendForwardSlash, removeLeadingForwardSlashWindows } from "../core/path.js"; import { viteID } from "../core/util.js"; export function getFileInfo(id, config) { const sitePathname = appendForwardSlash(config.site ? new URL(config.base, config.site).pathname : config.base); const fileId = id.split("?")[0]; let fileUrl = fileId.includes("/pages/") ? fileId.replace(/^.*?\/pages\//, sitePathname).replace(/(?:\/index)?\.(?:md|markdown|mdown|mkdn|mkd|mdwn|astro)$/, "") : undefined; if (fileUrl && config.trailingSlash === "always") { fileUrl = appendForwardSlash(fileUrl); } if (fileUrl && config.build.format === "file") { fileUrl = appendExtension(fileUrl, "html"); } return { fileId, fileUrl }; } /** * Normalizes different file names like: * * - /@fs/home/user/project/src/pages/index.astro * - /src/pages/index.astro * - ./src/pages/index.astro * * as absolute file paths with forward slashes. */ export function normalizeFilename(filename, root) { if (filename.startsWith("/@fs")) { filename = filename.slice("/@fs".length); } else if (filename.startsWith(".")) { // Handle relative paths (e.g. ./src/components/Foo.astro) by resolving against root. // This can occur on certain environments (e.g. Windows + newer Node.js) when a component // is imported via a TypeScript path alias and Vite produces a relative virtual module ID. const url = new URL(filename, root); filename = viteID(url); } else if (filename.startsWith("/") && !isPathInRoot(filename, fileURLToPath(root))) { const url = new URL("." + filename, root); filename = viteID(url); } return removeLeadingForwardSlashWindows(filename); } /** * Check whether `filename` lives under `rootPath`. Falls back to a case-insensitive * comparison so that paths whose case differs from `rootPath` (e.g. a `d:\dev\foo` * cwd versus a `D:\dev\foo` filesystem on Windows, or any case-insensitive macOS * volume) are still recognized as project-internal absolute paths. */ function isPathInRoot(filename, rootPath) { if (commonAncestorPath(filename, rootPath)) { return true; } return commonAncestorPath(filename.toLowerCase(), rootPath.toLowerCase()) !== ""; } const postfixRE = /[?#].*$/s; export function cleanUrl(url) { return url.replace(postfixRE, ""); } export const specialQueriesRE = /(?:\?|&)(?:url|raw|direct)(?:&|$)/; /** * Detect `?url`, `?raw`, and `?direct`, in which case we usually want to skip * transforming any code with this queries as Vite will handle it directly. */ export function hasSpecialQueries(id) { return specialQueriesRE.test(id); }