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

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

86 lines
2 KiB
TypeScript
Raw Normal View History

import type { AstroConfig, SSRError } from 'astro';
import type { Options as AcornOpts } from 'acorn';
import type { MdxjsEsm } from 'mdast-util-mdx';
import { parse } from 'acorn';
import matter from 'gray-matter';
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 };
}
/**
* Match YAML exception handling from Astro core errors
* @see 'astro/src/core/errors.ts'
2022-07-29 15:24:57 +00:00
*/
export function getFrontmatter(code: string, id: string) {
try {
return matter(code).data;
} catch (e: any) {
if (e.name === 'YAMLException') {
const err: SSRError = e;
err.id = id;
err.loc = { file: e.id, line: e.mark.line + 1, column: e.mark.column };
err.message = e.reason;
throw err;
} else {
throw e;
}
}
}
export function jsToTreeNode(
jsString: string,
acornOpts: AcornOpts = {
ecmaVersion: 'latest',
sourceType: 'module',
}
): MdxjsEsm {
return {
type: 'mdxjsEsm',
value: '',
data: {
estree: {
body: [],
...parse(jsString, acornOpts),
type: 'Program',
sourceType: 'module',
},
},
};
}