@astrojs/markdown-remark 0.0.0-cloudcannon-fix-20230306211609

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 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
+ """
@@ -0,0 +1,8 @@
1
+ import type { Data, VFile } from 'vfile';
2
+ import type { MarkdownAstroData } from './types.js';
3
+ export declare class InvalidAstroDataError extends TypeError {
4
+ }
5
+ export declare function safelyGetAstroData(vfileData: Data): MarkdownAstroData | InvalidAstroDataError;
6
+ export declare function toRemarkInitializeAstroData({ userFrontmatter, }: {
7
+ userFrontmatter: Record<string, any>;
8
+ }): () => (tree: any, vfile: VFile) => void;
@@ -0,0 +1,35 @@
1
+ function isValidAstroData(obj) {
2
+ if (typeof obj === "object" && obj !== null && obj.hasOwnProperty("frontmatter")) {
3
+ const { frontmatter } = obj;
4
+ try {
5
+ JSON.stringify(frontmatter);
6
+ } catch {
7
+ return false;
8
+ }
9
+ return typeof frontmatter === "object" && frontmatter !== null;
10
+ }
11
+ return false;
12
+ }
13
+ class InvalidAstroDataError extends TypeError {
14
+ }
15
+ function safelyGetAstroData(vfileData) {
16
+ const { astro } = vfileData;
17
+ if (!astro || !isValidAstroData(astro)) {
18
+ return new InvalidAstroDataError();
19
+ }
20
+ return astro;
21
+ }
22
+ function toRemarkInitializeAstroData({
23
+ userFrontmatter
24
+ }) {
25
+ return () => function(tree, vfile) {
26
+ if (!vfile.data.astro) {
27
+ vfile.data.astro = { frontmatter: userFrontmatter };
28
+ }
29
+ };
30
+ }
31
+ export {
32
+ InvalidAstroDataError,
33
+ safelyGetAstroData,
34
+ toRemarkInitializeAstroData
35
+ };
@@ -0,0 +1,6 @@
1
+ import type { AstroMarkdownOptions, MarkdownRenderingOptions, MarkdownRenderingResult } from './types';
2
+ export { rehypeHeadingIds } from './rehype-collect-headings.js';
3
+ export * from './types.js';
4
+ export declare const markdownConfigDefaults: Omit<Required<AstroMarkdownOptions>, 'drafts'>;
5
+ /** Shared utility for rendering markdown */
6
+ export declare function renderMarkdown(content: string, opts: MarkdownRenderingOptions): Promise<MarkdownRenderingResult>;
package/dist/index.js ADDED
@@ -0,0 +1,118 @@
1
+ import { toRemarkInitializeAstroData } from "./frontmatter-injection.js";
2
+ import { loadPlugins } from "./load-plugins.js";
3
+ import { rehypeHeadingIds } from "./rehype-collect-headings.js";
4
+ import toRemarkContentRelImageError from "./remark-content-rel-image-error.js";
5
+ import remarkPrism from "./remark-prism.js";
6
+ import scopedStyles from "./remark-scoped-styles.js";
7
+ import remarkShiki from "./remark-shiki.js";
8
+ import rehypeRaw from "rehype-raw";
9
+ import rehypeStringify from "rehype-stringify";
10
+ import remarkGfm from "remark-gfm";
11
+ import markdown from "remark-parse";
12
+ import markdownToHtml from "remark-rehype";
13
+ import remarkSmartypants from "remark-smartypants";
14
+ import { unified } from "unified";
15
+ import { VFile } from "vfile";
16
+ import { rehypeHeadingIds as rehypeHeadingIds2 } from "./rehype-collect-headings.js";
17
+ export * from "./types.js";
18
+ const markdownConfigDefaults = {
19
+ syntaxHighlight: "shiki",
20
+ shikiConfig: {
21
+ langs: [],
22
+ theme: "github-dark",
23
+ wrap: false
24
+ },
25
+ remarkPlugins: [],
26
+ rehypePlugins: [],
27
+ remarkRehype: {},
28
+ gfm: true,
29
+ smartypants: true
30
+ };
31
+ async function renderMarkdown(content, opts) {
32
+ var _a;
33
+ let {
34
+ fileURL,
35
+ syntaxHighlight = markdownConfigDefaults.syntaxHighlight,
36
+ shikiConfig = markdownConfigDefaults.shikiConfig,
37
+ remarkPlugins = markdownConfigDefaults.remarkPlugins,
38
+ rehypePlugins = markdownConfigDefaults.rehypePlugins,
39
+ remarkRehype = markdownConfigDefaults.remarkRehype,
40
+ gfm = markdownConfigDefaults.gfm,
41
+ smartypants = markdownConfigDefaults.smartypants,
42
+ contentDir,
43
+ frontmatter: userFrontmatter = {}
44
+ } = opts;
45
+ const input = new VFile({ value: content, path: fileURL });
46
+ const scopedClassName = (_a = opts.$) == null ? void 0 : _a.scopedClassName;
47
+ let parser = unified().use(markdown).use(toRemarkInitializeAstroData({ userFrontmatter })).use([]);
48
+ if (gfm) {
49
+ parser.use(remarkGfm);
50
+ }
51
+ if (smartypants) {
52
+ parser.use(remarkSmartypants);
53
+ }
54
+ const loadedRemarkPlugins = await Promise.all(loadPlugins(remarkPlugins));
55
+ const loadedRehypePlugins = await Promise.all(loadPlugins(rehypePlugins));
56
+ loadedRemarkPlugins.forEach(([plugin, pluginOpts]) => {
57
+ parser.use([[plugin, pluginOpts]]);
58
+ });
59
+ if (scopedClassName) {
60
+ parser.use([scopedStyles(scopedClassName)]);
61
+ }
62
+ if (syntaxHighlight === "shiki") {
63
+ parser.use([await remarkShiki(shikiConfig, scopedClassName)]);
64
+ } else if (syntaxHighlight === "prism") {
65
+ parser.use([remarkPrism(scopedClassName)]);
66
+ }
67
+ parser.use([toRemarkContentRelImageError({ contentDir })]);
68
+ parser.use([
69
+ [
70
+ markdownToHtml,
71
+ {
72
+ allowDangerousHtml: true,
73
+ passThrough: [],
74
+ ...remarkRehype
75
+ }
76
+ ]
77
+ ]);
78
+ loadedRehypePlugins.forEach(([plugin, pluginOpts]) => {
79
+ parser.use([[plugin, pluginOpts]]);
80
+ });
81
+ parser.use([rehypeHeadingIds, rehypeRaw]).use(rehypeStringify, { allowDangerousHtml: true });
82
+ let vfile;
83
+ try {
84
+ vfile = await parser.process(input);
85
+ } catch (err) {
86
+ err = prefixError(err, `Failed to parse Markdown file "${input.path}"`);
87
+ console.error(err);
88
+ throw err;
89
+ }
90
+ const headings = (vfile == null ? void 0 : vfile.data.__astroHeadings) || [];
91
+ return {
92
+ metadata: { headings, source: content, html: String(vfile.value) },
93
+ code: String(vfile.value),
94
+ vfile
95
+ };
96
+ }
97
+ function prefixError(err, prefix) {
98
+ if (err && err.message) {
99
+ try {
100
+ err.message = `${prefix}:
101
+ ${err.message}`;
102
+ return err;
103
+ } catch (error) {
104
+ }
105
+ }
106
+ const wrappedError = new Error(`${prefix}${err ? `: ${err}` : ""}`);
107
+ try {
108
+ wrappedError.stack = err.stack;
109
+ wrappedError.cause = err;
110
+ } catch (error) {
111
+ }
112
+ return wrappedError;
113
+ }
114
+ export {
115
+ markdownConfigDefaults,
116
+ rehypeHeadingIds2 as rehypeHeadingIds,
117
+ renderMarkdown
118
+ };
@@ -0,0 +1 @@
1
+ export { InvalidAstroDataError, safelyGetAstroData, toRemarkInitializeAstroData, } from './frontmatter-injection.js';
@@ -0,0 +1,10 @@
1
+ import {
2
+ InvalidAstroDataError,
3
+ safelyGetAstroData,
4
+ toRemarkInitializeAstroData
5
+ } from "./frontmatter-injection.js";
6
+ export {
7
+ InvalidAstroDataError,
8
+ safelyGetAstroData,
9
+ toRemarkInitializeAstroData
10
+ };
@@ -0,0 +1,2 @@
1
+ import * as unified from 'unified';
2
+ export declare function loadPlugins(items: (string | [string, any] | unified.Plugin<any[], any> | [unified.Plugin<any[], any>, any])[]): Promise<[unified.Plugin, any?]>[];
@@ -0,0 +1,31 @@
1
+ import { resolve as importMetaResolve } from "import-meta-resolve";
2
+ import path from "path";
3
+ import { pathToFileURL } from "url";
4
+ const cwdUrlStr = pathToFileURL(path.join(process.cwd(), "package.json")).toString();
5
+ async function importPlugin(p) {
6
+ if (typeof p === "string") {
7
+ try {
8
+ const importResult2 = await import(p);
9
+ return importResult2.default;
10
+ } catch {
11
+ }
12
+ const resolved = await importMetaResolve(p, cwdUrlStr);
13
+ const importResult = await import(resolved);
14
+ return importResult.default;
15
+ }
16
+ return p;
17
+ }
18
+ function loadPlugins(items) {
19
+ return items.map((p) => {
20
+ return new Promise((resolve, reject) => {
21
+ if (Array.isArray(p)) {
22
+ const [plugin, opts] = p;
23
+ return importPlugin(plugin).then((m) => resolve([m, opts])).catch((e) => reject(e));
24
+ }
25
+ return importPlugin(p).then((m) => resolve([m])).catch((e) => reject(e));
26
+ });
27
+ });
28
+ }
29
+ export {
30
+ loadPlugins
31
+ };
@@ -0,0 +1,2 @@
1
+ import type { RehypePlugin } from './types.js';
2
+ export declare function rehypeHeadingIds(): ReturnType<RehypePlugin>;
@@ -0,0 +1,99 @@
1
+ import Slugger from "github-slugger";
2
+ import { visit } from "unist-util-visit";
3
+ import { InvalidAstroDataError, safelyGetAstroData } from "./frontmatter-injection.js";
4
+ const rawNodeTypes = /* @__PURE__ */ new Set(["text", "raw", "mdxTextExpression"]);
5
+ const codeTagNames = /* @__PURE__ */ new Set(["code", "pre"]);
6
+ function rehypeHeadingIds() {
7
+ return function(tree, file) {
8
+ const headings = [];
9
+ const slugger = new Slugger();
10
+ const isMDX = isMDXFile(file);
11
+ const astroData = safelyGetAstroData(file.data);
12
+ visit(tree, (node) => {
13
+ if (node.type !== "element")
14
+ return;
15
+ const { tagName } = node;
16
+ if (tagName[0] !== "h")
17
+ return;
18
+ const [_, level] = tagName.match(/h([0-6])/) ?? [];
19
+ if (!level)
20
+ return;
21
+ const depth = Number.parseInt(level);
22
+ let text = "";
23
+ visit(node, (child, __, parent) => {
24
+ if (child.type === "element" || parent == null) {
25
+ return;
26
+ }
27
+ if (child.type === "raw") {
28
+ if (child.value.match(/^\n?<.*>\n?$/)) {
29
+ return;
30
+ }
31
+ }
32
+ if (rawNodeTypes.has(child.type)) {
33
+ if (isMDX || codeTagNames.has(parent.tagName)) {
34
+ let value = child.value;
35
+ if (isMdxTextExpression(child) && !(astroData instanceof InvalidAstroDataError)) {
36
+ const frontmatterPath = getMdxFrontmatterVariablePath(child);
37
+ if (Array.isArray(frontmatterPath) && frontmatterPath.length > 0) {
38
+ const frontmatterValue = getMdxFrontmatterVariableValue(astroData, frontmatterPath);
39
+ if (typeof frontmatterValue === "string") {
40
+ value = frontmatterValue;
41
+ }
42
+ }
43
+ }
44
+ text += value;
45
+ } else {
46
+ text += child.value.replace(/\{/g, "${");
47
+ }
48
+ }
49
+ });
50
+ node.properties = node.properties || {};
51
+ if (typeof node.properties.id !== "string") {
52
+ let slug = slugger.slug(text);
53
+ if (slug.endsWith("-"))
54
+ slug = slug.slice(0, -1);
55
+ node.properties.id = slug;
56
+ }
57
+ headings.push({ depth, slug: node.properties.id, text });
58
+ });
59
+ file.data.__astroHeadings = headings;
60
+ };
61
+ }
62
+ function isMDXFile(file) {
63
+ var _a;
64
+ return Boolean((_a = file.history[0]) == null ? void 0 : _a.endsWith(".mdx"));
65
+ }
66
+ function getMdxFrontmatterVariablePath(node) {
67
+ var _a;
68
+ if (!((_a = node.data) == null ? void 0 : _a.estree) || node.data.estree.body.length !== 1)
69
+ return new Error();
70
+ const statement = node.data.estree.body[0];
71
+ if ((statement == null ? void 0 : statement.type) !== "ExpressionStatement" || statement.expression.type !== "MemberExpression")
72
+ return new Error();
73
+ let expression = statement.expression;
74
+ const expressionPath = [];
75
+ while (expression.type === "MemberExpression" && expression.property.type === (expression.computed ? "Literal" : "Identifier")) {
76
+ expressionPath.push(
77
+ expression.property.type === "Literal" ? String(expression.property.value) : expression.property.name
78
+ );
79
+ expression = expression.object;
80
+ }
81
+ if (expression.type !== "Identifier" || expression.name !== "frontmatter")
82
+ return new Error();
83
+ return expressionPath.reverse();
84
+ }
85
+ function getMdxFrontmatterVariableValue(astroData, path) {
86
+ let value = astroData.frontmatter;
87
+ for (const key of path) {
88
+ if (!value[key])
89
+ return void 0;
90
+ value = value[key];
91
+ }
92
+ return value;
93
+ }
94
+ function isMdxTextExpression(node) {
95
+ return node.type === "mdxTextExpression";
96
+ }
97
+ export {
98
+ rehypeHeadingIds
99
+ };
@@ -0,0 +1,8 @@
1
+ import type { VFile } from 'vfile';
2
+ /**
3
+ * `src/content/` does not support relative image paths.
4
+ * This plugin throws an error if any are found
5
+ */
6
+ export default function toRemarkContentRelImageError({ contentDir }: {
7
+ contentDir: URL;
8
+ }): () => (tree: any, vfile: VFile) => void;
@@ -0,0 +1,41 @@
1
+ import { visit } from "unist-util-visit";
2
+ import { pathToFileURL } from "url";
3
+ function toRemarkContentRelImageError({ contentDir }) {
4
+ return function remarkContentRelImageError() {
5
+ return (tree, vfile) => {
6
+ if (typeof (vfile == null ? void 0 : vfile.path) !== "string")
7
+ return;
8
+ const isContentFile = pathToFileURL(vfile.path).href.startsWith(contentDir.href);
9
+ if (!isContentFile)
10
+ return;
11
+ const relImagePaths = /* @__PURE__ */ new Set();
12
+ visit(tree, "image", function raiseError(node) {
13
+ if (isRelativePath(node.url)) {
14
+ relImagePaths.add(node.url);
15
+ }
16
+ });
17
+ if (relImagePaths.size === 0)
18
+ return;
19
+ const errorMessage = `Relative image paths are not supported in the content/ directory. Place local images in the public/ directory and use absolute paths (see https://docs.astro.build/en/guides/images/#in-markdown-files)
20
+ ` + [...relImagePaths].map((path) => JSON.stringify(path)).join(",\n");
21
+ throw errorMessage;
22
+ };
23
+ };
24
+ }
25
+ function isRelativePath(path) {
26
+ return startsWithDotDotSlash(path) || startsWithDotSlash(path);
27
+ }
28
+ function startsWithDotDotSlash(path) {
29
+ const c1 = path[0];
30
+ const c2 = path[1];
31
+ const c3 = path[2];
32
+ return c1 === "." && c2 === "." && c3 === "/";
33
+ }
34
+ function startsWithDotSlash(path) {
35
+ const c1 = path[0];
36
+ const c2 = path[1];
37
+ return c1 === "." && c2 === "/";
38
+ }
39
+ export {
40
+ toRemarkContentRelImageError as default
41
+ };
@@ -0,0 +1,3 @@
1
+ declare type MaybeString = string | null | undefined;
2
+ declare function plugin(className: MaybeString): () => (tree: any) => void;
3
+ export default plugin;
@@ -0,0 +1,28 @@
1
+ import { runHighlighterWithAstro } from "@astrojs/prism/dist/highlighter";
2
+ import { visit } from "unist-util-visit";
3
+ const noVisit = /* @__PURE__ */ new Set(["root", "html", "text"]);
4
+ function transformer(className) {
5
+ return function(tree) {
6
+ const visitor = (node) => {
7
+ let { lang, value } = node;
8
+ node.type = "html";
9
+ let { html, classLanguage } = runHighlighterWithAstro(lang, value);
10
+ let classes = [classLanguage];
11
+ if (className) {
12
+ classes.push(className);
13
+ }
14
+ node.value = `<pre class="${classes.join(
15
+ " "
16
+ )}"><code is:raw class="${classLanguage}">${html}</code></pre>`;
17
+ return node;
18
+ };
19
+ return visit(tree, "code", visitor);
20
+ };
21
+ }
22
+ function plugin(className) {
23
+ return transformer.bind(null, className);
24
+ }
25
+ var remark_prism_default = plugin;
26
+ export {
27
+ remark_prism_default as default
28
+ };
@@ -0,0 +1,2 @@
1
+ /** */
2
+ export default function scopedStyles(className: string): () => (tree: any) => void;
@@ -0,0 +1,19 @@
1
+ import { visit } from "unist-util-visit";
2
+ const noVisit = /* @__PURE__ */ new Set(["root", "html", "text"]);
3
+ function scopedStyles(className) {
4
+ const visitor = (node) => {
5
+ var _a;
6
+ if (noVisit.has(node.type))
7
+ return;
8
+ const { data } = node;
9
+ let currentClassName = ((_a = data == null ? void 0 : data.hProperties) == null ? void 0 : _a.class) ?? "";
10
+ node.data = node.data || {};
11
+ node.data.hProperties = node.data.hProperties || {};
12
+ node.data.hProperties.class = `${className} ${currentClassName}`.trim();
13
+ return node;
14
+ };
15
+ return () => (tree) => visit(tree, visitor);
16
+ }
17
+ export {
18
+ scopedStyles as default
19
+ };
@@ -0,0 +1,3 @@
1
+ import type { ShikiConfig } from './types.js';
2
+ declare const remarkShiki: ({ langs, theme, wrap }: ShikiConfig, scopedClassName?: string | null) => Promise<() => (tree: any) => void>;
3
+ export default remarkShiki;
@@ -0,0 +1,75 @@
1
+ import { getHighlighter } from "shiki";
2
+ import { visit } from "unist-util-visit";
3
+ const highlighterCacheAsync = /* @__PURE__ */ new Map();
4
+ const remarkShiki = async ({ langs = [], theme = "github-dark", wrap = false }, scopedClassName) => {
5
+ const cacheID = typeof theme === "string" ? theme : theme.name;
6
+ let highlighterAsync = highlighterCacheAsync.get(cacheID);
7
+ if (!highlighterAsync) {
8
+ highlighterAsync = getHighlighter({ theme }).then((hl) => {
9
+ hl.setColorReplacements({
10
+ "#000001": "var(--astro-code-color-text)",
11
+ "#000002": "var(--astro-code-color-background)",
12
+ "#000004": "var(--astro-code-token-constant)",
13
+ "#000005": "var(--astro-code-token-string)",
14
+ "#000006": "var(--astro-code-token-comment)",
15
+ "#000007": "var(--astro-code-token-keyword)",
16
+ "#000008": "var(--astro-code-token-parameter)",
17
+ "#000009": "var(--astro-code-token-function)",
18
+ "#000010": "var(--astro-code-token-string-expression)",
19
+ "#000011": "var(--astro-code-token-punctuation)",
20
+ "#000012": "var(--astro-code-token-link)"
21
+ });
22
+ return hl;
23
+ });
24
+ highlighterCacheAsync.set(cacheID, highlighterAsync);
25
+ }
26
+ const highlighter = await highlighterAsync;
27
+ for (const lang of langs) {
28
+ await highlighter.loadLanguage(lang);
29
+ }
30
+ return () => (tree) => {
31
+ visit(tree, "code", (node) => {
32
+ let lang;
33
+ if (typeof node.lang === "string") {
34
+ const langExists = highlighter.getLoadedLanguages().includes(node.lang);
35
+ if (langExists) {
36
+ lang = node.lang;
37
+ } else {
38
+ console.warn(`The language "${node.lang}" doesn't exist, falling back to plaintext.`);
39
+ lang = "plaintext";
40
+ }
41
+ } else {
42
+ lang = "plaintext";
43
+ }
44
+ let html = highlighter.codeToHtml(node.value, { lang });
45
+ html = html.replace(
46
+ /<pre class="(.*?)shiki(.*?)"/,
47
+ `<pre is:raw class="$1astro-code$2${scopedClassName ? " " + scopedClassName : ""}"`
48
+ );
49
+ if (node.lang === "diff") {
50
+ html = html.replace(
51
+ /<span class="line"><span style="(.*?)">([\+|\-])/g,
52
+ '<span class="line"><span style="$1"><span style="user-select: none;">$2</span>'
53
+ );
54
+ }
55
+ if (wrap === false) {
56
+ html = html.replace(/style="(.*?)"/, 'style="$1; overflow-x: auto;"');
57
+ } else if (wrap === true) {
58
+ html = html.replace(
59
+ /style="(.*?)"/,
60
+ 'style="$1; overflow-x: auto; white-space: pre-wrap; word-wrap: break-word;"'
61
+ );
62
+ }
63
+ if (scopedClassName) {
64
+ html = html.replace(/\<span class="line"\>/g, `<span class="line ${scopedClassName}"`);
65
+ }
66
+ node.type = "html";
67
+ node.value = html;
68
+ node.children = [];
69
+ });
70
+ };
71
+ };
72
+ var remark_shiki_default = remarkShiki;
73
+ export {
74
+ remark_shiki_default as default
75
+ };
@@ -0,0 +1,65 @@
1
+ import type * as hast from 'hast';
2
+ import type * as mdast from 'mdast';
3
+ import type { all as Handlers, one as Handler, Options as RemarkRehypeOptions } from 'remark-rehype';
4
+ import type { ILanguageRegistration, IThemeRegistration, Theme } from 'shiki';
5
+ import type * as unified from 'unified';
6
+ import type { VFile } from 'vfile';
7
+ export type { Node } from 'unist';
8
+ export declare type MarkdownAstroData = {
9
+ frontmatter: Record<string, any>;
10
+ };
11
+ export declare type RemarkPlugin<PluginParameters extends any[] = any[]> = unified.Plugin<PluginParameters, mdast.Root>;
12
+ export declare type RemarkPlugins = (string | [string, any] | RemarkPlugin | [RemarkPlugin, any])[];
13
+ export declare type RehypePlugin<PluginParameters extends any[] = any[]> = unified.Plugin<PluginParameters, hast.Root>;
14
+ export declare type RehypePlugins = (string | [string, any] | RehypePlugin | [RehypePlugin, any])[];
15
+ export declare type RemarkRehype = Omit<RemarkRehypeOptions, 'handlers' | 'unknownHandler'> & {
16
+ handlers?: typeof Handlers;
17
+ handler?: typeof Handler;
18
+ };
19
+ export interface ShikiConfig {
20
+ langs?: ILanguageRegistration[];
21
+ theme?: Theme | IThemeRegistration;
22
+ wrap?: boolean | null;
23
+ }
24
+ export interface AstroMarkdownOptions {
25
+ drafts?: boolean;
26
+ syntaxHighlight?: 'shiki' | 'prism' | false;
27
+ shikiConfig?: ShikiConfig;
28
+ remarkPlugins?: RemarkPlugins;
29
+ rehypePlugins?: RehypePlugins;
30
+ remarkRehype?: RemarkRehype;
31
+ gfm?: boolean;
32
+ smartypants?: boolean;
33
+ }
34
+ export interface MarkdownRenderingOptions extends AstroMarkdownOptions {
35
+ /** @internal */
36
+ fileURL?: URL;
37
+ /** @internal */
38
+ $?: {
39
+ scopedClassName: string | null;
40
+ };
41
+ /** Used to prevent relative image imports from `src/content/` */
42
+ contentDir: URL;
43
+ /** Used for frontmatter injection plugins */
44
+ frontmatter?: Record<string, any>;
45
+ }
46
+ export interface MarkdownHeading {
47
+ depth: number;
48
+ slug: string;
49
+ text: string;
50
+ }
51
+ export interface MarkdownMetadata {
52
+ headings: MarkdownHeading[];
53
+ source: string;
54
+ html: string;
55
+ }
56
+ export interface MarkdownVFile extends VFile {
57
+ data: {
58
+ __astroHeadings?: MarkdownHeading[];
59
+ };
60
+ }
61
+ export interface MarkdownRenderingResult {
62
+ metadata: MarkdownMetadata;
63
+ vfile: VFile;
64
+ code: string;
65
+ }
package/dist/types.js ADDED
File without changes