返回 slidev
walker.test.ts
根目录 / packages / slidev / node / commands / pptx / walker.test.ts
1 import fs from 'node:fs'
2 import { dirname, join } from 'node:path'
3 import { fileURLToPath } from 'node:url'
4 import vm from 'node:vm'
5 import { describe, expect, it } from 'vitest'
6 import { collectSnapshot } from './walker'
7
8 /**
9 * The walker is serialized by Playwright and evaluated in a page where this
10 * module's scope does not exist, so a free variable becomes a `ReferenceError`
11 * inside someone else's browser. The guard has to run the reconstructed
12 * function, not compile it: an undeclared identifier resolves at call time, so
13 * `new Function(source)` accepts a body full of them. The sandbox global is a
14 * Proxy that throws on any identifier outside a browser allowlist.
15 *
16 * What the walker extracts is not tested here. jsdom has no layout engine, so
17 * `getBoundingClientRect` returns zeros and a DOM test would pass with every
18 * rect at the origin. The judgement it feeds lives in `normalize.ts`.
19 */
20
21 /** Globals a browser really provides. Anything else is a leak. */
22 const BROWSER_GLOBALS = new Set([
23 'document',
24 'window',
25 'getComputedStyle',
26 'Array',
27 'Boolean',
28 'Error',
29 'JSON',
30 'Map',
31 'Math',
32 'Number',
33 'Object',
34 'RegExp',
35 'Set',
36 'String',
37 'Symbol',
38 'undefined',
39 'NaN',
40 'Infinity',
41 'globalThis',
42 ])
43
44 function measureTextStub(): { width: number } {
45 return { width: 100 }
46 }
47
48 /**
49 * A canvas whose text measurement changes only for the families named, which is
50 * how `isAvailable` tells a font that exists from one that fell through to the
51 * base. Everything else keeps the constant width, so it reads as absent.
52 */
53 function installedFonts(...families: string[]) {
54 return function (this: { font: string }): { width: number } {
55 return {
56 width: families.some(f => this.font.includes(`"${f}"`))
57 ? 140
58 : 100,
59 }
60 }
61 }
62
63 const RECT = {
64 left: 0,
65 top: 0,
66 width: 100,
67 height: 20,
68 }
69
70 /**
71 * A slide container with one element and one text node under it.
72 *
73 * Not decoration: with an empty container list the guard only ever ran the
74 * walker's top-level setup, so every free variable inside `walk` and its
75 * helpers went unnoticed. `window` was one of them, referenced for `scrollX`
76 * and absent from the allowlist, and the suite passed regardless.
77 */
78 function containerStub() {
79 const text = { nodeType: 3, textContent: 'hello' }
80 const child: any = {
81 nodeType: 1,
82 tagName: 'DIV',
83 id: '',
84 childNodes: [text],
85 children: [],
86 classList: {
87 contains: () => false,
88 },
89 shadowRoot: null,
90 parentElement: null,
91 setAttribute: () => {},
92 getAttribute: () => null,
93 getBoundingClientRect: () => RECT,
94 getClientRects: () => [RECT],
95 }
96 const container: any = {
97 nodeType: 1,
98 tagName: 'DIV',
99 id: '003-02',
100 childNodes: [child],
101 children: [child],
102 classList: {
103 contains: () => false,
104 },
105 shadowRoot: null,
106 parentElement: null,
107 setAttribute: () => {},
108 getAttribute: () => null,
109 getBoundingClientRect: () => ({ ...RECT, width: 980, height: 552 }),
110 getClientRects: () => [RECT],
111 }
112 child.parentElement = container
113 return container
114 }
115
116 /** Just enough DOM for the walker to run to completion. */
117 function domStub(querySelectorAllResult: unknown[], measureText = measureTextStub) {
118 return {
119 createElement: () => ({
120 getContext: () => ({
121 font: '',
122 fillStyle: '',
123 measureText,
124 clearRect: () => {},
125 fillRect: () => {},
126 getImageData: () => ({
127 data: [0, 0, 0, 0],
128 }),
129 }),
130 }),
131 querySelectorAll: () => querySelectorAllResult,
132 createRange: () => ({
133 selectNodeContents: () => {},
134 getClientRects: () => [RECT],
135 detach: () => {},
136 }),
137 }
138 }
139
140 interface SandboxOptions {
141 measureText?: () => { width: number }
142 fontFamily?: string
143 }
144
145 function runInSandbox(source: string, containers: unknown[] = [], options: SandboxOptions = {}): unknown {
146 const base: Record<string, unknown> = {
147 document: domStub(containers, options.measureText),
148 getComputedStyle: () => ({
149 fontFamily: options.fontFamily ?? 'Inter, sans-serif',
150 display: 'block',
151 visibility: 'visible',
152 opacity: '1',
153 position: 'static',
154 backgroundColor: 'rgb(255, 255, 255)',
155 listStyleType: 'none',
156 content: 'none',
157 width: '100px',
158 height: '20px',
159 left: 'auto',
160 top: 'auto',
161 right: 'auto',
162 bottom: 'auto',
163 }),
164 Array,
165 Boolean,
166 Error,
167 JSON,
168 Map,
169 Math,
170 Number,
171 Object,
172 RegExp,
173 Set,
174 String,
175 Symbol,
176 globalThis: undefined,
177 window: { scrollX: 0, scrollY: 0 },
178 }
179
180 const sandbox = new Proxy(base, {
181 // Claim every name so V8 resolves lookups here rather than walking out.
182 has: () => true,
183 get(target, prop) {
184 if (typeof prop === 'symbol')
185 return (target as any)[prop]
186 if (BROWSER_GLOBALS.has(prop))
187 return target[prop]
188 throw new ReferenceError(
189 `walker referenced "${String(prop)}", which will not exist inside page.evaluate`,
190 )
191 },
192 })
193
194 const context = vm.createContext(sandbox)
195 const fn = vm.runInContext(`(${source})`, context)
196 return fn({ containerSelector: '.print-slide-container', idAttribute: 'data-slidev-export-id' })
197 }
198
199 describe('walker self-containedness', () => {
200 it('runs to completion using only browser globals', () => {
201 expect(() => runInSandbox(collectSnapshot.toString())).not.toThrow()
202 })
203
204 it('runs to completion over a real container, not just an empty page', () => {
205 // The empty-page case exercises none of `walk`, which is most of the file.
206 const snapshot = runInSandbox(collectSnapshot.toString(), [
207 containerStub(),
208 ]) as any
209 expect(snapshot.slides).toHaveLength(1)
210 expect(snapshot.slides[0].nodes.length).toBeGreaterThan(0)
211 })
212
213 it('fails when a walked node closes over module scope', () => {
214 // The same guard as below, but pinned on a path only a container reaches.
215 const leaked = collectSnapshot
216 .toString()
217 // The record built for every ELEMENT, so it is reached only by walking a
218 // container. Matched on its first field because the compiled source has
219 // two other `const record` declarations, in the style interners, which a
220 // page with no pseudo-elements never runs.
221 .replace(/const record\s*(?:(: any)\s*)?=\s*\{\s*id,/, 'const record = { leaked: LEAKED_FROM_WALK, id,')
222 expect(() => runInSandbox(leaked, [
223 containerStub(),
224 ])).toThrow(/LEAKED_FROM_WALK/)
225 })
226
227 it('fails when the walker closes over module scope', () => {
228 // The mutation this guard exists to catch, pinned so the guard itself
229 // cannot silently stop working.
230 const leaked = collectSnapshot
231 .toString()
232 .replace('const styles', 'const styles = [LEAKED_FROM_MODULE_SCOPE]; const _unused')
233 expect(() => runInSandbox(leaked)).toThrow(/LEAKED_FROM_MODULE_SCOPE/)
234 })
235
236 it('returns the expected snapshot shape', () => {
237 const snapshot = runInSandbox(collectSnapshot.toString()) as any
238 expect(snapshot).toHaveProperty('slides')
239 expect(snapshot).toHaveProperty('styles')
240 expect(snapshot).toHaveProperty('fontResolution')
241 })
242
243 it('detects a font the theme ships as a webfont, and names it without the suffix', () => {
244 // `@fontsource-variable/inter` registers the family as "Inter Variable",
245 // so probing the stripped name first asks whether a static "Inter" is
246 // installed. On a machine with no such copy, which is the normal case for
247 // a webfont, nothing in the stack matched and every run in the deck was
248 // written out as a system fallback instead of the theme's own face.
249 const snapshot = runInSandbox(collectSnapshot.toString(), [
250 containerStub(),
251 ], {
252 fontFamily: '"Inter Variable", Inter, sans-serif',
253 measureText: installedFonts('Inter Variable'),
254 }) as any
255 expect(snapshot.fontResolution['"Inter Variable", Inter, sans-serif']).toBe('Inter')
256 })
257
258 it('still resolves a family installed under its plain name', () => {
259 // The Google Fonts path, which registers "Inter" with no suffix. Every
260 // Slidev-themed deck takes it, which is why the bug above stayed invisible
261 // until a theme shipped its font through `@fontsource`.
262 const snapshot = runInSandbox(collectSnapshot.toString(), [
263 containerStub(),
264 ], {
265 fontFamily: 'Inter, sans-serif',
266 measureText: installedFonts('Inter'),
267 }) as any
268 expect(snapshot.fontResolution['Inter, sans-serif']).toBe('Inter')
269 })
270
271 it('reports no family when nothing in the stack resolves', () => {
272 const snapshot = runInSandbox(collectSnapshot.toString(), [
273 containerStub(),
274 ], {
275 fontFamily: '"Human Sans", sans-serif',
276 measureText: installedFonts('Something Else'),
277 }) as any
278 expect(snapshot.fontResolution['"Human Sans", sans-serif']).toBe('')
279 })
280
281 it('carries no bundler-injected identifiers', () => {
282 // tsdown and Vite rewrite bodies with helpers such as `__toESM`,
283 // `__publicField` or `__name`, none of which exist in the page.
284 expect(collectSnapshot.toString().match(/\b__\w+/g)).toBeNull()
285 })
286
287 it('does not reference the module registry', () => {
288 const source = collectSnapshot.toString()
289 for (const forbidden of [
290 'require(',
291 'import(',
292 'exports.',
293 'module.exports',
294 ])
295 expect(source).not.toContain(forbidden)
296 })
297 })
298
299 /**
300 * The walker as it is actually shipped.
301 *
302 * Everything above runs against Vitest's transform of the source, which is not
303 * what reaches a browser: `exportPptxEditable` hands Playwright the function
304 * from the bundle in `dist`, and a bundler is free to rewrite a body with
305 * helpers of its own. Testing only the transform leaves the invariant
306 * unenforced on the one artifact that matters.
307 *
308 * Needs a prior `pnpm build`, which is how this repository runs its tests
309 * anyway: workspace packages resolve through their built `dist`.
310 */
311 function bundledWalker(): string {
312 const dist = join(dirname(fileURLToPath(import.meta.url)), '../../../dist')
313 const file = fs.readdirSync(dist).find(name => /^pptx-.+\.mjs$/.test(name))
314 if (!file)
315 throw new Error(`no built pptx bundle in ${dist}; run \`pnpm build\` first`)
316
317 const source = fs.readFileSync(join(dist, file), 'utf8')
318 const start = source.indexOf('function collectSnapshot')
319 if (start < 0)
320 throw new Error('collectSnapshot is not in the built bundle under its own name')
321
322 // Brace matching rather than a regex: the body is thousands of characters of
323 // nested functions and object literals.
324 let depth = 0
325 let index = source.indexOf('{', start)
326 const open = index
327 for (; index < source.length; index++) {
328 if (source[index] === '{')
329 depth++
330 else if (source[index] === '}' && --depth === 0)
331 break
332 }
333 return `function collectSnapshot${source.slice(source.indexOf('(', start), open)}${source.slice(open, index + 1)}`
334 }
335
336 /** Block comments only: enough for the bundler's annotations, and it cannot eat a regex literal. */
337 function withoutComments(source: string): string {
338 return source.replace(/\/\*[\s\S]*?\*\//g, '')
339 }
340
341 describe('the built bundle keeps the walker self-contained', () => {
342 it('runs to completion using only browser globals', () => {
343 expect(() => runInSandbox(bundledWalker(), [
344 containerStub(),
345 ])).not.toThrow()
346 })
347
348 it('carries no bundler-injected identifiers', () => {
349 // tsdown and Vite rewrite bodies with helpers such as `__toESM`,
350 // `__publicField` or `__name`, none of which exist in the page.
351 //
352 // Block comments are stripped first: the bundler annotates calls with
353 // `/* @__PURE__ */`, which never executes and is not a leak.
354 expect(withoutComments(bundledWalker()).match(/\b__\w+/g)).toBeNull()
355 })
356
357 it('does not reference the module registry', () => {
358 const source = withoutComments(bundledWalker())
359 for (const forbidden of [
360 'require(',
361 'import(',
362 'exports.',
363 'module.exports',
364 ])
365 expect(source).not.toContain(forbidden)
366 })
367
368 it('fails when the bundle leaks a helper into the walker', () => {
369 // The guard pinned against the mutation it exists to catch, so it cannot
370 // quietly stop working the next time the bundler changes.
371 const leaked = bundledWalker().replace(/const nodes = \[\]/, 'const nodes = __name([])')
372 expect(() => runInSandbox(leaked, [
373 containerStub(),
374 ])).toThrow(/__name/)
375 })
376 })
377
377 lines TYPESCRIPT