astro/packages/integrations/mdx/src/utils.ts

40 lines
1 KiB
TypeScript
Raw Normal View History

import type { AstroConfig } from 'astro';
function appendForwardSlash(path: string) {
return path.endsWith('/') ? path : path + '/';
}
interface FileInfo {
fileId: string;
fileUrl: string;
}
/** @see 'vite-plugin-utils' for source */
export function getFileInfo(id: string, config: AstroConfig): FileInfo {
const sitePathname = appendForwardSlash(
config.site ? new URL(config.base, config.site).pathname : config.base
);
// Try to grab the file's actual URL
let url: URL | undefined = undefined;
try {
url = new URL(`file://${id}`);
} catch {}
const fileId = id.split('?')[0];
let fileUrl: string;
const isPage = fileId.includes('/pages/');
2022-07-28 15:00:32 +00:00
if (isPage) {
fileUrl = fileId.replace(/^.*?\/pages\//, sitePathname).replace(/(\/index)?\.mdx$/, '');
2022-07-28 15:00:32 +00:00
} else if (url && url.pathname.startsWith(config.root.pathname)) {
fileUrl = url.pathname.slice(config.root.pathname.length);
} else {
fileUrl = fileId;
}
if (fileUrl && config.trailingSlash === 'always') {
fileUrl = appendForwardSlash(fileUrl);
}
return { fileId, fileUrl };
}