@astrojs/mdx 0.5.0 → 0.8.0

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 (43) hide show
  1. package/.turbo/turbo-build.log +5 -5
  2. package/CHANGELOG.md +30 -0
  3. package/README.md +57 -76
  4. package/dist/astro-data-utils.d.ts +9 -0
  5. package/dist/astro-data-utils.js +47 -0
  6. package/dist/index.d.ts +0 -7
  7. package/dist/index.js +49 -44
  8. package/dist/utils.d.ts +2 -3
  9. package/dist/utils.js +4 -4
  10. package/package.json +4 -5
  11. package/src/astro-data-utils.ts +59 -0
  12. package/src/index.ts +63 -59
  13. package/src/utils.ts +2 -2
  14. package/test/fixtures/mdx-escape/src/components/Em.astro +7 -0
  15. package/test/fixtures/mdx-escape/src/components/P.astro +1 -0
  16. package/test/fixtures/mdx-escape/src/components/Title.astro +1 -0
  17. package/test/fixtures/mdx-escape/src/pages/html-tag.mdx +5 -0
  18. package/test/fixtures/mdx-escape/src/pages/index.mdx +13 -0
  19. package/test/fixtures/mdx-frontmatter/src/layouts/Base.astro +13 -3
  20. package/test/fixtures/mdx-frontmatter/src/pages/index.mdx +3 -0
  21. package/test/fixtures/mdx-frontmatter/src/pages/with-headings.mdx +7 -0
  22. package/test/fixtures/mdx-frontmatter-injection/astro.config.mjs +12 -0
  23. package/test/fixtures/mdx-frontmatter-injection/node_modules/.bin/astro +17 -0
  24. package/test/fixtures/mdx-frontmatter-injection/package.json +12 -0
  25. package/test/fixtures/mdx-frontmatter-injection/src/markdown-plugins.mjs +20 -0
  26. package/test/fixtures/mdx-frontmatter-injection/src/pages/glob.json.js +6 -0
  27. package/test/fixtures/mdx-frontmatter-injection/src/pages/page-1.mdx +3 -0
  28. package/test/fixtures/mdx-frontmatter-injection/src/pages/page-2.mdx +19 -0
  29. package/test/fixtures/mdx-frontmatter-injection/src/pages/with-overrides.mdx +7 -0
  30. package/test/fixtures/mdx-plus-react/astro.config.mjs +6 -0
  31. package/test/fixtures/mdx-plus-react/node_modules/.bin/astro +17 -0
  32. package/test/fixtures/mdx-plus-react/package.json +8 -0
  33. package/test/fixtures/mdx-plus-react/src/components/Component.jsx +5 -0
  34. package/test/fixtures/mdx-plus-react/src/pages/index.astro +11 -0
  35. package/test/fixtures/mdx-rehype-plugins/src/pages/reading-time.json.js +2 -2
  36. package/test/fixtures/mdx-remark-plugins/src/pages/headings-glob.json.js +6 -0
  37. package/test/mdx-escape.test.js +32 -0
  38. package/test/mdx-frontmatter-injection.test.js +44 -0
  39. package/test/mdx-frontmatter.test.js +20 -37
  40. package/test/mdx-plus-react.test.js +25 -0
  41. package/test/mdx-rehype-plugins.test.js +6 -17
  42. package/test/fixtures/mdx-custom-frontmatter-name/src/pages/glob.json.js +0 -9
  43. package/test/fixtures/mdx-custom-frontmatter-name/src/pages/index.mdx +0 -6
@@ -1,5 +1,5 @@
1
- @astrojs/mdx:build: cache hit, replaying output 87ac7debf5e14016
2
- @astrojs/mdx:build: 
3
- @astrojs/mdx:build: > @astrojs/mdx@0.5.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 fb941ae7dc16611b
2
+ @astrojs/mdx:build: 
3
+ @astrojs/mdx:build: > @astrojs/mdx@0.8.0 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,35 @@
1
1
  # @astrojs/mdx
2
2
 
3
+ ## 0.8.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#4204](https://github.com/withastro/astro/pull/4204) [`4c2ca5352`](https://github.com/withastro/astro/commit/4c2ca5352d0c4119ed2a9e5e0b78ce71eb1b414a) Thanks [@bholmesdev](https://github.com/bholmesdev)! - Remove `frontmatterOptions` from MDX config
8
+
9
+ ### Patch Changes
10
+
11
+ - [#4205](https://github.com/withastro/astro/pull/4205) [`6c9736cbc`](https://github.com/withastro/astro/commit/6c9736cbc90162f1de3ebccd7cfe98332749b639) Thanks [@bholmesdev](https://github.com/bholmesdev)! - Add frontmatter injection instructions to README
12
+
13
+ ## 0.7.0
14
+
15
+ ### Minor Changes
16
+
17
+ - [#4176](https://github.com/withastro/astro/pull/4176) [`2675b8633`](https://github.com/withastro/astro/commit/2675b8633c5d5c45b237ec87940d5eaf1bfb1b4b) Thanks [@bholmesdev](https://github.com/bholmesdev)! - Support frontmatter injection for MD and MDX using remark and rehype plugins
18
+
19
+ ### Patch Changes
20
+
21
+ - [#4181](https://github.com/withastro/astro/pull/4181) [`77cede720`](https://github.com/withastro/astro/commit/77cede720b09bce34f29c3d2d8b505311ce876b1) Thanks [@bholmesdev](https://github.com/bholmesdev)! - Make collect-headings rehype plugin non-overridable
22
+
23
+ * [#4174](https://github.com/withastro/astro/pull/4174) [`8eb3a8c6d`](https://github.com/withastro/astro/commit/8eb3a8c6d9554707963c3a3bc36ed8b68d3cf0fb) Thanks [@matthewp](https://github.com/matthewp)! - Allows using React with automatic imports alongside MDX
24
+
25
+ - [#4145](https://github.com/withastro/astro/pull/4145) [`c7efcf57e`](https://github.com/withastro/astro/commit/c7efcf57e00a0fcde3bc9f813e3cc59902bd484c) Thanks [@FredKSchott](https://github.com/FredKSchott)! - Fix a missing newline bug when `layout` was set.
26
+
27
+ ## 0.6.0
28
+
29
+ ### Minor Changes
30
+
31
+ - [#4134](https://github.com/withastro/astro/pull/4134) [`2968ba2b6`](https://github.com/withastro/astro/commit/2968ba2b6f00775b6e9872681b390cb466fdbfa2) Thanks [@bholmesdev](https://github.com/bholmesdev)! - Add `headings` and `frontmatter` properties to layout props
32
+
3
33
  ## 0.5.0
4
34
 
5
35
  ### Minor Changes
package/README.md CHANGED
@@ -20,33 +20,30 @@ Check out [“What is MDX?”](https://mdxjs.com/docs/what-is-mdx/), a deep-dive
20
20
 
21
21
  ## Installation
22
22
 
23
- <details>
24
- <summary>Quick Install</summary>
23
+ ### Quick Install
25
24
 
26
25
  The `astro add` command-line tool automates the installation for you. Run one of the following commands in a new terminal window. (If you aren't sure which package manager you're using, run the first command.) Then, follow the prompts, and type "y" in the terminal (meaning "yes") for each one.
27
26
 
28
- ```sh
29
- # Using NPM
30
- npx astro add mdx
31
- # Using Yarn
32
- yarn astro add mdx
33
- # Using PNPM
34
- pnpx astro add mdx
35
- ```
27
+ ```sh
28
+ # Using NPM
29
+ npx astro add mdx
30
+ # Using Yarn
31
+ yarn astro add mdx
32
+ # Using PNPM
33
+ pnpx astro add mdx
34
+ ```
36
35
 
37
36
  Then, restart the dev server by typing `CTRL-C` and then `npm run astro dev` in the terminal window that was running Astro.
38
37
 
39
38
  Because this command is new, it might not properly set things up. If that happens, [feel free to log an issue on our GitHub](https://github.com/withastro/astro/issues) and try the manual installation steps below.
40
- </details>
41
39
 
42
- <details>
43
- <summary>Manual Install</summary>
40
+ ### Manual Install
44
41
 
45
42
  First, install the `@astrojs/mdx` package using your package manager. If you're using npm or aren't sure, run this in the terminal:
46
43
 
47
- ```sh
48
- npm install @astrojs/mdx
49
- ```
44
+ ```sh
45
+ npm install @astrojs/mdx
46
+ ```
50
47
 
51
48
  Then, apply this integration to your `astro.config.*` file using the `integrations` property:
52
49
 
@@ -63,11 +60,14 @@ export default defineConfig({
63
60
  ```
64
61
 
65
62
  Finally, restart the dev server.
66
- </details>
67
63
 
68
64
  ## Usage
69
65
 
70
- To write your first MDX page in Astro, head to our [UI framework documentation][astro-ui-frameworks]. You'll explore:
66
+ You can [add MDX pages to your project](https://docs.astro.build/en/guides/markdown-content/#markdown-and-mdx-pages) by adding `.mdx` files within your `src/pages/` directory.
67
+
68
+ ### Components
69
+
70
+ To use components in your MDX pages in Astro, head to our [UI framework documentation][astro-ui-frameworks]. You'll explore:
71
71
  - 📦 how framework components are loaded,
72
72
  - 💧 client-side hydration options, and
73
73
  - 🪆 opportunities to mix and nest frameworks together
@@ -76,8 +76,6 @@ To write your first MDX page in Astro, head to our [UI framework documentation][
76
76
 
77
77
  > **Note**: `.mdx` files adhere to strict JSX syntax rather than Astro's HTML-like syntax.
78
78
 
79
- Also check our [Astro Integration Documentation][astro-integration] for more on integrations.
80
-
81
79
  ### Variables
82
80
 
83
81
  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.
@@ -123,7 +121,7 @@ A function that returns an array of all headings (i.e. `h1 -> h6` elements) in t
123
121
 
124
122
  ### Frontmatter
125
123
 
126
- 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.
124
+ Astro also supports YAML-based frontmatter out-of-the-box. By default, all variables declared in a frontmatter fence (`---`) will be accessible via the `frontmatter` export.
127
125
 
128
126
  For example, we can add a `title` and `publishDate` to an MDX page or component like so:
129
127
 
@@ -152,6 +150,40 @@ const posts = await Astro.glob('./*.mdx');
152
150
  ))}
153
151
  ```
154
152
 
153
+ ### Inject frontmatter via remark or rehype plugins
154
+
155
+ You may want to inject frontmatter properties across all of your MDX files. By using a [remark](#remarkPlugins) or [rehype](#remarkplugins) plugin, you can generate these properties based on a file’s contents.
156
+
157
+ You can append to the `data.astro.frontmatter` property from your plugin’s `file` argument like so:
158
+
159
+ ```js
160
+ // example-remark-plugin.mjs
161
+ export function exampleRemarkPlugin() {
162
+ // All remark and rehype plugins return a separate function
163
+ return function (tree, file) {
164
+ file.data.astro.frontmatter.customProperty = 'Generated property';
165
+ }
166
+ }
167
+ ```
168
+
169
+ After applying this plugin to your MDX integration config:
170
+
171
+ ```js
172
+ // astro.config.mjs
173
+ import mdx from '@astrojs/mdx';
174
+ import { exampleRemarkPlugin } from './example-remark-plugin.mjs';
175
+
176
+ export default {
177
+ integrations: [
178
+ mdx({
179
+ remarkPlugins: [exampleRemarkPlugin],
180
+ }),
181
+ ],
182
+ };
183
+ ```
184
+
185
+ …every MDX file will have `customProperty` in its frontmatter! See [our Markdown documentation](https://docs.astro.build/en/guides/markdown-content/#injecting-frontmatter) for more usage instructions and a [reading time plugin example](https://docs.astro.build/en/guides/markdown-content/#example-calculate-reading-time).
186
+
155
187
  ### Layouts
156
188
 
157
189
  Layouts can be applied [in the same way as standard Astro Markdown](https://docs.astro.build/en/guides/markdown-content/#markdown-layouts). You can add a `layout` to [your frontmatter](#frontmatter) like so:
@@ -255,8 +287,7 @@ This applies a minimal Prism renderer with added support for `astro` code blocks
255
287
 
256
288
  ## Configuration
257
289
 
258
- <details>
259
- <summary><strong>remarkPlugins</strong></summary>
290
+ ### remarkPlugins
260
291
 
261
292
  **Default plugins:** [remark-gfm](https://github.com/remarkjs/remark-gfm), [remark-smartypants](https://github.com/silvenon/remark-smartypants)
262
293
 
@@ -292,31 +323,13 @@ export default {
292
323
  }
293
324
  ```
294
325
 
295
- </details>
296
-
297
- <details>
298
- <summary><strong>rehypePlugins</strong></summary>
299
-
300
- **Default plugins:** [`collect-headings`](https://github.com/withastro/astro/blob/main/packages/integrations/mdx/src/rehype-collect-headings.ts)
326
+ ### rehypePlugins</strong>
301
327
 
302
328
  [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!
303
329
 
304
- We apply our own [`collect-headings`](https://github.com/withastro/astro/blob/main/packages/integrations/mdx/src/rehype-collect-headings.ts) plugin by default. This applies IDs to all headings (i.e. `h1 -> h6`) in your MDX files to [link to headings via anchor tags](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#linking_to_an_element_on_the_same_page).
330
+ We apply our own (non-overridable) [`collect-headings`](https://github.com/withastro/astro/blob/main/packages/integrations/mdx/src/rehype-collect-headings.ts) plugin. This applies IDs to all headings (i.e. `h1 -> h6`) in your MDX files to [link to headings via anchor tags](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#linking_to_an_element_on_the_same_page).
305
331
 
306
- To apply rehype plugins _while preserving_ Astro's default plugins, use a nested `extends` object like so:
307
-
308
- ```js
309
- // astro.config.mjs
310
- import rehypeMinifyHtml from 'rehype-minify';
311
-
312
- export default {
313
- integrations: [mdx({
314
- rehypePlugins: { extends: [rehypeMinifyHtml] },
315
- })],
316
- }
317
- ```
318
-
319
- To apply plugins _without_ Astro's defaults, you can apply a plain array:
332
+ To apply additional rehype plugins, pass an array to the `rehypePlugins` option like so:
320
333
 
321
334
  ```js
322
335
  // astro.config.mjs
@@ -328,38 +341,6 @@ export default {
328
341
  })],
329
342
  }
330
343
  ```
331
- </details>
332
-
333
- <details>
334
- <summary><strong>frontmatterOptions</strong></summary>
335
-
336
- **Default:** `{ name: 'frontmatter' }`
337
-
338
- 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.
339
-
340
- 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:
341
-
342
- ```js
343
- // astro.config.mjs
344
- export default {
345
- integrations: [mdx({
346
- frontmatterOptions: {
347
- name: '',
348
- }
349
- })],
350
- }
351
- ```
352
-
353
- ```mdx
354
- ---
355
- title: I'm just a variable now!
356
- ---
357
-
358
- # {title}
359
- ```
360
-
361
- See the [remark-mdx-frontmatter README](https://github.com/remcohaszing/remark-mdx-frontmatter#options) for a complete list of options.
362
- </details>
363
344
 
364
345
  ## Examples
365
346
 
@@ -0,0 +1,9 @@
1
+ import type { MarkdownAstroData } from 'astro';
2
+ import type { Data, VFile } from 'vfile';
3
+ export declare function remarkInitializeAstroData(): (tree: any, vfile: VFile) => void;
4
+ export declare function rehypeApplyFrontmatterExport(pageFrontmatter: Record<string, any>): (tree: any, vfile: VFile) => void;
5
+ /**
6
+ * Copied from markdown utils
7
+ * @see "vite-plugin-utils"
8
+ */
9
+ export declare function safelyGetAstroData(vfileData: Data): MarkdownAstroData;
@@ -0,0 +1,47 @@
1
+ import { jsToTreeNode } from "./utils.js";
2
+ function remarkInitializeAstroData() {
3
+ return function(tree, vfile) {
4
+ if (!vfile.data.astro) {
5
+ vfile.data.astro = { frontmatter: {} };
6
+ }
7
+ };
8
+ }
9
+ const EXPORT_NAME = "frontmatter";
10
+ function rehypeApplyFrontmatterExport(pageFrontmatter) {
11
+ return function(tree, vfile) {
12
+ const { frontmatter: injectedFrontmatter } = safelyGetAstroData(vfile.data);
13
+ const frontmatter = { ...injectedFrontmatter, ...pageFrontmatter };
14
+ const exportNodes = [
15
+ jsToTreeNode(`export const ${EXPORT_NAME} = ${JSON.stringify(frontmatter)};`)
16
+ ];
17
+ tree.children = exportNodes.concat(tree.children);
18
+ };
19
+ }
20
+ function isValidAstroData(obj) {
21
+ if (typeof obj === "object" && obj !== null && obj.hasOwnProperty("frontmatter")) {
22
+ const { frontmatter } = obj;
23
+ try {
24
+ JSON.stringify(frontmatter);
25
+ } catch {
26
+ return false;
27
+ }
28
+ return typeof frontmatter === "object" && frontmatter !== null;
29
+ }
30
+ return false;
31
+ }
32
+ function safelyGetAstroData(vfileData) {
33
+ const { astro } = vfileData;
34
+ if (!astro)
35
+ return { frontmatter: {} };
36
+ if (!isValidAstroData(astro)) {
37
+ throw Error(
38
+ `[MDX] A remark or rehype plugin tried to add invalid frontmatter. Ensure "astro.frontmatter" is a JSON object!`
39
+ );
40
+ }
41
+ return astro;
42
+ }
43
+ export {
44
+ rehypeApplyFrontmatterExport,
45
+ remarkInitializeAstroData,
46
+ safelyGetAstroData
47
+ };
package/dist/index.d.ts CHANGED
@@ -1,18 +1,11 @@
1
1
  import { Options as MdxRollupPluginOptions } from '@mdx-js/rollup';
2
2
  import type { AstroIntegration } from 'astro';
3
- import type { RemarkMdxFrontmatterOptions } from 'remark-mdx-frontmatter';
4
3
  declare type WithExtends<T> = T | {
5
4
  extends: T;
6
5
  };
7
6
  declare type MdxOptions = {
8
7
  remarkPlugins?: WithExtends<MdxRollupPluginOptions['remarkPlugins']>;
9
8
  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
9
  };
17
10
  export default function mdx(mdxOptions?: MdxOptions): AstroIntegration;
18
11
  export {};
package/dist/index.js CHANGED
@@ -2,52 +2,55 @@ import { compile as mdxCompile, nodeTypes } from "@mdx-js/mdx";
2
2
  import mdxPlugin from "@mdx-js/rollup";
3
3
  import { parse as parseESM } from "es-module-lexer";
4
4
  import rehypeRaw from "rehype-raw";
5
- import remarkFrontmatter from "remark-frontmatter";
6
5
  import remarkGfm from "remark-gfm";
7
- import remarkMdxFrontmatter from "remark-mdx-frontmatter";
8
6
  import remarkShikiTwoslash from "remark-shiki-twoslash";
9
7
  import remarkSmartypants from "remark-smartypants";
10
8
  import { VFile } from "vfile";
9
+ import { rehypeApplyFrontmatterExport, remarkInitializeAstroData } from "./astro-data-utils.js";
11
10
  import rehypeCollectHeadings from "./rehype-collect-headings.js";
12
11
  import remarkPrism from "./remark-prism.js";
13
- import { getFileInfo, getFrontmatter } from "./utils.js";
14
- const DEFAULT_REMARK_PLUGINS = [remarkGfm, remarkSmartypants];
15
- const DEFAULT_REHYPE_PLUGINS = [rehypeCollectHeadings];
12
+ import { getFileInfo, parseFrontmatter } from "./utils.js";
13
+ const DEFAULT_REMARK_PLUGINS = [
14
+ remarkGfm,
15
+ remarkSmartypants
16
+ ];
17
+ const DEFAULT_REHYPE_PLUGINS = [];
16
18
  function handleExtends(config, defaults = []) {
17
19
  if (Array.isArray(config))
18
20
  return config;
19
21
  return [...defaults, ...(config == null ? void 0 : config.extends) ?? []];
20
22
  }
23
+ function getRemarkPlugins(mdxOptions, config) {
24
+ let remarkPlugins = [
25
+ remarkInitializeAstroData,
26
+ ...handleExtends(mdxOptions.remarkPlugins, DEFAULT_REMARK_PLUGINS)
27
+ ];
28
+ if (config.markdown.syntaxHighlight === "shiki") {
29
+ const shikiTwoslash = remarkShikiTwoslash.default ?? remarkShikiTwoslash;
30
+ remarkPlugins.push([shikiTwoslash, config.markdown.shikiConfig]);
31
+ }
32
+ if (config.markdown.syntaxHighlight === "prism") {
33
+ remarkPlugins.push(remarkPrism);
34
+ }
35
+ return remarkPlugins;
36
+ }
37
+ function getRehypePlugins(mdxOptions, config) {
38
+ let rehypePlugins = handleExtends(mdxOptions.rehypePlugins, DEFAULT_REHYPE_PLUGINS);
39
+ if (config.markdown.syntaxHighlight === "shiki" || config.markdown.syntaxHighlight === "prism") {
40
+ rehypePlugins.push([rehypeRaw, { passThrough: nodeTypes }]);
41
+ }
42
+ rehypePlugins.push(rehypeCollectHeadings);
43
+ return rehypePlugins;
44
+ }
21
45
  function mdx(mdxOptions = {}) {
22
46
  return {
23
47
  name: "@astrojs/mdx",
24
48
  hooks: {
25
49
  "astro:config:setup": ({ updateConfig, config, addPageExtension, command }) => {
26
50
  addPageExtension(".mdx");
27
- let remarkPlugins = handleExtends(mdxOptions.remarkPlugins, DEFAULT_REMARK_PLUGINS);
28
- let rehypePlugins = handleExtends(mdxOptions.rehypePlugins, DEFAULT_REHYPE_PLUGINS);
29
- if (config.markdown.syntaxHighlight === "shiki") {
30
- remarkPlugins.push([
31
- remarkShikiTwoslash.default ?? remarkShikiTwoslash,
32
- config.markdown.shikiConfig
33
- ]);
34
- rehypePlugins.push([rehypeRaw, { passThrough: nodeTypes }]);
35
- }
36
- if (config.markdown.syntaxHighlight === "prism") {
37
- remarkPlugins.push(remarkPrism);
38
- rehypePlugins.push([rehypeRaw, { passThrough: nodeTypes }]);
39
- }
40
- remarkPlugins.push(remarkFrontmatter);
41
- remarkPlugins.push([
42
- remarkMdxFrontmatter,
43
- {
44
- name: "frontmatter",
45
- ...mdxOptions.frontmatterOptions
46
- }
47
- ]);
48
51
  const mdxPluginOpts = {
49
- remarkPlugins,
50
- rehypePlugins,
52
+ remarkPlugins: getRemarkPlugins(mdxOptions, config),
53
+ rehypePlugins: getRehypePlugins(mdxOptions, config),
51
54
  jsx: true,
52
55
  jsxImportSource: "astro",
53
56
  format: "mdx",
@@ -60,27 +63,29 @@ function mdx(mdxOptions = {}) {
60
63
  enforce: "pre",
61
64
  ...mdxPlugin(mdxPluginOpts),
62
65
  async transform(code, id) {
63
- var _a;
64
66
  if (!id.endsWith("mdx"))
65
67
  return;
66
- if (!((_a = mdxOptions.frontmatterOptions) == null ? void 0 : _a.parsers)) {
67
- const frontmatter = getFrontmatter(code, id);
68
- if (frontmatter.layout) {
69
- const { layout, ...content } = frontmatter;
70
- code += `
68
+ let { data: frontmatter, content: pageContent } = parseFrontmatter(code, id);
69
+ if (frontmatter.layout) {
70
+ const { layout, ...contentProp } = frontmatter;
71
+ pageContent += `
72
+
71
73
  export default async function({ children }) {
72
74
  const Layout = (await import(${JSON.stringify(
73
- frontmatter.layout
74
- )})).default;
75
- return <Layout content={${JSON.stringify(
76
- content
77
- )}}>{children}</Layout> }`;
78
- }
75
+ frontmatter.layout
76
+ )})).default;
77
+ const frontmatter=${JSON.stringify(
78
+ contentProp
79
+ )};
80
+ return <Layout frontmatter={frontmatter} content={frontmatter} headings={getHeadings()}>{children}</Layout> }`;
79
81
  }
80
- const compiled = await mdxCompile(
81
- new VFile({ value: code, path: id }),
82
- mdxPluginOpts
83
- );
82
+ const compiled = await mdxCompile(new VFile({ value: pageContent, path: id }), {
83
+ ...mdxPluginOpts,
84
+ rehypePlugins: [
85
+ ...mdxPluginOpts.rehypePlugins ?? [],
86
+ () => rehypeApplyFrontmatterExport(frontmatter)
87
+ ]
88
+ });
84
89
  return {
85
90
  code: String(compiled.value),
86
91
  map: compiled.map
package/dist/utils.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { Options as AcornOpts } from 'acorn';
2
2
  import type { AstroConfig } from 'astro';
3
3
  import type { MdxjsEsm } from 'mdast-util-mdx';
4
+ import matter from 'gray-matter';
4
5
  interface FileInfo {
5
6
  fileId: string;
6
7
  fileUrl: string;
@@ -11,8 +12,6 @@ export declare function getFileInfo(id: string, config: AstroConfig): FileInfo;
11
12
  * Match YAML exception handling from Astro core errors
12
13
  * @see 'astro/src/core/errors.ts'
13
14
  */
14
- export declare function getFrontmatter(code: string, id: string): {
15
- [key: string]: any;
16
- };
15
+ export declare function parseFrontmatter(code: string, id: string): matter.GrayMatterFile<string>;
17
16
  export declare function jsToTreeNode(jsString: string, acornOpts?: AcornOpts): MdxjsEsm;
18
17
  export {};
package/dist/utils.js CHANGED
@@ -27,9 +27,9 @@ function getFileInfo(id, config) {
27
27
  }
28
28
  return { fileId, fileUrl };
29
29
  }
30
- function getFrontmatter(code, id) {
30
+ function parseFrontmatter(code, id) {
31
31
  try {
32
- return matter(code).data;
32
+ return matter(code);
33
33
  } catch (e) {
34
34
  if (e.name === "YAMLException") {
35
35
  const err = e;
@@ -61,6 +61,6 @@ function jsToTreeNode(jsString, acornOpts = {
61
61
  }
62
62
  export {
63
63
  getFileInfo,
64
- getFrontmatter,
65
- jsToTreeNode
64
+ jsToTreeNode,
65
+ parseFrontmatter
66
66
  };
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.5.0",
4
+ "version": "0.8.0",
5
5
  "type": "module",
6
6
  "types": "./dist/index.d.ts",
7
7
  "author": "withastro",
@@ -14,7 +14,6 @@
14
14
  "keywords": [
15
15
  "astro-integration",
16
16
  "astro-component",
17
- "renderer",
18
17
  "mdx"
19
18
  ],
20
19
  "bugs": "https://github.com/withastro/astro/issues",
@@ -34,17 +33,17 @@
34
33
  "rehype-raw": "^6.1.1",
35
34
  "remark-frontmatter": "^4.0.1",
36
35
  "remark-gfm": "^3.0.1",
37
- "remark-mdx-frontmatter": "^2.0.2",
38
36
  "remark-shiki-twoslash": "^3.1.0",
39
37
  "remark-smartypants": "^2.0.0",
40
38
  "shiki": "^0.10.1",
41
- "unist-util-visit": "^4.1.0"
39
+ "unist-util-visit": "^4.1.0",
40
+ "vfile": "^5.3.2"
42
41
  },
43
42
  "devDependencies": {
44
43
  "@types/chai": "^4.3.1",
45
44
  "@types/mocha": "^9.1.1",
46
45
  "@types/yargs-parser": "^21.0.0",
47
- "astro": "1.0.0-rc.4",
46
+ "astro": "1.0.0-rc.8",
48
47
  "astro-scripts": "0.0.6",
49
48
  "chai": "^4.3.6",
50
49
  "linkedom": "^0.14.12",
@@ -0,0 +1,59 @@
1
+ import type { MarkdownAstroData } from 'astro';
2
+ import type { Data, VFile } from 'vfile';
3
+ import { jsToTreeNode } from './utils.js';
4
+
5
+ export function remarkInitializeAstroData() {
6
+ return function (tree: any, vfile: VFile) {
7
+ if (!vfile.data.astro) {
8
+ vfile.data.astro = { frontmatter: {} };
9
+ }
10
+ };
11
+ }
12
+
13
+ const EXPORT_NAME = 'frontmatter';
14
+
15
+ export function rehypeApplyFrontmatterExport(pageFrontmatter: Record<string, any>) {
16
+ return function (tree: any, vfile: VFile) {
17
+ const { frontmatter: injectedFrontmatter } = safelyGetAstroData(vfile.data);
18
+ const frontmatter = { ...injectedFrontmatter, ...pageFrontmatter };
19
+ const exportNodes = [
20
+ jsToTreeNode(`export const ${EXPORT_NAME} = ${JSON.stringify(frontmatter)};`),
21
+ ];
22
+ tree.children = exportNodes.concat(tree.children);
23
+ };
24
+ }
25
+
26
+ /**
27
+ * Copied from markdown utils
28
+ * @see "vite-plugin-utils"
29
+ */
30
+ function isValidAstroData(obj: unknown): obj is MarkdownAstroData {
31
+ if (typeof obj === 'object' && obj !== null && obj.hasOwnProperty('frontmatter')) {
32
+ const { frontmatter } = obj as any;
33
+ try {
34
+ // ensure frontmatter is JSON-serializable
35
+ JSON.stringify(frontmatter);
36
+ } catch {
37
+ return false;
38
+ }
39
+ return typeof frontmatter === 'object' && frontmatter !== null;
40
+ }
41
+ return false;
42
+ }
43
+
44
+ /**
45
+ * Copied from markdown utils
46
+ * @see "vite-plugin-utils"
47
+ */
48
+ export function safelyGetAstroData(vfileData: Data): MarkdownAstroData {
49
+ const { astro } = vfileData;
50
+
51
+ if (!astro) return { frontmatter: {} };
52
+ if (!isValidAstroData(astro)) {
53
+ throw Error(
54
+ `[MDX] A remark or rehype plugin tried to add invalid frontmatter. Ensure "astro.frontmatter" is a JSON object!`
55
+ );
56
+ }
57
+
58
+ return astro;
59
+ }