返回 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 = /^---(?:[^-].*)?$/
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' ? sources : async (path: string) => sources[path] ?? readFile(path, 'utf-8')
65
66 const markdown = await loadSource(filepath)
67
68 let extensions: SlidevPreparserExtension[] | undefined
69 if (preparserExtensionLoader) {
70 // #703
71 // identify the headmatter, to be able to load preparser extensions
72 // (strict parsing based on the parsing code)
73 const lines = markdown.split(RE_CRLF)
74 let hm = ''
75 if (RE_FRONTMATTER_START.test(lines[0]) && !lines[1]?.match(RE_BLANK_LINE)) {
76 let hEnd = 1
77 while (hEnd < lines.length && !RE_FRONTMATTER_END.test(lines[hEnd].trimEnd()))
78 hEnd++
79 hm = lines.slice(1, hEnd).join('\n')
80 }
81 const o = YAML.parse(hm) as Record<string, unknown> ?? {}
82 extensions = await preparserExtensionLoader(options.roots, o, filepath, mode)
83 }
84
85 const markdownFiles: Record<string, SlidevMarkdown> = {}
86 const watchFiles: Record<string, Set<number>> = {}
87 const slides: SlideInfo[] = []
88
89 async function loadMarkdown(path: string, range?: string, frontmatterOverride?: Record<string, unknown>, importers?: SourceSlideInfo[]) {
90 let md = markdownFiles[path]
91 if (!md) {
92 const raw = await loadSource(path)
93 md = await parse(raw, path, extensions)
94 markdownFiles[path] = md
95 watchFiles[path] = new Set()
96 }
97
98 const directImporter = importers?.at(-1)
99 for (const index of parseRangeString(md.slides.length, range)) {
100 const subSlide = md.slides[index - 1]
101 if (!subSlide) {
102 // `parseRangeString` only drops indexes above the total, so a range
103 // such as `#0` or `#-3` still reaches here and has no slide.
104 md.errors ??= []
105 md.errors.push({
106 row: 0,
107 message: `Slide ${index} does not exist in "${path}", which has ${md.slides.length} slides`,
108 })
109 continue
110 }
111 try {
112 await loadSlide(md, subSlide, frontmatterOverride, importers)
113 }
114 catch (e) {
115 md.errors ??= []
116 md.errors.push({
117 row: subSlide.start,
118 message: `Error when loading slide: ${e}`,
119 })
120 continue
121 }
122 if (directImporter)
123 (directImporter.imports ??= []).push(subSlide)
124 }
125
126 return md
127 }
128
129 async function loadSlide(md: SlidevMarkdown, slide: SourceSlideInfo, frontmatterOverride?: Record<string, unknown>, importChain?: SourceSlideInfo[]) {
130 if (slide.frontmatter.disabled || slide.frontmatter.hide)
131 return
132 if (slide.frontmatter.src) {
133 const [rawPath, rangeRaw] = slide.frontmatter.src.split('#')
134 const path = slash(
135 rawPath.startsWith('/')
136 ? resolve(options.userRoot, rawPath.substring(1))
137 : resolve(dirname(slide.filepath), rawPath),
138 )
139
140 frontmatterOverride = {
141 ...slide.frontmatter,
142 ...frontmatterOverride,
143 }
144 delete frontmatterOverride.src
145
146 const ancestorPaths = new Set((importChain ?? []).map(s => s.filepath))
147 if (path === slide.filepath || ancestorPaths.has(path)) {
148 md.errors ??= []
149 md.errors.push({
150 row: slide.start,
151 message: `Circular import detected for "${slide.frontmatter.src}" (${path})`,
152 })
153 return
154 }
155
156 if (options.allowedRoots && !isPathInsideRoots(path, options.allowedRoots)) {
157 md.errors ??= []
158 md.errors.push({
159 row: slide.start,
160 message: `Imported markdown escapes the project root: ${path}`,
161 })
162 }
163 else if (!existsSync(path)) {
164 md.errors ??= []
165 md.errors.push({
166 row: slide.start,
167 message: `Imported markdown file not found: ${path}`,
168 })
169 }
170 else {
171 await loadMarkdown(path, rangeRaw, frontmatterOverride, importChain ? [...importChain, slide] : [slide])
172 }
173 }
174 else {
175 slides.push({
176 frontmatter: { ...slide.frontmatter, ...frontmatterOverride },
177 content: slide.content,
178 revision: slide.revision,
179 frontmatterRaw: slide.frontmatterRaw,
180 note: slide.note,
181 title: slide.title,
182 level: slide.level,
183 index: slides.length,
184 importChain,
185 source: slide,
186 })
187 }
188 }
189
190 const entry = await loadMarkdown(slash(filepath))
191
192 const headmatter = { ...entry.slides[0]?.frontmatter }
193 if (slides[0]?.title)
194 headmatter.title ??= slides[0].title
195
196 return {
197 slides,
198 entry,
199 headmatter,
200 features: detectFeatures(slides.map(s => s.source.raw).join('')),
201 markdownFiles,
202 watchFiles,
203 }
204 }
205
206 export async function save(markdown: SlidevMarkdown) {
207 const fileContent = stringify(markdown)
208 await writeFile(markdown.filepath, fileContent, 'utf-8')
209 return fileContent
210 }
211
211 lines TYPESCRIPT