summaryrefslogtreecommitdiff
path: root/packages/integrations/mdx/src/utils.ts
blob: d4d13ab05ea8b4b00f61340ac0659b41bf80b8b0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import { nodeTypes } from '@mdx-js/mdx';
import type { PluggableList } from '@mdx-js/mdx/lib/core.js';
import type { Options as MdxRollupPluginOptions } from '@mdx-js/rollup';
import type { Options as AcornOpts } from 'acorn';
import { parse } from 'acorn';
import type { AstroConfig, SSRError } from 'astro';
import matter from 'gray-matter';
import { bold, yellow } from 'kleur/colors';
import type { MdxjsEsm } from 'mdast-util-mdx';
import rehypeRaw from 'rehype-raw';
import remarkGfm from 'remark-gfm';
import remarkSmartypants from 'remark-smartypants';
import { remarkInitializeAstroData } from './astro-data-utils.js';
import rehypeCollectHeadings from './rehype-collect-headings.js';
import remarkPrism from './remark-prism.js';
import remarkShiki from './remark-shiki.js';

export type MdxOptions = {
	remarkPlugins?: PluggableList;
	rehypePlugins?: PluggableList;
	/**
	 * Choose which remark and rehype plugins to inherit, if any.
	 *
	 * - "markdown" (default) - inherit your project’s markdown plugin config ([see Markdown docs](https://docs.astro.build/en/guides/markdown-content/#configuring-markdown))
	 * - "astroDefaults" - inherit Astro’s default plugins only ([see defaults](https://docs.astro.build/en/reference/configuration-reference/#markdownextenddefaultplugins))
	 * - false - do not inherit any plugins
	 */
	extendPlugins?: 'markdown' | 'astroDefaults' | false;
};

function appendForwardSlash(path: string) {
	return path.endsWith('/') ? path : path + '/';
}

interface FileInfo {
	fileId: string;
	fileUrl: string;
}

const DEFAULT_REMARK_PLUGINS: PluggableList = [remarkGfm, remarkSmartypants];
const DEFAULT_REHYPE_PLUGINS: PluggableList = [];

/** @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/');
	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 };
}

/**
 * Match YAML exception handling from Astro core errors
 * @see 'astro/src/core/errors.ts'
 */
export function parseFrontmatter(code: string, id: string) {
	try {
		return matter(code);
	} 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',
			},
		},
	};
}

export async function getRemarkPlugins(
	mdxOptions: MdxOptions,
	config: AstroConfig
): Promise<MdxRollupPluginOptions['remarkPlugins']> {
	let remarkPlugins: PluggableList = [
		// Set "vfile.data.astro" for plugins to inject frontmatter
		remarkInitializeAstroData,
	];
	switch (mdxOptions.extendPlugins) {
		case false:
			break;
		case 'astroDefaults':
			remarkPlugins = [...remarkPlugins, ...DEFAULT_REMARK_PLUGINS];
			break;
		default:
			remarkPlugins = [
				...remarkPlugins,
				...(markdownShouldExtendDefaultPlugins(config) ? DEFAULT_REMARK_PLUGINS : []),
				...ignoreStringPlugins(config.markdown.remarkPlugins ?? []),
			];
			break;
	}
	if (config.markdown.syntaxHighlight === 'shiki') {
		remarkPlugins.push([await remarkShiki(config.markdown.shikiConfig)]);
	}
	if (config.markdown.syntaxHighlight === 'prism') {
		remarkPlugins.push(remarkPrism);
	}

	remarkPlugins = [...remarkPlugins, ...(mdxOptions.remarkPlugins ?? [])];
	return remarkPlugins;
}

export function getRehypePlugins(
	mdxOptions: MdxOptions,
	config: AstroConfig
): MdxRollupPluginOptions['rehypePlugins'] {
	let rehypePlugins: PluggableList = [
		// getHeadings() is guaranteed by TS, so we can't allow user to override
		rehypeCollectHeadings,
		// rehypeRaw allows custom syntax highlighters to work without added config
		[rehypeRaw, { passThrough: nodeTypes }] as any,
	];
	switch (mdxOptions.extendPlugins) {
		case false:
			break;
		case 'astroDefaults':
			rehypePlugins = [...rehypePlugins, ...DEFAULT_REHYPE_PLUGINS];
			break;
		default:
			rehypePlugins = [
				...rehypePlugins,
				...(markdownShouldExtendDefaultPlugins(config) ? DEFAULT_REHYPE_PLUGINS : []),
				...ignoreStringPlugins(config.markdown.rehypePlugins ?? []),
			];
			break;
	}

	rehypePlugins = [...rehypePlugins, ...(mdxOptions.rehypePlugins ?? [])];
	return rehypePlugins;
}

function markdownShouldExtendDefaultPlugins(config: AstroConfig): boolean {
	return (
		config.markdown.extendDefaultPlugins ||
		(config.markdown.remarkPlugins.length === 0 && config.markdown.rehypePlugins.length === 0)
	);
}

function ignoreStringPlugins(plugins: any[]) {
	let validPlugins: PluggableList = [];
	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;
}

// TODO: remove for 1.0
export function handleExtendsNotSupported(pluginConfig: any) {
	if (
		typeof pluginConfig === 'object' &&
		pluginConfig !== null &&
		(pluginConfig as any).hasOwnProperty('extends')
	) {
		throw new Error(
			`[MDX] The "extends" plugin option is no longer supported! Astro now extends your project's \`markdown\` plugin configuration by default. To customize this behavior, see the \`extendPlugins\` option instead: https://docs.astro.build/en/guides/integrations-guide/mdx/#extendplugins`
		);
	}
}