@astrojs/markdown-remark 0.9.4 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @astrojs/markdown-remark
2
2
 
3
+ ## 0.10.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#3410](https://github.com/withastro/astro/pull/3410) [`cfae9760`](https://github.com/withastro/astro/commit/cfae9760b252052b6189e96398b819a4337634a8) Thanks [@natemoo-re](https://github.com/natemoo-re)! - Significantally more stable behavior for "Markdown + Components" usage, which now handles component serialization much more similarly to MDX. Also supports switching between Components and Markdown without extra newlines, removes wrapping `<p>` tags from standalone components, and improves JSX expression handling.
8
+
3
9
  ## 0.9.4
4
10
 
5
11
  ### Patch Changes
package/dist/index.d.ts CHANGED
@@ -2,5 +2,6 @@ import type { MarkdownRenderingOptions, MarkdownRenderingResult } from './types'
2
2
  export * from './types.js';
3
3
  export declare const DEFAULT_REMARK_PLUGINS: string[];
4
4
  export declare const DEFAULT_REHYPE_PLUGINS: never[];
5
+ export declare function slug(value: string): string;
5
6
  /** Shared utility for rendering markdown */
6
- export declare function renderMarkdown(content: string, opts: MarkdownRenderingOptions): Promise<MarkdownRenderingResult>;
7
+ export declare function renderMarkdown(content: string, opts?: MarkdownRenderingOptions): Promise<MarkdownRenderingResult>;
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import createCollectHeaders from "./rehype-collect-headers.js";
2
2
  import scopedStyles from "./remark-scoped-styles.js";
3
- import { remarkExpressions, loadRemarkExpressions } from "./remark-expressions.js";
4
3
  import rehypeExpressions from "./rehype-expressions.js";
5
4
  import rehypeIslands from "./rehype-islands.js";
6
- import { remarkJsx, loadRemarkJsx } from "./remark-jsx.js";
5
+ import remarkMdxish from "./remark-mdxish.js";
6
+ import remarkMarkAndUnravel from "./remark-mark-and-unravel.js";
7
7
  import rehypeJsx from "./rehype-jsx.js";
8
8
  import rehypeEscape from "./rehype-escape.js";
9
9
  import remarkPrism from "./remark-prism.js";
@@ -15,17 +15,30 @@ import markdown from "remark-parse";
15
15
  import markdownToHtml from "remark-rehype";
16
16
  import rehypeStringify from "rehype-stringify";
17
17
  import rehypeRaw from "rehype-raw";
18
+ import Slugger from "github-slugger";
19
+ import { VFile } from "vfile";
18
20
  export * from "./types.js";
19
21
  const DEFAULT_REMARK_PLUGINS = ["remark-gfm", "remark-smartypants"];
20
22
  const DEFAULT_REHYPE_PLUGINS = [];
21
- async function renderMarkdown(content, opts) {
23
+ const slugger = new Slugger();
24
+ function slug(value) {
25
+ return slugger.slug(value);
26
+ }
27
+ async function renderMarkdown(content, opts = {}) {
22
28
  var _a;
23
- let { mode, syntaxHighlight, shikiConfig, remarkPlugins, rehypePlugins } = opts;
29
+ let {
30
+ fileURL,
31
+ mode = "mdx",
32
+ syntaxHighlight = "shiki",
33
+ shikiConfig = {},
34
+ remarkPlugins = [],
35
+ rehypePlugins = []
36
+ } = opts;
37
+ const input = new VFile({ value: content, path: fileURL });
24
38
  const scopedClassName = (_a = opts.$) == null ? void 0 : _a.scopedClassName;
25
39
  const isMDX = mode === "mdx";
26
40
  const { headers, rehypeCollectHeaders } = createCollectHeaders();
27
- await Promise.all([loadRemarkExpressions(), loadRemarkJsx()]);
28
- let parser = unified().use(markdown).use(isMDX ? [remarkJsx, remarkExpressions] : []).use([remarkUnwrap]);
41
+ let parser = unified().use(markdown).use(isMDX ? [remarkMdxish, remarkMarkAndUnravel] : []).use([remarkUnwrap]);
29
42
  if (remarkPlugins.length === 0 && rehypePlugins.length === 0) {
30
43
  remarkPlugins = [...DEFAULT_REMARK_PLUGINS];
31
44
  rehypePlugins = [...DEFAULT_REHYPE_PLUGINS];
@@ -48,7 +61,13 @@ async function renderMarkdown(content, opts) {
48
61
  markdownToHtml,
49
62
  {
50
63
  allowDangerousHtml: true,
51
- passThrough: ["raw", "mdxTextExpression", "mdxJsxTextElement", "mdxJsxFlowElement"]
64
+ passThrough: [
65
+ "raw",
66
+ "mdxFlowExpression",
67
+ "mdxJsxFlowElement",
68
+ "mdxJsxTextElement",
69
+ "mdxTextExpression"
70
+ ]
52
71
  }
53
72
  ]
54
73
  ]);
@@ -58,7 +77,7 @@ async function renderMarkdown(content, opts) {
58
77
  parser.use(isMDX ? [rehypeJsx, rehypeExpressions] : [rehypeRaw]).use(rehypeEscape).use(rehypeIslands);
59
78
  let result;
60
79
  try {
61
- const vfile = await parser.use([rehypeCollectHeaders]).use(rehypeStringify, { allowDangerousHtml: true }).process(content);
80
+ const vfile = await parser.use([rehypeCollectHeaders]).use(rehypeStringify, { allowDangerousHtml: true }).process(input);
62
81
  result = vfile.toString();
63
82
  } catch (err) {
64
83
  console.error(err);
@@ -72,5 +91,6 @@ async function renderMarkdown(content, opts) {
72
91
  export {
73
92
  DEFAULT_REHYPE_PLUGINS,
74
93
  DEFAULT_REMARK_PLUGINS,
75
- renderMarkdown
94
+ renderMarkdown,
95
+ slug
76
96
  };
@@ -0,0 +1,2 @@
1
+ export declare function mdxFromMarkdown(): any;
2
+ export declare function mdxToMarkdown(): any;
@@ -0,0 +1,14 @@
1
+ import { mdxExpressionFromMarkdown, mdxExpressionToMarkdown } from "mdast-util-mdx-expression";
2
+ import { mdxJsxFromMarkdown, mdxJsxToMarkdown } from "mdast-util-mdx-jsx";
3
+ function mdxFromMarkdown() {
4
+ return [mdxExpressionFromMarkdown, mdxJsxFromMarkdown];
5
+ }
6
+ function mdxToMarkdown() {
7
+ return {
8
+ extensions: [mdxExpressionToMarkdown, mdxJsxToMarkdown]
9
+ };
10
+ }
11
+ export {
12
+ mdxFromMarkdown,
13
+ mdxToMarkdown
14
+ };
@@ -15,13 +15,34 @@ function createCollectHeaders() {
15
15
  if (!level)
16
16
  return;
17
17
  const depth = Number.parseInt(level);
18
+ let raw = "";
18
19
  let text = "";
19
- visit(node, "text", (child) => {
20
- text += child.value;
20
+ let isJSX = false;
21
+ visit(node, (child) => {
22
+ if (child.type === "element") {
23
+ return;
24
+ }
25
+ if (child.type === "raw") {
26
+ if (child.value.startsWith("\n<") || child.value.endsWith(">\n")) {
27
+ raw += child.value.replace(/^\n|\n$/g, "");
28
+ return;
29
+ }
30
+ }
31
+ if (child.type === "text" || child.type === "raw") {
32
+ raw += child.value;
33
+ text += child.value;
34
+ isJSX = isJSX || child.value.includes("{");
35
+ }
21
36
  });
22
37
  node.properties = node.properties || {};
23
38
  if (typeof node.properties.id !== "string") {
24
- node.properties.id = slugger.slug(text);
39
+ if (isJSX) {
40
+ node.properties.id = `$$slug(\`${text.replace(/\{/g, "${")}\`)`;
41
+ node.type = "raw";
42
+ node.value = `<${node.tagName} id={${node.properties.id}}>${raw}</${node.tagName}>`;
43
+ } else {
44
+ node.properties.id = slugger.slug(text);
45
+ }
25
46
  }
26
47
  headers.push({ depth, slug: node.properties.id, text });
27
48
  });
@@ -1,9 +1,34 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1
20
  import { map } from "unist-util-map";
2
21
  function rehypeExpressions() {
3
22
  return function(node) {
4
23
  return map(node, (child) => {
24
+ if (child.type === "text") {
25
+ return __spreadProps(__spreadValues({}, child), { type: "raw" });
26
+ }
5
27
  if (child.type === "mdxTextExpression") {
6
- return { type: "text", value: `{${child.value}}` };
28
+ return { type: "raw", value: `{${child.value}}` };
29
+ }
30
+ if (child.type === "mdxFlowExpression") {
31
+ return { type: "raw", value: `{${child.value}}` };
7
32
  }
8
33
  return child;
9
34
  });
@@ -26,18 +26,41 @@ function rehypeJsx() {
26
26
  return __spreadProps(__spreadValues({}, child), { tagName: `${child.tagName}` });
27
27
  }
28
28
  if (MDX_ELEMENTS.has(child.type)) {
29
+ const attrs = child.attributes.reduce((acc, entry) => {
30
+ let attr = entry.value;
31
+ if (attr && typeof attr === "object") {
32
+ attr = `{${attr.value}}`;
33
+ } else if (attr && entry.type === "mdxJsxExpressionAttribute") {
34
+ attr = `{${attr}}`;
35
+ } else if (attr === null) {
36
+ attr = "";
37
+ } else if (typeof attr === "string") {
38
+ attr = `"${attr}"`;
39
+ }
40
+ if (!entry.name) {
41
+ return acc + ` ${attr}`;
42
+ }
43
+ return acc + ` ${entry.name}${attr ? "=" : ""}${attr}`;
44
+ }, "");
45
+ if (child.children.length === 0) {
46
+ return {
47
+ type: "raw",
48
+ value: `<${child.name}${attrs} />`
49
+ };
50
+ }
51
+ child.children.splice(0, 0, {
52
+ type: "raw",
53
+ value: `
54
+ <${child.name}${attrs}>`
55
+ });
56
+ child.children.push({
57
+ type: "raw",
58
+ value: `</${child.name}>
59
+ `
60
+ });
29
61
  return __spreadProps(__spreadValues({}, child), {
30
62
  type: "element",
31
- tagName: `${child.name}`,
32
- properties: child.attributes.reduce((acc, entry) => {
33
- let attr = entry.value;
34
- if (attr && typeof attr === "object") {
35
- attr = `{${attr.value}}`;
36
- } else if (attr === null) {
37
- attr = `{true}`;
38
- }
39
- return Object.assign(acc, { [entry.name]: attr });
40
- }, {})
63
+ tagName: `Fragment`
41
64
  });
42
65
  }
43
66
  return child;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @typedef {import('mdast').Root} Root
3
+ * @typedef {import('mdast').Content} Content
4
+ * @typedef {Root|Content} Node
5
+ * @typedef {Extract<Node, import('unist').Parent>} Parent
6
+ *
7
+ * @typedef {import('remark-mdx')} DoNotTouchAsThisImportItIncludesMdxInTree
8
+ */
9
+ /**
10
+ * A tiny plugin that unravels `<p><h1>x</h1></p>` but also
11
+ * `<p><Component /></p>` (so it has no knowledge of “HTML”).
12
+ * It also marks JSX as being explicitly JSX, so when a user passes a `h1`
13
+ * component, it is used for `# heading` but not for `<h1>heading</h1>`.
14
+ *
15
+ * @type {import('unified').Plugin<Array<void>, Root>}
16
+ */
17
+ export default function remarkMarkAndUnravel(): (tree: any) => void;
@@ -0,0 +1,45 @@
1
+ import { visit } from "unist-util-visit";
2
+ function remarkMarkAndUnravel() {
3
+ return (tree) => {
4
+ visit(tree, (node, index, parent_) => {
5
+ const parent = parent_;
6
+ let offset = -1;
7
+ let all = true;
8
+ let oneOrMore;
9
+ if (parent && typeof index === "number" && node.type === "paragraph") {
10
+ const children = node.children;
11
+ while (++offset < children.length) {
12
+ const child = children[offset];
13
+ if (child.type === "mdxJsxTextElement" || child.type === "mdxTextExpression") {
14
+ oneOrMore = true;
15
+ } else if (child.type === "text" && /^[\t\r\n ]+$/.test(String(child.value))) {
16
+ } else {
17
+ all = false;
18
+ break;
19
+ }
20
+ }
21
+ if (all && oneOrMore) {
22
+ offset = -1;
23
+ while (++offset < children.length) {
24
+ const child = children[offset];
25
+ if (child.type === "mdxJsxTextElement") {
26
+ child.type = "mdxJsxFlowElement";
27
+ }
28
+ if (child.type === "mdxTextExpression") {
29
+ child.type = "mdxFlowExpression";
30
+ }
31
+ }
32
+ parent.children.splice(index, 1, ...children);
33
+ return index;
34
+ }
35
+ }
36
+ if (node.type === "mdxJsxFlowElement" || node.type === "mdxJsxTextElement") {
37
+ const data = node.data || (node.data = {});
38
+ data._mdxExplicitJsx = true;
39
+ }
40
+ });
41
+ };
42
+ }
43
+ export {
44
+ remarkMarkAndUnravel as default
45
+ };
@@ -0,0 +1 @@
1
+ export default function remarkMdxish(this: any, options?: {}): void;
@@ -0,0 +1,15 @@
1
+ import { mdxjs } from "micromark-extension-mdxjs";
2
+ import { mdxFromMarkdown, mdxToMarkdown } from "./mdast-util-mdxish.js";
3
+ function remarkMdxish(options = {}) {
4
+ const data = this.data();
5
+ add("micromarkExtensions", mdxjs(options));
6
+ add("fromMarkdownExtensions", mdxFromMarkdown());
7
+ add("toMarkdownExtensions", mdxToMarkdown());
8
+ function add(field, value) {
9
+ const list = data[field] ? data[field] : data[field] = [];
10
+ list.push(value);
11
+ }
12
+ }
13
+ export {
14
+ remarkMdxish as default
15
+ };
@@ -1,7 +1,7 @@
1
1
  import { getHighlighter } from "shiki";
2
2
  import { visit } from "unist-util-visit";
3
3
  const highlighterCacheAsync = /* @__PURE__ */ new Map();
4
- const remarkShiki = async ({ langs, theme, wrap }, scopedClassName) => {
4
+ const remarkShiki = async ({ langs = [], theme = "github-dark", wrap = false }, scopedClassName) => {
5
5
  const cacheID = typeof theme === "string" ? theme : theme.name;
6
6
  let highlighterAsync = highlighterCacheAsync.get(cacheID);
7
7
  if (!highlighterAsync) {
package/dist/types.d.ts CHANGED
@@ -8,19 +8,21 @@ export declare type RemarkPlugins = (string | [string, any] | RemarkPlugin | [Re
8
8
  export declare type RehypePlugin<PluginParameters extends any[] = any[]> = unified.Plugin<PluginParameters, hast.Root>;
9
9
  export declare type RehypePlugins = (string | [string, any] | RehypePlugin | [RehypePlugin, any])[];
10
10
  export interface ShikiConfig {
11
- langs: ILanguageRegistration[];
12
- theme: Theme | IThemeRegistration;
13
- wrap: boolean | null;
11
+ langs?: ILanguageRegistration[];
12
+ theme?: Theme | IThemeRegistration;
13
+ wrap?: boolean | null;
14
14
  }
15
15
  export interface AstroMarkdownOptions {
16
- mode: 'md' | 'mdx';
17
- drafts: boolean;
18
- syntaxHighlight: 'shiki' | 'prism' | false;
19
- shikiConfig: ShikiConfig;
20
- remarkPlugins: RemarkPlugins;
21
- rehypePlugins: RehypePlugins;
16
+ mode?: 'md' | 'mdx';
17
+ drafts?: boolean;
18
+ syntaxHighlight?: 'shiki' | 'prism' | false;
19
+ shikiConfig?: ShikiConfig;
20
+ remarkPlugins?: RemarkPlugins;
21
+ rehypePlugins?: RehypePlugins;
22
22
  }
23
23
  export interface MarkdownRenderingOptions extends AstroMarkdownOptions {
24
+ /** @internal */
25
+ fileURL?: URL;
24
26
  /** @internal */
25
27
  $?: {
26
28
  scopedClassName: string | null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrojs/markdown-remark",
3
- "version": "0.9.4",
3
+ "version": "0.10.0",
4
4
  "type": "module",
5
5
  "author": "withastro",
6
6
  "license": "MIT",
@@ -23,6 +23,7 @@
23
23
  "mdast-util-mdx-jsx": "^1.2.0",
24
24
  "mdast-util-to-string": "^3.1.0",
25
25
  "micromark-extension-mdx-jsx": "^1.0.3",
26
+ "micromark-extension-mdxjs": "^1.0.0",
26
27
  "prismjs": "^1.28.0",
27
28
  "rehype-raw": "^6.1.1",
28
29
  "rehype-stringify": "^9.0.3",
@@ -32,22 +33,28 @@
32
33
  "remark-smartypants": "^2.0.0",
33
34
  "shiki": "^0.10.1",
34
35
  "unified": "^10.1.2",
35
- "unist-util-map": "^3.0.1",
36
- "unist-util-visit": "^4.1.0"
36
+ "unist-util-map": "^3.1.1",
37
+ "unist-util-visit": "^4.1.0",
38
+ "vfile": "^5.3.2"
37
39
  },
38
40
  "devDependencies": {
41
+ "@types/chai": "^4.3.1",
39
42
  "@types/github-slugger": "^1.3.0",
40
43
  "@types/hast": "^2.3.4",
41
44
  "@types/mdast": "^3.0.10",
45
+ "@types/mocha": "^9.1.1",
42
46
  "@types/prismjs": "^1.26.0",
43
47
  "@types/unist": "^2.0.6",
44
- "astro-scripts": "0.0.3"
48
+ "astro-scripts": "0.0.4",
49
+ "chai": "^4.3.6",
50
+ "mocha": "^9.2.2"
45
51
  },
46
52
  "scripts": {
47
53
  "prepublish": "pnpm build",
48
54
  "build": "astro-scripts build \"src/**/*.ts\" && tsc -p tsconfig.json",
49
55
  "build:ci": "astro-scripts build \"src/**/*.ts\"",
50
56
  "postbuild": "astro-scripts copy \"src/**/*.js\"",
51
- "dev": "astro-scripts dev \"src/**/*.ts\""
57
+ "dev": "astro-scripts dev \"src/**/*.ts\"",
58
+ "test": "mocha --exit --timeout 20000"
52
59
  }
53
60
  }
package/src/index.ts CHANGED
@@ -2,10 +2,10 @@ import type { MarkdownRenderingOptions, MarkdownRenderingResult } from './types'
2
2
 
3
3
  import createCollectHeaders from './rehype-collect-headers.js';
4
4
  import scopedStyles from './remark-scoped-styles.js';
5
- import { remarkExpressions, loadRemarkExpressions } from './remark-expressions.js';
6
5
  import rehypeExpressions from './rehype-expressions.js';
7
6
  import rehypeIslands from './rehype-islands.js';
8
- import { remarkJsx, loadRemarkJsx } from './remark-jsx.js';
7
+ import remarkMdxish from './remark-mdxish.js';
8
+ import remarkMarkAndUnravel from './remark-mark-and-unravel.js';
9
9
  import rehypeJsx from './rehype-jsx.js';
10
10
  import rehypeEscape from './rehype-escape.js';
11
11
  import remarkPrism from './remark-prism.js';
@@ -18,27 +18,40 @@ import markdown from 'remark-parse';
18
18
  import markdownToHtml from 'remark-rehype';
19
19
  import rehypeStringify from 'rehype-stringify';
20
20
  import rehypeRaw from 'rehype-raw';
21
+ import Slugger from 'github-slugger';
22
+ import { VFile } from 'vfile';
21
23
 
22
24
  export * from './types.js';
23
25
 
24
26
  export const DEFAULT_REMARK_PLUGINS = ['remark-gfm', 'remark-smartypants'];
25
27
  export const DEFAULT_REHYPE_PLUGINS = [];
26
28
 
29
+ const slugger = new Slugger();
30
+ export function slug(value: string): string {
31
+ return slugger.slug(value);
32
+ }
33
+
27
34
  /** Shared utility for rendering markdown */
28
35
  export async function renderMarkdown(
29
36
  content: string,
30
- opts: MarkdownRenderingOptions
37
+ opts: MarkdownRenderingOptions = {}
31
38
  ): Promise<MarkdownRenderingResult> {
32
- let { mode, syntaxHighlight, shikiConfig, remarkPlugins, rehypePlugins } = opts;
39
+ let {
40
+ fileURL,
41
+ mode = 'mdx',
42
+ syntaxHighlight = 'shiki',
43
+ shikiConfig = {},
44
+ remarkPlugins = [],
45
+ rehypePlugins = [],
46
+ } = opts;
47
+ const input = new VFile({ value: content, path: fileURL });
33
48
  const scopedClassName = opts.$?.scopedClassName;
34
49
  const isMDX = mode === 'mdx';
35
50
  const { headers, rehypeCollectHeaders } = createCollectHeaders();
36
51
 
37
- await Promise.all([loadRemarkExpressions(), loadRemarkJsx()]); // Vite bug: dynamically import() these because of CJS interop (this will cache)
38
-
39
52
  let parser = unified()
40
53
  .use(markdown)
41
- .use(isMDX ? [remarkJsx, remarkExpressions] : [])
54
+ .use(isMDX ? [remarkMdxish, remarkMarkAndUnravel] : [])
42
55
  .use([remarkUnwrap]);
43
56
 
44
57
  if (remarkPlugins.length === 0 && rehypePlugins.length === 0) {
@@ -68,7 +81,13 @@ export async function renderMarkdown(
68
81
  markdownToHtml as any,
69
82
  {
70
83
  allowDangerousHtml: true,
71
- passThrough: ['raw', 'mdxTextExpression', 'mdxJsxTextElement', 'mdxJsxFlowElement'],
84
+ passThrough: [
85
+ 'raw',
86
+ 'mdxFlowExpression',
87
+ 'mdxJsxFlowElement',
88
+ 'mdxJsxTextElement',
89
+ 'mdxTextExpression',
90
+ ],
72
91
  },
73
92
  ],
74
93
  ]);
@@ -87,7 +106,7 @@ export async function renderMarkdown(
87
106
  const vfile = await parser
88
107
  .use([rehypeCollectHeaders])
89
108
  .use(rehypeStringify, { allowDangerousHtml: true })
90
- .process(content);
109
+ .process(input);
91
110
  result = vfile.toString();
92
111
  } catch (err) {
93
112
  console.error(err);
@@ -0,0 +1,12 @@
1
+ import { mdxExpressionFromMarkdown, mdxExpressionToMarkdown } from 'mdast-util-mdx-expression';
2
+ import { mdxJsxFromMarkdown, mdxJsxToMarkdown } from 'mdast-util-mdx-jsx';
3
+
4
+ export function mdxFromMarkdown(): any {
5
+ return [mdxExpressionFromMarkdown, mdxJsxFromMarkdown];
6
+ }
7
+
8
+ export function mdxToMarkdown(): any {
9
+ return {
10
+ extensions: [mdxExpressionToMarkdown, mdxJsxToMarkdown],
11
+ };
12
+ }
@@ -17,15 +17,39 @@ export default function createCollectHeaders() {
17
17
  if (!level) return;
18
18
  const depth = Number.parseInt(level);
19
19
 
20
+ let raw = '';
20
21
  let text = '';
21
-
22
- visit(node, 'text', (child) => {
23
- text += child.value;
22
+ let isJSX = false;
23
+ visit(node, (child) => {
24
+ if (child.type === 'element') {
25
+ return;
26
+ }
27
+ if (child.type === 'raw') {
28
+ // HACK: serialized JSX from internal plugins, ignore these for slug
29
+ if (child.value.startsWith('\n<') || child.value.endsWith('>\n')) {
30
+ raw += child.value.replace(/^\n|\n$/g, '');
31
+ return;
32
+ }
33
+ }
34
+ if (child.type === 'text' || child.type === 'raw') {
35
+ raw += child.value;
36
+ text += child.value;
37
+ isJSX = isJSX || child.value.includes('{');
38
+ }
24
39
  });
25
40
 
26
41
  node.properties = node.properties || {};
27
42
  if (typeof node.properties.id !== 'string') {
28
- node.properties.id = slugger.slug(text);
43
+ if (isJSX) {
44
+ // HACK: for ids that have JSX content, use $$slug helper to generate slug at runtime
45
+ node.properties.id = `$$slug(\`${text.replace(/\{/g, '${')}\`)`;
46
+ (node as any).type = 'raw';
47
+ (
48
+ node as any
49
+ ).value = `<${node.tagName} id={${node.properties.id}}>${raw}</${node.tagName}>`;
50
+ } else {
51
+ node.properties.id = slugger.slug(text);
52
+ }
29
53
  }
30
54
 
31
55
  headers.push({ depth, slug: node.properties.id, text });
@@ -3,8 +3,14 @@ import { map } from 'unist-util-map';
3
3
  export default function rehypeExpressions(): any {
4
4
  return function (node: any): any {
5
5
  return map(node, (child) => {
6
+ if (child.type === 'text') {
7
+ return { ...child, type: 'raw' };
8
+ }
6
9
  if (child.type === 'mdxTextExpression') {
7
- return { type: 'text', value: `{${(child as any).value}}` };
10
+ return { type: 'raw', value: `{${(child as any).value}}` };
11
+ }
12
+ if (child.type === 'mdxFlowExpression') {
13
+ return { type: 'raw', value: `{${(child as any).value}}` };
8
14
  }
9
15
  return child;
10
16
  });
package/src/rehype-jsx.ts CHANGED
@@ -8,19 +8,41 @@ export default function rehypeJsx(): any {
8
8
  return { ...child, tagName: `${child.tagName}` };
9
9
  }
10
10
  if (MDX_ELEMENTS.has(child.type)) {
11
+ const attrs = child.attributes.reduce((acc: any[], entry: any) => {
12
+ let attr = entry.value;
13
+ if (attr && typeof attr === 'object') {
14
+ attr = `{${attr.value}}`;
15
+ } else if (attr && entry.type === 'mdxJsxExpressionAttribute') {
16
+ attr = `{${attr}}`;
17
+ } else if (attr === null) {
18
+ attr = '';
19
+ } else if (typeof attr === 'string') {
20
+ attr = `"${attr}"`;
21
+ }
22
+ if (!entry.name) {
23
+ return acc + ` ${attr}`;
24
+ }
25
+ return acc + ` ${entry.name}${attr ? '=' : ''}${attr}`;
26
+ }, '');
27
+
28
+ if (child.children.length === 0) {
29
+ return {
30
+ type: 'raw',
31
+ value: `<${child.name}${attrs} />`,
32
+ };
33
+ }
34
+ child.children.splice(0, 0, {
35
+ type: 'raw',
36
+ value: `\n<${child.name}${attrs}>`,
37
+ });
38
+ child.children.push({
39
+ type: 'raw',
40
+ value: `</${child.name}>\n`,
41
+ });
11
42
  return {
12
43
  ...child,
13
44
  type: 'element',
14
- tagName: `${child.name}`,
15
- properties: child.attributes.reduce((acc: any[], entry: any) => {
16
- let attr = entry.value;
17
- if (attr && typeof attr === 'object') {
18
- attr = `{${attr.value}}`;
19
- } else if (attr === null) {
20
- attr = `{true}`;
21
- }
22
- return Object.assign(acc, { [entry.name]: attr });
23
- }, {}),
45
+ tagName: `Fragment`,
24
46
  };
25
47
  }
26
48
  return child;
@@ -0,0 +1,72 @@
1
+ // https://github.com/mdx-js/mdx/blob/main/packages/mdx/lib/plugin/remark-mark-and-unravel.js
2
+ /**
3
+ * @typedef {import('mdast').Root} Root
4
+ * @typedef {import('mdast').Content} Content
5
+ * @typedef {Root|Content} Node
6
+ * @typedef {Extract<Node, import('unist').Parent>} Parent
7
+ *
8
+ * @typedef {import('remark-mdx')} DoNotTouchAsThisImportItIncludesMdxInTree
9
+ */
10
+
11
+ import { visit } from 'unist-util-visit';
12
+
13
+ /**
14
+ * A tiny plugin that unravels `<p><h1>x</h1></p>` but also
15
+ * `<p><Component /></p>` (so it has no knowledge of “HTML”).
16
+ * It also marks JSX as being explicitly JSX, so when a user passes a `h1`
17
+ * component, it is used for `# heading` but not for `<h1>heading</h1>`.
18
+ *
19
+ * @type {import('unified').Plugin<Array<void>, Root>}
20
+ */
21
+ export default function remarkMarkAndUnravel() {
22
+ return (tree: any) => {
23
+ visit(tree, (node, index, parent_) => {
24
+ const parent = /** @type {Parent} */ parent_;
25
+ let offset = -1;
26
+ let all = true;
27
+ /** @type {boolean|undefined} */
28
+ let oneOrMore;
29
+
30
+ if (parent && typeof index === 'number' && node.type === 'paragraph') {
31
+ const children = node.children;
32
+
33
+ while (++offset < children.length) {
34
+ const child = children[offset];
35
+
36
+ if (child.type === 'mdxJsxTextElement' || child.type === 'mdxTextExpression') {
37
+ oneOrMore = true;
38
+ } else if (child.type === 'text' && /^[\t\r\n ]+$/.test(String(child.value))) {
39
+ // Empty.
40
+ } else {
41
+ all = false;
42
+ break;
43
+ }
44
+ }
45
+
46
+ if (all && oneOrMore) {
47
+ offset = -1;
48
+
49
+ while (++offset < children.length) {
50
+ const child = children[offset];
51
+
52
+ if (child.type === 'mdxJsxTextElement') {
53
+ child.type = 'mdxJsxFlowElement';
54
+ }
55
+
56
+ if (child.type === 'mdxTextExpression') {
57
+ child.type = 'mdxFlowExpression';
58
+ }
59
+ }
60
+
61
+ parent.children.splice(index, 1, ...children);
62
+ return index;
63
+ }
64
+ }
65
+
66
+ if (node.type === 'mdxJsxFlowElement' || node.type === 'mdxJsxTextElement') {
67
+ const data = node.data || (node.data = {});
68
+ data._mdxExplicitJsx = true;
69
+ }
70
+ });
71
+ };
72
+ }
@@ -0,0 +1,15 @@
1
+ import { mdxjs } from 'micromark-extension-mdxjs';
2
+ import { mdxFromMarkdown, mdxToMarkdown } from './mdast-util-mdxish.js';
3
+
4
+ export default function remarkMdxish(this: any, options = {}) {
5
+ const data = this.data();
6
+
7
+ add('micromarkExtensions', mdxjs(options));
8
+ add('fromMarkdownExtensions', mdxFromMarkdown());
9
+ add('toMarkdownExtensions', mdxToMarkdown());
10
+
11
+ function add(field: string, value: unknown) {
12
+ const list = data[field] ? data[field] : (data[field] = []);
13
+ list.push(value);
14
+ }
15
+ }
@@ -11,7 +11,7 @@ import type { ShikiConfig } from './types.js';
11
11
  const highlighterCacheAsync = new Map<string, Promise<shiki.Highlighter>>();
12
12
 
13
13
  const remarkShiki = async (
14
- { langs, theme, wrap }: ShikiConfig,
14
+ { langs = [], theme = 'github-dark', wrap = false }: ShikiConfig,
15
15
  scopedClassName?: string | null
16
16
  ) => {
17
17
  const cacheID: string = typeof theme === 'string' ? theme : theme.name;
package/src/types.ts CHANGED
@@ -20,21 +20,23 @@ export type RehypePlugin<PluginParameters extends any[] = any[]> = unified.Plugi
20
20
  export type RehypePlugins = (string | [string, any] | RehypePlugin | [RehypePlugin, any])[];
21
21
 
22
22
  export interface ShikiConfig {
23
- langs: ILanguageRegistration[];
24
- theme: Theme | IThemeRegistration;
25
- wrap: boolean | null;
23
+ langs?: ILanguageRegistration[];
24
+ theme?: Theme | IThemeRegistration;
25
+ wrap?: boolean | null;
26
26
  }
27
27
 
28
28
  export interface AstroMarkdownOptions {
29
- mode: 'md' | 'mdx';
30
- drafts: boolean;
31
- syntaxHighlight: 'shiki' | 'prism' | false;
32
- shikiConfig: ShikiConfig;
33
- remarkPlugins: RemarkPlugins;
34
- rehypePlugins: RehypePlugins;
29
+ mode?: 'md' | 'mdx';
30
+ drafts?: boolean;
31
+ syntaxHighlight?: 'shiki' | 'prism' | false;
32
+ shikiConfig?: ShikiConfig;
33
+ remarkPlugins?: RemarkPlugins;
34
+ rehypePlugins?: RehypePlugins;
35
35
  }
36
36
 
37
37
  export interface MarkdownRenderingOptions extends AstroMarkdownOptions {
38
+ /** @internal */
39
+ fileURL?: URL;
38
40
  /** @internal */
39
41
  $?: {
40
42
  scopedClassName: string | null;
@@ -0,0 +1,71 @@
1
+ import { renderMarkdown } from '../dist/index.js';
2
+ import chai from 'chai';
3
+
4
+ describe('components', () => {
5
+ it('should be able to serialize string', async () => {
6
+ const { code } = await renderMarkdown(`<Component str="cool!" />`, {});
7
+
8
+ chai.expect(code).to.equal(`<Component str="cool!" />`);
9
+ });
10
+
11
+ it('should be able to serialize boolean attribute', async () => {
12
+ const { code } = await renderMarkdown(`<Component bool={true} />`, {});
13
+
14
+ chai.expect(code).to.equal(`<Component bool={true} />`);
15
+ });
16
+
17
+ it('should be able to serialize array', async () => {
18
+ const { code } = await renderMarkdown(`<Component prop={["a", "b", "c"]} />`, {});
19
+
20
+ chai.expect(code).to.equal(`<Component prop={["a", "b", "c"]} />`);
21
+ });
22
+
23
+ it('should be able to serialize object', async () => {
24
+ const { code } = await renderMarkdown(`<Component prop={{ a: 0, b: 1, c: 2 }} />`, {});
25
+
26
+ chai.expect(code).to.equal(`<Component prop={{ a: 0, b: 1, c: 2 }} />`);
27
+ });
28
+
29
+ it('should be able to serialize empty attribute', async () => {
30
+ const { code } = await renderMarkdown(`<Component empty />`, {});
31
+
32
+ chai.expect(code).to.equal(`<Component empty />`);
33
+ });
34
+
35
+ // Notable omission: shorthand attribute
36
+
37
+ it('should be able to serialize spread attribute', async () => {
38
+ const { code } = await renderMarkdown(`<Component {...spread} />`, {});
39
+
40
+ chai.expect(code).to.equal(`<Component {...spread} />`);
41
+ });
42
+
43
+ it('should allow client:* directives', async () => {
44
+ const { code } = await renderMarkdown(`<Component client:load />`, {});
45
+
46
+ chai.expect(code).to.equal(`<Component client:load />`);
47
+ });
48
+
49
+ it('should normalize children', async () => {
50
+ const { code } = await renderMarkdown(`<Component bool={true}>Hello world!</Component>`, {});
51
+
52
+ chai
53
+ .expect(code)
54
+ .to.equal(`<Fragment>\n<Component bool={true}>Hello world!</Component>\n</Fragment>`);
55
+ });
56
+
57
+ it('should allow markdown without many spaces', async () => {
58
+ const { code } = await renderMarkdown(
59
+ `<Component>
60
+ # Hello world!
61
+ </Component>`,
62
+ {}
63
+ );
64
+
65
+ chai
66
+ .expect(code)
67
+ .to.equal(
68
+ `<Fragment>\n<Component><h1 id="hello-world">Hello world!</h1></Component>\n</Fragment>`
69
+ );
70
+ });
71
+ });
@@ -0,0 +1,51 @@
1
+ import { renderMarkdown } from '../dist/index.js';
2
+ import chai from 'chai';
3
+
4
+ describe('expressions', () => {
5
+ it('should be able to serialize bare expession', async () => {
6
+ const { code } = await renderMarkdown(`{a}`, {});
7
+
8
+ chai.expect(code).to.equal(`{a}`);
9
+ });
10
+
11
+ it('should be able to serialize expression inside component', async () => {
12
+ const { code } = await renderMarkdown(`<Component>{a}</Component>`, {});
13
+
14
+ chai.expect(code).to.equal(`<Fragment>\n<Component>{a}</Component>\n</Fragment>`);
15
+ });
16
+
17
+ it('should be able to serialize expression inside markdown', async () => {
18
+ const { code } = await renderMarkdown(`# {frontmatter.title}`, {});
19
+
20
+ chai
21
+ .expect(code)
22
+ .to.equal(`<h1 id={$$slug(\`\${frontmatter.title}\`)}>{frontmatter.title}</h1>`);
23
+ });
24
+
25
+ it('should be able to serialize complex expression inside markdown', async () => {
26
+ const { code } = await renderMarkdown(`# Hello {frontmatter.name}`, {});
27
+
28
+ chai
29
+ .expect(code)
30
+ .to.equal(`<h1 id={$$slug(\`Hello \${frontmatter.name}\`)}>Hello {frontmatter.name}</h1>`);
31
+ });
32
+
33
+ it('should be able to serialize complex expression with markup inside markdown', async () => {
34
+ const { code } = await renderMarkdown(`# Hello <span>{frontmatter.name}</span>`, {});
35
+
36
+ chai
37
+ .expect(code)
38
+ .to.equal(
39
+ `<h1 id={$$slug(\`Hello \${frontmatter.name}\`)}>Hello <span>{frontmatter.name}</span></h1>`
40
+ );
41
+ });
42
+
43
+ it('should be able to serialize function expression', async () => {
44
+ const { code } = await renderMarkdown(
45
+ `{frontmatter.list.map(item => <p id={item}>{item}</p>)}`,
46
+ {}
47
+ );
48
+
49
+ chai.expect(code).to.equal(`{frontmatter.list.map(item => <p id={item}>{item}</p>)}`);
50
+ });
51
+ });
@@ -0,0 +1,26 @@
1
+ import { renderMarkdown } from '../dist/index.js';
2
+ import chai from 'chai';
3
+
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ describe('plugins', () => {
7
+ // https://github.com/withastro/astro/issues/3264
8
+ it('should be able to get file path when passing fileURL', async () => {
9
+ let context;
10
+ await renderMarkdown(`test`, {
11
+ fileURL: new URL('virtual.md', import.meta.url),
12
+ remarkPlugins: [
13
+ function () {
14
+ const transformer = (tree, file) => {
15
+ context = file;
16
+ };
17
+
18
+ return transformer;
19
+ },
20
+ ],
21
+ });
22
+
23
+ chai.expect(typeof context).to.equal('object');
24
+ chai.expect(context.path).to.equal(fileURLToPath(new URL('virtual.md', import.meta.url)));
25
+ });
26
+ });
@@ -1,2 +0,0 @@
1
- export declare function remarkExpressions(this: any, options: any): void;
2
- export declare function loadRemarkExpressions(): Promise<void>;
@@ -1,25 +0,0 @@
1
- let mdxExpressionFromMarkdown;
2
- let mdxExpressionToMarkdown;
3
- function remarkExpressions(options) {
4
- let settings = options || {};
5
- let data = this.data();
6
- add("fromMarkdownExtensions", mdxExpressionFromMarkdown);
7
- add("toMarkdownExtensions", mdxExpressionToMarkdown);
8
- function add(field, value) {
9
- if (data[field])
10
- data[field].push(value);
11
- else
12
- data[field] = [value];
13
- }
14
- }
15
- async function loadRemarkExpressions() {
16
- if (!mdxExpressionFromMarkdown || !mdxExpressionToMarkdown) {
17
- const mdastUtilMdxExpression = await import("mdast-util-mdx-expression");
18
- mdxExpressionFromMarkdown = mdastUtilMdxExpression.mdxExpressionFromMarkdown;
19
- mdxExpressionToMarkdown = mdastUtilMdxExpression.mdxExpressionToMarkdown;
20
- }
21
- }
22
- export {
23
- loadRemarkExpressions,
24
- remarkExpressions
25
- };
@@ -1,2 +0,0 @@
1
- export declare function remarkJsx(this: any, options: any): void;
2
- export declare function loadRemarkJsx(): Promise<void>;
@@ -1,30 +0,0 @@
1
- let mdxJsx;
2
- let mdxJsxFromMarkdown;
3
- let mdxJsxToMarkdown;
4
- function remarkJsx(options) {
5
- let settings = options || {};
6
- let data = this.data();
7
- add("fromMarkdownExtensions", mdxJsxFromMarkdown);
8
- add("toMarkdownExtensions", mdxJsxToMarkdown);
9
- function add(field, value) {
10
- if (data[field])
11
- data[field].push(value);
12
- else
13
- data[field] = [value];
14
- }
15
- }
16
- async function loadRemarkJsx() {
17
- if (!mdxJsx) {
18
- const micromarkMdxJsx = await import("micromark-extension-mdx-jsx");
19
- mdxJsx = micromarkMdxJsx.mdxJsx;
20
- }
21
- if (!mdxJsxFromMarkdown || !mdxJsxToMarkdown) {
22
- const mdastUtilMdxJsx = await import("mdast-util-mdx-jsx");
23
- mdxJsxFromMarkdown = mdastUtilMdxJsx.mdxJsxFromMarkdown;
24
- mdxJsxToMarkdown = mdastUtilMdxJsx.mdxJsxToMarkdown;
25
- }
26
- }
27
- export {
28
- loadRemarkJsx,
29
- remarkJsx
30
- };
@@ -1,25 +0,0 @@
1
- // Vite bug: dynamically import() modules needed for CJS. Cache in memory to keep side effects
2
- let mdxExpressionFromMarkdown: any;
3
- let mdxExpressionToMarkdown: any;
4
-
5
- export function remarkExpressions(this: any, options: any) {
6
- let settings = options || {};
7
- let data = this.data();
8
-
9
- add('fromMarkdownExtensions', mdxExpressionFromMarkdown);
10
- add('toMarkdownExtensions', mdxExpressionToMarkdown);
11
-
12
- function add(field: any, value: any) {
13
- /* istanbul ignore if - other extensions. */
14
- if (data[field]) data[field].push(value);
15
- else data[field] = [value];
16
- }
17
- }
18
-
19
- export async function loadRemarkExpressions() {
20
- if (!mdxExpressionFromMarkdown || !mdxExpressionToMarkdown) {
21
- const mdastUtilMdxExpression = await import('mdast-util-mdx-expression');
22
- mdxExpressionFromMarkdown = mdastUtilMdxExpression.mdxExpressionFromMarkdown;
23
- mdxExpressionToMarkdown = mdastUtilMdxExpression.mdxExpressionToMarkdown;
24
- }
25
- }
package/src/remark-jsx.ts DELETED
@@ -1,31 +0,0 @@
1
- // Vite bug: dynamically import() modules needed for CJS. Cache in memory to keep side effects
2
- let mdxJsx: any;
3
- let mdxJsxFromMarkdown: any;
4
- let mdxJsxToMarkdown: any;
5
-
6
- export function remarkJsx(this: any, options: any) {
7
- let settings = options || {};
8
- let data = this.data();
9
-
10
- // TODO this seems to break adding slugs, no idea why add('micromarkExtensions', mdxJsx({}));
11
- add('fromMarkdownExtensions', mdxJsxFromMarkdown);
12
- add('toMarkdownExtensions', mdxJsxToMarkdown);
13
-
14
- function add(field: any, value: any) {
15
- /* istanbul ignore if - other extensions. */
16
- if (data[field]) data[field].push(value);
17
- else data[field] = [value];
18
- }
19
- }
20
-
21
- export async function loadRemarkJsx() {
22
- if (!mdxJsx) {
23
- const micromarkMdxJsx = await import('micromark-extension-mdx-jsx');
24
- mdxJsx = micromarkMdxJsx.mdxJsx;
25
- }
26
- if (!mdxJsxFromMarkdown || !mdxJsxToMarkdown) {
27
- const mdastUtilMdxJsx = await import('mdast-util-mdx-jsx');
28
- mdxJsxFromMarkdown = mdastUtilMdxJsx.mdxJsxFromMarkdown;
29
- mdxJsxToMarkdown = mdastUtilMdxJsx.mdxJsxToMarkdown;
30
- }
31
- }