MCPcopy
hub / github.com/vitest-dev/vitest / isValidNodeImport

Function isValidNodeImport

packages/vitest/src/node/resolver.ts:131–167  ·  view source on GitHub ↗
(id: string)

Source from the content-addressed store, hash-verified

129
130// The code from https://github.com/unjs/mlly/blob/c5bcca0cda175921344fd6de1bc0c499e73e5dac/src/syntax.ts#L51-L98
131async function isValidNodeImport(id: string) {
132 // clean url to strip off `?v=...` query etc.
133 // node can natively import files with query params, so externalizing them is safe.
134 id = cleanUrl(id)
135
136 const extension = extname(id)
137
138 if (BUILTIN_EXTENSIONS.has(extension)) {
139 return true
140 }
141
142 if (extension !== '.js') {
143 return false
144 }
145
146 id = id.replace('file:///', '')
147
148 const package_ = findNearestPackageData(dirname(id))
149
150 if (package_.type === 'module') {
151 return true
152 }
153
154 if (/\.(?:\w+-)?esm?(?:-\w+)?\.js$|\/esm?\//.test(id)) {
155 return false
156 }
157
158 try {
159 await esModuleLexer.init
160 const code = await fsp.readFile(id, 'utf8')
161 const [, , , hasModuleSyntax] = esModuleLexer.parse(code)
162 return !hasModuleSyntax
163 }
164 catch {
165 return false
166 }
167}
168
169export async function shouldExternalize(
170 id: string,

Callers 1

_shouldExternalizeFunction · 0.85

Calls 5

cleanUrlFunction · 0.90
findNearestPackageDataFunction · 0.90
readFileMethod · 0.80
hasMethod · 0.45
testMethod · 0.45

Tested by

no test coverage detected