@astrojs/mdx 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/.turbo/turbo-build.log +5 -5
  2. package/CHANGELOG.md +28 -0
  3. package/README.md +223 -1
  4. package/dist/index.d.ts +17 -1
  5. package/dist/index.js +58 -4
  6. package/dist/remark-prism.d.ts +2 -0
  7. package/dist/remark-prism.js +49 -0
  8. package/dist/utils.d.ts +8 -0
  9. package/dist/utils.js +30 -0
  10. package/package.json +18 -5
  11. package/src/index.ts +89 -6
  12. package/src/remark-prism.ts +60 -0
  13. package/src/utils.ts +39 -0
  14. package/test/fixtures/mdx-custom-frontmatter-name/src/pages/glob.json.js +9 -0
  15. package/test/fixtures/mdx-custom-frontmatter-name/src/pages/index.mdx +6 -0
  16. package/test/fixtures/mdx-frontmatter/src/pages/glob.json.js +9 -0
  17. package/test/fixtures/mdx-frontmatter/src/pages/index.mdx +6 -0
  18. package/test/fixtures/mdx-get-static-paths/src/content/1.mdx +5 -0
  19. package/test/fixtures/mdx-get-static-paths/src/pages/[slug].astro +34 -0
  20. package/test/fixtures/mdx-remark-plugins/src/pages/with-gfm.mdx +3 -0
  21. package/test/fixtures/mdx-remark-plugins/src/pages/with-toc.mdx +19 -0
  22. package/test/fixtures/mdx-syntax-hightlighting/src/pages/index.mdx +9 -0
  23. package/test/fixtures/mdx-url-export/src/pages/pages.json.js +9 -0
  24. package/test/fixtures/mdx-url-export/src/pages/test-1.mdx +1 -0
  25. package/test/fixtures/mdx-url-export/src/pages/test-2.mdx +1 -0
  26. package/test/fixtures/mdx-url-export/src/pages/with-url-override.mdx +3 -0
  27. package/test/mdx-frontmatter.test.js +45 -0
  28. package/test/mdx-get-static-paths.test.js +32 -0
  29. package/test/mdx-remark-plugins.test.js +62 -0
  30. package/test/mdx-syntax-highlighting.test.js +67 -0
  31. package/test/mdx-url-export.test.js +28 -0
@@ -1,5 +1,5 @@
1
- @astrojs/mdx:build: cache hit, replaying output 345323bc7c261c68
2
- @astrojs/mdx:build: 
3
- @astrojs/mdx:build: > @astrojs/mdx@0.2.0 build /home/runner/work/astro/astro/packages/integrations/mdx
4
- @astrojs/mdx:build: > astro-scripts build "src/**/*.ts" && tsc
5
- @astrojs/mdx:build: 
1
+ @astrojs/mdx:build: cache hit, replaying output 0a3d73b5c732032a
2
+ @astrojs/mdx:build: 
3
+ @astrojs/mdx:build: > @astrojs/mdx@0.3.1 build /home/runner/work/astro/astro/packages/integrations/mdx
4
+ @astrojs/mdx:build: > astro-scripts build "src/**/*.ts" && tsc
5
+ @astrojs/mdx:build: 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # @astrojs/mdx
2
2
 
3
+ ## 0.3.1
4
+
5
+ ### Patch Changes
6
+
7
+ - [#4076](https://github.com/withastro/astro/pull/4076) [`6120a71e5`](https://github.com/withastro/astro/commit/6120a71e5425ad55a17ddac800d64a3f50273bce) Thanks [@matthewp](https://github.com/matthewp)! - Ensure file and url are always present in MDX for Astro.glob
8
+
9
+ ## 0.3.0
10
+
11
+ ### Minor Changes
12
+
13
+ - [#3977](https://github.com/withastro/astro/pull/3977) [`19433eb4a`](https://github.com/withastro/astro/commit/19433eb4a4441522f68492ca914ad2ab4f061343) Thanks [@bholmesdev](https://github.com/bholmesdev)! - Add remarkPlugins and rehypePlugins to config, with the same default plugins as our standard Markdown parser
14
+
15
+ * [#4002](https://github.com/withastro/astro/pull/4002) [`3b8a74452`](https://github.com/withastro/astro/commit/3b8a7445247221100462ba035f6778b43ea180e7) Thanks [@bholmesdev](https://github.com/bholmesdev)! - Support Prism and Shiki syntax highlighting based on project config
16
+
17
+ - [#3995](https://github.com/withastro/astro/pull/3995) [`b2b367c96`](https://github.com/withastro/astro/commit/b2b367c969493aaf21c974064beb241d05228066) Thanks [@bholmesdev](https://github.com/bholmesdev)! - Support YAML frontmatter in MDX files
18
+
19
+ ### Patch Changes
20
+
21
+ - [#4050](https://github.com/withastro/astro/pull/4050) [`9ab66c4ba`](https://github.com/withastro/astro/commit/9ab66c4ba9bf2250990114c76b792f26d0694365) Thanks [@FredKSchott](https://github.com/FredKSchott)! - Add support for injected "page-ssr" scripts
22
+
23
+ * [#3981](https://github.com/withastro/astro/pull/3981) [`61fec6304`](https://github.com/withastro/astro/commit/61fec63044e1585348e8405bee6fdf4dec635efa) Thanks [@bholmesdev](https://github.com/bholmesdev)! - Include page url in MDX glob result
24
+
25
+ ## 0.2.1
26
+
27
+ ### Patch Changes
28
+
29
+ - [#3937](https://github.com/withastro/astro/pull/3937) [`31f9c0bf0`](https://github.com/withastro/astro/commit/31f9c0bf029ffa4b470e620f2c32e1370643e81e) Thanks [@delucis](https://github.com/delucis)! - Roll back supported Node engines
30
+
3
31
  ## 0.2.0
4
32
 
5
33
  ### Minor Changes
package/README.md CHANGED
@@ -78,9 +78,231 @@ To write your first MDX page in Astro, head to our [UI framework documentation][
78
78
 
79
79
  Also check our [Astro Integration Documentation][astro-integration] for more on integrations.
80
80
 
81
+ ### Variables
82
+
83
+ MDX supports `export` statements to add variables to your templates. These variables are accessible both from the template itself _and_ as named properties when importing the template somewhere else.
84
+
85
+ For instance, you can export a `title` field from an MDX page or component to use as a heading with `{JSX expressions}`:
86
+
87
+ ```mdx
88
+ export const title = 'My first MDX post'
89
+
90
+ # {title}
91
+ ```
92
+
93
+ This `title` will be accessible from `import` and [glob](https://docs.astro.build/en/reference/api-reference/#astroglob) statements as well:
94
+
95
+ ```astro
96
+ ---
97
+ // src/pages/index.astro
98
+ const posts = await Astro.glob('./*.mdx');
99
+ ---
100
+
101
+ {posts.map(post => <p>{post.title}</p>)}
102
+ ```
103
+
104
+ See [the official "how MDX works" guide](https://mdxjs.com/docs/using-mdx/#how-mdx-works) for more on MDX variables.
105
+
106
+ ### Frontmatter
107
+
108
+ Astro also supports YAML-based frontmatter out-of-the-box using the [remark-mdx-frontmatter](https://github.com/remcohaszing/remark-mdx-frontmatter) plugin. By default, all variables declared in a frontmatter fence (`---`) will be accessible via the `frontmatter` export. See the `frontmatterOptions` configuration to customize this behavior.
109
+
110
+ For example, we can add a `title` and `publishDate` to an MDX page or component like so:
111
+
112
+ ```mdx
113
+ ---
114
+ title: 'My first MDX post'
115
+ publishDate: '21 September 2022'
116
+ ---
117
+
118
+ # {frontmatter.title}
119
+ ```
120
+
121
+ Now, this `title` and `publishDate` will be accessible from `import` and [glob](https://docs.astro.build/en/reference/api-reference/#astroglob) statements via the `frontmatter` property. This matches the behavior of [plain markdown in Astro](https://docs.astro.build/en/reference/api-reference/#markdown-files) as well!
122
+
123
+ ```astro
124
+ ---
125
+ // src/pages/index.astro
126
+ const posts = await Astro.glob('./*.mdx');
127
+ ---
128
+
129
+ {posts.map(post => (
130
+ <Fragment>
131
+ <h2>{post.frontmatter.title}</h2>
132
+ <time>{post.frontmatter.publishDate}</time>
133
+ </Fragment>
134
+ ))}
135
+ ```
136
+
137
+ ### Layouts
138
+
139
+ You can use the [MDX layout component](https://mdxjs.com/docs/using-mdx/#layout) to specify a layout component to wrap all page content. This is done with a default export statement at the end of your `.mdx` file:
140
+
141
+ ```mdx
142
+ // src/pages/my-page.mdx
143
+
144
+ export {default} from '../../layouts/BaseLayout.astro';
145
+ ```
146
+
147
+ You can also import and use a [`<Layout />` component](/en/core-concepts/layouts/) for your MDX page content, and pass all the variables declared in frontmatter as props.
148
+
149
+ ```mdx
150
+ ---
151
+ // src/pages/posts/first-post.mdx
152
+
153
+ title: 'My first MDX post'
154
+ publishDate: '21 September 2022'
155
+ ---
156
+ import BaseLayout from '../layouts/BaseLayout.astro';
157
+
158
+ <BaseLayout {...frontmatter}>
159
+ # {frontmatter.title}
160
+
161
+ Welcome to my new Astro blog, using MDX!
162
+ </BaseLayout>
163
+ ```
164
+ Then, your values are available to you through `Astro.props` in your layout, and your MDX content will be injected into the page where your `<slot />` component is written:
165
+
166
+ ```astro
167
+ ---
168
+ // src/layouts/BaseLayout.astro
169
+ const { title, publishDate } = Astro.props;
170
+ ---
171
+ <!-- -->
172
+ <h1>{title}</h1>
173
+ <slot />
174
+ <p>Published on {publishDate}</p>
175
+ <!-- -->
176
+ ```
177
+
178
+ ### Syntax highlighting
179
+
180
+ The MDX integration respects [your project's `markdown.syntaxHighlight` configuration](https://docs.astro.build/en/guides/markdown-content/#syntax-highlighting).
181
+
182
+ We will highlight your code blocks with [Shiki](https://github.com/shikijs/shiki) by default [using Shiki twoslash](https://shikijs.github.io/twoslash/). You can customize [this remark plugin](https://www.npmjs.com/package/remark-shiki-twoslash) using the `markdown.shikiConfig` option in your `astro.config`. For example, you can apply a different built-in theme like so:
183
+
184
+ ```js
185
+ // astro.config.mjs
186
+ export default {
187
+ markdown: {
188
+ shikiConfig: {
189
+ theme: 'dracula',
190
+ },
191
+ },
192
+ integrations: [mdx()],
193
+ }
194
+ ```
195
+
196
+ Visit [our Shiki configuration docs](https://docs.astro.build/en/guides/markdown-content/#shiki-configuration) for more on using Shiki with Astro.
197
+
198
+ #### Switch to Prism
199
+
200
+ You can also use the [Prism](https://prismjs.com/) syntax highlighter by setting `markdown.syntaxHighlight` to `'prism'` in your `astro.config` like so:
201
+
202
+ ```js
203
+ // astro.config.mjs
204
+ export default {
205
+ markdown: {
206
+ syntaxHighlight: 'prism',
207
+ },
208
+ integrations: [mdx()],
209
+ }
210
+ ```
211
+
212
+ This applies a minimal Prism renderer with added support for `astro` code blocks. Visit [our "Prism configuration" docs](https://docs.astro.build/en/guides/markdown-content/#prism-configuration) for more on using Prism with Astro.
213
+
81
214
  ## Configuration
82
215
 
83
- There are currently no configuration options for the `@astrojs/mdx` integration. Please [open an issue](https://github.com/withastro/astro/issues/new/choose) if you have a compelling use case to share.
216
+ <details>
217
+ <summary><strong>remarkPlugins</strong></summary>
218
+
219
+ **Default plugins:** [remark-gfm](https://github.com/remarkjs/remark-gfm), [remark-smartypants](https://github.com/silvenon/remark-smartypants)
220
+
221
+ [Remark plugins](https://github.com/remarkjs/remark/blob/main/doc/plugins.md) allow you to extend your Markdown with new capabilities. This includes [auto-generating a table of contents](https://github.com/remarkjs/remark-toc), [applying accessible emoji labels](https://github.com/florianeckerstorfer/remark-a11y-emoji), and more. We encourage you to browse [awesome-remark](https://github.com/remarkjs/awesome-remark) for a full curated list!
222
+
223
+ We apply [GitHub-flavored Markdown](https://github.com/remarkjs/remark-gfm) and [Smartypants](https://github.com/silvenon/remark-smartypants) by default. This brings some niceties like auto-generating clickable links from text (ex. `https://example.com`) and formatting quotes for readability. When applying your own plugins, you can choose to preserve or remove these defaults.
224
+
225
+ To apply plugins _while preserving_ Astro's default plugins, use a nested `extends` object like so:
226
+
227
+ ```js
228
+ // astro.config.mjs
229
+ import remarkToc from 'remark-toc';
230
+
231
+ export default {
232
+ integrations: [mdx({
233
+ // apply remark-toc alongside GitHub-flavored markdown and Smartypants
234
+ remarkPlugins: { extends: [remarkToc] },
235
+ })],
236
+ }
237
+ ```
238
+
239
+ To apply plugins _without_ Astro's defaults, you can apply a plain array:
240
+
241
+ ```js
242
+ // astro.config.mjs
243
+ import remarkToc from 'remark-toc';
244
+
245
+ export default {
246
+ integrations: [mdx({
247
+ // apply remark-toc alone, removing other defaults
248
+ remarkPlugins: [remarkToc],
249
+ })],
250
+ }
251
+ ```
252
+
253
+ </details>
254
+
255
+ <details>
256
+ <summary><strong>rehypePlugins</strong></summary>
257
+
258
+ **Default plugins:** none
259
+
260
+ [Rehype plugins](https://github.com/rehypejs/rehype/blob/main/doc/plugins.md) allow you to transform the HTML that your Markdown generates. We recommend checking the [Remark plugin](https://github.com/remarkjs/remark/blob/main/doc/plugins.md) catalog first _before_ considering rehype plugins, since most users want to transform their Markdown syntax instead. If HTML transforms are what you need, we encourage you to browse [awesome-rehype](https://github.com/rehypejs/awesome-rehype) for a full curated list of plugins!
261
+
262
+ To apply rehype plugins, use the `rehypePlugins` configuration option like so:
263
+
264
+ ```js
265
+ // astro.config.mjs
266
+ import rehypeMinifyHtml from 'rehype-minify';
267
+
268
+ export default {
269
+ integrations: [mdx({
270
+ rehypePlugins: [rehypeMinifyHtml],
271
+ })],
272
+ }
273
+ ```
274
+ </details>
275
+
276
+ <details>
277
+ <summary><strong>frontmatterOptions</strong></summary>
278
+
279
+ **Default:** `{ name: 'frontmatter' }`
280
+
281
+ We use [remark-mdx-frontmatter](https://github.com/remcohaszing/remark-mdx-frontmatter) to parse YAML-based frontmatter in your MDX files. If you want to override our default configuration or extend remark-mdx-frontmatter (ex. to [apply a custom frontmatter parser](https://github.com/remcohaszing/remark-mdx-frontmatter#parsers)), you can supply a `frontmatterOptions` configuration.
282
+
283
+ For example, say you want to access frontmatter as root-level variables without a nested `frontmatter` object. You can override the [`name` configuration option](https://github.com/remcohaszing/remark-mdx-frontmatter#name) like so:
284
+
285
+ ```js
286
+ // astro.config.mjs
287
+ export default {
288
+ integrations: [mdx({
289
+ frontmatterOptions: {
290
+ name: '',
291
+ }
292
+ })],
293
+ }
294
+ ```
295
+
296
+ ```mdx
297
+ ---
298
+ title: I'm just a variable now!
299
+ ---
300
+
301
+ # {title}
302
+ ```
303
+
304
+ See the [remark-mdx-frontmatter README](https://github.com/remcohaszing/remark-mdx-frontmatter#options) for a complete list of options.
305
+ </details>
84
306
 
85
307
  ## Examples
86
308
 
package/dist/index.d.ts CHANGED
@@ -1,2 +1,18 @@
1
+ import { Options as MdxRollupPluginOptions } from '@mdx-js/rollup';
1
2
  import type { AstroIntegration } from 'astro';
2
- export default function mdx(): AstroIntegration;
3
+ import type { RemarkMdxFrontmatterOptions } from 'remark-mdx-frontmatter';
4
+ declare type WithExtends<T> = T | {
5
+ extends: T;
6
+ };
7
+ declare type MdxOptions = {
8
+ remarkPlugins?: WithExtends<MdxRollupPluginOptions['remarkPlugins']>;
9
+ rehypePlugins?: WithExtends<MdxRollupPluginOptions['rehypePlugins']>;
10
+ /**
11
+ * Configure the remark-mdx-frontmatter plugin
12
+ * @see https://github.com/remcohaszing/remark-mdx-frontmatter#options for a full list of options
13
+ * @default {{ name: 'frontmatter' }}
14
+ */
15
+ frontmatterOptions?: RemarkMdxFrontmatterOptions;
16
+ };
17
+ export default function mdx(mdxOptions?: MdxOptions): AstroIntegration;
18
+ export {};
package/dist/index.js CHANGED
@@ -1,31 +1,85 @@
1
+ import { nodeTypes } from "@mdx-js/mdx";
1
2
  import mdxPlugin from "@mdx-js/rollup";
2
- function mdx() {
3
+ import { parse as parseESM } from "es-module-lexer";
4
+ import rehypeRaw from "rehype-raw";
5
+ import remarkFrontmatter from "remark-frontmatter";
6
+ import remarkGfm from "remark-gfm";
7
+ import remarkMdxFrontmatter from "remark-mdx-frontmatter";
8
+ import remarkShikiTwoslash from "remark-shiki-twoslash";
9
+ import remarkSmartypants from "remark-smartypants";
10
+ import remarkPrism from "./remark-prism.js";
11
+ import { getFileInfo } from "./utils.js";
12
+ const DEFAULT_REMARK_PLUGINS = [remarkGfm, remarkSmartypants];
13
+ function handleExtends(config, defaults = []) {
14
+ if (Array.isArray(config))
15
+ return config;
16
+ return [...defaults, ...(config == null ? void 0 : config.extends) ?? []];
17
+ }
18
+ function mdx(mdxOptions = {}) {
3
19
  return {
4
20
  name: "@astrojs/mdx",
5
21
  hooks: {
6
- "astro:config:setup": ({ updateConfig, addPageExtension, command }) => {
22
+ "astro:config:setup": ({ updateConfig, config, addPageExtension, command }) => {
7
23
  addPageExtension(".mdx");
24
+ let remarkPlugins = handleExtends(mdxOptions.remarkPlugins, DEFAULT_REMARK_PLUGINS);
25
+ let rehypePlugins = handleExtends(mdxOptions.rehypePlugins);
26
+ if (config.markdown.syntaxHighlight === "shiki") {
27
+ remarkPlugins.push([
28
+ remarkShikiTwoslash.default,
29
+ config.markdown.shikiConfig
30
+ ]);
31
+ rehypePlugins.push([rehypeRaw, { passThrough: nodeTypes }]);
32
+ }
33
+ if (config.markdown.syntaxHighlight === "prism") {
34
+ remarkPlugins.push(remarkPrism);
35
+ rehypePlugins.push([rehypeRaw, { passThrough: nodeTypes }]);
36
+ }
37
+ remarkPlugins.push(remarkFrontmatter);
38
+ remarkPlugins.push([
39
+ remarkMdxFrontmatter,
40
+ {
41
+ name: "frontmatter",
42
+ ...mdxOptions.frontmatterOptions
43
+ }
44
+ ]);
8
45
  updateConfig({
9
46
  vite: {
10
47
  plugins: [
11
48
  {
12
49
  enforce: "pre",
13
50
  ...mdxPlugin({
51
+ remarkPlugins,
52
+ rehypePlugins,
14
53
  jsx: true,
15
54
  jsxImportSource: "astro",
16
55
  format: "mdx",
17
56
  mdExtensions: []
18
57
  })
19
58
  },
20
- command === "dev" && {
59
+ {
21
60
  name: "@astrojs/mdx",
22
61
  transform(code, id) {
23
62
  if (!id.endsWith(".mdx"))
24
63
  return;
25
- return `${code}
64
+ const [, moduleExports] = parseESM(code);
65
+ code += `
66
+ import "${"astro:scripts/page-ssr.js"}";`;
67
+ const { fileUrl, fileId } = getFileInfo(id, config);
68
+ if (!moduleExports.includes("url")) {
69
+ code += `
70
+ export const url = ${JSON.stringify(fileUrl)};`;
71
+ }
72
+ if (!moduleExports.includes("file")) {
73
+ code += `
74
+ export const file = ${JSON.stringify(fileId)};`;
75
+ }
76
+ if (command === "dev") {
77
+ code += `
26
78
  if (import.meta.hot) {
27
79
  import.meta.hot.decline();
28
80
  }`;
81
+ }
82
+ return code;
29
83
  }
30
84
  }
31
85
  ]
@@ -0,0 +1,2 @@
1
+ /** */
2
+ export default function remarkPrism(): (tree: any) => void;
@@ -0,0 +1,49 @@
1
+ import { addAstro } from "@astrojs/prism/internal";
2
+ import Prism from "prismjs";
3
+ import loadLanguages from "prismjs/components/index.js";
4
+ import { visit } from "unist-util-visit";
5
+ const languageMap = /* @__PURE__ */ new Map([["ts", "typescript"]]);
6
+ function runHighlighter(lang, code) {
7
+ let classLanguage = `language-${lang}`;
8
+ if (lang == null) {
9
+ lang = "plaintext";
10
+ }
11
+ const ensureLoaded = (language) => {
12
+ if (language && !Prism.languages[language]) {
13
+ loadLanguages([language]);
14
+ }
15
+ };
16
+ if (languageMap.has(lang)) {
17
+ ensureLoaded(languageMap.get(lang));
18
+ } else if (lang === "astro") {
19
+ ensureLoaded("typescript");
20
+ addAstro(Prism);
21
+ } else {
22
+ ensureLoaded("markup-templating");
23
+ ensureLoaded(lang);
24
+ }
25
+ if (lang && !Prism.languages[lang]) {
26
+ console.warn(`Unable to load the language: ${lang}`);
27
+ }
28
+ const grammar = Prism.languages[lang];
29
+ let html = code;
30
+ if (grammar) {
31
+ html = Prism.highlight(code, grammar, lang);
32
+ }
33
+ return { classLanguage, html };
34
+ }
35
+ function remarkPrism() {
36
+ return (tree) => visit(tree, "code", (node) => {
37
+ let { lang, value } = node;
38
+ node.type = "html";
39
+ let { html, classLanguage } = runHighlighter(lang, value);
40
+ let classes = [classLanguage];
41
+ node.value = `<pre class="${classes.join(
42
+ " "
43
+ )}"><code class="${classLanguage}">${html}</code></pre>`;
44
+ return node;
45
+ });
46
+ }
47
+ export {
48
+ remarkPrism as default
49
+ };
@@ -0,0 +1,8 @@
1
+ import type { AstroConfig } from 'astro';
2
+ interface FileInfo {
3
+ fileId: string;
4
+ fileUrl: string;
5
+ }
6
+ /** @see 'vite-plugin-utils' for source */
7
+ export declare function getFileInfo(id: string, config: AstroConfig): FileInfo;
8
+ export {};
package/dist/utils.js ADDED
@@ -0,0 +1,30 @@
1
+ function appendForwardSlash(path) {
2
+ return path.endsWith("/") ? path : path + "/";
3
+ }
4
+ function getFileInfo(id, config) {
5
+ const sitePathname = appendForwardSlash(
6
+ config.site ? new URL(config.base, config.site).pathname : config.base
7
+ );
8
+ let url = void 0;
9
+ try {
10
+ url = new URL(`file://${id}`);
11
+ } catch {
12
+ }
13
+ const fileId = id.split("?")[0];
14
+ let fileUrl;
15
+ const isPage = fileId.includes("/pages/");
16
+ if (isPage) {
17
+ fileUrl = fileId.replace(/^.*?\/pages\//, sitePathname).replace(/(\/index)?\.mdx$/, "");
18
+ } else if (url && url.pathname.startsWith(config.root.pathname)) {
19
+ fileUrl = url.pathname.slice(config.root.pathname.length);
20
+ } else {
21
+ fileUrl = fileId;
22
+ }
23
+ if (fileUrl && config.trailingSlash === "always") {
24
+ fileUrl = appendForwardSlash(fileUrl);
25
+ }
26
+ return { fileId, fileUrl };
27
+ }
28
+ export {
29
+ getFileInfo
30
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@astrojs/mdx",
3
3
  "description": "Use MDX within Astro",
4
- "version": "0.2.0",
4
+ "version": "0.3.1",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",
7
7
  "author": "withastro",
@@ -24,20 +24,33 @@
24
24
  "./package.json": "./package.json"
25
25
  },
26
26
  "dependencies": {
27
- "@mdx-js/rollup": "^2.1.1"
27
+ "@astrojs/prism": "^0.6.1",
28
+ "@mdx-js/mdx": "^2.1.2",
29
+ "@mdx-js/rollup": "^2.1.1",
30
+ "es-module-lexer": "^0.10.5",
31
+ "prismjs": "^1.28.0",
32
+ "rehype-raw": "^6.1.1",
33
+ "remark-gfm": "^3.0.1",
34
+ "remark-shiki-twoslash": "^3.1.0",
35
+ "remark-smartypants": "^2.0.0",
36
+ "shiki": "^0.10.1",
37
+ "unist-util-visit": "^4.1.0",
38
+ "remark-frontmatter": "^4.0.1",
39
+ "remark-mdx-frontmatter": "^2.0.2"
28
40
  },
29
41
  "devDependencies": {
30
42
  "@types/chai": "^4.3.1",
31
43
  "@types/mocha": "^9.1.1",
32
44
  "@types/yargs-parser": "^21.0.0",
33
- "astro": "1.0.0-beta.70",
45
+ "astro": "1.0.0-rc.2",
34
46
  "astro-scripts": "0.0.6",
35
47
  "chai": "^4.3.6",
48
+ "linkedom": "^0.14.12",
36
49
  "mocha": "^9.2.2",
37
- "linkedom": "^0.14.12"
50
+ "remark-toc": "^8.0.1"
38
51
  },
39
52
  "engines": {
40
- "node": "^14.20.0 || >=16.14.0"
53
+ "node": "^14.18.0 || >=16.12.0"
41
54
  },
42
55
  "scripts": {
43
56
  "build": "astro-scripts build \"src/**/*.ts\" && tsc",
package/src/index.ts CHANGED
@@ -1,18 +1,81 @@
1
- import mdxPlugin from '@mdx-js/rollup';
1
+ import { nodeTypes } from '@mdx-js/mdx';
2
+ import mdxPlugin, { Options as MdxRollupPluginOptions } from '@mdx-js/rollup';
2
3
  import type { AstroIntegration } from 'astro';
4
+ import { parse as parseESM } from 'es-module-lexer';
5
+ import rehypeRaw from 'rehype-raw';
6
+ import remarkFrontmatter from 'remark-frontmatter';
7
+ import remarkGfm from 'remark-gfm';
8
+ import type { RemarkMdxFrontmatterOptions } from 'remark-mdx-frontmatter';
9
+ import remarkMdxFrontmatter from 'remark-mdx-frontmatter';
10
+ import remarkShikiTwoslash from 'remark-shiki-twoslash';
11
+ import remarkSmartypants from 'remark-smartypants';
12
+ import remarkPrism from './remark-prism.js';
13
+ import { getFileInfo } from './utils.js';
3
14
 
4
- export default function mdx(): AstroIntegration {
15
+ type WithExtends<T> = T | { extends: T };
16
+
17
+ type MdxOptions = {
18
+ remarkPlugins?: WithExtends<MdxRollupPluginOptions['remarkPlugins']>;
19
+ rehypePlugins?: WithExtends<MdxRollupPluginOptions['rehypePlugins']>;
20
+ /**
21
+ * Configure the remark-mdx-frontmatter plugin
22
+ * @see https://github.com/remcohaszing/remark-mdx-frontmatter#options for a full list of options
23
+ * @default {{ name: 'frontmatter' }}
24
+ */
25
+ frontmatterOptions?: RemarkMdxFrontmatterOptions;
26
+ };
27
+
28
+ const DEFAULT_REMARK_PLUGINS = [remarkGfm, remarkSmartypants];
29
+
30
+ function handleExtends<T>(config: WithExtends<T[] | undefined>, defaults: T[] = []): T[] {
31
+ if (Array.isArray(config)) return config;
32
+
33
+ return [...defaults, ...(config?.extends ?? [])];
34
+ }
35
+
36
+ export default function mdx(mdxOptions: MdxOptions = {}): AstroIntegration {
5
37
  return {
6
38
  name: '@astrojs/mdx',
7
39
  hooks: {
8
- 'astro:config:setup': ({ updateConfig, addPageExtension, command }: any) => {
40
+ 'astro:config:setup': ({ updateConfig, config, addPageExtension, command }: any) => {
9
41
  addPageExtension('.mdx');
42
+ let remarkPlugins = handleExtends(mdxOptions.remarkPlugins, DEFAULT_REMARK_PLUGINS);
43
+ let rehypePlugins = handleExtends(mdxOptions.rehypePlugins);
44
+
45
+ if (config.markdown.syntaxHighlight === 'shiki') {
46
+ remarkPlugins.push([
47
+ // Default export still requires ".default" chaining for some reason
48
+ // Workarounds tried:
49
+ // - "import * as remarkShikiTwoslash"
50
+ // - "import { default as remarkShikiTwoslash }"
51
+ (remarkShikiTwoslash as any).default,
52
+ config.markdown.shikiConfig,
53
+ ]);
54
+ rehypePlugins.push([rehypeRaw, { passThrough: nodeTypes }]);
55
+ }
56
+
57
+ if (config.markdown.syntaxHighlight === 'prism') {
58
+ remarkPlugins.push(remarkPrism);
59
+ rehypePlugins.push([rehypeRaw, { passThrough: nodeTypes }]);
60
+ }
61
+
62
+ remarkPlugins.push(remarkFrontmatter);
63
+ remarkPlugins.push([
64
+ remarkMdxFrontmatter,
65
+ {
66
+ name: 'frontmatter',
67
+ ...mdxOptions.frontmatterOptions,
68
+ },
69
+ ]);
70
+
10
71
  updateConfig({
11
72
  vite: {
12
73
  plugins: [
13
74
  {
14
75
  enforce: 'pre',
15
76
  ...mdxPlugin({
77
+ remarkPlugins,
78
+ rehypePlugins,
16
79
  jsx: true,
17
80
  jsxImportSource: 'astro',
18
81
  // Note: disable `.md` support
@@ -20,14 +83,34 @@ export default function mdx(): AstroIntegration {
20
83
  mdExtensions: [],
21
84
  }),
22
85
  },
23
- command === 'dev' && {
86
+ {
24
87
  name: '@astrojs/mdx',
25
88
  transform(code: string, id: string) {
26
89
  if (!id.endsWith('.mdx')) return;
27
- // TODO: decline HMR updates until we have a stable approach
28
- return `${code}\nif (import.meta.hot) {
90
+ const [, moduleExports] = parseESM(code);
91
+
92
+ // This adds support for injected "page-ssr" scripts in MDX files.
93
+ // TODO: This should only be happening on page entrypoints, not all imported MDX.
94
+ // TODO: This code is copy-pasted across all Astro/Vite plugins that deal with page
95
+ // entrypoints (.astro, .md, .mdx). This should be handled in some centralized place,
96
+ // or otherwise refactored to not require copy-paste handling logic.
97
+ code += `\nimport "${'astro:scripts/page-ssr.js'}";`;
98
+
99
+ const { fileUrl, fileId } = getFileInfo(id, config);
100
+ if (!moduleExports.includes('url')) {
101
+ code += `\nexport const url = ${JSON.stringify(fileUrl)};`;
102
+ }
103
+ if (!moduleExports.includes('file')) {
104
+ code += `\nexport const file = ${JSON.stringify(fileId)};`;
105
+ }
106
+
107
+ if (command === 'dev') {
108
+ // TODO: decline HMR updates until we have a stable approach
109
+ code += `\nif (import.meta.hot) {
29
110
  import.meta.hot.decline();
30
111
  }`;
112
+ }
113
+ return code;
31
114
  },
32
115
  },
33
116
  ],
@@ -0,0 +1,60 @@
1
+ // TODO: discuss extracting this file to @astrojs/prism
2
+ import { addAstro } from '@astrojs/prism/internal';
3
+ import Prism from 'prismjs';
4
+ import loadLanguages from 'prismjs/components/index.js';
5
+ import { visit } from 'unist-util-visit';
6
+
7
+ const languageMap = new Map([['ts', 'typescript']]);
8
+
9
+ function runHighlighter(lang: string, code: string) {
10
+ let classLanguage = `language-${lang}`;
11
+
12
+ if (lang == null) {
13
+ lang = 'plaintext';
14
+ }
15
+
16
+ const ensureLoaded = (language: string) => {
17
+ if (language && !Prism.languages[language]) {
18
+ loadLanguages([language]);
19
+ }
20
+ };
21
+
22
+ if (languageMap.has(lang)) {
23
+ ensureLoaded(languageMap.get(lang)!);
24
+ } else if (lang === 'astro') {
25
+ ensureLoaded('typescript');
26
+ addAstro(Prism);
27
+ } else {
28
+ ensureLoaded('markup-templating'); // Prism expects this to exist for a number of other langs
29
+ ensureLoaded(lang);
30
+ }
31
+
32
+ if (lang && !Prism.languages[lang]) {
33
+ // eslint-disable-next-line no-console
34
+ console.warn(`Unable to load the language: ${lang}`);
35
+ }
36
+
37
+ const grammar = Prism.languages[lang];
38
+ let html = code;
39
+ if (grammar) {
40
+ html = Prism.highlight(code, grammar, lang);
41
+ }
42
+
43
+ return { classLanguage, html };
44
+ }
45
+
46
+ /** */
47
+ export default function remarkPrism() {
48
+ return (tree: any) =>
49
+ visit(tree, 'code', (node: any) => {
50
+ let { lang, value } = node;
51
+ node.type = 'html';
52
+
53
+ let { html, classLanguage } = runHighlighter(lang, value);
54
+ let classes = [classLanguage];
55
+ node.value = `<pre class="${classes.join(
56
+ ' '
57
+ )}"><code class="${classLanguage}">${html}</code></pre>`;
58
+ return node;
59
+ });
60
+ }
package/src/utils.ts ADDED
@@ -0,0 +1,39 @@
1
+ import type { AstroConfig } from 'astro';
2
+
3
+ function appendForwardSlash(path: string) {
4
+ return path.endsWith('/') ? path : path + '/';
5
+ }
6
+
7
+ interface FileInfo {
8
+ fileId: string;
9
+ fileUrl: string;
10
+ }
11
+
12
+ /** @see 'vite-plugin-utils' for source */
13
+ export function getFileInfo(id: string, config: AstroConfig): FileInfo {
14
+ const sitePathname = appendForwardSlash(
15
+ config.site ? new URL(config.base, config.site).pathname : config.base
16
+ );
17
+
18
+ // Try to grab the file's actual URL
19
+ let url: URL | undefined = undefined;
20
+ try {
21
+ url = new URL(`file://${id}`);
22
+ } catch {}
23
+
24
+ const fileId = id.split('?')[0];
25
+ let fileUrl: string;
26
+ const isPage = fileId.includes('/pages/');
27
+ if (isPage) {
28
+ fileUrl = fileId.replace(/^.*?\/pages\//, sitePathname).replace(/(\/index)?\.mdx$/, '');
29
+ } else if (url && url.pathname.startsWith(config.root.pathname)) {
30
+ fileUrl = url.pathname.slice(config.root.pathname.length);
31
+ } else {
32
+ fileUrl = fileId;
33
+ }
34
+
35
+ if (fileUrl && config.trailingSlash === 'always') {
36
+ fileUrl = appendForwardSlash(fileUrl);
37
+ }
38
+ return { fileId, fileUrl };
39
+ }
@@ -0,0 +1,9 @@
1
+ export async function get() {
2
+ const mdxPages = await import.meta.glob('./*.mdx', { eager: true });
3
+
4
+ return {
5
+ body: JSON.stringify({
6
+ titles: Object.values(mdxPages ?? {}).map(v => v?.customFrontmatter?.title),
7
+ })
8
+ }
9
+ }
@@ -0,0 +1,6 @@
1
+ ---
2
+ title: 'Using YAML frontmatter'
3
+ illThrowIfIDontExist: "Oh no, that's scary!"
4
+ ---
5
+
6
+ # {customFrontmatter.illThrowIfIDontExist}
@@ -0,0 +1,9 @@
1
+ export async function get() {
2
+ const mdxPages = await import.meta.glob('./*.mdx', { eager: true });
3
+
4
+ return {
5
+ body: JSON.stringify({
6
+ titles: Object.values(mdxPages ?? {}).map(v => v?.frontmatter?.title),
7
+ })
8
+ }
9
+ }
@@ -0,0 +1,6 @@
1
+ ---
2
+ title: 'Using YAML frontmatter'
3
+ illThrowIfIDontExist: "Oh no, that's scary!"
4
+ ---
5
+
6
+ # {frontmatter.illThrowIfIDontExist}
@@ -0,0 +1,5 @@
1
+ ---
2
+ one: hello
3
+ slug: one
4
+ ---
5
+ First mdx file
@@ -0,0 +1,34 @@
1
+ ---
2
+ export const getStaticPaths = async () => {
3
+ const content = await Astro.glob('../content/*.mdx');
4
+
5
+ return content
6
+ .filter((page) => !page.frontmatter.draft) // skip drafts
7
+ .map(({ default: MdxContent, frontmatter, url, file }) => {
8
+ return {
9
+ params: { slug: frontmatter.slug || "index" },
10
+ props: {
11
+ MdxContent,
12
+ file,
13
+ frontmatter,
14
+ url
15
+ }
16
+ }
17
+ })
18
+ }
19
+
20
+ const { MdxContent, frontmatter, url, file } = Astro.props;
21
+ ---
22
+
23
+ <html>
24
+ <head>
25
+ <title>Page</title>
26
+ </head>
27
+ <body>
28
+ <MdxContent />
29
+
30
+ <div id="one">{frontmatter.one}</div>
31
+ <div id="url">{url}</div>
32
+ <div id="file">{file}</div>
33
+ </body>
34
+ </html>
@@ -0,0 +1,3 @@
1
+ # GitHub-flavored Markdown test
2
+
3
+ This should auto-gen a link: https://example.com
@@ -0,0 +1,19 @@
1
+ # TOC test
2
+
3
+ ## Table of contents
4
+
5
+ ## Section 1
6
+
7
+ Some text!
8
+
9
+ ### Subsection 1
10
+
11
+ Some subsection test!
12
+
13
+ ### Subsection 2
14
+
15
+ Oh cool, more text!
16
+
17
+ ## Section 2
18
+
19
+ And section 2, with a hyperlink to check GFM is preserved: https://handle-me-gfm.com
@@ -0,0 +1,9 @@
1
+ # Syntax highlighting
2
+
3
+ ```astro
4
+ ---
5
+ const handlesAstroSyntax = true
6
+ ---
7
+
8
+ <h1>{handlesAstroSyntax}</h1>
9
+ ```
@@ -0,0 +1,9 @@
1
+ export async function get() {
2
+ const mdxPages = await import.meta.glob('./*.mdx', { eager: true });
3
+
4
+ return {
5
+ body: JSON.stringify({
6
+ urls: Object.values(mdxPages ?? {}).map(v => v?.url),
7
+ })
8
+ }
9
+ }
@@ -0,0 +1 @@
1
+ # I'm a page with a url of "/test-1!"
@@ -0,0 +1 @@
1
+ # I'm a page with a url of "/test-2!"
@@ -0,0 +1,3 @@
1
+ export const url = '/AH!'
2
+
3
+ # I'm a test with a url override!
@@ -0,0 +1,45 @@
1
+ import mdx from '@astrojs/mdx';
2
+
3
+ import { expect } from 'chai';
4
+ import { loadFixture } from '../../../astro/test/test-utils.js';
5
+
6
+ const FIXTURE_ROOT = new URL('./fixtures/mdx-frontmatter/', import.meta.url);
7
+
8
+ describe('MDX frontmatter', () => {
9
+ it('builds when "frontmatter.property" is in JSX expression', async () => {
10
+ const fixture = await loadFixture({
11
+ root: FIXTURE_ROOT,
12
+ integrations: [mdx()],
13
+ });
14
+ await fixture.build();
15
+ expect(true).to.equal(true);
16
+ });
17
+
18
+ it('extracts frontmatter to "frontmatter" export', async () => {
19
+ const fixture = await loadFixture({
20
+ root: FIXTURE_ROOT,
21
+ integrations: [mdx()],
22
+ });
23
+ await fixture.build();
24
+
25
+ const { titles } = JSON.parse(await fixture.readFile('/glob.json'));
26
+ expect(titles).to.include('Using YAML frontmatter');
27
+ });
28
+
29
+ it('extracts frontmatter to "customFrontmatter" export when configured', async () => {
30
+ const fixture = await loadFixture({
31
+ root: new URL('./fixtures/mdx-custom-frontmatter-name/', import.meta.url),
32
+ integrations: [
33
+ mdx({
34
+ frontmatterOptions: {
35
+ name: 'customFrontmatter',
36
+ },
37
+ }),
38
+ ],
39
+ });
40
+ await fixture.build();
41
+
42
+ const { titles } = JSON.parse(await fixture.readFile('/glob.json'));
43
+ expect(titles).to.include('Using YAML frontmatter');
44
+ });
45
+ });
@@ -0,0 +1,32 @@
1
+ import mdx from '@astrojs/mdx';
2
+
3
+ import { expect } from 'chai';
4
+ import { loadFixture } from '../../../astro/test/test-utils.js';
5
+ import * as cheerio from 'cheerio';
6
+
7
+ const FIXTURE_ROOT = new URL('./fixtures/mdx-get-static-paths', import.meta.url);
8
+
9
+ describe('getStaticPaths', () => {
10
+ /** @type {import('astro/test/test-utils').Fixture} */
11
+ let fixture;
12
+ before(async () => {
13
+ fixture = await loadFixture({
14
+ root: FIXTURE_ROOT,
15
+ integrations: [mdx()],
16
+ });
17
+ await fixture.build();
18
+ });
19
+
20
+ it('Provides file and url', async () => {
21
+ const html = await fixture.readFile('/one/index.html');
22
+
23
+ const $ = cheerio.load(html);
24
+ expect($('p').text()).to.equal('First mdx file');
25
+ expect($('#one').text()).to.equal('hello', 'Frontmatter included');
26
+ expect($('#url').text()).to.equal('/src/content/1.mdx', 'url is included');
27
+ expect($('#file').text()).to.contain(
28
+ 'fixtures/mdx-get-static-paths/src/content/1.mdx',
29
+ 'file is included'
30
+ );
31
+ });
32
+ });
@@ -0,0 +1,62 @@
1
+ import mdx from '@astrojs/mdx';
2
+
3
+ import { expect } from 'chai';
4
+ import { parseHTML } from 'linkedom';
5
+ import { loadFixture } from '../../../astro/test/test-utils.js';
6
+ import remarkToc from 'remark-toc';
7
+
8
+ const FIXTURE_ROOT = new URL('./fixtures/mdx-remark-plugins/', import.meta.url);
9
+
10
+ describe('MDX remark plugins', () => {
11
+ it('supports custom remark plugins - TOC', async () => {
12
+ const fixture = await loadFixture({
13
+ root: FIXTURE_ROOT,
14
+ integrations: [
15
+ mdx({
16
+ remarkPlugins: [remarkToc],
17
+ }),
18
+ ],
19
+ });
20
+ await fixture.build();
21
+
22
+ const html = await fixture.readFile('/with-toc/index.html');
23
+ const { document } = parseHTML(html);
24
+
25
+ const tocLink1 = document.querySelector('ul a[href="#section-1"]');
26
+ expect(tocLink1).to.not.be.null;
27
+ });
28
+
29
+ it('applies GitHub-flavored markdown by default', async () => {
30
+ const fixture = await loadFixture({
31
+ root: FIXTURE_ROOT,
32
+ integrations: [mdx()],
33
+ });
34
+ await fixture.build();
35
+
36
+ const html = await fixture.readFile('/with-gfm/index.html');
37
+ const { document } = parseHTML(html);
38
+
39
+ const autoGenLink = document.querySelector('a[href="https://example.com"]');
40
+ expect(autoGenLink).to.not.be.null;
41
+ });
42
+
43
+ it('preserves default GitHub-flavored markdown with "extends"', async () => {
44
+ const fixture = await loadFixture({
45
+ root: FIXTURE_ROOT,
46
+ integrations: [
47
+ mdx({
48
+ remarkPlugins: { extends: [remarkToc] },
49
+ }),
50
+ ],
51
+ });
52
+ await fixture.build();
53
+
54
+ const html = await fixture.readFile('/with-toc/index.html');
55
+ const { document } = parseHTML(html);
56
+
57
+ const tocLink1 = document.querySelector('ul a[href="#section-1"]');
58
+ expect(tocLink1).to.not.be.null;
59
+ const autoGenLink = document.querySelector('a[href="https://handle-me-gfm.com"]');
60
+ expect(autoGenLink).to.not.be.null;
61
+ });
62
+ });
@@ -0,0 +1,67 @@
1
+ import mdx from '@astrojs/mdx';
2
+
3
+ import { expect } from 'chai';
4
+ import { parseHTML } from 'linkedom';
5
+ import { loadFixture } from '../../../astro/test/test-utils.js';
6
+
7
+ const FIXTURE_ROOT = new URL('./fixtures/mdx-syntax-hightlighting/', import.meta.url);
8
+
9
+ describe('MDX syntax highlighting', () => {
10
+ describe('shiki', () => {
11
+ it('works', async () => {
12
+ const fixture = await loadFixture({
13
+ root: FIXTURE_ROOT,
14
+ markdown: {
15
+ syntaxHighlight: 'shiki',
16
+ },
17
+ integrations: [mdx()],
18
+ });
19
+ await fixture.build();
20
+
21
+ const html = await fixture.readFile('/index.html');
22
+ const { document } = parseHTML(html);
23
+
24
+ const shikiCodeBlock = document.querySelector('pre.shiki');
25
+ expect(shikiCodeBlock).to.not.be.null;
26
+ });
27
+
28
+ it('respects markdown.shikiConfig.theme', async () => {
29
+ const fixture = await loadFixture({
30
+ root: FIXTURE_ROOT,
31
+ markdown: {
32
+ syntaxHighlight: 'shiki',
33
+ shikiConfig: {
34
+ theme: 'dracula',
35
+ },
36
+ },
37
+ integrations: [mdx()],
38
+ });
39
+ await fixture.build();
40
+
41
+ const html = await fixture.readFile('/index.html');
42
+ const { document } = parseHTML(html);
43
+
44
+ const shikiCodeBlock = document.querySelector('pre.shiki.dracula');
45
+ expect(shikiCodeBlock).to.not.be.null;
46
+ });
47
+ });
48
+
49
+ describe('prism', () => {
50
+ it('works', async () => {
51
+ const fixture = await loadFixture({
52
+ root: FIXTURE_ROOT,
53
+ markdown: {
54
+ syntaxHighlight: 'prism',
55
+ },
56
+ integrations: [mdx()],
57
+ });
58
+ await fixture.build();
59
+
60
+ const html = await fixture.readFile('/index.html');
61
+ const { document } = parseHTML(html);
62
+
63
+ const prismCodeBlock = document.querySelector('pre.language-astro');
64
+ expect(prismCodeBlock).to.not.be.null;
65
+ });
66
+ });
67
+ });
@@ -0,0 +1,28 @@
1
+ import mdx from '@astrojs/mdx';
2
+
3
+ import { expect } from 'chai';
4
+ import { loadFixture } from '../../../astro/test/test-utils.js';
5
+
6
+ describe('MDX url export', () => {
7
+ let fixture;
8
+
9
+ before(async () => {
10
+ fixture = await loadFixture({
11
+ root: new URL('./fixtures/mdx-url-export/', import.meta.url),
12
+ integrations: [mdx()],
13
+ });
14
+
15
+ await fixture.build();
16
+ });
17
+
18
+ it('generates correct urls in glob result', async () => {
19
+ const { urls } = JSON.parse(await fixture.readFile('/pages.json'));
20
+ expect(urls).to.include('/test-1');
21
+ expect(urls).to.include('/test-2');
22
+ });
23
+
24
+ it('respects "export url" overrides in glob result', async () => {
25
+ const { urls } = JSON.parse(await fixture.readFile('/pages.json'));
26
+ expect(urls).to.include('/AH!');
27
+ });
28
+ });