-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
markdownToVue.ts
232 lines (199 loc) · 6.06 KB
/
markdownToVue.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import fs from 'fs'
import path from 'path'
import matter from 'gray-matter'
import LRUCache from 'lru-cache'
import { createMarkdownRenderer, MarkdownOptions } from './markdown/markdown'
import { deeplyParseHeader } from './utils/parseHeader'
import { PageData, HeadConfig, EXTERNAL_URL_RE } from './shared'
import { slash } from './utils/slash'
import chalk from 'chalk'
import _debug from 'debug'
const debug = _debug('vitepress:md')
const cache = new LRUCache<string, MarkdownCompileResult>({ max: 1024 })
const includesRE = /<!--\s*@include:\s*(.*?)\s*-->/g
export interface MarkdownCompileResult {
vueSrc: string
pageData: PageData
deadLinks: string[]
includes: string[]
}
export function createMarkdownToVueRenderFn(
srcDir: string,
options: MarkdownOptions = {},
pages: string[],
userDefines: Record<string, any> | undefined,
isBuild = false
) {
const md = createMarkdownRenderer(srcDir, options)
pages = pages.map((p) => slash(p.replace(/\.md$/, '')))
const userDefineRegex = userDefines
? new RegExp(
`\\b(${Object.keys(userDefines)
.map((key) => key.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&'))
.join('|')})`,
'g'
)
: null
return (
src: string,
file: string,
publicDir: string
): MarkdownCompileResult => {
const relativePath = slash(path.relative(srcDir, file))
const dir = path.dirname(file)
const cached = cache.get(src)
if (cached) {
debug(`[cache hit] ${relativePath}`)
return cached
}
const start = Date.now()
// resolve includes
let includes: string[] = []
src = src.replace(includesRE, (_, m1) => {
const includePath = path.join(dir, m1)
const content = fs.readFileSync(includePath, 'utf-8')
includes.push(slash(includePath))
return content
})
const { content, data: frontmatter } = matter(src)
// reset state before render
md.__path = file
md.__relativePath = relativePath
let html = md.render(content)
const data = md.__data
if (isBuild) {
// avoid env variables being replaced by vite
html = html
.replace(/\bimport\.meta/g, 'import.<wbr/>meta')
.replace(/\bprocess\.env/g, 'process.<wbr/>env')
// also avoid replacing vite user defines
if (userDefineRegex) {
html = html.replace(
userDefineRegex,
(_) => `${_[0]}<wbr/>${_.slice(1)}`
)
}
}
// validate data.links
const deadLinks: string[] = []
const recordDeadLink = (url: string) => {
console.warn(
chalk.yellow(
`\n(!) Found dead link ${chalk.cyan(url)} in file ${chalk.white.dim(
file
)}`
)
)
deadLinks.push(url)
}
if (data.links) {
const dir = path.dirname(file)
for (let url of data.links) {
if (/\.(?!html|md)\w+($|\?)/i.test(url)) continue
if (url.replace(EXTERNAL_URL_RE, '').startsWith('//localhost:')) {
recordDeadLink(url)
continue
}
url = url.replace(/[?#].*$/, '').replace(/\.(html|md)$/, '')
if (url.endsWith('/')) url += `index`
const resolved = decodeURIComponent(
slash(
url.startsWith('/')
? url.slice(1)
: path.relative(srcDir, path.resolve(dir, url))
)
)
if (
!pages.includes(resolved) &&
!fs.existsSync(path.resolve(dir, publicDir, `${resolved}.html`))
) {
recordDeadLink(url)
}
}
}
const pageData: PageData = {
title: inferTitle(frontmatter, content),
description: inferDescription(frontmatter),
frontmatter,
headers: data.headers || [],
relativePath,
// TODO use git timestamp?
lastUpdated: Math.round(fs.statSync(file).mtimeMs)
}
const vueSrc =
genPageDataCode(data.hoistedTags || [], pageData).join('\n') +
`\n<template><div>${html}</div></template>`
debug(`[render] ${file} in ${Date.now() - start}ms.`)
const result = {
vueSrc,
pageData,
deadLinks,
includes
}
cache.set(src, result)
return result
}
}
const scriptRE = /<\/script>/
const scriptSetupRE = /<\s*script[^>]*\bsetup\b[^>]*/
const scriptClientRe = /<\s*script[^>]*\bclient\b[^>]*/
const defaultExportRE = /((?:^|\n|;)\s*)export(\s*)default/
const namedDefaultExportRE = /((?:^|\n|;)\s*)export(.+)as(\s*)default/
function genPageDataCode(tags: string[], data: PageData) {
const code = `\nexport const __pageData = ${JSON.stringify(
JSON.stringify(data)
)}`
const existingScriptIndex = tags.findIndex((tag) => {
return (
scriptRE.test(tag) &&
!scriptSetupRE.test(tag) &&
!scriptClientRe.test(tag)
)
})
if (existingScriptIndex > -1) {
const tagSrc = tags[existingScriptIndex]
// user has <script> tag inside markdown
// if it doesn't have export default it will error out on build
const hasDefaultExport =
defaultExportRE.test(tagSrc) || namedDefaultExportRE.test(tagSrc)
tags[existingScriptIndex] = tagSrc.replace(
scriptRE,
code + (hasDefaultExport ? `` : `\nexport default{}\n`) + `</script>`
)
} else {
tags.unshift(`<script>${code}\nexport default {}</script>`)
}
return tags
}
const inferTitle = (frontmatter: any, content: string) => {
if (frontmatter.title) {
return deeplyParseHeader(frontmatter.title)
}
if (frontmatter.home) {
return 'Home'
}
const match = content.match(/^\s*#+\s+(.*)/m)
if (match) {
return deeplyParseHeader(match[1].trim())
}
return ''
}
const inferDescription = (frontmatter: Record<string, any>) => {
const { description, head } = frontmatter
if (description !== undefined) {
return description
}
return (head && getHeadMetaContent(head, 'description')) || ''
}
const getHeadMetaContent = (
head: HeadConfig[],
name: string
): string | undefined => {
if (!head || !head.length) {
return undefined
}
const meta = head.find(([tag, attrs = {}]) => {
return tag === 'meta' && attrs.name === name && attrs.content
})
return meta && meta[1].content
}