返回 slidev
fs.ts
根目录 / packages / parser / src / fs.ts
1 import type {
2 PreparserExtensionLoader,
3 SlideInfo,
4 SlidevData,
5 SlidevMarkdown,
6 SlidevPreparserExtension,
7 SourceSlideInfo,
8 } from '@slidev/types'
9 import { existsSync } from 'node:fs'
10 import { readFile, writeFile } from 'node:fs/promises'
11 import { slash } from '@antfu/utils'
12 import { dirname, isAbsolute, relative, resolve } from 'pathe'
13 import YAML from 'yaml'
14 import { detectFeatures, parse, parseRangeString, stringify } from './core'
15
16 /**
17 * Whether `filePath` resolves inside any of `roots` (no `..` escape).
18 * Inlined here (rather than imported from the `slidev` package) because
19 * `@slidev/parser` must stay independent of `@slidev/slidev`.
20 */
21 export function isPathInsideRoots(filePath: string, roots: string[]): boolean {
22 return roots.some((root) => {
23 const rel = relative(root, filePath)
24 return rel === '' || (!!rel && !rel.startsWith('..') && !isAbsolute(rel))
25 })
26 }
27
28 const RE_FRONTMATTER_START = /^\uFEFF?---(?:[^-].*)?$/
29 const RE_BLANK_LINE = /^\s*$/
30 const RE_FRONTMATTER_END = /^---$/
31 const RE_CRLF = /\r?\n/g
32
33 export * from './core'
34
35 let preparserExtensionLoader: PreparserExtensionLoader | null = null
36
37 export function injectPreparserExtensionLoader(fn: PreparserExtensionLoader) {
38 preparserExtensionLoader = fn
39 }
40
41 export interface LoadRootsInfo {
42 roots: string[]
43 userRoot: string
44 /**
45 * When provided, `src:` includes resolving outside these roots are
46 * rejected (recorded as an error) instead of being loaded. Optional for
47 * backward compatibility with other `@slidev/parser` consumers.
48 */
49 allowedRoots?: string[]
50 }
51
52 /**
53 * Slidev data without config and themeMeta,
54 * because config and themeMeta depends on the theme to be loaded.
55 */
56 export type LoadedSlidevData = Omit<SlidevData, 'config' | 'themeMeta'>
57
58 export async function load(
59 options: LoadRootsInfo,
60 filepath: string,
61 sources: Record<string, string> | ((path: string) => Promise<string>) = {},
62 mode?: string,
63 ): Promise<LoadedSlidevData> {
64 const loadSource = typeof sources === 'function'
65 ? sources
66 : async (path: string) => sources[path] ?? readFile(path, 'utf-8')
67
68 const markdown = await loadSource(filepath)
69
70 let extensions: SlidevPreparserExtension[] | undefined
71 if (preparserExtensionLoader) {
72 // #703
73 // identify the headmatter, to be able to load preparser extensions
74 // (strict parsing based on the parsing code)
75 const lines = markdown.split(RE_CRLF)
76 let hm = ''
77 if (RE_FRONTMATTER_START.test(lines[0]) && !lines[1]?.match(RE_BLANK_LINE)) {
78 let hEnd = 1
79 while (hEnd < lines.length && !RE_FRONTMATTER_END.test(lines[hEnd].trimEnd()))
80 hEnd++
81 hm = lines.slice(1, hEnd).join('\n')
82 }
83 const o = YAML.parse(hm) as Record<string, unknown> ?? {}
84 extensions = await preparserExtensionLoader(options.roots, o, filepath, mode)
85 }
86
87 const markdownFiles: Record<string, SlidevMarkdown> = {}
88 const watchFiles: Record<string, Set<number>> = {}
89 const slides: SlideInfo[] = []
90
91 async function loadMarkdown(path: string, range?: string, frontmatterOverride?: Record<string, unknown>, importers?: SourceSlideInfo[]) {
92 let md = markdownFiles[path]
93 if (!md) {
94 const raw = await loadSource(path)
95 md = await parse(raw, path, extensions)
96 markdownFiles[path] = md
97 watchFiles[path] = new Set()
98 }
99
100 const directImporter = importers?.at(-1)
101 for (const index of parseRangeString(md.slides.length, range)) {
102 const subSlide = md.slides[index - 1]
103 if (!subSlide) {
104 // `parseRangeString` only drops indexes above the total, so a range
105 // such as `#0` or `#-3` still reaches here and has no slide.
106 md.errors ??= []
107 md.errors.push({
108 row: 0,
109 message: `Slide ${index} does not exist in "${path}", which has ${md.slides.length} slides`,
110 })
111 continue
112 }
113 try {
114 await loadSlide(md, subSlide, frontmatterOverride, importers)
115 }
116 catch (e) {
117 md.errors ??= []
118 md.errors.push({
119 row: subSlide.start,
120 message: `Error when loading slide: ${e}`,
121 })
122 continue
123 }
124 if (directImporter)
125 (directImporter.imports ??= []).push(subSlide)
126 }
127
128 return md
129 }
130
131 async function loadSlide(md: SlidevMarkdown, slide: SourceSlideInfo, frontmatterOverride?: Record<string, unknown>, importChain?: SourceSlideInfo[]) {
132 if (slide.frontmatter.disabled || slide.frontmatter.hide)
133 return
134 if (slide.frontmatter.src) {
135 const [rawPath, rangeRaw] = slide.frontmatter.src.split('#')
136 const path = slash(
137 rawPath.startsWith('/')
138 ? resolve(options.userRoot, rawPath.substring(1))
139 : resolve(dirname(slide.filepath), rawPath),
140 )
141
142 frontmatterOverride = {
143 ...slide.frontmatter,
144 ...frontmatterOverride,
145 }
146 delete frontmatterOverride.src
147
148 const ancestorPaths = new Set((importChain ?? []).map(s => s.filepath))
149 if (path === slide.filepath || ancestorPaths.has(path)) {
150 md.errors ??= []
151 md.errors.push({
152 row: slide.start,
153 message: `Circular import detected for "${slide.frontmatter.src}" (${path})`,
154 })
155 return
156 }
157
158 if (options.allowedRoots && !isPathInsideRoots(path, options.allowedRoots)) {
159 md.errors ??= []
160 md.errors.push({
161 row: slide.start,
162 message: `Imported markdown escapes the project root: ${path}`,
163 })
164 }
165 else if (!existsSync(path)) {
166 md.errors ??= []
167 md.errors.push({
168 row: slide.start,
169 message: `Imported markdown file not found: ${path}`,
170 })
171 }
172 else {
173 await loadMarkdown(path, rangeRaw, frontmatterOverride, importChain
174 ? [...importChain, slide]
175 : [slide])
176 }
177 }
178 else {
179 slides.push({
180 frontmatter: {
181 ...slide.frontmatter,
182 ...frontmatterOverride,
183 },
184 content: slide.content,
185 revision: slide.revision,
186 frontmatterRaw: slide.frontmatterRaw,
187 note: slide.note,
188 title: slide.title,
189 level: slide.level,
190 index: slides.length,
191 importChain,
192 source: slide,
193 })
194 }
195 }
196
197 const entry = await loadMarkdown(slash(filepath))
198
199 const headmatter = { ...entry.slides[0]?.frontmatter }
200 if (slides[0]?.title)
201 headmatter.title ??= slides[0].title
202
203 return {
204 slides,
205 entry,
206 headmatter,
207 features: detectFeatures(slides.map(s => s.source.raw).join('')),
208 markdownFiles,
209 watchFiles,
210 }
211 }
212
213 export async function save(markdown: SlidevMarkdown) {
214 const fileContent = stringify(markdown)
215 await writeFile(markdown.filepath, fileContent, 'utf-8')
216 return fileContent
217 }
218
218 lines TYPESCRIPT