-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathmarkdown.ts
262 lines (217 loc) · 7.31 KB
/
markdown.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
import type { TransformResult } from 'vite'
import type { MarkdownEnv, ResolvedOptions } from '../types'
import { toArray, uniq } from '@antfu/utils'
import { componentPlugin } from '@mdit-vue/plugin-component'
import { frontmatterPlugin } from '@mdit-vue/plugin-frontmatter'
import MarkdownIt from 'markdown-it-async'
import { preprocessHead } from './head'
const scriptSetupRE = /<\s*script([^>]*)\bsetup\b([^>]*)>([\s\S]*)<\/script>/g
const defineExposeRE = /defineExpose\s*\(/g
const EXPORTS_KEYWORDS = [
'class',
'default',
'export',
'function',
'import',
'let',
'var',
'const',
'from',
'as',
'return',
'if',
'else',
'switch',
'case',
'break',
'for',
'while',
'do',
]
interface ScriptMeta {
code: string
attr: string
}
function extractScriptSetup(html: string) {
const scripts: ScriptMeta[] = []
html = html.replace(scriptSetupRE, (_, attr1, attr2, code) => {
scripts.push({
code,
attr: `${attr1} ${attr2}`.trim(),
})
return ''
})
return { html, scripts }
}
function extractCustomBlock(html: string, options: ResolvedOptions) {
const blocks: string[] = []
for (const tag of options.customSfcBlocks) {
html = html.replace(new RegExp(`<${tag}[^>]*\\b[^>]*>[^<]*<\\/${tag}>`, 'gm'), (code) => {
blocks.push(code)
return ''
})
}
return { html, blocks }
}
export function createMarkdown(options: ResolvedOptions) {
const isVue2 = options.vueVersion.startsWith('2.')
const markdown = MarkdownIt({
html: true,
linkify: true,
typographer: true,
...options.markdownItOptions,
})
markdown.use(componentPlugin, options.componentOptions)
if (options.frontmatter || options.excerpt) {
markdown.use(frontmatterPlugin, {
...options.frontmatterOptions,
grayMatterOptions: {
excerpt: options.excerpt,
...options.frontmatterOptions.grayMatterOptions,
},
})
}
markdown.linkify.set({ fuzzyLink: false })
options.markdownItUses.forEach((e) => {
const [plugin, options] = toArray(e)
markdown.use(plugin, options)
})
const setupPromise = (async () => {
await options.markdownItSetup(markdown)
})()
return async (id: string, raw: string): Promise<TransformResult> => {
await setupPromise
const {
wrapperClasses,
wrapperComponent,
transforms,
headEnabled,
frontmatterPreprocess,
} = options
raw = raw.trimStart()
raw = transforms.before?.(raw, id) ?? raw
const env: MarkdownEnv = { id }
let html = await markdown.renderAsync(raw, env)
const { excerpt = '', frontmatter: data = null } = env
const wrapperClassesResolved = toArray(
typeof wrapperClasses === 'function'
? wrapperClasses(id, raw)
: wrapperClasses,
)
.filter(Boolean)
.join(' ')
if (wrapperClassesResolved)
html = `<div class="${wrapperClassesResolved}">${html}</div>`
else
html = `<div>${html}</div>`
const wrapperComponentName = typeof wrapperComponent === 'function'
? wrapperComponent(id, raw)
: wrapperComponent
if (wrapperComponentName) {
const attrs = [
options.frontmatter && ':frontmatter="frontmatter"',
options.excerpt && ':excerpt="excerpt"',
].filter(Boolean).join(' ')
html = `<${wrapperComponentName} ${attrs}>${html}</${wrapperComponentName}>`
}
html = transforms.after?.(html, id) ?? html
if (options.escapeCodeTagInterpolation) {
// escape curly brackets interpolation in <code>, #14
html = html.replace(/<code(.*?)>/g, '<code$1 v-pre>')
}
const hoistScripts = extractScriptSetup(html)
html = hoistScripts.html
const customBlocks = extractCustomBlock(html, options)
html = customBlocks.html
const scriptLines: string[] = []
let frontmatterExportsLines: string[] = []
let excerptExportsLine = ''
let excerptKeyOverlapping = false
function hasExplicitExports() {
return defineExposeRE.test(hoistScripts.scripts.map(i => i.code).join(''))
}
if (options.frontmatter) {
if (options.excerpt && data) {
if (data.excerpt !== undefined)
excerptKeyOverlapping = true
data.excerpt = excerpt
}
const { head, frontmatter } = frontmatterPreprocess(data || {}, options, id, preprocessHead)
if (options.excerpt && !excerptKeyOverlapping && frontmatter.excerpt !== undefined)
delete frontmatter.excerpt
scriptLines.push(
`import { computed } from 'vue'`,
'const props = defineProps({ frontmatterMerge: { type: Object } })',
`const _frontmatter = ${JSON.stringify(frontmatter)}`,
`const frontmatter = computed(() => {
if (props.frontmatterReplace && typeof props.frontmatterReplace === 'object') {
const replaceKeys = Object.keys(props.frontmatterReplace)
return Object.entries(_frontmatter).reduce((acc, [key, value]) => ({ ...acc, [key]: replaceKeys.includes(key) ? value : undefined }), {})
}
return { ..._frontmatter, ...props.frontmatterMerge }
})`,
)
if (options.exportFrontmatter) {
frontmatterExportsLines = Object.entries(frontmatter)
.map(([key, value]) => {
if (EXPORTS_KEYWORDS.includes(key))
key = `_${key}`
return `export const ${key} = ${JSON.stringify(value)}`
})
}
if (!isVue2 && options.exposeFrontmatter && !hasExplicitExports())
scriptLines.push('defineExpose({ frontmatter: frontmatter.value })')
if (!isVue2 && headEnabled && head) {
// @ts-expect-error legacy option
if (headEnabled === 'vueuse')
throw new Error('unplugin-vue-markdown no longer supports @vueuse/head. Change `headEnabled` to `true` and install `@unhead/vue` instead.')
scriptLines.push(`const head = ${JSON.stringify(head)}`)
scriptLines.unshift(`import { useHead } from "@unhead/vue"`)
scriptLines.push('useHead(head)')
}
scriptLines.push(...transforms.extraScripts?.(frontmatter, id) || [])
}
if (options.excerpt) {
scriptLines.push(`const excerpt = ${JSON.stringify(excerpt)}`)
if (!excerptKeyOverlapping)
excerptExportsLine = `export const excerpt = ${JSON.stringify(excerpt)}\n`
if (!isVue2 && options.exposeExcerpt && !hasExplicitExports())
scriptLines.push('defineExpose({ excerpt })')
}
scriptLines.push(...hoistScripts.scripts.map(i => i.code))
let attrs = uniq(hoistScripts.scripts.map(i => i.attr)).join(' ').trim()
if (attrs)
attrs = ` ${attrs}`
const scripts = isVue2
? [
`<script${attrs}>`,
...scriptLines,
...frontmatterExportsLines,
excerptExportsLine,
'export default { data() { return { frontmatter } } }',
'</script>',
]
: [
`<script setup${attrs}>`,
...scriptLines,
'</script>',
...((frontmatterExportsLines.length || excerptExportsLine)
? [
`<script${attrs}>`,
...frontmatterExportsLines,
excerptExportsLine,
'</script>',
]
: []),
]
const code = [
`<template>${html}</template>`,
...scripts.map(i => i.trim()).filter(Boolean),
...customBlocks.blocks,
].join('\n')
return {
code,
map: { mappings: '' } as any,
}
}
}