🎉 initiate project *astro_rewrite*

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

61
node_modules/@astrojs/mdx/LICENSE generated vendored Normal file
View file

@ -0,0 +1,61 @@
MIT License
Copyright (c) 2021 Fred K. Schott
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:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
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.
"""
This license applies to parts of the `packages/create-astro` and `packages/astro` subdirectories originating from the https://github.com/sveltejs/kit repository:
Copyright (c) 2020 [these people](https://github.com/sveltejs/kit/graphs/contributors)
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:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
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.
"""
"""
This license applies to parts of the `packages/create-astro` and `packages/astro` subdirectories originating from the https://github.com/vitejs/vite repository:
MIT License
Copyright (c) 2019-present, Yuxi (Evan) You and Vite contributors
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:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
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.
"""

272
node_modules/@astrojs/mdx/README.md generated vendored Normal file
View file

@ -0,0 +1,272 @@
# @astrojs/mdx 📝
This **[Astro integration][astro-integration]** enables the usage of [MDX](https://mdxjs.com/) components and allows you to create pages as `.mdx` files.
- <strong>[Why MDX?](#why-mdx)</strong>
- <strong>[Installation](#installation)</strong>
- <strong>[Usage](#usage)</strong>
- <strong>[Configuration](#configuration)</strong>
- <strong>[Examples](#examples)</strong>
- <strong>[Troubleshooting](#troubleshooting)</strong>
- <strong>[Contributing](#contributing)</strong>
- <strong>[Changelog](#changelog)</strong>
## Why MDX?
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.
## Installation
### Quick Install
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.
```sh
# Using NPM
npx astro add mdx
# Using Yarn
yarn astro add mdx
# Using PNPM
pnpm astro add mdx
```
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.
### Manual Install
First, install the `@astrojs/mdx` package using your package manager. If you're using npm or aren't sure, run this in the terminal:
```sh
npm install @astrojs/mdx
```
Then, apply this integration to your `astro.config.*` file using the `integrations` property:
__`astro.config.mjs`__
```js ins={2} "mdx()"
import { defineConfig } from 'astro/config';
import mdx from '@astrojs/mdx';
export default defineConfig({
// ...
integrations: [mdx()],
});
```
### Editor Integration
[VS Code](https://code.visualstudio.com/) supports Markdown by default. However, for MDX editor support, you may wish to add the following setting in your VSCode config. This ensures authoring MDX files provides a Markdown-like editor experience.
```json title=".vscode/settings.json"
"files.associations": {
"*.mdx": "markdown"
}
```
## Usage
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.
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) and a [property for marking a page as a draft](https://docs.astro.build/en/guides/markdown-content/#draft-pages).
See how MDX works in Astro with examples in our [Markdown & MDX guide](https://docs.astro.build/en/guides/markdown-content/).
Visit the [MDX docs](https://mdxjs.com/docs/what-is-mdx/) to learn about using standard MDX features.
## Configuration
Once the MDX integration is installed, no configuration is necessary to use `.mdx` files in your Astro project.
You can configure how your MDX is rendered with the following options:
- [Options inherited from Markdown config](#options-inherited-from-markdown-config)
- [`extendMarkdownConfig`](#extendmarkdownconfig)
- [`recmaPlugins`](#recmaplugins)
- [`optimize`](#optimize)
### Options inherited from Markdown config
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).
:::note
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.
:::
__`astro.config.mjs`__
```js
import { defineConfig } from 'astro/config';
import mdx from '@astrojs/mdx';
import remarkToc from 'remark-toc';
import rehypeMinifyHtml from 'rehype-minify-html';
export default defineConfig({
integrations: [
mdx({
syntaxHighlight: 'shiki',
shikiConfig: { theme: 'dracula' },
remarkPlugins: [remarkToc],
rehypePlugins: [rehypeMinifyHtml],
remarkRehype: { footnoteLabel: 'Footnotes' },
gfm: false,
})
]
})
```
:::caution
MDX does not support passing remark and rehype plugins as a string. You should install, import, and apply the plugin function instead.
:::
📚 See the [Markdown Options reference](https://docs.astro.build/en/reference/configuration-reference/#markdown-options) for a complete list of options.
### `extendMarkdownConfig`
- **Type:** `boolean`
- **Default:** `true`
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.
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:
__`astro.config.mjs`__
```js
import { defineConfig } from 'astro/config';
import mdx from '@astrojs/mdx';
export default defineConfig({
markdown: {
syntaxHighlight: 'prism',
remarkPlugins: [remarkPlugin1],
gfm: true,
},
integrations: [
mdx({
// `syntaxHighlight` inherited from Markdown
// Markdown `remarkPlugins` ignored,
// only `remarkPlugin2` applied.
remarkPlugins: [remarkPlugin2],
// `gfm` overridden to `false`
gfm: false,
})
]
});
```
You may also need to disable `markdown` config extension in MDX. For this, set `extendMarkdownConfig` to `false`:
__`astro.config.mjs`__
```js
import { defineConfig } from 'astro/config';
import mdx from '@astrojs/mdx';
export default defineConfig({
markdown: {
remarkPlugins: [remarkPlugin1],
},
integrations: [
mdx({
// Markdown config now ignored
extendMarkdownConfig: false,
// No `remarkPlugins` applied
})
]
});
```
### `recmaPlugins`
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.
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.
### `optimize`
- **Type:** `boolean | { customComponentNames?: string[] }`
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.
This is disabled by default. To enable MDX optimization, add the following to your MDX integration configuration:
__`astro.config.mjs`__
```js
import { defineConfig } from 'astro/config';
import mdx from '@astrojs/mdx';
export default defineConfig({
integrations: [
mdx({
optimize: true,
})
]
});
```
#### `customComponentNames`
- **Type:** `string[]`
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).
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.
For example, the intended MDX output of the following is `<Heading>...</Heading>` in place of every `"<h1>...</h1>"`:
```astro
---
import { Content, components } from '../content.mdx';
import Heading from '../Heading.astro';
---
<Content components={{...components, h1: Heading }} />
```
To configure optimization for this using the `customComponentNames` property, specify an array of HTML element names that should be treated as custom components:
__`astro.config.mjs`__
```js
import { defineConfig } from 'astro/config';
import mdx from '@astrojs/mdx';
export default defineConfig({
integrations: [
mdx({
optimize: {
// Prevent the optimizer from handling `h1` elements
// These will be treated as custom components
customComponentNames: ['h1'],
},
})
]
});
```
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.
## Examples
* 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.
## Troubleshooting
For help, check out the `#support` channel on [Discord](https://astro.build/chat). Our friendly Support Squad members are here to help!
You can also check our [Astro Integration Documentation][astro-integration] for more on integrations.
## Contributing
This package is maintained by Astro's Core team. You're welcome to submit an issue or PR!
## Changelog
See [CHANGELOG.md](https://github.com/withastro/astro/tree/main/packages/integrations/mdx/CHANGELOG.md) for a history of changes to this integration.
[astro-integration]: https://docs.astro.build/en/guides/integrations-guide/
[astro-ui-frameworks]: https://docs.astro.build/en/core-concepts/framework-components/#using-framework-components

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

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

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

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

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

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

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

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

View file

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

View file

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

View file

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

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

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

View file

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

View file

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

View file

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

View file

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

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

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

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

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

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

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

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

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

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

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

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

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

1
node_modules/@astrojs/mdx/node_modules/.bin/acorn generated vendored Symbolic link
View file

@ -0,0 +1 @@
../../../../acorn/bin/acorn

83
node_modules/@astrojs/mdx/package.json generated vendored Normal file
View file

@ -0,0 +1,83 @@
{
"name": "@astrojs/mdx",
"description": "Add support for MDX pages in your Astro site",
"version": "0.19.7",
"type": "module",
"types": "./dist/index.d.ts",
"author": "withastro",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/withastro/astro.git",
"directory": "packages/integrations/mdx"
},
"keywords": [
"astro-integration",
"astro-component",
"mdx"
],
"bugs": "https://github.com/withastro/astro/issues",
"homepage": "https://docs.astro.build/en/guides/integrations-guide/mdx/",
"exports": {
".": "./dist/index.js",
"./package.json": "./package.json"
},
"files": [
"dist",
"template"
],
"dependencies": {
"@astrojs/markdown-remark": "^2.2.1",
"@astrojs/prism": "^2.1.2",
"@mdx-js/mdx": "^2.3.0",
"acorn": "^8.8.0",
"es-module-lexer": "^1.1.1",
"estree-util-visit": "^1.2.0",
"github-slugger": "^1.4.0",
"gray-matter": "^4.0.3",
"hast-util-to-html": "^8.0.4",
"kleur": "^4.1.4",
"rehype-raw": "^6.1.1",
"remark-frontmatter": "^4.0.1",
"remark-gfm": "^3.0.1",
"remark-smartypants": "^2.0.0",
"shiki": "^0.14.1",
"source-map": "^0.7.4",
"unist-util-visit": "^4.1.0",
"vfile": "^5.3.2"
},
"devDependencies": {
"@types/chai": "^4.3.1",
"@types/estree": "^1.0.0",
"@types/github-slugger": "^1.3.0",
"@types/mdast": "^3.0.10",
"@types/mocha": "^9.1.1",
"@types/yargs-parser": "^21.0.0",
"chai": "^4.3.6",
"cheerio": "^1.0.0-rc.11",
"linkedom": "^0.14.12",
"mdast-util-mdx": "^2.0.0",
"mdast-util-to-string": "^3.1.0",
"mocha": "^9.2.2",
"reading-time": "^1.5.0",
"rehype-mathjax": "^4.0.2",
"rehype-pretty-code": "^0.4.0",
"remark-math": "^5.1.1",
"remark-rehype": "^10.1.0",
"remark-shiki-twoslash": "^3.1.0",
"remark-toc": "^8.0.1",
"vite": "^4.3.1",
"astro": "2.6.1",
"astro-scripts": "0.0.14"
},
"engines": {
"node": ">=16.12.0"
},
"scripts": {
"build": "astro-scripts build \"src/**/*.ts\" && tsc",
"build:ci": "astro-scripts build \"src/**/*.ts\"",
"dev": "astro-scripts dev \"src/**/*.ts\"",
"test": "mocha --exit --timeout 20000",
"test:match": "mocha --timeout 20000 -g"
}
}

View file

@ -0,0 +1,9 @@
declare module 'astro:content' {
interface Render {
'.mdx': Promise<{
Content: import('astro').MarkdownInstance<{}>['Content'];
headings: import('astro').MarkdownHeading[];
remarkPluginFrontmatter: Record<string, any>;
}>;
}
}