返回 slidev
utils.ts
根目录 / packages / slidev / node / utils.ts
1 import type { ResolvedFontOptions, SourceSlideInfo } from '@slidev/types'
2 import type MarkdownExit from 'markdown-exit'
3 import type { Connect, GeneralImportGlobOptions } from 'vite'
4 import { createHash } from 'node:crypto'
5 import { mkdirSync, writeFileSync } from 'node:fs'
6 import { fileURLToPath } from 'node:url'
7 import { slash } from '@antfu/utils'
8 import { createJiti } from 'jiti'
9 import { dirname, join, relative, win32 } from 'pathe'
10 import YAML from 'yaml'
11 import { toAtFS } from './resolver'
12 import { isAllowedFile } from './vite/importGuard'
13
14 /**
15 * Whether `filePath` resolves inside any of `roots` (no `..` escape). Shared
16 * containment predicate reused by the snippet (`<<<`) and `src:` deck-file
17 * reads, and by the Vite slide-import guard (`isAllowedFile`).
18 */
19 export function isPathInsideRoots(filePath: string, roots: string[]): boolean {
20 return isAllowedFile(filePath, roots)
21 }
22
23 const RE_WHITESPACE_ONLY = /^\s*$/
24 const RE_QUOTED_STRING = /^(['"])(.*)\1$/
25 const RE_WHITESPACE = /\s+/g
26 const RE_WINDOWS_DRIVE = /^[A-Z]:\//i
27
28 type Token = ReturnType<MarkdownExit['parseInline']>[number]
29
30 type Jiti = ReturnType<typeof createJiti>
31 let jiti: Jiti | undefined
32 export function loadModule<T = unknown>(absolutePath: string): Promise<T> {
33 jiti ??= createJiti(fileURLToPath(import.meta.url), {
34 // Allows changes to take effect
35 moduleCache: false,
36 })
37 return jiti.import(absolutePath) as Promise<T>
38 }
39
40 export function stringifyMarkdownTokens(tokens: Token[]) {
41 return tokens.map(token => token.children
42 ?.filter(t => ['text', 'code_inline'].includes(t.type) && !t.content.match(RE_WHITESPACE_ONLY))
43 .map(t => t.content.trim())
44 .join(' '))
45 .filter(Boolean)
46 .join(' ')
47 }
48
49 const RE_WORD_CHARS_ONLY = /^[\w-]+$/
50 const RE_REGEXP_CHARS = /[.*+?^${}()|[\]\\]/g
51
52 export function applyNotesAutoRuby(md: string, notesAutoRuby: Record<string, string | undefined>) {
53 const keys = Object.keys(notesAutoRuby)
54 // Longest first, otherwise a shorter key shadows every key starting with it
55 .sort((a, b) => b.length - a.length)
56 // Add word boundaries to the keys when they are simple alphabets or numbers
57 .map(i => RE_WORD_CHARS_ONLY.test(i)
58 ? `\\b${i}\\b`
59 : i.replace(RE_REGEXP_CHARS, '\\$&'))
60
61 if (!keys.length)
62 return md
63
64 return md.replace(
65 new RegExp(`(${keys.join('|')})`, 'g'),
66 (match) => {
67 if (notesAutoRuby[match])
68 return `<ruby>${match}<rt>${notesAutoRuby[match]}</rt></ruby>`
69 return match
70 },
71 )
72 }
73
74 export function generateFontParams(options: ResolvedFontOptions) {
75 const weights = options.weights
76 .flatMap(i => options.italic
77 ? [`0,${i}`, `1,${i}`]
78 : [`${i}`])
79 .sort()
80 .join(';')
81 const fontParams = options.webfonts
82 .map(i => `family=${i.replace(RE_QUOTED_STRING, '$2').replace(RE_WHITESPACE, '+')}:${options.italic ? 'ital,' : ''}wght@${weights}`)
83 .join('&')
84 return fontParams
85 }
86
87 export function generateGoogleFontsUrl(options: ResolvedFontOptions) {
88 return `https://fonts.googleapis.com/css2?${generateFontParams(options)}&display=swap`
89 }
90
91 export function generateCoollabsFontsUrl(options: ResolvedFontOptions) {
92 return `https://api.fonts.coollabs.io/fonts?${generateFontParams(options)}&display=swap`
93 }
94
95 /**
96 * Update frontmatter patch and preserve the comments
97 */
98 export function updateFrontmatterPatch(source: SourceSlideInfo, frontmatter: Record<string, any>) {
99 let doc = source.frontmatterDoc
100 if (!doc) {
101 source.frontmatterStyle = 'frontmatter'
102 source.frontmatterDoc = doc = new YAML.Document({})
103 }
104 for (const [key, value] of Object.entries(frontmatter)) {
105 source.frontmatter[key] = value
106 if (value == null) {
107 doc.delete(key)
108 }
109 else {
110 const valueNode = doc.createNode(value)
111 let found = false
112 YAML.visit(doc.contents, {
113 Pair(_key, node, path) {
114 if (path.length === 1 && YAML.isScalar(node.key) && node.key.value === key) {
115 node.value = valueNode
116 found = true
117 return YAML.visit.BREAK
118 }
119 },
120 })
121 if (!found) {
122 if (!YAML.isMap(doc.contents))
123 doc.contents = doc.createNode({})
124 doc.contents.add(
125 doc.createPair(key, valueNode),
126 )
127 }
128 }
129 }
130 }
131
132 export function getBodyJson(req: Connect.IncomingMessage) {
133 return new Promise<any>((resolve, reject) => {
134 let body = ''
135 // A chunk can end in the middle of a character
136 req.setEncoding('utf8')
137 req.on('data', chunk => body += chunk)
138 req.on('error', reject)
139 req.on('end', () => {
140 try {
141 resolve(JSON.parse(body) || {})
142 }
143 catch (e) {
144 reject(e)
145 }
146 })
147 })
148 }
149
150 function getImportGlobRelativePath(from: string, to: string) {
151 const normalizedFrom = slash(from)
152 const normalizedTo = slash(to)
153 return slash(
154 RE_WINDOWS_DRIVE.test(normalizedFrom) || RE_WINDOWS_DRIVE.test(normalizedTo)
155 ? win32.relative(normalizedFrom, normalizedTo)
156 : relative(normalizedFrom, normalizedTo),
157 )
158 }
159
160 function resolveImportGlobProxyModule(proxyBase: string, content: string) {
161 const hash = createHash('sha256').update(content).digest('hex').slice(0, 10)
162 return `${proxyBase}.${hash}.ts`
163 }
164
165 export function createMakeAbsoluteImportGlob(baseRoot: string) {
166 const proxyModules = new Map<string, string>()
167 const proxyBasename = 'node_modules/.slidev/virtual/import-glob'
168 const proxyBase = slash(join(baseRoot, proxyBasename))
169
170 return function makeAbsoluteImportGlob(
171 globs: string[],
172 options: Partial<GeneralImportGlobOptions> = {},
173 ) {
174 // Vite does not treat /@slidev/* as a real filesystem importer. Emit
175 // import.meta.glob from a proxy file so Vite resolves imports from disk.
176 const content = `export default ${makeAbsoluteImportGlobExpression(dirname(proxyBase), globs, options)}\n`
177 const proxyModule = resolveImportGlobProxyModule(proxyBase, content)
178 if (proxyModules.get(proxyModule) !== content) {
179 mkdirSync(dirname(proxyModule), { recursive: true })
180 writeFileSync(proxyModule, content, 'utf-8')
181 proxyModules.set(proxyModule, content)
182 }
183 return toAtFS(proxyModule)
184 }
185 }
186
187 export type MakeAbsoluteImportGlob = ReturnType<typeof createMakeAbsoluteImportGlob>
188
189 function makeAbsoluteImportGlobExpression(
190 self: string,
191 globs: string[],
192 options: Partial<GeneralImportGlobOptions> = {},
193 ) {
194 const relativeGlobs = globs.map((glob) => {
195 const relativeGlob = getImportGlobRelativePath(self, glob)
196 return !relativeGlob.startsWith('.') && !RE_WINDOWS_DRIVE.test(relativeGlob)
197 ? `./${relativeGlob}`
198 : relativeGlob
199 })
200 const opts: GeneralImportGlobOptions = {
201 eager: true,
202 exhaustive: true,
203 ...options,
204 }
205 return `import.meta.glob(${JSON.stringify(relativeGlobs)}, ${JSON.stringify(opts)})`
206 }
207
207 lines TYPESCRIPT