🎉 initiate project *astro_rewrite*

This commit is contained in:
sindrekjelsrud 2023-07-19 21:31:30 +02:00
parent ffd4d5e86c
commit 2ba37bfbe3
8658 changed files with 2268794 additions and 2538 deletions

14
node_modules/@astrojs/mdx/dist/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,14 @@
import { markdownConfigDefaults } from '@astrojs/markdown-remark';
import type { PluggableList } from '@mdx-js/mdx/lib/core.js';
import type { AstroIntegration } from 'astro';
import type { Options as RemarkRehypeOptions } from 'remark-rehype';
import type { OptimizeOptions } from './rehype-optimize-static.js';
export type MdxOptions = Omit<typeof markdownConfigDefaults, 'remarkPlugins' | 'rehypePlugins'> & {
extendMarkdownConfig: boolean;
recmaPlugins: PluggableList;
remarkPlugins: PluggableList;
rehypePlugins: PluggableList;
remarkRehype: RemarkRehypeOptions;
optimize: boolean | OptimizeOptions;
};
export default function mdx(partialMdxOptions?: Partial<MdxOptions>): AstroIntegration;

184
node_modules/@astrojs/mdx/dist/index.js generated vendored Normal file
View file

@ -0,0 +1,184 @@
import { markdownConfigDefaults } from "@astrojs/markdown-remark";
import { toRemarkInitializeAstroData } from "@astrojs/markdown-remark/dist/internal.js";
import { compile as mdxCompile } from "@mdx-js/mdx";
import { parse as parseESM } from "es-module-lexer";
import fs from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { SourceMapGenerator } from "source-map";
import { VFile } from "vfile";
import { getRehypePlugins, getRemarkPlugins, recmaInjectImportMetaEnvPlugin } from "./plugins.js";
import { getFileInfo, ignoreStringPlugins, parseFrontmatter } from "./utils.js";
function mdx(partialMdxOptions = {}) {
return {
name: "@astrojs/mdx",
hooks: {
"astro:config:setup": async (params) => {
const { updateConfig, config, addPageExtension, addContentEntryType, command } = params;
addPageExtension(".mdx");
addContentEntryType({
extensions: [".mdx"],
async getEntryInfo({ fileUrl, contents }) {
const parsed = parseFrontmatter(contents, fileURLToPath(fileUrl));
return {
data: parsed.data,
body: parsed.content,
slug: parsed.data.slug,
rawData: parsed.matter
};
},
contentModuleTypes: await fs.readFile(
new URL("../template/content-module-types.d.ts", import.meta.url),
"utf-8"
),
// MDX can import scripts and styles,
// so wrap all MDX files with script / style propagation checks
handlePropagation: true
});
const extendMarkdownConfig = partialMdxOptions.extendMarkdownConfig ?? defaultMdxOptions.extendMarkdownConfig;
const mdxOptions = applyDefaultOptions({
options: partialMdxOptions,
defaults: markdownConfigToMdxOptions(
extendMarkdownConfig ? config.markdown : markdownConfigDefaults
)
});
const mdxPluginOpts = {
remarkPlugins: await getRemarkPlugins(mdxOptions, config),
rehypePlugins: getRehypePlugins(mdxOptions),
recmaPlugins: mdxOptions.recmaPlugins,
remarkRehypeOptions: mdxOptions.remarkRehype,
jsx: true,
jsxImportSource: "astro",
// Note: disable `.md` (and other alternative extensions for markdown files like `.markdown`) support
format: "mdx",
mdExtensions: []
};
let importMetaEnv = {
SITE: config.site
};
updateConfig({
vite: {
plugins: [
{
name: "@mdx-js/rollup",
enforce: "pre",
configResolved(resolved) {
importMetaEnv = { ...importMetaEnv, ...resolved.env };
},
// Override transform to alter code before MDX compilation
// ex. inject layouts
async transform(_, id) {
var _a;
if (!id.endsWith(".mdx"))
return;
const { fileId } = getFileInfo(id, config);
const code = await fs.readFile(fileId, "utf-8");
const { data: frontmatter, content: pageContent } = parseFrontmatter(code, id);
const compiled = await mdxCompile(new VFile({ value: pageContent, path: id }), {
...mdxPluginOpts,
elementAttributeNameCase: "html",
remarkPlugins: [
// Ensure `data.astro` is available to all remark plugins
toRemarkInitializeAstroData({ userFrontmatter: frontmatter }),
...mdxPluginOpts.remarkPlugins ?? []
],
recmaPlugins: [
...mdxPluginOpts.recmaPlugins ?? [],
() => recmaInjectImportMetaEnvPlugin({ importMetaEnv })
],
SourceMapGenerator: ((_a = config.vite.build) == null ? void 0 : _a.sourcemap) ? SourceMapGenerator : void 0
});
return {
code: escapeViteEnvReferences(String(compiled.value)),
map: compiled.map
};
}
},
{
name: "@astrojs/mdx-postprocess",
// These transforms must happen *after* JSX runtime transformations
transform(code, id) {
if (!id.endsWith(".mdx"))
return;
const [moduleImports, moduleExports] = parseESM(code);
const importsFromJSXRuntime = moduleImports.filter(({ n }) => n === "astro/jsx-runtime").map(({ ss, se }) => code.substring(ss, se));
const hasFragmentImport = importsFromJSXRuntime.some(
(statement) => /[\s,{](Fragment,|Fragment\s*})/.test(statement)
);
if (!hasFragmentImport) {
code = 'import { Fragment } from "astro/jsx-runtime"\n' + code;
}
const { fileUrl, fileId } = getFileInfo(id, config);
if (!moduleExports.find(({ n }) => n === "url")) {
code += `
export const url = ${JSON.stringify(fileUrl)};`;
}
if (!moduleExports.find(({ n }) => n === "file")) {
code += `
export const file = ${JSON.stringify(fileId)};`;
}
if (!moduleExports.find(({ n }) => n === "Content")) {
code = code.replace("export default MDXContent;", "");
code += `
export const Content = (props = {}) => MDXContent({
...props,
components: { Fragment, ...props.components },
});
export default Content;`;
}
code += `
Content[Symbol.for('astro.needsHeadRendering')] = !Boolean(frontmatter.layout);`;
code += `
Content.moduleId = ${JSON.stringify(id)};`;
if (command === "dev") {
code += `
if (import.meta.hot) {
import.meta.hot.decline();
}`;
}
return { code: escapeViteEnvReferences(code), map: null };
}
}
]
}
});
}
}
};
}
const defaultMdxOptions = {
extendMarkdownConfig: true,
recmaPlugins: []
};
function markdownConfigToMdxOptions(markdownConfig) {
return {
...defaultMdxOptions,
...markdownConfig,
remarkPlugins: ignoreStringPlugins(markdownConfig.remarkPlugins),
rehypePlugins: ignoreStringPlugins(markdownConfig.rehypePlugins),
remarkRehype: markdownConfig.remarkRehype ?? {},
optimize: false
};
}
function applyDefaultOptions({
options,
defaults
}) {
return {
syntaxHighlight: options.syntaxHighlight ?? defaults.syntaxHighlight,
extendMarkdownConfig: options.extendMarkdownConfig ?? defaults.extendMarkdownConfig,
recmaPlugins: options.recmaPlugins ?? defaults.recmaPlugins,
remarkRehype: options.remarkRehype ?? defaults.remarkRehype,
gfm: options.gfm ?? defaults.gfm,
smartypants: options.smartypants ?? defaults.smartypants,
remarkPlugins: options.remarkPlugins ?? defaults.remarkPlugins,
rehypePlugins: options.rehypePlugins ?? defaults.rehypePlugins,
shikiConfig: options.shikiConfig ?? defaults.shikiConfig,
optimize: options.optimize ?? defaults.optimize
};
}
function escapeViteEnvReferences(code) {
return code.replace(/import\.meta\.env/g, "import\\u002Emeta.env");
}
export {
mdx as default
};

10
node_modules/@astrojs/mdx/dist/plugins.d.ts generated vendored Normal file
View file

@ -0,0 +1,10 @@
import type { PluggableList } from '@mdx-js/mdx/lib/core.js';
import type { AstroConfig } from 'astro';
import type { VFile } from 'vfile';
import type { MdxOptions } from './index.js';
export declare function recmaInjectImportMetaEnvPlugin({ importMetaEnv, }: {
importMetaEnv: Record<string, any>;
}): (tree: any) => void;
export declare function rehypeApplyFrontmatterExport(): (tree: any, vfile: VFile) => void;
export declare function getRemarkPlugins(mdxOptions: MdxOptions, config: AstroConfig): Promise<PluggableList>;
export declare function getRehypePlugins(mdxOptions: MdxOptions): PluggableList;

151
node_modules/@astrojs/mdx/dist/plugins.js generated vendored Normal file
View file

@ -0,0 +1,151 @@
import { rehypeHeadingIds, remarkCollectImages } from "@astrojs/markdown-remark";
import {
InvalidAstroDataError,
safelyGetAstroData
} from "@astrojs/markdown-remark/dist/internal.js";
import { nodeTypes } from "@mdx-js/mdx";
import { visit as estreeVisit } from "estree-util-visit";
import rehypeRaw from "rehype-raw";
import remarkGfm from "remark-gfm";
import remarkSmartypants from "remark-smartypants";
import { rehypeInjectHeadingsExport } from "./rehype-collect-headings.js";
import rehypeMetaString from "./rehype-meta-string.js";
import { rehypeOptimizeStatic } from "./rehype-optimize-static.js";
import { remarkImageToComponent } from "./remark-images-to-component.js";
import remarkPrism from "./remark-prism.js";
import remarkShiki from "./remark-shiki.js";
import { jsToTreeNode } from "./utils.js";
const isPerformanceBenchmark = Boolean(process.env.ASTRO_PERFORMANCE_BENCHMARK);
function recmaInjectImportMetaEnvPlugin({
importMetaEnv
}) {
return (tree) => {
estreeVisit(tree, (node) => {
if (node.type === "MemberExpression") {
const envVarName = getImportMetaEnvVariableName(node);
if (typeof envVarName === "string") {
for (const key in node) {
delete node[key];
}
const envVarLiteral = {
type: "Literal",
value: importMetaEnv[envVarName],
raw: JSON.stringify(importMetaEnv[envVarName])
};
Object.assign(node, envVarLiteral);
}
}
});
};
}
function rehypeApplyFrontmatterExport() {
return function(tree, vfile) {
const astroData = safelyGetAstroData(vfile.data);
if (astroData instanceof InvalidAstroDataError)
throw new Error(
// Copied from Astro core `errors-data`
// TODO: find way to import error data from core
'[MDX] A remark or rehype plugin attempted to inject invalid frontmatter. Ensure "astro.frontmatter" is set to a valid JSON object that is not `null` or `undefined`.'
);
const { frontmatter } = astroData;
const exportNodes = [
jsToTreeNode(`export const frontmatter = ${JSON.stringify(frontmatter)};`)
];
if (frontmatter.layout) {
exportNodes.unshift(
jsToTreeNode(
/** @see 'vite-plugin-markdown' for layout props reference */
`import { jsx as layoutJsx } from 'astro/jsx-runtime';
export default async function ({ children }) {
const Layout = (await import(${JSON.stringify(frontmatter.layout)})).default;
const { layout, ...content } = frontmatter;
content.file = file;
content.url = url;
return layoutJsx(Layout, {
file,
url,
content,
frontmatter: content,
headings: getHeadings(),
'server:root': true,
children,
});
};`
)
);
}
tree.children = exportNodes.concat(tree.children);
};
}
async function getRemarkPlugins(mdxOptions, config) {
let remarkPlugins = [
...config.experimental.assets ? [remarkCollectImages, remarkImageToComponent] : []
];
if (!isPerformanceBenchmark) {
if (mdxOptions.gfm) {
remarkPlugins.push(remarkGfm);
}
if (mdxOptions.smartypants) {
remarkPlugins.push(remarkSmartypants);
}
}
remarkPlugins = [...remarkPlugins, ...mdxOptions.remarkPlugins];
if (!isPerformanceBenchmark) {
if (mdxOptions.syntaxHighlight === "shiki") {
remarkPlugins.push([await remarkShiki(mdxOptions.shikiConfig)]);
}
if (mdxOptions.syntaxHighlight === "prism") {
remarkPlugins.push(remarkPrism);
}
}
return remarkPlugins;
}
function getRehypePlugins(mdxOptions) {
let rehypePlugins = [
// ensure `data.meta` is preserved in `properties.metastring` for rehype syntax highlighters
rehypeMetaString,
// rehypeRaw allows custom syntax highlighters to work without added config
[rehypeRaw, { passThrough: nodeTypes }]
];
rehypePlugins = [
...rehypePlugins,
...mdxOptions.rehypePlugins,
// getHeadings() is guaranteed by TS, so this must be included.
// We run `rehypeHeadingIds` _last_ to respect any custom IDs set by user plugins.
...isPerformanceBenchmark ? [] : [rehypeHeadingIds, rehypeInjectHeadingsExport],
// computed from `astro.data.frontmatter` in VFile data
rehypeApplyFrontmatterExport
];
if (mdxOptions.optimize) {
const options = mdxOptions.optimize === true ? void 0 : mdxOptions.optimize;
rehypePlugins.push([rehypeOptimizeStatic, options]);
}
return rehypePlugins;
}
function getImportMetaEnvVariableName(node) {
try {
if (node.object.type !== "MemberExpression" || node.property.type !== "Identifier")
return new Error();
const nestedExpression = node.object;
if (nestedExpression.property.type !== "Identifier" || nestedExpression.property.name !== "env")
return new Error();
const envExpression = nestedExpression.object;
if (envExpression.type !== "MetaProperty" || envExpression.property.type !== "Identifier" || envExpression.property.name !== "meta")
return new Error();
if (envExpression.meta.name !== "import")
return new Error();
return node.property.name;
} catch (e) {
if (e instanceof Error) {
return e;
}
return new Error("Unknown parsing error");
}
}
export {
getRehypePlugins,
getRemarkPlugins,
recmaInjectImportMetaEnvPlugin,
rehypeApplyFrontmatterExport
};

View file

@ -0,0 +1,2 @@
import type { MarkdownVFile } from '@astrojs/markdown-remark';
export declare function rehypeInjectHeadingsExport(): (tree: any, file: MarkdownVFile) => void;

View file

@ -0,0 +1,12 @@
import { jsToTreeNode } from "./utils.js";
function rehypeInjectHeadingsExport() {
return function(tree, file) {
const headings = file.data.__astroHeadings || [];
tree.children.unshift(
jsToTreeNode(`export function getHeadings() { return ${JSON.stringify(headings)} }`)
);
};
}
export {
rehypeInjectHeadingsExport
};

View file

@ -0,0 +1,6 @@
/**
* Moves `data.meta` to `properties.metastring` for the `code` element node
* as `rehype-raw` strips `data` from all nodes, which may contain useful information.
* e.g. ```js {1:3} => metastring: "{1:3}"
*/
export default function rehypeMetaString(): (tree: any) => void;

15
node_modules/@astrojs/mdx/dist/rehype-meta-string.js generated vendored Normal file
View file

@ -0,0 +1,15 @@
import { visit } from "unist-util-visit";
function rehypeMetaString() {
return function(tree) {
visit(tree, (node) => {
var _a;
if (node.type === "element" && node.tagName === "code" && ((_a = node.data) == null ? void 0 : _a.meta)) {
node.properties ??= {};
node.properties.metastring = node.data.meta;
}
});
};
}
export {
rehypeMetaString as default
};

View file

@ -0,0 +1,11 @@
export interface OptimizeOptions {
customComponentNames?: string[];
}
/**
* For MDX only, collapse static subtrees of the hast into `set:html`. Subtrees
* do not include any MDX elements.
*
* This optimization reduces the JS output as more content are represented as a
* string instead, which also reduces the AST size that Rollup holds in memory.
*/
export declare function rehypeOptimizeStatic(options?: OptimizeOptions): (tree: any) => void;

View file

@ -0,0 +1,63 @@
import { visit } from "estree-util-visit";
import { toHtml } from "hast-util-to-html";
const exportConstComponentsRe = /export\s+const\s+components\s*=/;
function rehypeOptimizeStatic(options) {
return (tree) => {
var _a, _b, _c, _d, _e, _f;
const customComponentNames = new Set(options == null ? void 0 : options.customComponentNames);
for (const child of tree.children) {
if (child.type === "mdxjsEsm" && exportConstComponentsRe.test(child.value)) {
const objectPropertyNodes = (_d = (_c = (_b = (_a = child.data.estree.body[0]) == null ? void 0 : _a.declarations) == null ? void 0 : _b[0]) == null ? void 0 : _c.init) == null ? void 0 : _d.properties;
if (objectPropertyNodes) {
for (const objectPropertyNode of objectPropertyNodes) {
const componentName = ((_e = objectPropertyNode.key) == null ? void 0 : _e.name) ?? ((_f = objectPropertyNode.key) == null ? void 0 : _f.value);
if (componentName) {
customComponentNames.add(componentName);
}
}
}
}
}
const allPossibleElements = /* @__PURE__ */ new Set();
const elementStack = [];
visit(tree, {
enter(node) {
const isCustomComponent = node.tagName && customComponentNames.has(node.tagName);
if (node.type.startsWith("mdx") || isCustomComponent) {
for (const el of elementStack) {
allPossibleElements.delete(el);
}
elementStack.length = 0;
}
if (node.type === "element" || node.type === "mdxJsxFlowElement") {
elementStack.push(node);
allPossibleElements.add(node);
}
},
leave(node, _, __, parents) {
if (node.type === "element" || node.type === "mdxJsxFlowElement") {
elementStack.pop();
const parent = parents[parents.length - 1];
if (allPossibleElements.has(parent)) {
allPossibleElements.delete(node);
}
}
}
});
for (const el of allPossibleElements) {
if (el.type === "mdxJsxFlowElement") {
el.attributes.push({
type: "mdxJsxAttribute",
name: "set:html",
value: toHtml(el.children)
});
} else {
el.properties["set:html"] = toHtml(el.children);
}
el.children = [];
}
};
}
export {
rehypeOptimizeStatic
};

View file

@ -0,0 +1,2 @@
import type { MarkdownVFile } from '@astrojs/markdown-remark';
export declare function remarkImageToComponent(): (tree: any, file: MarkdownVFile) => void;

View file

@ -0,0 +1,84 @@
import { visit } from "unist-util-visit";
import { jsToTreeNode } from "./utils.js";
function remarkImageToComponent() {
return function(tree, file) {
if (!file.data.imagePaths)
return;
const importsStatements = [];
const importedImages = /* @__PURE__ */ new Map();
visit(tree, "image", (node, index, parent) => {
var _a;
if ((_a = file.data.imagePaths) == null ? void 0 : _a.has(node.url)) {
let importName = importedImages.get(node.url);
if (!importName) {
importName = `__${importedImages.size}_${node.url.replace(/\W/g, "_")}__`;
importsStatements.push({
type: "mdxjsEsm",
value: "",
data: {
estree: {
type: "Program",
sourceType: "module",
body: [
{
type: "ImportDeclaration",
source: { type: "Literal", value: node.url, raw: JSON.stringify(node.url) },
specifiers: [
{
type: "ImportDefaultSpecifier",
local: { type: "Identifier", name: importName }
}
]
}
]
}
}
});
importedImages.set(node.url, importName);
}
const componentElement = {
name: "__AstroImage__",
type: "mdxJsxFlowElement",
attributes: [
{
name: "src",
type: "mdxJsxAttribute",
value: {
type: "mdxJsxAttributeValueExpression",
value: importName,
data: {
estree: {
type: "Program",
sourceType: "module",
comments: [],
body: [
{
type: "ExpressionStatement",
expression: { type: "Identifier", name: importName }
}
]
}
}
}
},
{ name: "alt", type: "mdxJsxAttribute", value: node.alt || "" }
],
children: []
};
if (node.title) {
componentElement.attributes.push({
type: "mdxJsxAttribute",
name: "title",
value: node.title
});
}
parent.children.splice(index, 1, componentElement);
}
});
tree.children.unshift(...importsStatements);
tree.children.unshift(jsToTreeNode(`import { Image as __AstroImage__ } from "astro:assets";`));
};
}
export {
remarkImageToComponent
};

2
node_modules/@astrojs/mdx/dist/remark-prism.d.ts generated vendored Normal file
View file

@ -0,0 +1,2 @@
/** */
export default function remarkPrism(): (tree: any) => void;

17
node_modules/@astrojs/mdx/dist/remark-prism.js generated vendored Normal file
View file

@ -0,0 +1,17 @@
import { runHighlighterWithAstro } from "@astrojs/prism/dist/highlighter";
import { visit } from "unist-util-visit";
function remarkPrism() {
return (tree) => visit(tree, "code", (node) => {
let { lang, value } = node;
node.type = "html";
let { html, classLanguage } = runHighlighterWithAstro(lang, value);
let classes = [classLanguage];
node.value = `<pre class="${classes.join(
" "
)}"><code class="${classLanguage}">${html}</code></pre>`;
return node;
});
}
export {
remarkPrism as default
};

3
node_modules/@astrojs/mdx/dist/remark-shiki.d.ts generated vendored Normal file
View file

@ -0,0 +1,3 @@
import type { ShikiConfig } from 'astro';
declare const remarkShiki: ({ langs, theme, wrap }: ShikiConfig) => Promise<() => (tree: any) => void>;
export default remarkShiki;

86
node_modules/@astrojs/mdx/dist/remark-shiki.js generated vendored Normal file
View file

@ -0,0 +1,86 @@
import { getHighlighter } from "shiki";
import { visit } from "unist-util-visit";
const highlighterCacheAsync = /* @__PURE__ */ new Map();
const compatThemes = {
"material-darker": "material-theme-darker",
"material-default": "material-theme",
"material-lighter": "material-theme-lighter",
"material-ocean": "material-theme-ocean",
"material-palenight": "material-theme-palenight"
};
const normalizeTheme = (theme) => {
if (typeof theme === "string") {
return compatThemes[theme] || theme;
} else if (compatThemes[theme.name]) {
return { ...theme, name: compatThemes[theme.name] };
} else {
return theme;
}
};
const remarkShiki = async ({ langs = [], theme = "github-dark", wrap = false }) => {
theme = normalizeTheme(theme);
const cacheID = typeof theme === "string" ? theme : theme.name;
let highlighterAsync = highlighterCacheAsync.get(cacheID);
if (!highlighterAsync) {
highlighterAsync = getHighlighter({ theme }).then((hl) => {
hl.setColorReplacements({
"#000001": "var(--astro-code-color-text)",
"#000002": "var(--astro-code-color-background)",
"#000004": "var(--astro-code-token-constant)",
"#000005": "var(--astro-code-token-string)",
"#000006": "var(--astro-code-token-comment)",
"#000007": "var(--astro-code-token-keyword)",
"#000008": "var(--astro-code-token-parameter)",
"#000009": "var(--astro-code-token-function)",
"#000010": "var(--astro-code-token-string-expression)",
"#000011": "var(--astro-code-token-punctuation)",
"#000012": "var(--astro-code-token-link)"
});
return hl;
});
highlighterCacheAsync.set(cacheID, highlighterAsync);
}
const highlighter = await highlighterAsync;
for (const lang of langs) {
await highlighter.loadLanguage(lang);
}
return () => (tree) => {
visit(tree, "code", (node) => {
let lang;
if (typeof node.lang === "string") {
const langExists = highlighter.getLoadedLanguages().includes(node.lang);
if (langExists) {
lang = node.lang;
} else {
console.warn(`The language "${node.lang}" doesn't exist, falling back to plaintext.`);
lang = "plaintext";
}
} else {
lang = "plaintext";
}
let html = highlighter.codeToHtml(node.value, { lang });
html = html.replace(/<pre class="(.*?)shiki(.*?)"/, `<pre class="$1astro-code$2"`);
if (node.lang === "diff") {
html = html.replace(
/<span class="line"><span style="(.*?)">([\+|\-])/g,
'<span class="line"><span style="$1"><span style="user-select: none;">$2</span>'
);
}
if (wrap === false) {
html = html.replace(/style="(.*?)"/, 'style="$1; overflow-x: auto;"');
} else if (wrap === true) {
html = html.replace(
/style="(.*?)"/,
'style="$1; overflow-x: auto; white-space: pre-wrap; word-wrap: break-word;"'
);
}
node.type = "html";
node.value = html;
node.children = [];
});
};
};
var remark_shiki_default = remarkShiki;
export {
remark_shiki_default as default
};

19
node_modules/@astrojs/mdx/dist/utils.d.ts generated vendored Normal file
View file

@ -0,0 +1,19 @@
import type { PluggableList } from '@mdx-js/mdx/lib/core.js';
import type { Options as AcornOpts } from 'acorn';
import type { AstroConfig } from 'astro';
import matter from 'gray-matter';
import type { MdxjsEsm } from 'mdast-util-mdx';
interface FileInfo {
fileId: string;
fileUrl: string;
}
/** @see 'vite-plugin-utils' for source */
export declare function getFileInfo(id: string, config: AstroConfig): FileInfo;
/**
* Match YAML exception handling from Astro core errors
* @see 'astro/src/core/errors.ts'
*/
export declare function parseFrontmatter(code: string, id: string): matter.GrayMatterFile<string>;
export declare function jsToTreeNode(jsString: string, acornOpts?: AcornOpts): MdxjsEsm;
export declare function ignoreStringPlugins(plugins: any[]): PluggableList;
export {};

89
node_modules/@astrojs/mdx/dist/utils.js generated vendored Normal file
View file

@ -0,0 +1,89 @@
import { parse } from "acorn";
import matter from "gray-matter";
import { bold, yellow } from "kleur/colors";
function appendForwardSlash(path) {
return path.endsWith("/") ? path : path + "/";
}
function getFileInfo(id, config) {
const sitePathname = appendForwardSlash(
config.site ? new URL(config.base, config.site).pathname : config.base
);
let url = void 0;
try {
url = new URL(`file://${id}`);
} catch {
}
const fileId = id.split("?")[0];
let fileUrl;
const isPage = fileId.includes("/pages/");
if (isPage) {
fileUrl = fileId.replace(/^.*?\/pages\//, sitePathname).replace(/(\/index)?\.mdx$/, "");
} 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 };
}
function parseFrontmatter(code, id) {
try {
return matter(code);
} catch (e) {
if (e.name === "YAMLException") {
const err = 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;
}
}
}
function jsToTreeNode(jsString, acornOpts = {
ecmaVersion: "latest",
sourceType: "module"
}) {
return {
type: "mdxjsEsm",
value: "",
data: {
estree: {
body: [],
...parse(jsString, acornOpts),
type: "Program",
sourceType: "module"
}
}
};
}
function ignoreStringPlugins(plugins) {
let validPlugins = [];
let hasInvalidPlugin = false;
for (const plugin of plugins) {
if (typeof plugin === "string") {
console.warn(yellow(`[MDX] ${bold(plugin)} not applied.`));
hasInvalidPlugin = true;
} else if (Array.isArray(plugin) && typeof plugin[0] === "string") {
console.warn(yellow(`[MDX] ${bold(plugin[0])} not applied.`));
hasInvalidPlugin = true;
} else {
validPlugins.push(plugin);
}
}
if (hasInvalidPlugin) {
console.warn(
`To inherit Markdown plugins in MDX, please use explicit imports in your config instead of "strings." See Markdown docs: https://docs.astro.build/en/guides/markdown-content/#markdown-plugins`
);
}
return validPlugins;
}
export {
getFileInfo,
ignoreStringPlugins,
jsToTreeNode,
parseFrontmatter
};