@astrojs/mdx 0.0.0-assets-uint8array-20231109073138
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.
- package/LICENSE +61 -0
- package/README.md +262 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +203 -0
- package/dist/plugins.d.ts +8 -0
- package/dist/plugins.js +82 -0
- package/dist/recma-inject-import-meta-env.d.ts +3 -0
- package/dist/recma-inject-import-meta-env.js +46 -0
- package/dist/rehype-apply-frontmatter-export.d.ts +2 -0
- package/dist/rehype-apply-frontmatter-export.js +46 -0
- package/dist/rehype-collect-headings.d.ts +2 -0
- package/dist/rehype-collect-headings.js +12 -0
- package/dist/rehype-meta-string.d.ts +6 -0
- package/dist/rehype-meta-string.js +14 -0
- package/dist/rehype-optimize-static.d.ts +11 -0
- package/dist/rehype-optimize-static.js +62 -0
- package/dist/remark-images-to-component.d.ts +5 -0
- package/dist/remark-images-to-component.js +92 -0
- package/dist/utils.d.ts +19 -0
- package/dist/utils.js +89 -0
- package/package.json +86 -0
- package/template/content-module-types.d.ts +9 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2021 Fred K. Schott
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
"""
|
|
25
|
+
This license applies to parts of the `packages/create-astro` and `packages/astro` subdirectories originating from the https://github.com/sveltejs/kit repository:
|
|
26
|
+
|
|
27
|
+
Copyright (c) 2020 [these people](https://github.com/sveltejs/kit/graphs/contributors)
|
|
28
|
+
|
|
29
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
30
|
+
|
|
31
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
32
|
+
|
|
33
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
"""
|
|
38
|
+
This license applies to parts of the `packages/create-astro` and `packages/astro` subdirectories originating from the https://github.com/vitejs/vite repository:
|
|
39
|
+
|
|
40
|
+
MIT License
|
|
41
|
+
|
|
42
|
+
Copyright (c) 2019-present, Yuxi (Evan) You and Vite contributors
|
|
43
|
+
|
|
44
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
45
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
46
|
+
in the Software without restriction, including without limitation the rights
|
|
47
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
48
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
49
|
+
furnished to do so, subject to the following conditions:
|
|
50
|
+
|
|
51
|
+
The above copyright notice and this permission notice shall be included in all
|
|
52
|
+
copies or substantial portions of the Software.
|
|
53
|
+
|
|
54
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
55
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
56
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
57
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
58
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
59
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
60
|
+
SOFTWARE.
|
|
61
|
+
"""
|
package/README.md
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
# @astrojs/mdx 📝
|
|
2
|
+
|
|
3
|
+
This **[Astro integration][astro-integration]** enables the usage of [MDX](https://mdxjs.com/) components and allows you to create pages as `.mdx` files.
|
|
4
|
+
|
|
5
|
+
- <strong>[Why MDX?](#why-mdx)</strong>
|
|
6
|
+
- <strong>[Installation](#installation)</strong>
|
|
7
|
+
- <strong>[Usage](#usage)</strong>
|
|
8
|
+
- <strong>[Configuration](#configuration)</strong>
|
|
9
|
+
- <strong>[Examples](#examples)</strong>
|
|
10
|
+
- <strong>[Troubleshooting](#troubleshooting)</strong>
|
|
11
|
+
- <strong>[Contributing](#contributing)</strong>
|
|
12
|
+
- <strong>[Changelog](#changelog)</strong>
|
|
13
|
+
|
|
14
|
+
## Why MDX?
|
|
15
|
+
|
|
16
|
+
MDX allows you to [use variables, JSX expressions and components within Markdown content](https://docs.astro.build/en/guides/markdown-content/#mdx-only-features) in Astro. If you have existing content authored in MDX, this integration allows you to bring those files to your Astro project.
|
|
17
|
+
|
|
18
|
+
## Installation
|
|
19
|
+
|
|
20
|
+
### Quick Install
|
|
21
|
+
|
|
22
|
+
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.
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
# Using NPM
|
|
26
|
+
npx astro add mdx
|
|
27
|
+
# Using Yarn
|
|
28
|
+
yarn astro add mdx
|
|
29
|
+
# Using PNPM
|
|
30
|
+
pnpm astro add mdx
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
If you run into any issues, [feel free to report them to us on GitHub](https://github.com/withastro/astro/issues) and try the manual installation steps below.
|
|
34
|
+
|
|
35
|
+
### Manual Install
|
|
36
|
+
|
|
37
|
+
First, install the `@astrojs/mdx` package using your package manager. If you're using npm or aren't sure, run this in the terminal:
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
npm install @astrojs/mdx
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Then, apply this integration to your `astro.config.*` file using the `integrations` property:
|
|
44
|
+
|
|
45
|
+
```diff lang="js" "mdx()"
|
|
46
|
+
// astro.config.mjs
|
|
47
|
+
import { defineConfig } from 'astro/config';
|
|
48
|
+
+ import mdx from '@astrojs/mdx';
|
|
49
|
+
|
|
50
|
+
export default defineConfig({
|
|
51
|
+
// ...
|
|
52
|
+
integrations: [mdx()],
|
|
53
|
+
// ^^^^^
|
|
54
|
+
});
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### Editor Integration
|
|
58
|
+
|
|
59
|
+
For editor support in [VS Code](https://code.visualstudio.com/), install the [official MDX extension](https://marketplace.visualstudio.com/items?itemName=unifiedjs.vscode-mdx).
|
|
60
|
+
|
|
61
|
+
For other editors, use the [MDX language server](https://github.com/mdx-js/mdx-analyzer/tree/main/packages/language-server).
|
|
62
|
+
|
|
63
|
+
## Usage
|
|
64
|
+
|
|
65
|
+
With the Astro MDX integration, 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. You can also [import `.mdx` files](https://docs.astro.build/en/guides/markdown-content/#importing-markdown) into `.astro` files.
|
|
66
|
+
|
|
67
|
+
Astro's MDX integration adds extra features to standard MDX, including Markdown-style frontmatter. This allows you to use most of Astro's built-in Markdown features like a [special frontmatter `layout` property](https://docs.astro.build/en/guides/markdown-content/#frontmatter-layout).
|
|
68
|
+
|
|
69
|
+
See how MDX works in Astro with examples in our [Markdown & MDX guide](https://docs.astro.build/en/guides/markdown-content/).
|
|
70
|
+
|
|
71
|
+
Visit the [MDX docs](https://mdxjs.com/docs/what-is-mdx/) to learn about using standard MDX features.
|
|
72
|
+
|
|
73
|
+
## Configuration
|
|
74
|
+
|
|
75
|
+
Once the MDX integration is installed, no configuration is necessary to use `.mdx` files in your Astro project.
|
|
76
|
+
|
|
77
|
+
You can configure how your MDX is rendered with the following options:
|
|
78
|
+
|
|
79
|
+
- [Options inherited from Markdown config](#options-inherited-from-markdown-config)
|
|
80
|
+
- [`extendMarkdownConfig`](#extendmarkdownconfig)
|
|
81
|
+
- [`recmaPlugins`](#recmaplugins)
|
|
82
|
+
- [`optimize`](#optimize)
|
|
83
|
+
|
|
84
|
+
### Options inherited from Markdown config
|
|
85
|
+
|
|
86
|
+
All [`markdown` configuration options](https://docs.astro.build/en/reference/configuration-reference/#markdown-options) except `drafts` can be configured separately in the MDX integration. This includes remark and rehype plugins, syntax highlighting, and more. Options will default to those in your Markdown config ([see the `extendMarkdownConfig` option](#extendmarkdownconfig) to modify this).
|
|
87
|
+
|
|
88
|
+
:::note
|
|
89
|
+
There is no separate MDX configuration for [including pages marked as draft in the build](https://docs.astro.build/en/reference/configuration-reference/#markdowndrafts). This Markdown setting will be respected by both Markdown and MDX files and cannot be overridden for MDX files specifically.
|
|
90
|
+
:::
|
|
91
|
+
|
|
92
|
+
```js
|
|
93
|
+
// astro.config.mjs
|
|
94
|
+
import { defineConfig } from 'astro/config';
|
|
95
|
+
import mdx from '@astrojs/mdx';
|
|
96
|
+
import remarkToc from 'remark-toc';
|
|
97
|
+
import rehypeMinifyHtml from 'rehype-minify-html';
|
|
98
|
+
|
|
99
|
+
export default defineConfig({
|
|
100
|
+
integrations: [
|
|
101
|
+
mdx({
|
|
102
|
+
syntaxHighlight: 'shiki',
|
|
103
|
+
shikiConfig: { theme: 'dracula' },
|
|
104
|
+
remarkPlugins: [remarkToc],
|
|
105
|
+
rehypePlugins: [rehypeMinifyHtml],
|
|
106
|
+
remarkRehype: { footnoteLabel: 'Footnotes' },
|
|
107
|
+
gfm: false,
|
|
108
|
+
}),
|
|
109
|
+
],
|
|
110
|
+
});
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
:::caution
|
|
114
|
+
MDX does not support passing remark and rehype plugins as a string. You should install, import, and apply the plugin function instead.
|
|
115
|
+
:::
|
|
116
|
+
|
|
117
|
+
📚 See the [Markdown Options reference](https://docs.astro.build/en/reference/configuration-reference/#markdown-options) for a complete list of options.
|
|
118
|
+
|
|
119
|
+
### `extendMarkdownConfig`
|
|
120
|
+
|
|
121
|
+
- **Type:** `boolean`
|
|
122
|
+
- **Default:** `true`
|
|
123
|
+
|
|
124
|
+
MDX will extend [your project's existing Markdown configuration](https://docs.astro.build/en/reference/configuration-reference/#markdown-options) by default. To override individual options, you can specify their equivalent in your MDX configuration.
|
|
125
|
+
|
|
126
|
+
For example, say you need to disable GitHub-Flavored Markdown and apply a different set of remark plugins for MDX files. You can apply these options like so, with `extendMarkdownConfig` enabled by default:
|
|
127
|
+
|
|
128
|
+
```js
|
|
129
|
+
// astro.config.mjs
|
|
130
|
+
import { defineConfig } from 'astro/config';
|
|
131
|
+
import mdx from '@astrojs/mdx';
|
|
132
|
+
|
|
133
|
+
export default defineConfig({
|
|
134
|
+
markdown: {
|
|
135
|
+
syntaxHighlight: 'prism',
|
|
136
|
+
remarkPlugins: [remarkPlugin1],
|
|
137
|
+
gfm: true,
|
|
138
|
+
},
|
|
139
|
+
integrations: [
|
|
140
|
+
mdx({
|
|
141
|
+
// `syntaxHighlight` inherited from Markdown
|
|
142
|
+
|
|
143
|
+
// Markdown `remarkPlugins` ignored,
|
|
144
|
+
// only `remarkPlugin2` applied.
|
|
145
|
+
remarkPlugins: [remarkPlugin2],
|
|
146
|
+
// `gfm` overridden to `false`
|
|
147
|
+
gfm: false,
|
|
148
|
+
}),
|
|
149
|
+
],
|
|
150
|
+
});
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
You may also need to disable `markdown` config extension in MDX. For this, set `extendMarkdownConfig` to `false`:
|
|
154
|
+
|
|
155
|
+
```js
|
|
156
|
+
// astro.config.mjs
|
|
157
|
+
import { defineConfig } from 'astro/config';
|
|
158
|
+
import mdx from '@astrojs/mdx';
|
|
159
|
+
|
|
160
|
+
export default defineConfig({
|
|
161
|
+
markdown: {
|
|
162
|
+
remarkPlugins: [remarkPlugin1],
|
|
163
|
+
},
|
|
164
|
+
integrations: [
|
|
165
|
+
mdx({
|
|
166
|
+
// Markdown config now ignored
|
|
167
|
+
extendMarkdownConfig: false,
|
|
168
|
+
// No `remarkPlugins` applied
|
|
169
|
+
}),
|
|
170
|
+
],
|
|
171
|
+
});
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
### `recmaPlugins`
|
|
175
|
+
|
|
176
|
+
These are plugins that modify the output [estree](https://github.com/estree/estree) directly. This is useful for modifying or injecting JavaScript variables in your MDX files.
|
|
177
|
+
|
|
178
|
+
We suggest [using AST Explorer](https://astexplorer.net/) to play with estree outputs, and trying [`estree-util-visit`](https://unifiedjs.com/explore/package/estree-util-visit/) for searching across JavaScript nodes.
|
|
179
|
+
|
|
180
|
+
### `optimize`
|
|
181
|
+
|
|
182
|
+
- **Type:** `boolean | { customComponentNames?: string[] }`
|
|
183
|
+
|
|
184
|
+
This is an optional configuration setting to optimize the MDX output for faster builds and rendering via an internal rehype plugin. This may be useful if you have many MDX files and notice slow builds. However, this option may generate some unescaped HTML, so make sure your site's interactive parts still work correctly after enabling it.
|
|
185
|
+
|
|
186
|
+
This is disabled by default. To enable MDX optimization, add the following to your MDX integration configuration:
|
|
187
|
+
|
|
188
|
+
```js
|
|
189
|
+
// astro.config.mjs
|
|
190
|
+
import { defineConfig } from 'astro/config';
|
|
191
|
+
import mdx from '@astrojs/mdx';
|
|
192
|
+
|
|
193
|
+
export default defineConfig({
|
|
194
|
+
integrations: [
|
|
195
|
+
mdx({
|
|
196
|
+
optimize: true,
|
|
197
|
+
}),
|
|
198
|
+
],
|
|
199
|
+
});
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
#### `customComponentNames`
|
|
203
|
+
|
|
204
|
+
- **Type:** `string[]`
|
|
205
|
+
|
|
206
|
+
An optional property of `optimize` to prevent the MDX optimizer from handling any [custom components passed to imported MDX content via the components prop](https://docs.astro.build/en/guides/markdown-content/#custom-components-with-imported-mdx).
|
|
207
|
+
|
|
208
|
+
You will need to exclude these components from optimization as the optimizer eagerly converts content into a static string, which will break custom components that needs to be dynamically rendered.
|
|
209
|
+
|
|
210
|
+
For example, the intended MDX output of the following is `<Heading>...</Heading>` in place of every `"<h1>...</h1>"`:
|
|
211
|
+
|
|
212
|
+
```astro
|
|
213
|
+
---
|
|
214
|
+
import { Content, components } from '../content.mdx';
|
|
215
|
+
import Heading from '../Heading.astro';
|
|
216
|
+
---
|
|
217
|
+
|
|
218
|
+
<Content components={{ ...components, h1: Heading }} />
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
To configure optimization for this using the `customComponentNames` property, specify an array of HTML element names that should be treated as custom components:
|
|
222
|
+
|
|
223
|
+
```js
|
|
224
|
+
// astro.config.mjs
|
|
225
|
+
import { defineConfig } from 'astro/config';
|
|
226
|
+
import mdx from '@astrojs/mdx';
|
|
227
|
+
|
|
228
|
+
export default defineConfig({
|
|
229
|
+
integrations: [
|
|
230
|
+
mdx({
|
|
231
|
+
optimize: {
|
|
232
|
+
// Prevent the optimizer from handling `h1` elements
|
|
233
|
+
// These will be treated as custom components
|
|
234
|
+
customComponentNames: ['h1'],
|
|
235
|
+
},
|
|
236
|
+
}),
|
|
237
|
+
],
|
|
238
|
+
});
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
Note that if your MDX file [configures custom components using `export const components = { ... }`](https://docs.astro.build/en/guides/markdown-content/#assigning-custom-components-to-html-elements), then you do not need to manually configure this option. The optimizer will automatically detect them.
|
|
242
|
+
|
|
243
|
+
## Examples
|
|
244
|
+
|
|
245
|
+
- The [Astro MDX starter template](https://github.com/withastro/astro/tree/latest/examples/with-mdx) shows how to use MDX files in your Astro project.
|
|
246
|
+
|
|
247
|
+
## Troubleshooting
|
|
248
|
+
|
|
249
|
+
For help, check out the `#support` channel on [Discord](https://astro.build/chat). Our friendly Support Squad members are here to help!
|
|
250
|
+
|
|
251
|
+
You can also check our [Astro Integration Documentation][astro-integration] for more on integrations.
|
|
252
|
+
|
|
253
|
+
## Contributing
|
|
254
|
+
|
|
255
|
+
This package is maintained by Astro's Core team. You're welcome to submit an issue or PR!
|
|
256
|
+
|
|
257
|
+
## Changelog
|
|
258
|
+
|
|
259
|
+
See [CHANGELOG.md](https://github.com/withastro/astro/tree/main/packages/integrations/mdx/CHANGELOG.md) for a history of changes to this integration.
|
|
260
|
+
|
|
261
|
+
[astro-integration]: https://docs.astro.build/en/guides/integrations-guide/
|
|
262
|
+
[astro-ui-frameworks]: https://docs.astro.build/en/core-concepts/framework-components/#using-framework-components
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { markdownConfigDefaults } from '@astrojs/markdown-remark';
|
|
2
|
+
import type { PluggableList } from '@mdx-js/mdx/lib/core.js';
|
|
3
|
+
import type { AstroIntegration } from 'astro';
|
|
4
|
+
import type { Options as RemarkRehypeOptions } from 'remark-rehype';
|
|
5
|
+
import type { OptimizeOptions } from './rehype-optimize-static.js';
|
|
6
|
+
export type MdxOptions = Omit<typeof markdownConfigDefaults, 'remarkPlugins' | 'rehypePlugins'> & {
|
|
7
|
+
extendMarkdownConfig: boolean;
|
|
8
|
+
recmaPlugins: PluggableList;
|
|
9
|
+
remarkPlugins: PluggableList;
|
|
10
|
+
rehypePlugins: PluggableList;
|
|
11
|
+
remarkRehype: RemarkRehypeOptions;
|
|
12
|
+
optimize: boolean | OptimizeOptions;
|
|
13
|
+
};
|
|
14
|
+
export default function mdx(partialMdxOptions?: Partial<MdxOptions>): AstroIntegration;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { markdownConfigDefaults, setVfileFrontmatter } from "@astrojs/markdown-remark";
|
|
2
|
+
import astroJSXRenderer from "astro/jsx/renderer.js";
|
|
3
|
+
import { parse as parseESM } from "es-module-lexer";
|
|
4
|
+
import fs from "node:fs/promises";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { VFile } from "vfile";
|
|
7
|
+
import { createMdxProcessor } from "./plugins.js";
|
|
8
|
+
import {
|
|
9
|
+
ASTRO_IMAGE_ELEMENT,
|
|
10
|
+
ASTRO_IMAGE_IMPORT,
|
|
11
|
+
USES_ASTRO_IMAGE_FLAG
|
|
12
|
+
} from "./remark-images-to-component.js";
|
|
13
|
+
import { getFileInfo, ignoreStringPlugins, parseFrontmatter } from "./utils.js";
|
|
14
|
+
function mdx(partialMdxOptions = {}) {
|
|
15
|
+
return {
|
|
16
|
+
name: "@astrojs/mdx",
|
|
17
|
+
hooks: {
|
|
18
|
+
"astro:config:setup": async (params) => {
|
|
19
|
+
const {
|
|
20
|
+
updateConfig,
|
|
21
|
+
config,
|
|
22
|
+
addPageExtension,
|
|
23
|
+
addContentEntryType,
|
|
24
|
+
command,
|
|
25
|
+
addRenderer
|
|
26
|
+
} = params;
|
|
27
|
+
addRenderer(astroJSXRenderer);
|
|
28
|
+
addPageExtension(".mdx");
|
|
29
|
+
addContentEntryType({
|
|
30
|
+
extensions: [".mdx"],
|
|
31
|
+
async getEntryInfo({ fileUrl, contents }) {
|
|
32
|
+
const parsed = parseFrontmatter(contents, fileURLToPath(fileUrl));
|
|
33
|
+
return {
|
|
34
|
+
data: parsed.data,
|
|
35
|
+
body: parsed.content,
|
|
36
|
+
slug: parsed.data.slug,
|
|
37
|
+
rawData: parsed.matter
|
|
38
|
+
};
|
|
39
|
+
},
|
|
40
|
+
contentModuleTypes: await fs.readFile(
|
|
41
|
+
new URL("../template/content-module-types.d.ts", import.meta.url),
|
|
42
|
+
"utf-8"
|
|
43
|
+
),
|
|
44
|
+
// MDX can import scripts and styles,
|
|
45
|
+
// so wrap all MDX files with script / style propagation checks
|
|
46
|
+
handlePropagation: true
|
|
47
|
+
});
|
|
48
|
+
const extendMarkdownConfig = partialMdxOptions.extendMarkdownConfig ?? defaultMdxOptions.extendMarkdownConfig;
|
|
49
|
+
const mdxOptions = applyDefaultOptions({
|
|
50
|
+
options: partialMdxOptions,
|
|
51
|
+
defaults: markdownConfigToMdxOptions(
|
|
52
|
+
extendMarkdownConfig ? config.markdown : markdownConfigDefaults
|
|
53
|
+
)
|
|
54
|
+
});
|
|
55
|
+
let processor;
|
|
56
|
+
updateConfig({
|
|
57
|
+
vite: {
|
|
58
|
+
plugins: [
|
|
59
|
+
{
|
|
60
|
+
name: "@mdx-js/rollup",
|
|
61
|
+
enforce: "pre",
|
|
62
|
+
configResolved(resolved) {
|
|
63
|
+
processor = createMdxProcessor(mdxOptions, {
|
|
64
|
+
sourcemap: !!resolved.build.sourcemap,
|
|
65
|
+
importMetaEnv: { SITE: config.site, ...resolved.env }
|
|
66
|
+
});
|
|
67
|
+
const jsxPluginIndex = resolved.plugins.findIndex((p) => p.name === "astro:jsx");
|
|
68
|
+
if (jsxPluginIndex !== -1) {
|
|
69
|
+
const myPluginIndex = resolved.plugins.findIndex(
|
|
70
|
+
(p) => p.name === "@mdx-js/rollup"
|
|
71
|
+
);
|
|
72
|
+
if (myPluginIndex !== -1) {
|
|
73
|
+
const myPlugin = resolved.plugins[myPluginIndex];
|
|
74
|
+
resolved.plugins.splice(myPluginIndex, 1);
|
|
75
|
+
resolved.plugins.splice(jsxPluginIndex, 0, myPlugin);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
// Override transform to alter code before MDX compilation
|
|
80
|
+
// ex. inject layouts
|
|
81
|
+
async transform(_, id) {
|
|
82
|
+
if (!id.endsWith(".mdx"))
|
|
83
|
+
return;
|
|
84
|
+
const { fileId } = getFileInfo(id, config);
|
|
85
|
+
const code = await fs.readFile(fileId, "utf-8");
|
|
86
|
+
const { data: frontmatter, content: pageContent } = parseFrontmatter(code, id);
|
|
87
|
+
const vfile = new VFile({ value: pageContent, path: id });
|
|
88
|
+
setVfileFrontmatter(vfile, frontmatter);
|
|
89
|
+
try {
|
|
90
|
+
const compiled = await processor.process(vfile);
|
|
91
|
+
return {
|
|
92
|
+
code: escapeViteEnvReferences(String(compiled.value)),
|
|
93
|
+
map: compiled.map
|
|
94
|
+
};
|
|
95
|
+
} catch (e) {
|
|
96
|
+
const err = e;
|
|
97
|
+
err.name = "MDXError";
|
|
98
|
+
err.loc = { file: fileId, line: e.line, column: e.column };
|
|
99
|
+
Error.captureStackTrace(err);
|
|
100
|
+
throw err;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
},
|
|
104
|
+
{
|
|
105
|
+
name: "@astrojs/mdx-postprocess",
|
|
106
|
+
// These transforms must happen *after* JSX runtime transformations
|
|
107
|
+
transform(code, id) {
|
|
108
|
+
if (!id.endsWith(".mdx"))
|
|
109
|
+
return;
|
|
110
|
+
const [moduleImports, moduleExports] = parseESM(code);
|
|
111
|
+
const importsFromJSXRuntime = moduleImports.filter(({ n }) => n === "astro/jsx-runtime").map(({ ss, se }) => code.substring(ss, se));
|
|
112
|
+
const hasFragmentImport = importsFromJSXRuntime.some(
|
|
113
|
+
(statement) => /[\s,{](Fragment,|Fragment\s*})/.test(statement)
|
|
114
|
+
);
|
|
115
|
+
if (!hasFragmentImport) {
|
|
116
|
+
code = 'import { Fragment } from "astro/jsx-runtime"\n' + code;
|
|
117
|
+
}
|
|
118
|
+
const { fileUrl, fileId } = getFileInfo(id, config);
|
|
119
|
+
if (!moduleExports.find(({ n }) => n === "url")) {
|
|
120
|
+
code += `
|
|
121
|
+
export const url = ${JSON.stringify(fileUrl)};`;
|
|
122
|
+
}
|
|
123
|
+
if (!moduleExports.find(({ n }) => n === "file")) {
|
|
124
|
+
code += `
|
|
125
|
+
export const file = ${JSON.stringify(fileId)};`;
|
|
126
|
+
}
|
|
127
|
+
if (!moduleExports.find(({ n }) => n === "Content")) {
|
|
128
|
+
const hasComponents = moduleExports.find(({ n }) => n === "components");
|
|
129
|
+
const usesAstroImage = moduleExports.find(
|
|
130
|
+
({ n }) => n === USES_ASTRO_IMAGE_FLAG
|
|
131
|
+
);
|
|
132
|
+
let componentsCode = `{ Fragment${hasComponents ? ", ...components" : ""}, ...props.components,`;
|
|
133
|
+
if (usesAstroImage) {
|
|
134
|
+
componentsCode += ` ${JSON.stringify(ASTRO_IMAGE_ELEMENT)}: ${hasComponents ? "components.img ?? " : ""} props.components?.img ?? ${ASTRO_IMAGE_IMPORT}`;
|
|
135
|
+
}
|
|
136
|
+
componentsCode += " }";
|
|
137
|
+
code = code.replace("export default MDXContent;", "");
|
|
138
|
+
code += `
|
|
139
|
+
export const Content = (props = {}) => MDXContent({
|
|
140
|
+
...props,
|
|
141
|
+
components: ${componentsCode},
|
|
142
|
+
});
|
|
143
|
+
export default Content;`;
|
|
144
|
+
}
|
|
145
|
+
code += `
|
|
146
|
+
Content[Symbol.for('mdx-component')] = true`;
|
|
147
|
+
code += `
|
|
148
|
+
Content[Symbol.for('astro.needsHeadRendering')] = !Boolean(frontmatter.layout);`;
|
|
149
|
+
code += `
|
|
150
|
+
Content.moduleId = ${JSON.stringify(id)};`;
|
|
151
|
+
if (command === "dev") {
|
|
152
|
+
code += `
|
|
153
|
+
if (import.meta.hot) {
|
|
154
|
+
import.meta.hot.decline();
|
|
155
|
+
}`;
|
|
156
|
+
}
|
|
157
|
+
return { code: escapeViteEnvReferences(code), map: null };
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
]
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
const defaultMdxOptions = {
|
|
168
|
+
extendMarkdownConfig: true,
|
|
169
|
+
recmaPlugins: []
|
|
170
|
+
};
|
|
171
|
+
function markdownConfigToMdxOptions(markdownConfig) {
|
|
172
|
+
return {
|
|
173
|
+
...defaultMdxOptions,
|
|
174
|
+
...markdownConfig,
|
|
175
|
+
remarkPlugins: ignoreStringPlugins(markdownConfig.remarkPlugins),
|
|
176
|
+
rehypePlugins: ignoreStringPlugins(markdownConfig.rehypePlugins),
|
|
177
|
+
remarkRehype: markdownConfig.remarkRehype ?? {},
|
|
178
|
+
optimize: false
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
function applyDefaultOptions({
|
|
182
|
+
options,
|
|
183
|
+
defaults
|
|
184
|
+
}) {
|
|
185
|
+
return {
|
|
186
|
+
syntaxHighlight: options.syntaxHighlight ?? defaults.syntaxHighlight,
|
|
187
|
+
extendMarkdownConfig: options.extendMarkdownConfig ?? defaults.extendMarkdownConfig,
|
|
188
|
+
recmaPlugins: options.recmaPlugins ?? defaults.recmaPlugins,
|
|
189
|
+
remarkRehype: options.remarkRehype ?? defaults.remarkRehype,
|
|
190
|
+
gfm: options.gfm ?? defaults.gfm,
|
|
191
|
+
smartypants: options.smartypants ?? defaults.smartypants,
|
|
192
|
+
remarkPlugins: options.remarkPlugins ?? defaults.remarkPlugins,
|
|
193
|
+
rehypePlugins: options.rehypePlugins ?? defaults.rehypePlugins,
|
|
194
|
+
shikiConfig: options.shikiConfig ?? defaults.shikiConfig,
|
|
195
|
+
optimize: options.optimize ?? defaults.optimize
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
function escapeViteEnvReferences(code) {
|
|
199
|
+
return code.replace(/import\.meta\.env/g, "import\\u002Emeta.env");
|
|
200
|
+
}
|
|
201
|
+
export {
|
|
202
|
+
mdx as default
|
|
203
|
+
};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Processor } from 'unified';
|
|
2
|
+
import type { MdxOptions } from './index.js';
|
|
3
|
+
interface MdxProcessorExtraOptions {
|
|
4
|
+
sourcemap: boolean;
|
|
5
|
+
importMetaEnv: Record<string, any>;
|
|
6
|
+
}
|
|
7
|
+
export declare function createMdxProcessor(mdxOptions: MdxOptions, extraOptions: MdxProcessorExtraOptions): Processor;
|
|
8
|
+
export {};
|
package/dist/plugins.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import {
|
|
2
|
+
rehypeHeadingIds,
|
|
3
|
+
remarkCollectImages,
|
|
4
|
+
remarkPrism,
|
|
5
|
+
remarkShiki
|
|
6
|
+
} from "@astrojs/markdown-remark";
|
|
7
|
+
import { createProcessor, nodeTypes } from "@mdx-js/mdx";
|
|
8
|
+
import rehypeRaw from "rehype-raw";
|
|
9
|
+
import remarkGfm from "remark-gfm";
|
|
10
|
+
import remarkSmartypants from "remark-smartypants";
|
|
11
|
+
import { SourceMapGenerator } from "source-map";
|
|
12
|
+
import { recmaInjectImportMetaEnv } from "./recma-inject-import-meta-env.js";
|
|
13
|
+
import { rehypeApplyFrontmatterExport } from "./rehype-apply-frontmatter-export.js";
|
|
14
|
+
import { rehypeInjectHeadingsExport } from "./rehype-collect-headings.js";
|
|
15
|
+
import rehypeMetaString from "./rehype-meta-string.js";
|
|
16
|
+
import { rehypeOptimizeStatic } from "./rehype-optimize-static.js";
|
|
17
|
+
import { remarkImageToComponent } from "./remark-images-to-component.js";
|
|
18
|
+
const isPerformanceBenchmark = Boolean(process.env.ASTRO_PERFORMANCE_BENCHMARK);
|
|
19
|
+
function createMdxProcessor(mdxOptions, extraOptions) {
|
|
20
|
+
return createProcessor({
|
|
21
|
+
remarkPlugins: getRemarkPlugins(mdxOptions),
|
|
22
|
+
rehypePlugins: getRehypePlugins(mdxOptions),
|
|
23
|
+
recmaPlugins: getRecmaPlugins(mdxOptions, extraOptions.importMetaEnv),
|
|
24
|
+
remarkRehypeOptions: mdxOptions.remarkRehype,
|
|
25
|
+
jsx: true,
|
|
26
|
+
jsxImportSource: "astro",
|
|
27
|
+
// Note: disable `.md` (and other alternative extensions for markdown files like `.markdown`) support
|
|
28
|
+
format: "mdx",
|
|
29
|
+
mdExtensions: [],
|
|
30
|
+
elementAttributeNameCase: "html",
|
|
31
|
+
SourceMapGenerator: extraOptions.sourcemap ? SourceMapGenerator : void 0
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
function getRemarkPlugins(mdxOptions) {
|
|
35
|
+
let remarkPlugins = [remarkCollectImages, remarkImageToComponent];
|
|
36
|
+
if (!isPerformanceBenchmark) {
|
|
37
|
+
if (mdxOptions.gfm) {
|
|
38
|
+
remarkPlugins.push(remarkGfm);
|
|
39
|
+
}
|
|
40
|
+
if (mdxOptions.smartypants) {
|
|
41
|
+
remarkPlugins.push(remarkSmartypants);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
remarkPlugins = [...remarkPlugins, ...mdxOptions.remarkPlugins];
|
|
45
|
+
if (!isPerformanceBenchmark) {
|
|
46
|
+
if (mdxOptions.syntaxHighlight === "shiki") {
|
|
47
|
+
remarkPlugins.push([remarkShiki, mdxOptions.shikiConfig]);
|
|
48
|
+
}
|
|
49
|
+
if (mdxOptions.syntaxHighlight === "prism") {
|
|
50
|
+
remarkPlugins.push(remarkPrism);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return remarkPlugins;
|
|
54
|
+
}
|
|
55
|
+
function getRehypePlugins(mdxOptions) {
|
|
56
|
+
let rehypePlugins = [
|
|
57
|
+
// ensure `data.meta` is preserved in `properties.metastring` for rehype syntax highlighters
|
|
58
|
+
rehypeMetaString,
|
|
59
|
+
// rehypeRaw allows custom syntax highlighters to work without added config
|
|
60
|
+
[rehypeRaw, { passThrough: nodeTypes }]
|
|
61
|
+
];
|
|
62
|
+
rehypePlugins = [
|
|
63
|
+
...rehypePlugins,
|
|
64
|
+
...mdxOptions.rehypePlugins,
|
|
65
|
+
// getHeadings() is guaranteed by TS, so this must be included.
|
|
66
|
+
// We run `rehypeHeadingIds` _last_ to respect any custom IDs set by user plugins.
|
|
67
|
+
...isPerformanceBenchmark ? [] : [rehypeHeadingIds, rehypeInjectHeadingsExport],
|
|
68
|
+
// computed from `astro.data.frontmatter` in VFile data
|
|
69
|
+
rehypeApplyFrontmatterExport
|
|
70
|
+
];
|
|
71
|
+
if (mdxOptions.optimize) {
|
|
72
|
+
const options = mdxOptions.optimize === true ? void 0 : mdxOptions.optimize;
|
|
73
|
+
rehypePlugins.push([rehypeOptimizeStatic, options]);
|
|
74
|
+
}
|
|
75
|
+
return rehypePlugins;
|
|
76
|
+
}
|
|
77
|
+
function getRecmaPlugins(mdxOptions, importMetaEnv) {
|
|
78
|
+
return [...mdxOptions.recmaPlugins ?? [], [recmaInjectImportMetaEnv, { importMetaEnv }]];
|
|
79
|
+
}
|
|
80
|
+
export {
|
|
81
|
+
createMdxProcessor
|
|
82
|
+
};
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { visit as estreeVisit } from "estree-util-visit";
|
|
2
|
+
function recmaInjectImportMetaEnv({
|
|
3
|
+
importMetaEnv
|
|
4
|
+
}) {
|
|
5
|
+
return (tree) => {
|
|
6
|
+
estreeVisit(tree, (node) => {
|
|
7
|
+
if (node.type === "MemberExpression") {
|
|
8
|
+
const envVarName = getImportMetaEnvVariableName(node);
|
|
9
|
+
if (typeof envVarName === "string") {
|
|
10
|
+
for (const key in node) {
|
|
11
|
+
delete node[key];
|
|
12
|
+
}
|
|
13
|
+
const envVarLiteral = {
|
|
14
|
+
type: "Literal",
|
|
15
|
+
value: importMetaEnv[envVarName],
|
|
16
|
+
raw: JSON.stringify(importMetaEnv[envVarName])
|
|
17
|
+
};
|
|
18
|
+
Object.assign(node, envVarLiteral);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
function getImportMetaEnvVariableName(node) {
|
|
25
|
+
try {
|
|
26
|
+
if (node.object.type !== "MemberExpression" || node.property.type !== "Identifier")
|
|
27
|
+
return new Error();
|
|
28
|
+
const nestedExpression = node.object;
|
|
29
|
+
if (nestedExpression.property.type !== "Identifier" || nestedExpression.property.name !== "env")
|
|
30
|
+
return new Error();
|
|
31
|
+
const envExpression = nestedExpression.object;
|
|
32
|
+
if (envExpression.type !== "MetaProperty" || envExpression.property.type !== "Identifier" || envExpression.property.name !== "meta")
|
|
33
|
+
return new Error();
|
|
34
|
+
if (envExpression.meta.name !== "import")
|
|
35
|
+
return new Error();
|
|
36
|
+
return node.property.name;
|
|
37
|
+
} catch (e) {
|
|
38
|
+
if (e instanceof Error) {
|
|
39
|
+
return e;
|
|
40
|
+
}
|
|
41
|
+
return new Error("Unknown parsing error");
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
export {
|
|
45
|
+
recmaInjectImportMetaEnv
|
|
46
|
+
};
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { InvalidAstroDataError } from "@astrojs/markdown-remark";
|
|
2
|
+
import { safelyGetAstroData } from "@astrojs/markdown-remark/dist/internal.js";
|
|
3
|
+
import { jsToTreeNode } from "./utils.js";
|
|
4
|
+
function rehypeApplyFrontmatterExport() {
|
|
5
|
+
return function(tree, vfile) {
|
|
6
|
+
const astroData = safelyGetAstroData(vfile.data);
|
|
7
|
+
if (astroData instanceof InvalidAstroDataError)
|
|
8
|
+
throw new Error(
|
|
9
|
+
// Copied from Astro core `errors-data`
|
|
10
|
+
// TODO: find way to import error data from core
|
|
11
|
+
'[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`.'
|
|
12
|
+
);
|
|
13
|
+
const { frontmatter } = astroData;
|
|
14
|
+
const exportNodes = [
|
|
15
|
+
jsToTreeNode(`export const frontmatter = ${JSON.stringify(frontmatter)};`)
|
|
16
|
+
];
|
|
17
|
+
if (frontmatter.layout) {
|
|
18
|
+
exportNodes.unshift(
|
|
19
|
+
jsToTreeNode(
|
|
20
|
+
/** @see 'vite-plugin-markdown' for layout props reference */
|
|
21
|
+
`import { jsx as layoutJsx } from 'astro/jsx-runtime';
|
|
22
|
+
|
|
23
|
+
export default async function ({ children }) {
|
|
24
|
+
const Layout = (await import(${JSON.stringify(frontmatter.layout)})).default;
|
|
25
|
+
const { layout, ...content } = frontmatter;
|
|
26
|
+
content.file = file;
|
|
27
|
+
content.url = url;
|
|
28
|
+
return layoutJsx(Layout, {
|
|
29
|
+
file,
|
|
30
|
+
url,
|
|
31
|
+
content,
|
|
32
|
+
frontmatter: content,
|
|
33
|
+
headings: getHeadings(),
|
|
34
|
+
'server:root': true,
|
|
35
|
+
children,
|
|
36
|
+
});
|
|
37
|
+
};`
|
|
38
|
+
)
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
tree.children = exportNodes.concat(tree.children);
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
export {
|
|
45
|
+
rehypeApplyFrontmatterExport
|
|
46
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { jsToTreeNode } from "./utils.js";
|
|
2
|
+
function rehypeInjectHeadingsExport() {
|
|
3
|
+
return function(tree, file) {
|
|
4
|
+
const headings = file.data.__astroHeadings || [];
|
|
5
|
+
tree.children.unshift(
|
|
6
|
+
jsToTreeNode(`export function getHeadings() { return ${JSON.stringify(headings)} }`)
|
|
7
|
+
);
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
export {
|
|
11
|
+
rehypeInjectHeadingsExport
|
|
12
|
+
};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Moves `data.meta` to `properties.metastring` for the `code` element node
|
|
3
|
+
* as `rehype-raw` strips `data` from all nodes, which may contain useful information.
|
|
4
|
+
* e.g. ```js {1:3} => metastring: "{1:3}"
|
|
5
|
+
*/
|
|
6
|
+
export default function rehypeMetaString(): (tree: any) => void;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { visit } from "unist-util-visit";
|
|
2
|
+
function rehypeMetaString() {
|
|
3
|
+
return function(tree) {
|
|
4
|
+
visit(tree, (node) => {
|
|
5
|
+
if (node.type === "element" && node.tagName === "code" && node.data?.meta) {
|
|
6
|
+
node.properties ??= {};
|
|
7
|
+
node.properties.metastring = node.data.meta;
|
|
8
|
+
}
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
export {
|
|
13
|
+
rehypeMetaString as default
|
|
14
|
+
};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface OptimizeOptions {
|
|
2
|
+
customComponentNames?: string[];
|
|
3
|
+
}
|
|
4
|
+
/**
|
|
5
|
+
* For MDX only, collapse static subtrees of the hast into `set:html`. Subtrees
|
|
6
|
+
* do not include any MDX elements.
|
|
7
|
+
*
|
|
8
|
+
* This optimization reduces the JS output as more content are represented as a
|
|
9
|
+
* string instead, which also reduces the AST size that Rollup holds in memory.
|
|
10
|
+
*/
|
|
11
|
+
export declare function rehypeOptimizeStatic(options?: OptimizeOptions): (tree: any) => void;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { visit } from "estree-util-visit";
|
|
2
|
+
import { toHtml } from "hast-util-to-html";
|
|
3
|
+
const exportConstComponentsRe = /export\s+const\s+components\s*=/;
|
|
4
|
+
function rehypeOptimizeStatic(options) {
|
|
5
|
+
return (tree) => {
|
|
6
|
+
const customComponentNames = new Set(options?.customComponentNames);
|
|
7
|
+
for (const child of tree.children) {
|
|
8
|
+
if (child.type === "mdxjsEsm" && exportConstComponentsRe.test(child.value)) {
|
|
9
|
+
const objectPropertyNodes = child.data.estree.body[0]?.declarations?.[0]?.init?.properties;
|
|
10
|
+
if (objectPropertyNodes) {
|
|
11
|
+
for (const objectPropertyNode of objectPropertyNodes) {
|
|
12
|
+
const componentName = objectPropertyNode.key?.name ?? objectPropertyNode.key?.value;
|
|
13
|
+
if (componentName) {
|
|
14
|
+
customComponentNames.add(componentName);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
const allPossibleElements = /* @__PURE__ */ new Set();
|
|
21
|
+
const elementStack = [];
|
|
22
|
+
visit(tree, {
|
|
23
|
+
enter(node) {
|
|
24
|
+
const isCustomComponent = node.tagName && customComponentNames.has(node.tagName);
|
|
25
|
+
if (node.type.startsWith("mdx") || isCustomComponent) {
|
|
26
|
+
for (const el of elementStack) {
|
|
27
|
+
allPossibleElements.delete(el);
|
|
28
|
+
}
|
|
29
|
+
elementStack.length = 0;
|
|
30
|
+
}
|
|
31
|
+
if (node.type === "element" || node.type === "mdxJsxFlowElement") {
|
|
32
|
+
elementStack.push(node);
|
|
33
|
+
allPossibleElements.add(node);
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
leave(node, _, __, parents) {
|
|
37
|
+
if (node.type === "element" || node.type === "mdxJsxFlowElement") {
|
|
38
|
+
elementStack.pop();
|
|
39
|
+
const parent = parents[parents.length - 1];
|
|
40
|
+
if (allPossibleElements.has(parent)) {
|
|
41
|
+
allPossibleElements.delete(node);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
for (const el of allPossibleElements) {
|
|
47
|
+
if (el.type === "mdxJsxFlowElement") {
|
|
48
|
+
el.attributes.push({
|
|
49
|
+
type: "mdxJsxAttribute",
|
|
50
|
+
name: "set:html",
|
|
51
|
+
value: toHtml(el.children)
|
|
52
|
+
});
|
|
53
|
+
} else {
|
|
54
|
+
el.properties["set:html"] = toHtml(el.children);
|
|
55
|
+
}
|
|
56
|
+
el.children = [];
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
export {
|
|
61
|
+
rehypeOptimizeStatic
|
|
62
|
+
};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { MarkdownVFile } from '@astrojs/markdown-remark';
|
|
2
|
+
export declare const ASTRO_IMAGE_ELEMENT = "astro-image";
|
|
3
|
+
export declare const ASTRO_IMAGE_IMPORT = "__AstroImage__";
|
|
4
|
+
export declare const USES_ASTRO_IMAGE_FLAG = "__usesAstroImage";
|
|
5
|
+
export declare function remarkImageToComponent(): (tree: any, file: MarkdownVFile) => void;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { visit } from "unist-util-visit";
|
|
2
|
+
import { jsToTreeNode } from "./utils.js";
|
|
3
|
+
const ASTRO_IMAGE_ELEMENT = "astro-image";
|
|
4
|
+
const ASTRO_IMAGE_IMPORT = "__AstroImage__";
|
|
5
|
+
const USES_ASTRO_IMAGE_FLAG = "__usesAstroImage";
|
|
6
|
+
function remarkImageToComponent() {
|
|
7
|
+
return function(tree, file) {
|
|
8
|
+
if (!file.data.imagePaths)
|
|
9
|
+
return;
|
|
10
|
+
const importsStatements = [];
|
|
11
|
+
const importedImages = /* @__PURE__ */ new Map();
|
|
12
|
+
visit(tree, "image", (node, index, parent) => {
|
|
13
|
+
if (file.data.imagePaths?.has(node.url)) {
|
|
14
|
+
let importName = importedImages.get(node.url);
|
|
15
|
+
if (!importName) {
|
|
16
|
+
importName = `__${importedImages.size}_${node.url.replace(/\W/g, "_")}__`;
|
|
17
|
+
importsStatements.push({
|
|
18
|
+
type: "mdxjsEsm",
|
|
19
|
+
value: "",
|
|
20
|
+
data: {
|
|
21
|
+
estree: {
|
|
22
|
+
type: "Program",
|
|
23
|
+
sourceType: "module",
|
|
24
|
+
body: [
|
|
25
|
+
{
|
|
26
|
+
type: "ImportDeclaration",
|
|
27
|
+
source: { type: "Literal", value: node.url, raw: JSON.stringify(node.url) },
|
|
28
|
+
specifiers: [
|
|
29
|
+
{
|
|
30
|
+
type: "ImportDefaultSpecifier",
|
|
31
|
+
local: { type: "Identifier", name: importName }
|
|
32
|
+
}
|
|
33
|
+
]
|
|
34
|
+
}
|
|
35
|
+
]
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
importedImages.set(node.url, importName);
|
|
40
|
+
}
|
|
41
|
+
const componentElement = {
|
|
42
|
+
name: ASTRO_IMAGE_ELEMENT,
|
|
43
|
+
type: "mdxJsxFlowElement",
|
|
44
|
+
attributes: [
|
|
45
|
+
{
|
|
46
|
+
name: "src",
|
|
47
|
+
type: "mdxJsxAttribute",
|
|
48
|
+
value: {
|
|
49
|
+
type: "mdxJsxAttributeValueExpression",
|
|
50
|
+
value: importName,
|
|
51
|
+
data: {
|
|
52
|
+
estree: {
|
|
53
|
+
type: "Program",
|
|
54
|
+
sourceType: "module",
|
|
55
|
+
comments: [],
|
|
56
|
+
body: [
|
|
57
|
+
{
|
|
58
|
+
type: "ExpressionStatement",
|
|
59
|
+
expression: { type: "Identifier", name: importName }
|
|
60
|
+
}
|
|
61
|
+
]
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
},
|
|
66
|
+
{ name: "alt", type: "mdxJsxAttribute", value: node.alt || "" }
|
|
67
|
+
],
|
|
68
|
+
children: []
|
|
69
|
+
};
|
|
70
|
+
if (node.title) {
|
|
71
|
+
componentElement.attributes.push({
|
|
72
|
+
type: "mdxJsxAttribute",
|
|
73
|
+
name: "title",
|
|
74
|
+
value: node.title
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
parent.children.splice(index, 1, componentElement);
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
tree.children.unshift(...importsStatements);
|
|
81
|
+
tree.children.unshift(
|
|
82
|
+
jsToTreeNode(`import { Image as ${ASTRO_IMAGE_IMPORT} } from "astro:assets";`)
|
|
83
|
+
);
|
|
84
|
+
tree.children.push(jsToTreeNode(`export const ${USES_ASTRO_IMAGE_FLAG} = true`));
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
export {
|
|
88
|
+
ASTRO_IMAGE_ELEMENT,
|
|
89
|
+
ASTRO_IMAGE_IMPORT,
|
|
90
|
+
USES_ASTRO_IMAGE_FLAG,
|
|
91
|
+
remarkImageToComponent
|
|
92
|
+
};
|
package/dist/utils.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { PluggableList } from '@mdx-js/mdx/lib/core.js';
|
|
2
|
+
import type { Options as AcornOpts } from 'acorn';
|
|
3
|
+
import type { AstroConfig } from 'astro';
|
|
4
|
+
import matter from 'gray-matter';
|
|
5
|
+
import type { MdxjsEsm } from 'mdast-util-mdx';
|
|
6
|
+
interface FileInfo {
|
|
7
|
+
fileId: string;
|
|
8
|
+
fileUrl: string;
|
|
9
|
+
}
|
|
10
|
+
/** @see 'vite-plugin-utils' for source */
|
|
11
|
+
export declare function getFileInfo(id: string, config: AstroConfig): FileInfo;
|
|
12
|
+
/**
|
|
13
|
+
* Match YAML exception handling from Astro core errors
|
|
14
|
+
* @see 'astro/src/core/errors.ts'
|
|
15
|
+
*/
|
|
16
|
+
export declare function parseFrontmatter(code: string, id: string): matter.GrayMatterFile<string>;
|
|
17
|
+
export declare function jsToTreeNode(jsString: string, acornOpts?: AcornOpts): MdxjsEsm;
|
|
18
|
+
export declare function ignoreStringPlugins(plugins: any[]): PluggableList;
|
|
19
|
+
export {};
|
package/dist/utils.js
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { parse } from "acorn";
|
|
2
|
+
import matter from "gray-matter";
|
|
3
|
+
import { bold, yellow } from "kleur/colors";
|
|
4
|
+
function appendForwardSlash(path) {
|
|
5
|
+
return path.endsWith("/") ? path : path + "/";
|
|
6
|
+
}
|
|
7
|
+
function getFileInfo(id, config) {
|
|
8
|
+
const sitePathname = appendForwardSlash(
|
|
9
|
+
config.site ? new URL(config.base, config.site).pathname : config.base
|
|
10
|
+
);
|
|
11
|
+
let url = void 0;
|
|
12
|
+
try {
|
|
13
|
+
url = new URL(`file://${id}`);
|
|
14
|
+
} catch {
|
|
15
|
+
}
|
|
16
|
+
const fileId = id.split("?")[0];
|
|
17
|
+
let fileUrl;
|
|
18
|
+
const isPage = fileId.includes("/pages/");
|
|
19
|
+
if (isPage) {
|
|
20
|
+
fileUrl = fileId.replace(/^.*?\/pages\//, sitePathname).replace(/(\/index)?\.mdx$/, "");
|
|
21
|
+
} else if (url?.pathname.startsWith(config.root.pathname)) {
|
|
22
|
+
fileUrl = url.pathname.slice(config.root.pathname.length);
|
|
23
|
+
} else {
|
|
24
|
+
fileUrl = fileId;
|
|
25
|
+
}
|
|
26
|
+
if (fileUrl && config.trailingSlash === "always") {
|
|
27
|
+
fileUrl = appendForwardSlash(fileUrl);
|
|
28
|
+
}
|
|
29
|
+
return { fileId, fileUrl };
|
|
30
|
+
}
|
|
31
|
+
function parseFrontmatter(code, id) {
|
|
32
|
+
try {
|
|
33
|
+
return matter(code);
|
|
34
|
+
} catch (e) {
|
|
35
|
+
if (e.name === "YAMLException") {
|
|
36
|
+
const err = e;
|
|
37
|
+
err.id = id;
|
|
38
|
+
err.loc = { file: e.id, line: e.mark.line + 1, column: e.mark.column };
|
|
39
|
+
err.message = e.reason;
|
|
40
|
+
throw err;
|
|
41
|
+
} else {
|
|
42
|
+
throw e;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function jsToTreeNode(jsString, acornOpts = {
|
|
47
|
+
ecmaVersion: "latest",
|
|
48
|
+
sourceType: "module"
|
|
49
|
+
}) {
|
|
50
|
+
return {
|
|
51
|
+
type: "mdxjsEsm",
|
|
52
|
+
value: "",
|
|
53
|
+
data: {
|
|
54
|
+
estree: {
|
|
55
|
+
body: [],
|
|
56
|
+
...parse(jsString, acornOpts),
|
|
57
|
+
type: "Program",
|
|
58
|
+
sourceType: "module"
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
function ignoreStringPlugins(plugins) {
|
|
64
|
+
let validPlugins = [];
|
|
65
|
+
let hasInvalidPlugin = false;
|
|
66
|
+
for (const plugin of plugins) {
|
|
67
|
+
if (typeof plugin === "string") {
|
|
68
|
+
console.warn(yellow(`[MDX] ${bold(plugin)} not applied.`));
|
|
69
|
+
hasInvalidPlugin = true;
|
|
70
|
+
} else if (Array.isArray(plugin) && typeof plugin[0] === "string") {
|
|
71
|
+
console.warn(yellow(`[MDX] ${bold(plugin[0])} not applied.`));
|
|
72
|
+
hasInvalidPlugin = true;
|
|
73
|
+
} else {
|
|
74
|
+
validPlugins.push(plugin);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
if (hasInvalidPlugin) {
|
|
78
|
+
console.warn(
|
|
79
|
+
`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`
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
return validPlugins;
|
|
83
|
+
}
|
|
84
|
+
export {
|
|
85
|
+
getFileInfo,
|
|
86
|
+
ignoreStringPlugins,
|
|
87
|
+
jsToTreeNode,
|
|
88
|
+
parseFrontmatter
|
|
89
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@astrojs/mdx",
|
|
3
|
+
"description": "Add support for MDX pages in your Astro site",
|
|
4
|
+
"version": "0.0.0-assets-uint8array-20231109073138",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"types": "./dist/index.d.ts",
|
|
7
|
+
"author": "withastro",
|
|
8
|
+
"license": "MIT",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "https://github.com/withastro/astro.git",
|
|
12
|
+
"directory": "packages/integrations/mdx"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [
|
|
15
|
+
"astro-integration",
|
|
16
|
+
"astro-component",
|
|
17
|
+
"mdx"
|
|
18
|
+
],
|
|
19
|
+
"bugs": "https://github.com/withastro/astro/issues",
|
|
20
|
+
"homepage": "https://docs.astro.build/en/guides/integrations-guide/mdx/",
|
|
21
|
+
"exports": {
|
|
22
|
+
".": "./dist/index.js",
|
|
23
|
+
"./package.json": "./package.json"
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"dist",
|
|
27
|
+
"template"
|
|
28
|
+
],
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@mdx-js/mdx": "^2.3.0",
|
|
31
|
+
"acorn": "^8.10.0",
|
|
32
|
+
"es-module-lexer": "^1.3.0",
|
|
33
|
+
"estree-util-visit": "^1.2.1",
|
|
34
|
+
"github-slugger": "^2.0.0",
|
|
35
|
+
"gray-matter": "^4.0.3",
|
|
36
|
+
"hast-util-to-html": "^8.0.4",
|
|
37
|
+
"kleur": "^4.1.4",
|
|
38
|
+
"rehype-raw": "^6.1.1",
|
|
39
|
+
"remark-gfm": "^3.0.1",
|
|
40
|
+
"remark-smartypants": "^2.0.0",
|
|
41
|
+
"source-map": "^0.7.4",
|
|
42
|
+
"unist-util-visit": "^4.1.2",
|
|
43
|
+
"vfile": "^5.3.7",
|
|
44
|
+
"@astrojs/markdown-remark": "0.0.0-assets-uint8array-20231109073138"
|
|
45
|
+
},
|
|
46
|
+
"peerDependencies": {
|
|
47
|
+
"astro": "0.0.0-assets-uint8array-20231109073138"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@types/chai": "^4.3.5",
|
|
51
|
+
"@types/estree": "^1.0.1",
|
|
52
|
+
"@types/mdast": "^3.0.12",
|
|
53
|
+
"@types/mocha": "^10.0.1",
|
|
54
|
+
"@types/yargs-parser": "^21.0.0",
|
|
55
|
+
"chai": "^4.3.7",
|
|
56
|
+
"cheerio": "1.0.0-rc.12",
|
|
57
|
+
"linkedom": "^0.15.1",
|
|
58
|
+
"mdast-util-mdx": "^2.0.1",
|
|
59
|
+
"mdast-util-to-string": "^3.2.0",
|
|
60
|
+
"mocha": "^10.2.0",
|
|
61
|
+
"reading-time": "^1.5.0",
|
|
62
|
+
"rehype-mathjax": "^4.0.3",
|
|
63
|
+
"rehype-pretty-code": "^0.10.0",
|
|
64
|
+
"remark-math": "^5.1.1",
|
|
65
|
+
"remark-rehype": "^10.1.0",
|
|
66
|
+
"remark-shiki-twoslash": "^3.1.3",
|
|
67
|
+
"remark-toc": "^8.0.1",
|
|
68
|
+
"unified": "^10.1.2",
|
|
69
|
+
"vite": "^4.4.9",
|
|
70
|
+
"astro": "0.0.0-assets-uint8array-20231109073138",
|
|
71
|
+
"astro-scripts": "0.0.14"
|
|
72
|
+
},
|
|
73
|
+
"engines": {
|
|
74
|
+
"node": ">=18.14.1"
|
|
75
|
+
},
|
|
76
|
+
"publishConfig": {
|
|
77
|
+
"provenance": true
|
|
78
|
+
},
|
|
79
|
+
"scripts": {
|
|
80
|
+
"build": "astro-scripts build \"src/**/*.ts\" && tsc",
|
|
81
|
+
"build:ci": "astro-scripts build \"src/**/*.ts\"",
|
|
82
|
+
"dev": "astro-scripts dev \"src/**/*.ts\"",
|
|
83
|
+
"test": "mocha --exit --timeout 20000",
|
|
84
|
+
"test:match": "mocha --timeout 20000 -g"
|
|
85
|
+
}
|
|
86
|
+
}
|