返回 slidev
snippet-hmr.test.ts
根目录 / test / snippet-hmr.test.ts
1 /**
2 * Regression for https://github.com/slidevjs/slidev/issues/2241
3 *
4 * Snippet imports (`<<<`) register their files in `data.watchFiles` while a
5 * slide is rendered. Every HMR reload replaces `data` with freshly parsed data,
6 * so after the first reload edits to imported snippets must still update the
7 * slides that import them.
8 */
9 import type { ResolvedSlidevOptions } from '@slidev/types'
10 import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
11 import { tmpdir } from 'node:os'
12 import { join } from 'node:path'
13 import { afterEach, describe, expect, it } from 'vitest'
14 import { createServer, parser, resolveOptions } from '../packages/slidev/node'
15
16 const ENTRY_MD = `---
17 theme: none
18 ---
19
20 # One
21
22 <<< ./snippets/one.ts
23
24 ---
25
26 # Two
27
28 <<< ./snippets/two.ts
29 `
30
31 async function createReproServer(entry: string) {
32 const options = await resolveOptions({ entry, theme: 'none' }, 'dev')
33 const updatedSlides: number[] = []
34
35 const server = await createServer(
36 options,
37 {
38 plugins: [
39 {
40 name: 'slidev-snippet-hmr-capture',
41 configureServer(s) {
42 const hot = s.environments.client.hot
43 const send = hot.send.bind(hot)
44 hot.send = ((...args: any[]) => {
45 if (args[0] === 'slidev:update-slide')
46 updatedSlides.push(args[1].no)
47 return (send as any)(...args)
48 }) as typeof hot.send
49 },
50 },
51 ],
52 server: { middlewareMode: true },
53 clearScreen: false,
54 logLevel: 'error',
55 },
56 {
57 async loadData(loadedSource) {
58 const loaded = await parser.load(options, options.entry, loadedSource, 'dev')
59 return {
60 ...loaded,
61 themeMeta: options.data.themeMeta,
62 config: parser.resolveConfig(loaded.headmatter, options.data.themeMeta, options.entry),
63 }
64 },
65 },
66 )
67
68 return { server, options, updatedSlides }
69 }
70
71 // What the browser does when it loads a slide: render its Markdown.
72 async function renderSlides(server: Awaited<ReturnType<typeof createServer>>, options: ResolvedSlidevOptions) {
73 for (let i = 0; i < options.data.slides.length; i++)
74 await server.environments.client.transformRequest(`${options.data.slides[i].source.filepath}__slidev_${i + 1}.md`)
75 }
76
77 describe('snippet import HMR (#2241)', () => {
78 const cleanups: Array<() => Promise<void>> = []
79
80 afterEach(async () => {
81 while (cleanups.length)
82 await cleanups.pop()!()
83 })
84
85 it('updates the importing slide on every snippet edit', async () => {
86 const dir = await mkdtemp(join(tmpdir(), 'slidev-snippet-hmr-'))
87 const entry = join(dir, 'slides.md')
88 await mkdir(join(dir, 'snippets'))
89 await writeFile(join(dir, 'snippets/one.ts'), 'export const one = 1\n')
90 await writeFile(join(dir, 'snippets/two.ts'), 'export const two = 2\n')
91 await writeFile(entry, ENTRY_MD)
92
93 const { server, options, updatedSlides } = await createReproServer(entry)
94 cleanups.push(async () => {
95 await server.close()
96 await rm(dir, { recursive: true, force: true })
97 })
98
99 await renderSlides(server, options)
100 await waitForWatched(server, [
101 join(dir, 'snippets/one.ts'),
102 join(dir, 'snippets/two.ts'),
103 ])
104
105 await writeFile(join(dir, 'snippets/one.ts'), 'export const one = 10\n')
106 await waitFor(() => updatedSlides.includes(1))
107 expect(updatedSlides).toEqual([1])
108
109 updatedSlides.length = 0
110 await writeFile(join(dir, 'snippets/two.ts'), 'export const two = 20\n')
111 await waitFor(() => updatedSlides.includes(2))
112 expect(updatedSlides).toEqual([2])
113
114 updatedSlides.length = 0
115 await writeFile(join(dir, 'snippets/one.ts'), 'export const one = 100\n')
116 await waitFor(() => updatedSlides.includes(1))
117 expect(updatedSlides).toEqual([1])
118 }, 30_000)
119
120 it('still updates the importing slide after slides.md was edited', async () => {
121 const dir = await mkdtemp(join(tmpdir(), 'slidev-snippet-hmr-entry-'))
122 const entry = join(dir, 'slides.md')
123 await mkdir(join(dir, 'snippets'))
124 await writeFile(join(dir, 'snippets/one.ts'), 'export const one = 1\n')
125 await writeFile(join(dir, 'snippets/two.ts'), 'export const two = 2\n')
126 await writeFile(entry, ENTRY_MD)
127
128 const { server, options, updatedSlides } = await createReproServer(entry)
129 cleanups.push(async () => {
130 await server.close()
131 await rm(dir, { recursive: true, force: true })
132 })
133
134 await renderSlides(server, options)
135 await waitForWatched(server, [
136 entry,
137 join(dir, 'snippets/two.ts'),
138 ])
139
140 await writeFile(entry, ENTRY_MD.replace('# One', '# One edited'))
141 await waitFor(() => updatedSlides.includes(1))
142
143 updatedSlides.length = 0
144 await writeFile(join(dir, 'snippets/two.ts'), 'export const two = 20\n')
145 await waitFor(() => updatedSlides.includes(2))
146 expect(updatedSlides).toEqual([2])
147 }, 30_000)
148 })
149
150 async function waitFor(predicate: () => boolean, timeout = 5_000, interval = 50) {
151 const start = Date.now()
152 while (Date.now() - start < timeout) {
153 if (predicate())
154 return
155 await new Promise(r => setTimeout(r, interval))
156 }
157 throw new Error(`Timed out after ${timeout}ms waiting for HMR activity`)
158 }
159
160 // Chokidar starts watching asynchronously (notably on macOS and Windows), so an
161 // edit made right after the server starts can be missed.
162 async function waitForWatched(server: Awaited<ReturnType<typeof createServer>>, files: string[]) {
163 const slash = (p: string) => p.replace(/\\/g, '/')
164 await waitFor(() => {
165 const watched = new Set(
166 Object.entries(server.watcher.getWatched())
167 .flatMap(([dir, names]) => names.map(name => slash(join(dir, name)))),
168 )
169 return files.every(file => watched.has(slash(file)))
170 })
171 }
172
172 lines TYPESCRIPT