返回 slidev
resolver.test.ts
根目录 / packages / slidev / node / resolver.test.ts
1 import { resolve, sep } from 'pathe'
2 import { beforeEach, describe, expect, it, vi } from 'vitest'
3 import {
4 computeInvocationSearchPaths,
5 createResolver,
6 findInvocationNodeModulesPath,
7 getRoots,
8 } from './resolver'
9
10 const vitefuMocks = vi.hoisted(() => {
11 const FAKE_ROOT = '/user/project'
12 return {
13 findDepPkgJsonPath: vi.fn((name: string) => {
14 if (name === '@slidev/client')
15 return `${FAKE_ROOT}/node_modules/@slidev/client/package.json`
16 if (name === '@slidev/theme-official')
17 return `${FAKE_ROOT}/node_modules/@slidev/theme-official/package.json`
18 if (name === 'slidev-theme-xyz')
19 return `${FAKE_ROOT}/node_modules/slidev-theme-xyz/package.json`
20 if (name === 'slidev-theme-full')
21 return `${FAKE_ROOT}/node_modules/slidev-theme-full/package.json`
22 return null
23 }),
24 findClosestPkgJsonPath: vi.fn().mockResolvedValue(`${FAKE_ROOT}/package.json`),
25 }
26 })
27
28 vi.mock('vitefu', () => vitefuMocks)
29
30 // Virtual filesystem the `node:fs` mock reads from. Tests populate it with
31 // the paths they care about before exercising the resolver helpers.
32 type FsNodeKind = 'dir' | 'file' | 'symlink'
33 interface FsNode { kind: FsNodeKind, target?: string }
34 const fsMocks = vi.hoisted(() => {
35 const tree = new Map<string, { kind: 'dir' | 'file' | 'symlink', target?: string }>()
36 const ENOENT = (path: string) => {
37 const err = Object.assign(new Error(`ENOENT: no such file or directory '${path}'`), { code: 'ENOENT' })
38 return err
39 }
40 return {
41 tree,
42 existsSync: vi.fn((path: string) => tree.has(path)),
43 lstatSync: vi.fn((path: string) => {
44 const node = tree.get(path)
45 if (!node)
46 throw ENOENT(path)
47 return {
48 isSymbolicLink: () => node.kind === 'symlink',
49 isDirectory: () => node.kind === 'dir',
50 isFile: () => node.kind === 'file',
51 }
52 }),
53 readlinkSync: vi.fn((path: string) => {
54 const node = tree.get(path)
55 if (!node || node.kind !== 'symlink')
56 throw Object.assign(new Error(`EINVAL: readlink '${path}'`), { code: 'EINVAL' })
57 return node.target!
58 }),
59 readdirSync: vi.fn((path: string) => {
60 const node = tree.get(path)
61 if (!node || node.kind !== 'dir')
62 throw Object.assign(new Error(`ENOTDIR: scandir '${path}'`), { code: 'ENOTDIR' })
63 const prefix = path.endsWith(sep)
64 ? path
65 : `${path}${sep}`
66 const children = new Set<string>()
67 for (const key of tree.keys()) {
68 if (key === path)
69 continue
70 if (key.startsWith(prefix)) {
71 const rest = key.slice(prefix.length)
72 const first = rest.split(sep)[0]
73 if (first)
74 children.add(first)
75 }
76 }
77 return Array.from(children).sort()
78 }),
79 }
80 })
81
82 vi.mock('node:fs', () => fsMocks)
83
84 describe('createResolver', () => {
85 beforeEach(async () => {
86 await getRoots('/user/project')
87 })
88
89 it('resolves @slidev/ official prefixed theme', async () => {
90 const resolver = createResolver('theme', {})
91
92 const res = await resolver('official', '/')
93
94 expect(res).toEqual([
95 '@slidev/theme-official',
96 '/user/project/node_modules/@slidev/theme-official',
97 ],
98 )
99 })
100
101 it('resolves slidev-theme- third party prefixed theme', async () => {
102 const resolver = createResolver('theme', {})
103
104 const res = await resolver('xyz', '/')
105
106 expect(res).toEqual([
107 'slidev-theme-xyz',
108 '/user/project/node_modules/slidev-theme-xyz',
109 ],
110 )
111 })
112
113 it('resolves fully-specified package', async () => {
114 const resolver = createResolver('theme', {})
115
116 const res = await resolver('slidev-theme-full', '/')
117
118 expect(res).toEqual([
119 'slidev-theme-full',
120 '/user/project/node_modules/slidev-theme-full',
121 ],
122 )
123 })
124
125 it('resolves valid scoped name through validation', async () => {
126 const resolver = createResolver('theme', {})
127
128 const res = await resolver('@slidev/theme-official', '/')
129
130 expect(res).toEqual([
131 '@slidev/theme-official',
132 '/user/project/node_modules/@slidev/theme-official',
133 ])
134 })
135
136 it('passes through "none" without validation', async () => {
137 const resolver = createResolver('theme', {})
138
139 const res = await resolver('none', '/')
140
141 expect(res).toEqual(['', null])
142 })
143
144 it('rejects names with shell metacharacters', async () => {
145 const resolver = createResolver('theme', {})
146
147 await expect(resolver('evil$(rm -rf)', '/')).rejects.toThrowError(
148 'Invalid theme name "evil$(rm -rf)". Only valid npm package names are allowed.',
149 )
150 })
151
152 it('rejects names with backslashes', async () => {
153 const resolver = createResolver('theme', {})
154
155 await expect(resolver('evil\\package', '/')).rejects.toThrowError(
156 /Invalid theme name/,
157 )
158 })
159
160 it('rejects names with uppercase letters', async () => {
161 const resolver = createResolver('theme', {})
162
163 await expect(resolver('EvilTheme', '/')).rejects.toThrowError(
164 /Invalid theme name/,
165 )
166 })
167
168 it('rejects scoped names with extra slash segments', async () => {
169 const resolver = createResolver('theme', {})
170
171 await expect(resolver('@scope/foo/bar', '/')).rejects.toThrowError(
172 /Invalid theme name/,
173 )
174 })
175
176 it('rejects scoped names with parent traversal segment', async () => {
177 const resolver = createResolver('theme', {})
178
179 await expect(resolver('@evil/../escape', '/')).rejects.toThrowError(
180 /Invalid theme name/,
181 )
182 })
183
184 it('rejects empty string', async () => {
185 const resolver = createResolver('theme', {})
186
187 await expect(resolver('', '/')).rejects.toThrowError(
188 /Invalid theme name/,
189 )
190 })
191
192 it('reflects the resolver type in the error message', async () => {
193 const resolver = createResolver('addon', {})
194
195 await expect(resolver('evil$(rm -rf)', '/')).rejects.toThrowError(
196 'Invalid addon name "evil$(rm -rf)". Only valid npm package names are allowed.',
197 )
198 })
199 })
200
201 function setNode(path: string, node: FsNode) {
202 fsMocks.tree.set(resolve(path), node)
203 }
204 function dir(path: string) {
205 setNode(path, { kind: 'dir' })
206 }
207 function symlink(path: string, target: string) {
208 // `readlinkSync` returns the target verbatim — relative or absolute — so we
209 // store it as-given rather than resolving eagerly, so relative-target paths
210 // exercise the dirname-relative branch in `findInvocationNodeModulesPath`.
211 setNode(path, { kind: 'symlink', target })
212 }
213
214 describe('findInvocationNodeModulesPath', () => {
215 beforeEach(() => {
216 fsMocks.tree.clear()
217 })
218
219 it('returns undefined when argv1 is undefined', () => {
220 expect(findInvocationNodeModulesPath(undefined)).toBeUndefined()
221 })
222
223 it('returns undefined when argv1 is empty', () => {
224 expect(findInvocationNodeModulesPath('')).toBeUndefined()
225 })
226
227 it('extracts the trailing node_modules from a pnpm v11 shell-shim dispatched path', () => {
228 // `{PNPM_HOME}/bin/slidev` shell shim exec's `node <path-to-cli>.mjs`.
229 const argv1 = resolve('/pnpm-home/v11/abc123/node_modules/@slidev/cli/bin/slidev.mjs')
230 expect(findInvocationNodeModulesPath(argv1)).toBe(
231 resolve('/pnpm-home/v11/abc123/node_modules'),
232 )
233 })
234
235 it('extracts node_modules from an npm/yarn globals path', () => {
236 const argv1 = resolve('/usr/local/lib/node_modules/@slidev/cli/bin/slidev.mjs')
237 expect(findInvocationNodeModulesPath(argv1)).toBe(
238 resolve('/usr/local/lib/node_modules'),
239 )
240 })
241
242 it('extracts node_modules from a local project install path', () => {
243 const argv1 = resolve('/my/project/node_modules/@slidev/cli/bin/slidev.mjs')
244 expect(findInvocationNodeModulesPath(argv1)).toBe(
245 resolve('/my/project/node_modules'),
246 )
247 })
248
249 it('uses the last node_modules segment when paths nest', () => {
250 // Some monorepos have stacked node_modules (e.g. project-level + pnpm's
251 // own `.pnpm` virtual store). The closest one to the script wins.
252 const argv1 = resolve('/project/node_modules/.pnpm/@slidev+cli@x/node_modules/@slidev/cli/bin/slidev.mjs')
253 expect(findInvocationNodeModulesPath(argv1)).toBe(
254 resolve('/project/node_modules/.pnpm/@slidev+cli@x/node_modules'),
255 )
256 })
257
258 it('follows a single fs symlink when argv1 itself has no node_modules segment', () => {
259 // Legacy `.bin` symlink layout: `{prefix}/bin/slidev` -> install group's
260 // `node_modules/@slidev/cli/bin/slidev.mjs`.
261 symlink('/usr/local/bin/slidev', '/usr/local/lib/node_modules/@slidev/cli/bin/slidev.mjs')
262 expect(findInvocationNodeModulesPath('/usr/local/bin/slidev')).toBe(
263 resolve('/usr/local/lib/node_modules'),
264 )
265 })
266
267 it('returns undefined when argv1 is neither a symlink nor under a node_modules', () => {
268 setNode('/some/random/binary', { kind: 'file' })
269 expect(findInvocationNodeModulesPath('/some/random/binary')).toBeUndefined()
270 })
271
272 it('returns undefined when argv1 does not exist and has no node_modules in its literal path', () => {
273 expect(findInvocationNodeModulesPath('/does/not/exist')).toBeUndefined()
274 })
275
276 it('handles relative symlink targets', () => {
277 // pnpm typically writes relative targets like `../../@slidev/cli/...`.
278 symlink('/usr/local/bin/slidev', '../lib/node_modules/@slidev/cli/bin/slidev.mjs')
279 expect(findInvocationNodeModulesPath('/usr/local/bin/slidev')).toBe(
280 resolve('/usr/local/lib/node_modules'),
281 )
282 })
283
284 it('follows multi-hop symlink chains and stops at the first node_modules', () => {
285 // `bin/slidev` -> `bin/slidev.real` (still under `bin/`) -> the actual
286 // `.mjs` file under a `node_modules/`.
287 symlink('/prefix/bin/slidev', '/prefix/bin/slidev.real')
288 symlink('/prefix/bin/slidev.real', '/prefix/lib/node_modules/@slidev/cli/bin/slidev.mjs')
289 expect(findInvocationNodeModulesPath('/prefix/bin/slidev')).toBe(
290 resolve('/prefix/lib/node_modules'),
291 )
292 })
293
294 it('gives up after a long symlink chain that never enters a node_modules', () => {
295 // Build a 20-hop chain of symlinks that all point at each other,
296 // none of which contain `node_modules`.
297 for (let i = 0; i < 20; i++)
298 symlink(`/chain/${i}`, `/chain/${i + 1}`)
299 setNode(resolve('/chain/20'), { kind: 'file' })
300 expect(findInvocationNodeModulesPath('/chain/0')).toBeUndefined()
301 })
302 })
303
304 describe('computeInvocationSearchPaths', () => {
305 beforeEach(() => {
306 fsMocks.tree.clear()
307 })
308
309 it('returns an empty array when input is undefined', () => {
310 expect(computeInvocationSearchPaths(undefined)).toEqual([])
311 })
312
313 it('returns just the input when there are no siblings to enumerate', () => {
314 // The grandparent of `ownNodeModules` doesn't contain any other install
315 // groups (e.g. npm globals layout: only `/usr/local/lib/node_modules`).
316 dir('/usr/local')
317 dir('/usr/local/lib')
318 dir('/usr/local/lib/node_modules')
319 expect(computeInvocationSearchPaths(resolve('/usr/local/lib/node_modules'))).toEqual([
320 resolve('/usr/local/lib/node_modules'),
321 ])
322 })
323
324 it('enumerates every sibling install group in pnpm v11\'s isolated globals layout', () => {
325 // pnpm v11 creates one `{hash}/` directory per top-level `pnpm add -g`
326 // target. Each has its own `node_modules/`.
327 dir('/pnpm-home/v11')
328 dir('/pnpm-home/v11/abc')
329 dir('/pnpm-home/v11/abc/node_modules')
330 dir('/pnpm-home/v11/def')
331 dir('/pnpm-home/v11/def/node_modules')
332 dir('/pnpm-home/v11/ghi')
333 dir('/pnpm-home/v11/ghi/node_modules')
334 const result = computeInvocationSearchPaths(resolve('/pnpm-home/v11/abc/node_modules'))
335 expect(result).toEqual(expect.arrayContaining([
336 resolve('/pnpm-home/v11/abc/node_modules'),
337 resolve('/pnpm-home/v11/def/node_modules'),
338 resolve('/pnpm-home/v11/ghi/node_modules'),
339 ]))
340 expect(result[0]).toBe(resolve('/pnpm-home/v11/abc/node_modules'))
341 expect(result).toHaveLength(3)
342 })
343
344 it('skips sibling install groups that have no node_modules subdirectory', () => {
345 dir('/pnpm-home/v11')
346 dir('/pnpm-home/v11/abc')
347 dir('/pnpm-home/v11/abc/node_modules')
348 dir('/pnpm-home/v11/empty') // no node_modules child
349 expect(computeInvocationSearchPaths(resolve('/pnpm-home/v11/abc/node_modules'))).toEqual([
350 resolve('/pnpm-home/v11/abc/node_modules'),
351 ])
352 })
353
354 it('returns just the input when the global root is unreadable', () => {
355 // Grandparent isn't listed in the virtual fs at all -> readdirSync throws.
356 expect(computeInvocationSearchPaths(resolve('/missing-root/abc/node_modules'))).toEqual([
357 resolve('/missing-root/abc/node_modules'),
358 ])
359 })
360
361 it('does not include the input directory as its own sibling', () => {
362 dir('/pnpm-home/v11')
363 dir('/pnpm-home/v11/abc')
364 dir('/pnpm-home/v11/abc/node_modules')
365 const result = computeInvocationSearchPaths(resolve('/pnpm-home/v11/abc/node_modules'))
366 // Exactly one occurrence of the input path.
367 expect(result.filter(p => p === resolve('/pnpm-home/v11/abc/node_modules'))).toHaveLength(1)
368 })
369 })
370
370 lines TYPESCRIPT