@vuepress/markdown 2.0.0-rc.26 → 2.0.0-rc.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.d.ts +131 -118
  2. package/dist/index.js +298 -428
  3. package/package.json +23 -29
package/dist/index.d.ts CHANGED
@@ -1,73 +1,68 @@
1
- import { SfcPluginOptions } from '@mdit-vue/plugin-sfc';
2
- export { MarkdownSfcBlocks, SfcPluginOptions, sfcPlugin } from '@mdit-vue/plugin-sfc';
3
- import { MarkdownItEnv } from '@mdit-vue/types';
4
- import { PageFrontmatter, PageHeader } from '@vuepress/shared';
5
- import MarkdownIt, { PluginWithOptions, Options as Options$1 } from 'markdown-it';
6
- import { FrontmatterPluginOptions } from '@mdit-vue/plugin-frontmatter';
7
- export { FrontmatterPluginOptions, frontmatterPlugin } from '@mdit-vue/plugin-frontmatter';
8
- import { HeadersPluginOptions } from '@mdit-vue/plugin-headers';
9
- export { HeadersPluginOptions, headersPlugin } from '@mdit-vue/plugin-headers';
10
- import { TocPluginOptions } from '@mdit-vue/plugin-toc';
11
- export { TocPluginOptions, tocPlugin } from '@mdit-vue/plugin-toc';
12
- import anchorPlugin from 'markdown-it-anchor';
13
- export { default as anchorPlugin } from 'markdown-it-anchor';
14
- import { Options } from 'markdown-it-emoji';
15
- export { full as emojiPlugin } from 'markdown-it-emoji';
16
- export { ComponentPluginOptions, componentPlugin } from '@mdit-vue/plugin-component';
17
- export { titlePlugin } from '@mdit-vue/plugin-title';
1
+ import MarkdownIt, { Options, PluginWithOptions } from "markdown-it";
2
+ import { ComponentPluginOptions, componentPlugin } from "@mdit-vue/plugin-component";
3
+ import { FrontmatterPluginOptions, frontmatterPlugin } from "@mdit-vue/plugin-frontmatter";
4
+ import { HeadersPluginOptions, headersPlugin } from "@mdit-vue/plugin-headers";
5
+ import { MarkdownSfcBlocks, SfcPluginOptions, sfcPlugin } from "@mdit-vue/plugin-sfc";
6
+ import { titlePlugin } from "@mdit-vue/plugin-title";
7
+ import { TocPluginOptions, tocPlugin } from "@mdit-vue/plugin-toc";
8
+ import anchorPlugin from "markdown-it-anchor";
9
+ import { Options as Options$1, full as emojiPlugin } from "markdown-it-emoji";
10
+ import { PageFrontmatter, PageHeader } from "@vuepress/shared";
11
+ import { MarkdownItEnv } from "@mdit-vue/types";
18
12
 
13
+ //#region src/plugins/anchorPlugin.d.ts
19
14
  type AnchorPluginOptions = anchorPlugin.AnchorOptions;
20
-
15
+ //#endregion
16
+ //#region src/plugins/assetsPlugin/assetsPlugin.d.ts
21
17
  interface AssetsPluginOptions {
22
- /**
23
- * Whether to prepend base to absolute path
24
- */
25
- absolutePathPrependBase?: boolean;
26
- /**
27
- * Prefix to add to relative assets links
28
- */
29
- relativePathPrefix?: string;
18
+ /**
19
+ * Whether to prepend base to absolute path
20
+ */
21
+ absolutePathPrependBase?: boolean;
30
22
  }
31
23
  /**
32
24
  * Plugin to handle assets links
33
25
  */
34
26
  declare const assetsPlugin: PluginWithOptions<AssetsPluginOptions>;
35
-
36
- type EmojiPluginOptions = Options;
37
-
27
+ //#endregion
28
+ //#region src/plugins/emojiPlugin.d.ts
29
+ type EmojiPluginOptions = Options$1;
30
+ //#endregion
31
+ //#region src/plugins/importCodePlugin/importCodePlugin.d.ts
38
32
  interface ImportCodePluginOptions {
39
- /**
40
- * A function to handle the import path
41
- */
42
- handleImportPath?: (str: string) => string;
33
+ /**
34
+ * A function to handle the import path
35
+ */
36
+ handleImportPath?: (str: string) => string;
43
37
  }
44
38
  declare const importCodePlugin: PluginWithOptions<ImportCodePluginOptions>;
45
-
39
+ //#endregion
40
+ //#region src/plugins/linksPlugin/linksPlugin.d.ts
46
41
  interface LinksPluginOptions {
47
- /**
48
- * Additional attributes for external links
49
- *
50
- * @default
51
- * ```js
52
- * ({
53
- * target: '_blank',
54
- * rel: 'noopener noreferrer',
55
- * })
56
- * ```
57
- */
58
- externalAttrs?: Record<string, string>;
59
- /**
60
- * Tag for internal links
61
- *
62
- * @default 'RouteLink'
63
- */
64
- internalTag?: 'a' | 'RouteLink' | 'RouterLink';
65
- /**
66
- * Method to check if a link is external
67
- *
68
- * @default import { isLinkExternal } from '@vuepress/shared'
69
- */
70
- isExternal?: (href: string, env: MarkdownEnv) => boolean;
42
+ /**
43
+ * Additional attributes for external links
44
+ *
45
+ * @default
46
+ * ```js
47
+ * ({
48
+ * target: '_blank',
49
+ * rel: 'noopener noreferrer',
50
+ * })
51
+ * ```
52
+ */
53
+ externalAttrs?: Record<string, string>;
54
+ /**
55
+ * Tag for internal links
56
+ *
57
+ * @default 'RouteLink'
58
+ */
59
+ internalTag?: 'a' | 'RouteLink' | 'RouterLink';
60
+ /**
61
+ * Method to check if a link is external
62
+ *
63
+ * @default import { isLinkExternal } from '@vuepress/shared'
64
+ */
65
+ isExternal?: (href: string, env: MarkdownEnv) => boolean;
71
66
  }
72
67
  /**
73
68
  * Process links in markdown file
@@ -76,42 +71,43 @@ interface LinksPluginOptions {
76
71
  * - external links: add extra attrs
77
72
  */
78
73
  declare const linksPlugin: PluginWithOptions<LinksPluginOptions>;
79
-
74
+ //#endregion
75
+ //#region src/plugins/vPrePlugin/vPrePlugin.d.ts
80
76
  interface VPrePluginOptions {
81
- /**
82
- * Add `v-pre` directive to `<pre>` tag of code block or not
83
- */
84
- block?: boolean;
85
- /**
86
- * Add `v-pre` directive to `<code>` tag of inline code or not
87
- */
88
- inline?: boolean;
77
+ /**
78
+ * Add `v-pre` directive to `<pre>` tag of code block or not
79
+ */
80
+ block?: boolean;
81
+ /**
82
+ * Add `v-pre` directive to `<code>` tag of inline code or not
83
+ */
84
+ inline?: boolean;
89
85
  }
90
86
  /**
91
87
  * v-pre plugin
92
88
  */
93
89
  declare const vPrePlugin: PluginWithOptions<VPrePluginOptions>;
94
-
90
+ //#endregion
91
+ //#region src/types.d.ts
95
92
  type Markdown = MarkdownIt;
96
-
97
- interface MarkdownOptions extends Options$1 {
98
- anchor?: AnchorPluginOptions | false;
99
- assets?: AssetsPluginOptions | false;
100
- component?: false;
101
- emoji?: EmojiPluginOptions | false;
102
- frontmatter?: FrontmatterPluginOptions | false;
103
- headers?: HeadersPluginOptions | false;
104
- title?: false;
105
- importCode?: ImportCodePluginOptions | false;
106
- links?: LinksPluginOptions | false;
107
- sfc?: SfcPluginOptions | false;
108
- slugify?: MarkdownSlugifyFunction;
109
- toc?: TocPluginOptions | false;
110
- vPre?: VPrePluginOptions | false;
111
- /**
112
- * @deprecated This feature has been removed. Please use `@vuepress/plugin-prismjs` or `@vuepress/plugin-shiki` instead.
113
- */
114
- code?: never;
93
+ interface MarkdownOptions extends Options {
94
+ anchor?: AnchorPluginOptions | false;
95
+ assets?: AssetsPluginOptions | false;
96
+ component?: false;
97
+ emoji?: EmojiPluginOptions | false;
98
+ frontmatter?: FrontmatterPluginOptions | false;
99
+ headers?: HeadersPluginOptions | false;
100
+ title?: false;
101
+ importCode?: ImportCodePluginOptions | false;
102
+ links?: LinksPluginOptions | false;
103
+ sfc?: SfcPluginOptions | false;
104
+ slugify?: MarkdownSlugifyFunction;
105
+ toc?: TocPluginOptions | false;
106
+ vPre?: VPrePluginOptions | false;
107
+ /**
108
+ * @deprecated This feature has been removed. Please use `@vuepress/plugin-prismjs` or `@vuepress/plugin-shiki` instead.
109
+ */
110
+ code?: never;
115
111
  }
116
112
  /**
117
113
  * Headers in markdown file
@@ -123,9 +119,9 @@ type MarkdownHeader = PageHeader;
123
119
  * Used for file existence check
124
120
  */
125
121
  interface MarkdownLink {
126
- raw: string;
127
- relative: string;
128
- absolute: string | null;
122
+ raw: string;
123
+ relative: string;
124
+ absolute: string | null;
129
125
  }
130
126
  /**
131
127
  * The `env` object to be passed to markdown-it render function
@@ -135,39 +131,56 @@ interface MarkdownLink {
135
131
  * Output some resources from the markdown file
136
132
  */
137
133
  interface MarkdownEnv extends MarkdownItEnv {
138
- /**
139
- * Base / publicPath of current site
140
- */
141
- base?: string;
142
- /**
143
- * Absolute file path of the markdown file
144
- */
145
- filePath?: string | null;
146
- /**
147
- * Relative file path of the markdown file
148
- */
149
- filePathRelative?: string | null;
150
- /**
151
- * Frontmatter of the markdown file
152
- */
153
- frontmatter?: PageFrontmatter;
154
- /**
155
- * Imported file that extracted by importCodePlugin
156
- */
157
- importedFiles?: string[];
158
- /**
159
- * Links that extracted by linksPlugin
160
- */
161
- links?: MarkdownLink[];
134
+ /**
135
+ * Base / publicPath of current site
136
+ */
137
+ base?: string;
138
+ /**
139
+ * Absolute file path of the markdown file
140
+ */
141
+ filePath?: string | null;
142
+ /**
143
+ * Relative file path of the markdown file
144
+ */
145
+ filePathRelative?: string | null;
146
+ /**
147
+ * Frontmatter of the markdown file
148
+ */
149
+ frontmatter?: PageFrontmatter;
150
+ /**
151
+ * Imported file that extracted by importCodePlugin
152
+ */
153
+ importedFiles?: string[];
154
+ /**
155
+ * Links that extracted by linksPlugin
156
+ */
157
+ links?: MarkdownLink[];
162
158
  }
163
159
  /**
164
160
  * Type of `slugify` function
165
161
  */
166
162
  type MarkdownSlugifyFunction = (str: string) => string;
167
-
163
+ //#endregion
164
+ //#region src/markdown.d.ts
168
165
  /**
169
166
  * Create vuepress customized markdown-it instance
170
167
  */
171
- declare const createMarkdown: ({ anchor, assets, code, vPre, component, emoji, frontmatter, headers, title, importCode, links, sfc, slugify, toc, ...markdownItOptions }?: MarkdownOptions) => Markdown;
172
-
173
- export { type AnchorPluginOptions, type AssetsPluginOptions, type EmojiPluginOptions, type ImportCodePluginOptions, type LinksPluginOptions, type Markdown, type MarkdownEnv, type MarkdownHeader, type MarkdownLink, type MarkdownOptions, type MarkdownSlugifyFunction, type VPrePluginOptions, assetsPlugin, createMarkdown, importCodePlugin, linksPlugin, vPrePlugin };
168
+ declare const createMarkdown: ({
169
+ anchor,
170
+ assets,
171
+ code,
172
+ vPre,
173
+ component,
174
+ emoji,
175
+ frontmatter,
176
+ headers,
177
+ title,
178
+ importCode,
179
+ links,
180
+ sfc,
181
+ slugify,
182
+ toc,
183
+ ...markdownItOptions
184
+ }?: MarkdownOptions) => Markdown;
185
+ //#endregion
186
+ export { type AnchorPluginOptions, type AssetsPluginOptions, type ComponentPluginOptions, type EmojiPluginOptions, type FrontmatterPluginOptions, type HeadersPluginOptions, type ImportCodePluginOptions, type LinksPluginOptions, Markdown, MarkdownEnv, MarkdownHeader, MarkdownLink, MarkdownOptions, type MarkdownSfcBlocks, MarkdownSlugifyFunction, type SfcPluginOptions, type TocPluginOptions, type VPrePluginOptions, anchorPlugin, assetsPlugin, componentPlugin, createMarkdown, emojiPlugin, frontmatterPlugin, headersPlugin, importCodePlugin, linksPlugin, sfcPlugin, titlePlugin, tocPlugin, vPrePlugin };
package/dist/index.js CHANGED
@@ -1,444 +1,314 @@
1
- // src/markdown.ts
2
- import { slugify as defaultSlugify } from "@mdit-vue/shared";
3
- import { logger as logger2 } from "@vuepress/utils";
1
+ import { slugify } from "@mdit-vue/shared";
2
+ import { colors, fs, logger, path } from "@vuepress/utils";
4
3
  import MarkdownIt from "markdown-it";
5
-
6
- // src/plugins.ts
7
- import {
8
- componentPlugin
9
- } from "@mdit-vue/plugin-component";
10
- import {
11
- frontmatterPlugin
12
- } from "@mdit-vue/plugin-frontmatter";
13
- import {
14
- headersPlugin
15
- } from "@mdit-vue/plugin-headers";
4
+ import { componentPlugin } from "@mdit-vue/plugin-component";
5
+ import { frontmatterPlugin } from "@mdit-vue/plugin-frontmatter";
6
+ import { headersPlugin } from "@mdit-vue/plugin-headers";
16
7
  import { sfcPlugin } from "@mdit-vue/plugin-sfc";
17
8
  import { titlePlugin } from "@mdit-vue/plugin-title";
18
9
  import { tocPlugin } from "@mdit-vue/plugin-toc";
19
-
20
- // src/plugins/anchorPlugin.ts
21
10
  import anchorPlugin from "markdown-it-anchor";
22
-
23
- // src/plugins/assetsPlugin/resolveLink.ts
24
- import { path } from "@vuepress/utils";
25
11
  import { decode } from "mdurl";
26
- var resolveLink = (link, {
27
- env,
28
- absolutePathPrependBase = false,
29
- relativePathPrefix,
30
- strict = false
31
- }) => {
32
- if (link.startsWith("data:")) return link;
33
- let resolvedLink = decode(link);
34
- const isRelativePath = strict ? (
35
- // in strict mode, only link that starts with `./` or `../` is considered as relative path
36
- /^\.{1,2}\//.test(link)
37
- ) : (
38
- // in non-strict mode, link that does not start with `/` and does not have protocol is considered as relative path
39
- !link.startsWith("/") && !/[A-z]+:\/\//.test(link)
40
- );
41
- if (isRelativePath && env.filePathRelative) {
42
- resolvedLink = `${relativePathPrefix}/${path.join(
43
- path.dirname(env.filePathRelative),
44
- resolvedLink
45
- )}`;
46
- }
47
- if (absolutePathPrependBase && env.base && link.startsWith("/")) {
48
- resolvedLink = path.join(env.base, resolvedLink);
49
- }
50
- return resolvedLink;
51
- };
52
-
53
- // src/plugins/assetsPlugin/assetsPlugin.ts
54
- var assetsPlugin = (md, {
55
- absolutePathPrependBase = false,
56
- relativePathPrefix = "@source"
57
- } = {}) => {
58
- const rawImageRule = md.renderer.rules.image;
59
- md.renderer.rules.image = (tokens, idx, options, env, self) => {
60
- const token = tokens[idx];
61
- const link = token.attrGet("src");
62
- if (link) {
63
- token.attrSet(
64
- "src",
65
- resolveLink(link, { env, absolutePathPrependBase, relativePathPrefix })
66
- );
67
- }
68
- return rawImageRule(tokens, idx, options, env, self);
69
- };
70
- const createHtmlRule = (rawHtmlRule) => (tokens, idx, options, env, self) => {
71
- tokens[idx].content = tokens[idx].content.replace(
72
- /(<img\b.*?src=)(['"])(.*?)\2/gs,
73
- (_, prefix, quote, src) => `${prefix}${quote}${resolveLink(src.trim(), {
74
- env,
75
- absolutePathPrependBase,
76
- relativePathPrefix,
77
- strict: true
78
- })}${quote}`
79
- ).replace(
80
- /(<img\b.*?srcset=)(['"])(.*?)\2/gs,
81
- (_, prefix, quote, srcset) => `${prefix}${quote}${srcset.split(",").map(
82
- (item) => item.trim().replace(
83
- /^([^ ]*?)([ \n].*)?$/,
84
- (__, url, descriptor = "") => `${resolveLink(url.trim(), {
85
- env,
86
- absolutePathPrependBase,
87
- relativePathPrefix,
88
- strict: true
89
- })}${descriptor.replace(/[ \n]+/g, " ").trimEnd()}`
90
- )
91
- ).join(", ")}${quote}`
92
- );
93
- return rawHtmlRule(tokens, idx, options, env, self);
94
- };
95
- const rawHtmlBlockRule = md.renderer.rules.html_block;
96
- const rawHtmlInlineRule = md.renderer.rules.html_inline;
97
- md.renderer.rules.html_block = createHtmlRule(rawHtmlBlockRule);
98
- md.renderer.rules.html_inline = createHtmlRule(rawHtmlInlineRule);
99
- };
100
-
101
- // src/plugins/emojiPlugin.ts
102
12
  import { full as emojiPlugin } from "markdown-it-emoji";
103
-
104
- // src/plugins/importCodePlugin/createImportCodeBlockRule.ts
105
- import { path as path2 } from "@vuepress/utils";
106
- var MIN_LENGTH = 9;
107
- var START_CODES = [64, 91, 99, 111, 100, 101];
108
- var SYNTAX_RE = /^@\[code(?:{(?:(?:(?<lineStart>\d+)?-(?<lineEnd>\d+)?)|(?<lineSingle>\d+))})?(?: (?<info>[^\]]+))?\]\((?<importPath>[^)]*)\)/;
109
- var parseLineNumber = (line) => line ? Number.parseInt(line, 10) : void 0;
110
- var createImportCodeBlockRule = ({ handleImportPath = (str) => str }) => (state, startLine, endLine, silent) => {
111
- if (state.sCount[startLine] - state.blkIndent >= 4) {
112
- return false;
113
- }
114
- const pos = state.bMarks[startLine] + state.tShift[startLine];
115
- const max = state.eMarks[startLine];
116
- if (pos + MIN_LENGTH > max) return false;
117
- for (let i = 0; i < START_CODES.length; i += 1) {
118
- if (state.src.charCodeAt(pos + i) !== START_CODES[i]) {
119
- return false;
120
- }
121
- }
122
- const match = state.src.slice(pos, max).match(SYNTAX_RE);
123
- if (!match?.groups) return false;
124
- if (silent) return true;
125
- const { info, importPath } = match.groups;
126
- const lineSingle = parseLineNumber(match.groups.lineSingle);
127
- const lineStart = lineSingle ?? parseLineNumber(match.groups.lineStart) ?? 0;
128
- const lineEnd = lineSingle ?? parseLineNumber(match.groups.lineEnd);
129
- const meta = {
130
- importPath: handleImportPath(importPath),
131
- lineStart,
132
- lineEnd
133
- };
134
- const token = state.push("import_code", "code", 0);
135
- token.info = info ?? path2.extname(meta.importPath).slice(1);
136
- token.markup = "```";
137
- token.map = [startLine, startLine + 1];
138
- token.meta = meta;
139
- state.line = startLine + 1;
140
- return true;
13
+ import { inferRoutePath, isLinkExternal, removeLeadingSlash } from "@vuepress/shared";
14
+ //#region src/plugins/assetsPlugin/resolveLink.ts
15
+ const resolveLink = (link, { env, absolutePathPrependBase = false }) => {
16
+ if (link.startsWith("data:")) return link;
17
+ let resolvedLink = decode(link);
18
+ if (absolutePathPrependBase && env.base && link.startsWith("/")) resolvedLink = path.join(env.base, resolvedLink);
19
+ return resolvedLink;
20
+ };
21
+ //#endregion
22
+ //#region src/plugins/assetsPlugin/assetsPlugin.ts
23
+ /**
24
+ * Plugin to handle assets links
25
+ */
26
+ const assetsPlugin = (md, { absolutePathPrependBase = false } = {}) => {
27
+ const rawImageRule = md.renderer.rules.image;
28
+ md.renderer.rules.image = (tokens, idx, options, env, self) => {
29
+ const token = tokens[idx];
30
+ const link = token.attrGet("src");
31
+ if (link) token.attrSet("src", resolveLink(link, {
32
+ env,
33
+ absolutePathPrependBase
34
+ }));
35
+ return rawImageRule(tokens, idx, options, env, self);
36
+ };
37
+ const createHtmlRule = (rawHtmlRule) => (tokens, idx, options, env, self) => {
38
+ tokens[idx].content = tokens[idx].content.replace(/(<img\b.*?src=)(['"])(.*?)\2/gs, (_, prefix, quote, src) => `${prefix}${quote}${resolveLink(src.trim(), {
39
+ env,
40
+ absolutePathPrependBase
41
+ })}${quote}`).replace(/(<img\b.*?srcset=)(['"])(.*?)\2/gs, (_, prefix, quote, srcset) => `${prefix}${quote}${srcset.split(",").map((item) => item.trim().replace(/^([^ ]*?)([ \n].*)?$/, (__, url, descriptor = "") => `${resolveLink(url.trim(), {
42
+ env,
43
+ absolutePathPrependBase
44
+ })}${descriptor.replace(/[ \n]+/g, " ").trimEnd()}`)).join(", ")}${quote}`);
45
+ return rawHtmlRule(tokens, idx, options, env, self);
46
+ };
47
+ const rawHtmlBlockRule = md.renderer.rules.html_block;
48
+ const rawHtmlInlineRule = md.renderer.rules.html_inline;
49
+ md.renderer.rules.html_block = createHtmlRule(rawHtmlBlockRule);
50
+ md.renderer.rules.html_inline = createHtmlRule(rawHtmlInlineRule);
141
51
  };
142
-
143
- // src/plugins/importCodePlugin/resolveImportCode.ts
144
- import { colors, fs, logger, path as path3 } from "@vuepress/utils";
145
- var resolveImportCode = ({ importPath, lineStart, lineEnd }, { filePath }) => {
146
- let importFilePath = importPath;
147
- if (!path3.isAbsolute(importPath)) {
148
- if (!filePath) {
149
- logger.error(
150
- `Import file ${colors.magenta(importPath)} can not be resolved`
151
- );
152
- return {
153
- importFilePath: null,
154
- importCode: "Error when resolving path"
155
- };
156
- }
157
- importFilePath = path3.resolve(filePath, "..", importPath);
158
- }
159
- if (!fs.existsSync(importFilePath)) {
160
- logger.error(`Import file ${colors.magenta(importPath)} not found`);
161
- return {
162
- importFilePath,
163
- importCode: "File not found"
164
- };
165
- }
166
- const fileContent = fs.readFileSync(importFilePath).toString();
167
- return {
168
- importFilePath,
169
- importCode: fileContent.split("\n").slice(lineStart ? lineStart - 1 : lineStart, lineEnd).join("\n").replace(/\n?$/, "\n")
170
- };
52
+ //#endregion
53
+ //#region src/plugins/importCodePlugin/createImportCodeBlockRule.ts
54
+ const MIN_LENGTH = 9;
55
+ const START_CODES = [
56
+ 64,
57
+ 91,
58
+ 99,
59
+ 111,
60
+ 100,
61
+ 101
62
+ ];
63
+ const SYNTAX_RE = /^@\[code(?:{(?:(?:(?<lineStart>\d+)?-(?<lineEnd>\d+)?)|(?<lineSingle>\d+))})?(?: (?<info>[^\]]+))?\]\((?<importPath>[^)]*)\)/;
64
+ /**
65
+ * Utility function to parse line number from line string that matched by SYNTAX_RE
66
+ */
67
+ const parseLineNumber = (line) => line ? Number.parseInt(line, 10) : void 0;
68
+ const createImportCodeBlockRule = ({ handleImportPath = (str) => str }) => (state, startLine, endLine, silent) => {
69
+ /* istanbul ignore if */
70
+ if (state.sCount[startLine] - state.blkIndent >= 4) return false;
71
+ const pos = state.bMarks[startLine] + state.tShift[startLine];
72
+ const max = state.eMarks[startLine];
73
+ if (pos + MIN_LENGTH > max) return false;
74
+ for (let i = 0; i < START_CODES.length; i += 1) if (state.src.charCodeAt(pos + i) !== START_CODES[i]) return false;
75
+ const match = state.src.slice(pos, max).match(SYNTAX_RE);
76
+ if (!match?.groups) return false;
77
+ if (silent) return true;
78
+ const { info, importPath } = match.groups;
79
+ const lineSingle = parseLineNumber(match.groups.lineSingle);
80
+ const lineStart = lineSingle ?? parseLineNumber(match.groups.lineStart) ?? 0;
81
+ const lineEnd = lineSingle ?? parseLineNumber(match.groups.lineEnd);
82
+ const meta = {
83
+ importPath: handleImportPath(importPath),
84
+ lineStart,
85
+ lineEnd
86
+ };
87
+ const token = state.push("import_code", "code", 0);
88
+ token.info = info ?? path.extname(meta.importPath).slice(1);
89
+ token.markup = "```";
90
+ token.map = [startLine, startLine + 1];
91
+ token.meta = meta;
92
+ state.line = startLine + 1;
93
+ return true;
171
94
  };
172
-
173
- // src/plugins/importCodePlugin/importCodePlugin.ts
174
- var importCodePlugin = (md, options = {}) => {
175
- md.block.ruler.before(
176
- "fence",
177
- "import_code",
178
- createImportCodeBlockRule(options),
179
- {
180
- alt: ["paragraph", "reference", "blockquote", "list"]
181
- }
182
- );
183
- md.renderer.rules.import_code = (tokens, idx, opts, env, slf) => {
184
- const token = tokens[idx];
185
- const { importFilePath, importCode } = resolveImportCode(
186
- token.meta,
187
- env
188
- );
189
- token.content = importCode;
190
- if (importFilePath) {
191
- ;
192
- (env.importedFiles ??= []).push(importFilePath);
193
- }
194
- return md.renderer.rules.fence(tokens, idx, opts, env, slf);
195
- };
95
+ //#endregion
96
+ //#region src/plugins/importCodePlugin/resolveImportCode.ts
97
+ const resolveImportCode = ({ importPath, lineStart, lineEnd }, { filePath }) => {
98
+ let importFilePath = importPath;
99
+ if (!path.isAbsolute(importPath)) {
100
+ if (!filePath) {
101
+ logger.error(`Import file ${colors.magenta(importPath)} can not be resolved`);
102
+ return {
103
+ importFilePath: null,
104
+ importCode: "Error when resolving path"
105
+ };
106
+ }
107
+ importFilePath = path.resolve(filePath, "..", importPath);
108
+ }
109
+ if (!fs.existsSync(importFilePath)) {
110
+ logger.error(`Import file ${colors.magenta(importPath)} not found`);
111
+ return {
112
+ importFilePath,
113
+ importCode: "File not found"
114
+ };
115
+ }
116
+ const fileContent = fs.readFileSync(importFilePath).toString();
117
+ return {
118
+ importFilePath,
119
+ importCode: fileContent.split("\n").slice(lineStart ? lineStart - 1 : lineStart, lineEnd).join("\n").replace(/\n?$/, "\n")
120
+ };
196
121
  };
197
-
198
- // src/plugins/linksPlugin/linksPlugin.ts
199
- import { inferRoutePath, isLinkExternal } from "@vuepress/shared";
200
-
201
- // src/plugins/linksPlugin/resolvePaths.ts
202
- import { removeLeadingSlash } from "@vuepress/shared";
203
- import { path as path4 } from "@vuepress/utils";
204
- var resolvePaths = (rawPath, base, filePathRelative) => {
205
- let absolutePath;
206
- let relativePath;
207
- if (rawPath.startsWith("/")) {
208
- if (rawPath.endsWith(".md")) {
209
- absolutePath = path4.join(base, rawPath);
210
- relativePath = removeLeadingSlash(rawPath);
211
- } else {
212
- absolutePath = rawPath;
213
- relativePath = path4.relative(base, absolutePath);
214
- }
215
- } else if (filePathRelative) {
216
- relativePath = path4.join(
217
- // file path may contain non-ASCII characters
218
- path4.dirname(encodeURI(filePathRelative)),
219
- rawPath
220
- );
221
- absolutePath = path4.join(base, relativePath);
222
- } else {
223
- relativePath = rawPath.replace(/^(?:\.\/)?(.*)$/, "$1");
224
- absolutePath = null;
225
- }
226
- return {
227
- absolutePath,
228
- relativePath
229
- };
122
+ //#endregion
123
+ //#region src/plugins/importCodePlugin/importCodePlugin.ts
124
+ const importCodePlugin = (md, options = {}) => {
125
+ md.block.ruler.before("fence", "import_code", createImportCodeBlockRule(options), { alt: [
126
+ "paragraph",
127
+ "reference",
128
+ "blockquote",
129
+ "list"
130
+ ] });
131
+ md.renderer.rules.import_code = (tokens, idx, opts, env, slf) => {
132
+ const token = tokens[idx];
133
+ const { importFilePath, importCode } = resolveImportCode(token.meta, env);
134
+ token.content = importCode;
135
+ if (importFilePath) (env.importedFiles ??= []).push(importFilePath);
136
+ return md.renderer.rules.fence(tokens, idx, opts, env, slf);
137
+ };
230
138
  };
231
-
232
- // src/plugins/linksPlugin/linksPlugin.ts
233
- var linksPlugin = (md, options = {}) => {
234
- const internalTag = options.internalTag || "RouteLink";
235
- const isExternal = options.isExternal ?? ((href, env) => isLinkExternal(href, env.base));
236
- const externalAttrs = {
237
- target: "_blank",
238
- rel: "noopener noreferrer",
239
- ...options.externalAttrs
240
- };
241
- let hasOpenInternalLink = false;
242
- const handleLinkOpen = (tokens, idx, env) => {
243
- const token = tokens[idx];
244
- const hrefIndex = token.attrIndex("href");
245
- if (hrefIndex < 0) {
246
- return;
247
- }
248
- const hrefAttr = token.attrs[hrefIndex];
249
- const hrefLink = hrefAttr[1];
250
- const { base = "/", filePathRelative = null } = env;
251
- if (isExternal(hrefLink, env)) {
252
- Object.entries(externalAttrs).forEach(([key, val]) => {
253
- token.attrSet(key, val);
254
- });
255
- return;
256
- }
257
- const internalLinkMatch = hrefLink.match(
258
- /^([^#?]*?(?:\/|\.md|\.html))([#?].*)?$/
259
- );
260
- if (!internalLinkMatch) {
261
- return;
262
- }
263
- const rawPath = internalLinkMatch[1];
264
- const rawHashAndQueries = (internalLinkMatch[2] || "").replace(
265
- /^#(\d)/,
266
- "#_$1"
267
- );
268
- const { relativePath, absolutePath } = resolvePaths(
269
- rawPath,
270
- base,
271
- filePathRelative
272
- );
273
- if (["RouterLink", "RouteLink"].includes(internalTag)) {
274
- token.tag = internalTag;
275
- hrefAttr[0] = "to";
276
- const normalizedPath = inferRoutePath(
277
- absolutePath ? absolutePath.replace(new RegExp(`^${base}`), "/") : relativePath
278
- );
279
- hrefAttr[1] = `${normalizedPath}${rawHashAndQueries}`;
280
- hasOpenInternalLink = true;
281
- } else {
282
- const normalizedPath = inferRoutePath(absolutePath ?? relativePath);
283
- hrefAttr[1] = `${normalizedPath}${rawHashAndQueries}`;
284
- }
285
- ;
286
- (env.links ??= []).push({
287
- raw: hrefLink,
288
- relative: relativePath,
289
- absolute: absolutePath
290
- });
291
- };
292
- md.renderer.rules.link_open = (tokens, idx, opts, env, self) => {
293
- handleLinkOpen(tokens, idx, env);
294
- return self.renderToken(tokens, idx, opts);
295
- };
296
- md.renderer.rules.link_close = (tokens, idx, opts, _env, self) => {
297
- if (hasOpenInternalLink) {
298
- hasOpenInternalLink = false;
299
- tokens[idx].tag = internalTag;
300
- }
301
- return self.renderToken(tokens, idx, opts);
302
- };
139
+ //#endregion
140
+ //#region src/plugins/linksPlugin/resolvePaths.ts
141
+ /**
142
+ * Resolve relative and absolute paths according to the `base` and `filePathRelative`
143
+ */
144
+ const resolvePaths = (rawPath, base, filePathRelative) => {
145
+ let absolutePath;
146
+ let relativePath;
147
+ if (rawPath.startsWith("/")) if (rawPath.endsWith(".md")) {
148
+ absolutePath = path.join(base, rawPath);
149
+ relativePath = removeLeadingSlash(rawPath);
150
+ } else {
151
+ absolutePath = rawPath;
152
+ relativePath = path.relative(base, absolutePath);
153
+ }
154
+ else if (filePathRelative) {
155
+ relativePath = path.join(path.dirname(encodeURI(filePathRelative)), rawPath);
156
+ absolutePath = path.join(base, relativePath);
157
+ } else {
158
+ relativePath = rawPath.replace(/^(?:\.\/)?(.*)$/, "$1");
159
+ absolutePath = null;
160
+ }
161
+ return {
162
+ absolutePath,
163
+ relativePath
164
+ };
303
165
  };
304
-
305
- // src/plugins/vPrePlugin/resolveVPre.ts
306
- var resolveVPre = (info) => {
307
- if (/:v-pre\b/.test(info)) {
308
- return true;
309
- }
310
- if (/:no-v-pre\b/.test(info)) {
311
- return false;
312
- }
313
- return null;
166
+ //#endregion
167
+ //#region src/plugins/linksPlugin/linksPlugin.ts
168
+ /**
169
+ * Process links in markdown file
170
+ *
171
+ * - internal links: convert `<a>` tag into internalTag
172
+ * - external links: add extra attrs
173
+ */
174
+ const linksPlugin = (md, options = {}) => {
175
+ const internalTag = options.internalTag || "RouteLink";
176
+ const isExternal = options.isExternal ?? ((href, env) => isLinkExternal(href, env.base));
177
+ const externalAttrs = {
178
+ target: "_blank",
179
+ rel: "noopener noreferrer",
180
+ ...options.externalAttrs
181
+ };
182
+ let hasOpenInternalLink = false;
183
+ const handleLinkOpen = (tokens, idx, env) => {
184
+ const token = tokens[idx];
185
+ const hrefIndex = token.attrIndex("href");
186
+ /* istanbul ignore if */
187
+ if (hrefIndex < 0) return;
188
+ const hrefAttr = token.attrs[hrefIndex];
189
+ const hrefLink = hrefAttr[1];
190
+ const { base = "/", filePathRelative = null } = env;
191
+ if (isExternal(hrefLink, env)) {
192
+ Object.entries(externalAttrs).forEach(([key, val]) => {
193
+ token.attrSet(key, val);
194
+ });
195
+ return;
196
+ }
197
+ const internalLinkMatch = hrefLink.match(/^([^#?]*?(?:\/|\.md|\.html))([#?].*)?$/);
198
+ if (!internalLinkMatch) return;
199
+ const rawPath = internalLinkMatch[1];
200
+ const rawHashAndQueries = (internalLinkMatch[2] || "").replace(/^#(\d)/, "#_$1");
201
+ const { relativePath, absolutePath } = resolvePaths(rawPath, base, filePathRelative);
202
+ if (["RouterLink", "RouteLink"].includes(internalTag)) {
203
+ token.tag = internalTag;
204
+ hrefAttr[0] = "to";
205
+ hrefAttr[1] = `${inferRoutePath(absolutePath ? absolutePath.replace(new RegExp(`^${base}`), "/") : relativePath)}${rawHashAndQueries}`;
206
+ hasOpenInternalLink = true;
207
+ } else hrefAttr[1] = `${inferRoutePath(absolutePath ?? relativePath)}${rawHashAndQueries}`;
208
+ (env.links ??= []).push({
209
+ raw: hrefLink,
210
+ relative: relativePath,
211
+ absolute: absolutePath
212
+ });
213
+ };
214
+ md.renderer.rules.link_open = (tokens, idx, opts, env, self) => {
215
+ handleLinkOpen(tokens, idx, env);
216
+ return self.renderToken(tokens, idx, opts);
217
+ };
218
+ md.renderer.rules.link_close = (tokens, idx, opts, _env, self) => {
219
+ if (hasOpenInternalLink) {
220
+ hasOpenInternalLink = false;
221
+ tokens[idx].tag = internalTag;
222
+ }
223
+ return self.renderToken(tokens, idx, opts);
224
+ };
314
225
  };
315
-
316
- // src/plugins/vPrePlugin/vPrePlugin.ts
317
- var vPrePlugin = (md, { inline = true, block = true } = {}) => {
318
- const rawFence = md.renderer.rules.fence;
319
- md.renderer.rules.fence = (...args) => {
320
- const [tokens, idx] = args;
321
- const token = tokens[idx];
322
- const info = token.info ? md.utils.unescapeAll(token.info).trim() : "";
323
- let result = rawFence(...args);
324
- if (resolveVPre(info) ?? block) {
325
- result = `<pre v-pre${result.slice("<pre".length)}`;
326
- }
327
- return result;
328
- };
329
- if (inline) {
330
- const rawInlineCodeRule = md.renderer.rules.code_inline;
331
- md.renderer.rules.code_inline = (...args) => {
332
- const result = rawInlineCodeRule(...args);
333
- return `<code v-pre${result.slice("<code".length)}`;
334
- };
335
- }
226
+ //#endregion
227
+ //#region src/plugins/vPrePlugin/resolveVPre.ts
228
+ /**
229
+ * Resolve the `:v-pre` / `:no-v-pre` mark from token info
230
+ */
231
+ const resolveVPre = (info) => {
232
+ if (/:v-pre\b/.test(info)) return true;
233
+ if (/:no-v-pre\b/.test(info)) return false;
234
+ return null;
336
235
  };
337
-
338
- // src/markdown.ts
339
- var createMarkdown = ({
340
- anchor,
341
- assets,
342
- // eslint-disable-next-line @typescript-eslint/no-deprecated
343
- code,
344
- vPre,
345
- component,
346
- emoji,
347
- frontmatter,
348
- headers,
349
- title,
350
- importCode,
351
- links,
352
- sfc,
353
- slugify = defaultSlugify,
354
- toc,
355
- ...markdownItOptions
356
- } = {}) => {
357
- const md = MarkdownIt({
358
- ...markdownItOptions,
359
- // should always enable html option
360
- html: true
361
- });
362
- if (anchor !== false) {
363
- md.use(anchorPlugin, {
364
- level: [1, 2, 3, 4, 5, 6],
365
- slugify,
366
- permalink: anchorPlugin.permalink.headerLink({
367
- class: "header-anchor",
368
- // Add a span inside the link so Safari shows headings in reader view.
369
- safariReaderFix: true
370
- }),
371
- ...anchor
372
- });
373
- }
374
- if (assets !== false) {
375
- md.use(assetsPlugin, assets);
376
- }
377
- if (code) {
378
- logger2.warn(
379
- `\`markdown.code\` option has been removed, please use '@vuepress/plugin-shiki' or '@vuepress/plugin-prismjs' instead.
380
- See https://vuepress.vuejs.org/reference/config.html#markdown-code`
381
- );
382
- }
383
- if (component !== false) {
384
- md.use(componentPlugin);
385
- }
386
- if (emoji !== false) {
387
- md.use(emojiPlugin, emoji);
388
- }
389
- if (frontmatter !== false) {
390
- md.use(frontmatterPlugin, {
391
- ...frontmatter,
392
- grayMatterOptions: {
393
- excerpt: false,
394
- ...frontmatter?.grayMatterOptions
395
- }
396
- });
397
- }
398
- if (headers !== false) {
399
- md.use(headersPlugin, {
400
- level: [2, 3],
401
- slugify,
402
- ...headers
403
- });
404
- }
405
- if (importCode !== false) {
406
- md.use(importCodePlugin, importCode);
407
- }
408
- if (links !== false) {
409
- md.use(linksPlugin, links);
410
- }
411
- if (sfc !== false) {
412
- md.use(sfcPlugin, sfc);
413
- }
414
- if (toc !== false) {
415
- md.use(tocPlugin, {
416
- level: [2, 3],
417
- slugify,
418
- linkTag: "router-link",
419
- ...toc
420
- });
421
- }
422
- if (title !== false) {
423
- md.use(titlePlugin);
424
- }
425
- if (vPre !== false) {
426
- md.use(vPrePlugin, vPre);
427
- }
428
- return md;
236
+ //#endregion
237
+ //#region src/plugins/vPrePlugin/vPrePlugin.ts
238
+ /**
239
+ * v-pre plugin
240
+ */
241
+ const vPrePlugin = (md, { inline = true, block = true } = {}) => {
242
+ const rawFence = md.renderer.rules.fence;
243
+ md.renderer.rules.fence = (...args) => {
244
+ const [tokens, idx] = args;
245
+ const token = tokens[idx];
246
+ const info = token.info ? md.utils.unescapeAll(token.info).trim() : "";
247
+ let result = rawFence(...args);
248
+ if (resolveVPre(info) ?? block) result = `<pre v-pre${result.slice(4)}`;
249
+ return result;
250
+ };
251
+ if (inline) {
252
+ const rawInlineCodeRule = md.renderer.rules.code_inline;
253
+ md.renderer.rules.code_inline = (...args) => {
254
+ return `<code v-pre${rawInlineCodeRule(...args).slice(5)}`;
255
+ };
256
+ }
429
257
  };
430
- export {
431
- anchorPlugin,
432
- assetsPlugin,
433
- componentPlugin,
434
- createMarkdown,
435
- emojiPlugin,
436
- frontmatterPlugin,
437
- headersPlugin,
438
- importCodePlugin,
439
- linksPlugin,
440
- sfcPlugin,
441
- titlePlugin,
442
- tocPlugin,
443
- vPrePlugin
258
+ //#endregion
259
+ //#region src/markdown.ts
260
+ /**
261
+ * Create vuepress customized markdown-it instance
262
+ */
263
+ const createMarkdown = ({ anchor, assets, code, vPre, component, emoji, frontmatter, headers, title, importCode, links, sfc, slugify: slugify$1 = slugify, toc, ...markdownItOptions } = {}) => {
264
+ const md = MarkdownIt({
265
+ ...markdownItOptions,
266
+ html: true
267
+ });
268
+ if (anchor !== false) md.use(anchorPlugin, {
269
+ level: [
270
+ 1,
271
+ 2,
272
+ 3,
273
+ 4,
274
+ 5,
275
+ 6
276
+ ],
277
+ slugify: slugify$1,
278
+ permalink: anchorPlugin.permalink.headerLink({
279
+ class: "header-anchor",
280
+ safariReaderFix: true
281
+ }),
282
+ ...anchor
283
+ });
284
+ if (assets !== false) md.use(assetsPlugin, assets);
285
+ if (code) logger.warn(`\`markdown.code\` option has been removed, please use '@vuepress/plugin-shiki' or '@vuepress/plugin-prismjs' instead.\n See https://vuepress.vuejs.org/reference/config.html#markdown-code`);
286
+ if (component !== false) md.use(componentPlugin);
287
+ if (emoji !== false) md.use(emojiPlugin, emoji);
288
+ if (frontmatter !== false) md.use(frontmatterPlugin, {
289
+ ...frontmatter,
290
+ grayMatterOptions: {
291
+ excerpt: false,
292
+ ...frontmatter?.grayMatterOptions
293
+ }
294
+ });
295
+ if (headers !== false) md.use(headersPlugin, {
296
+ level: [2, 3],
297
+ slugify: slugify$1,
298
+ ...headers
299
+ });
300
+ if (importCode !== false) md.use(importCodePlugin, importCode);
301
+ if (links !== false) md.use(linksPlugin, links);
302
+ if (sfc !== false) md.use(sfcPlugin, sfc);
303
+ if (toc !== false) md.use(tocPlugin, {
304
+ level: [2, 3],
305
+ slugify: slugify$1,
306
+ linkTag: "router-link",
307
+ ...toc
308
+ });
309
+ if (title !== false) md.use(titlePlugin);
310
+ if (vPre !== false) md.use(vPrePlugin, vPre);
311
+ return md;
444
312
  };
313
+ //#endregion
314
+ export { anchorPlugin, assetsPlugin, componentPlugin, createMarkdown, emojiPlugin, frontmatterPlugin, headersPlugin, importCodePlugin, linksPlugin, sfcPlugin, titlePlugin, tocPlugin, vPrePlugin };
package/package.json CHANGED
@@ -1,32 +1,35 @@
1
1
  {
2
2
  "name": "@vuepress/markdown",
3
- "version": "2.0.0-rc.26",
3
+ "version": "2.0.0-rc.28",
4
4
  "description": "Markdown package of VuePress",
5
5
  "keywords": [
6
- "vuepress",
7
- "markdown"
6
+ "markdown",
7
+ "vuepress"
8
8
  ],
9
9
  "homepage": "https://github.com/vuepress",
10
10
  "bugs": {
11
11
  "url": "https://github.com/vuepress/core/issues"
12
12
  },
13
+ "license": "MIT",
14
+ "author": "meteorlxy",
13
15
  "repository": {
14
16
  "type": "git",
15
17
  "url": "git+https://github.com/vuepress/core.git"
16
18
  },
17
- "license": "MIT",
18
- "author": "meteorlxy",
19
+ "files": [
20
+ "dist"
21
+ ],
19
22
  "type": "module",
23
+ "main": "./dist/index.js",
24
+ "module": "./dist/index.js",
25
+ "types": "./dist/index.d.ts",
20
26
  "exports": {
21
27
  ".": "./dist/index.js",
22
28
  "./package.json": "./package.json"
23
29
  },
24
- "main": "./dist/index.js",
25
- "module": "./dist/index.js",
26
- "types": "./dist/index.d.ts",
27
- "files": [
28
- "dist"
29
- ],
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
30
33
  "dependencies": {
31
34
  "@mdit-vue/plugin-component": "^3.0.2",
32
35
  "@mdit-vue/plugin-frontmatter": "^3.0.2",
@@ -38,35 +41,26 @@
38
41
  "@mdit-vue/types": "^3.0.2",
39
42
  "@types/markdown-it": "^14.1.2",
40
43
  "@types/markdown-it-emoji": "^3.0.1",
41
- "markdown-it": "^14.1.0",
44
+ "markdown-it": "^14.1.1",
42
45
  "markdown-it-anchor": "^9.2.0",
43
46
  "markdown-it-emoji": "^3.0.0",
44
47
  "mdurl": "^2.0.0",
45
- "@vuepress/shared": "2.0.0-rc.26",
46
- "@vuepress/utils": "2.0.0-rc.26"
48
+ "@vuepress/shared": "2.0.0-rc.28",
49
+ "@vuepress/utils": "2.0.0-rc.28"
47
50
  },
48
51
  "devDependencies": {
49
52
  "@types/mdurl": "^2.0.0"
50
53
  },
51
- "publishConfig": {
52
- "access": "public"
53
- },
54
- "tsup": {
55
- "clean": true,
56
- "dts": "./src/index.ts",
57
- "entry": [
58
- "./src/index.ts"
59
- ],
60
- "format": [
61
- "esm"
62
- ],
63
- "outDir": "./dist",
64
- "sourcemap": false,
54
+ "tsdown": {
55
+ "dts": true,
56
+ "entry": "./src/index.ts",
57
+ "fixedExtension": false,
58
+ "format": "esm",
65
59
  "target": "es2023",
66
60
  "tsconfig": "../../tsconfig.dts.json"
67
61
  },
68
62
  "scripts": {
69
- "build": "tsup",
63
+ "build": "tsdown",
70
64
  "clean": "rimraf dist"
71
65
  }
72
66
  }