/
markdownToVue.ts
275 lines (237 loc) · 7.59 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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
import fs from 'fs'
import path from 'path'
import c from 'picocolors'
import matter from 'gray-matter'
import LRUCache from 'lru-cache'
import { PageData, HeadConfig, EXTERNAL_URL_RE } from './shared'
import { slash } from './utils/slash'
import { deeplyParseHeader } from './utils/parseHeader'
import { getGitTimestamp } from './utils/getGitTimestamp'
import { createMarkdownRenderer, MarkdownOptions } from './markdown/markdown'
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 clearCache() {
cache.reset()
}
export async function createMarkdownToVueRenderFn(
srcDir: string,
options: MarkdownOptions = {},
pages: string[],
userDefines: Record<string, any> | undefined,
isBuild = false,
base = '/',
includeLastUpdatedData = false
) {
const md = await createMarkdownRenderer(srcDir, options, base)
pages = pages.map((p) => slash(p.replace(/\.md$/, '')))
const replaceRegex = genReplaceRegexp(userDefines, isBuild)
return async (
src: string,
file: string,
publicDir: string
): Promise<MarkdownCompileResult> => {
const relativePath = slash(path.relative(srcDir, file))
const dir = path.dirname(file)
const cacheKey = JSON.stringify({ src, file })
const cached = cache.get(cacheKey)
if (cached) {
debug(`[cache hit] ${relativePath}`)
return cached
}
const start = Date.now()
// resolve includes
let includes: string[] = []
src = src.replace(includesRE, (m, m1) => {
try {
const includePath = path.join(dir, m1)
const content = fs.readFileSync(includePath, 'utf-8')
includes.push(slash(includePath))
return content
} catch (error) {
return m // silently ignore error if file is not present
}
})
const { content, data: frontmatter } = matter(src)
// reset state before render
md.__path = file
md.__relativePath = relativePath
const html = md.render(content)
const data = md.__data
// validate data.links
const deadLinks: string[] = []
const recordDeadLink = (url: string) => {
console.warn(
c.yellow(
`\n(!) Found dead link ${c.cyan(url)} in file ${c.white(
c.dim(file)
)}\nIf it is intended, you can use:\n ${c.cyan(
`<a href="${url}" target="_blank" rel="noreferrer">${url}</a>`
)}`
)
)
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),
titleTemplate: frontmatter.titleTemplate,
description: inferDescription(frontmatter),
frontmatter,
headers: data.headers || [],
relativePath
}
if (includeLastUpdatedData) {
pageData.lastUpdated = await getGitTimestamp(file)
}
const vueSrc =
genPageDataCode(data.hoistedTags || [], pageData, replaceRegex).join(
'\n'
) +
`\n<template><div>${replaceConstants(
html,
replaceRegex,
vueTemplateBreaker
)}</div></template>`
debug(`[render] ${file} in ${Date.now() - start}ms.`)
const result = {
vueSrc,
pageData,
deadLinks,
includes
}
cache.set(cacheKey, result)
return result
}
}
const scriptRE = /<\/script>/
const scriptLangTsRE = /<\s*script[^>]*\blang=['"]ts['"][^>]*/
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/
const jsStringBreaker = '\u200b'
const vueTemplateBreaker = '<wbr>'
function genReplaceRegexp(
userDefines: Record<string, any> = {},
isBuild: boolean
): RegExp {
// `process.env` need to be handled in both dev and build
// @see https://github.com/vitejs/vite/blob/cad27ee8c00bbd5aeeb2be9bfb3eb164c1b77885/packages/vite/src/node/plugins/clientInjections.ts#L57-L64
const replacements = ['process.env']
if (isBuild) {
replacements.push('import.meta', ...Object.keys(userDefines))
}
return new RegExp(
`\\b(${replacements
.map((key) => key.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&'))
.join('|')})`,
'g'
)
}
/**
* To avoid env variables being replaced by vite:
* - insert `'\u200b'` char into those strings inside js string (page data)
* - insert `<wbr>` tag into those strings inside html string (vue template)
*
* @see https://vitejs.dev/guide/env-and-mode.html#production-replacement
*/
function replaceConstants(str: string, replaceRegex: RegExp, breaker: string) {
return str.replace(replaceRegex, (_) => `${_[0]}${breaker}${_.slice(1)}`)
}
function genPageDataCode(tags: string[], data: PageData, replaceRegex: RegExp) {
const dataJson = JSON.stringify(data)
const code = `\nexport const __pageData = JSON.parse(${JSON.stringify(
replaceConstants(dataJson, replaceRegex, jsStringBreaker)
)})`
const existingScriptIndex = tags.findIndex((tag) => {
return (
scriptRE.test(tag) &&
!scriptSetupRE.test(tag) &&
!scriptClientRE.test(tag)
)
})
const isUsingTS = tags.findIndex((tag) => scriptLangTsRE.test(tag)) > -1
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 {name:'${data.relativePath}'}`) +
`</script>`
)
} else {
tags.unshift(
`<script ${isUsingTS ? 'lang="ts"' : ''}>${code}\nexport default {name:'${
data.relativePath
}'}</script>`
)
}
return tags
}
const inferTitle = (frontmatter: Record<string, any>, content: string) => {
if (frontmatter.title) {
return deeplyParseHeader(frontmatter.title)
}
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
}