Open History to see the last commit
1import { readFile } from 'node:fs/promises'
2import { dirname, resolve } from 'node:path'
3import { fileURLToPath } from 'node:url'
4import { describe, expect, it } from 'vitest'
5import * as rootEntry from '../src/index'
6
7const SRC_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '../src')
8
9/** Resolve a `.`-relative import specifier to its on-disk source file. */
10async function resolveRelative(
11 entry: string,
12 spec: string,
13): Promise<string | undefined> {
14 const base = resolve(dirname(entry), spec)
15 // Try the literal path first (covers `./foo.js` NodeNext/ESM-style specifiers
16 // whose source is `foo.ts`), then the usual TS source extensions and barrels.
17 const candidates = [
18 base,
19 base.replace(/\.[cm]?js$/, '.ts'),
20 base.replace(/\.[cm]?js$/, '.tsx'),
21 `${base}.ts`,
22 `${base}.tsx`,
23 resolve(base, 'index.ts'),
24 resolve(base, 'index.tsx'),
25 ]
26 for (const candidate of candidates) {
27 try {
28 await readFile(candidate, 'utf8')
29 return candidate
30 } catch (err) {
31 // Only "file not found" means "try the next candidate"; anything else
32 // (permissions, decode failure) is a real problem and must surface.
33 if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err
34 }
35 }
36 return undefined
37}
38
39/**
40 * Walk the transitive module graph of an entry file (following only relative
41 * imports — package imports are treated as leaves) and collect every
42 * `node:`-prefixed builtin it statically references. Both static `from '…'`
43 * forms and dynamic `import('…')` calls are followed.
44 *
45 * This guards the regression behind issue #486: the root entry must stay safe
46 * to bundle for Cloudflare Workers / browsers, so it must not statically reach
47 * the Node-only file storage that imports `node:fs` / `node:path`.
48 */
49async function collectNodeBuiltins(
50 entry: string,
51 seen = new Set<string>(),
52 builtins = new Set<string>(),
53): Promise<Set<string>> {
54 if (seen.has(entry)) return builtins
55 seen.add(entry)
56
57 const source = await readFile(entry, 'utf8')
58 // Static `import/export … from '…'` plus dynamic `import('…')`.
59 const specRe =
60 /(?:(?:import|export)[\s\S]*?from\s*['"]([^'"]+)['"])|(?:import\s*\(\s*['"]([^'"]+)['"]\s*\))/g
61
62 for (const match of source.matchAll(specRe)) {
63 const spec = match[1] ?? match[2]
64 if (!spec) continue
65
66 if (spec.startsWith('node:')) {
67 builtins.add(spec)
68 continue
69 }
70
71 if (spec.startsWith('.')) {
72 const resolved = await resolveRelative(entry, spec)
73 if (!resolved) {
74 // A real relative import the walker can't follow would silently drop a
75 // subtree (and any node: import in it), turning this guard into a false
76 // pass. Fail loudly instead.
77 throw new Error(
78 `Could not resolve relative import "${spec}" from "${entry}". ` +
79 `The module-graph walk would silently skip this subtree and the ` +
80 `#486 guard would be unsound.`,
81 )
82 }
83 await collectNodeBuiltins(resolved, seen, builtins)
84 }
85 }
86
87 return builtins
88}
89
90describe('root export worker/browser safety (#486)', () => {
91 it('does not statically import any node: builtin from the root entry', async () => {
92 const builtins = await collectNodeBuiltins(resolve(SRC_DIR, 'index.ts'))
93 expect([...builtins]).toEqual([])
94 })
95
96 it('keeps node: builtins reachable through the /storage subpath', async () => {
97 const builtins = await collectNodeBuiltins(
98 resolve(SRC_DIR, 'storage/index.ts'),
99 )
100 expect([...builtins].sort()).toEqual([
101 'node:fs',
102 'node:fs/promises',
103 'node:path',
104 ])
105 })
106
107 it('re-exports the browser-safe memory storage but not the Node-only file storage from root', () => {
108 // The public contract issue #486 is about: the root entry must expose the
109 // in-memory storage and must NOT expose the Node-only file storage.
110 expect(typeof rootEntry.createMemorySnippetStorage).toBe('function')
111 expect(
112 (rootEntry as Record<string, unknown>).createFileSnippetStorage,
113 ).toBeUndefined()
114 })
115})