Debian Codegraph @

common/hexec/esmloader.mjs

raw
1 // Node.js ESM resolver hook installed by Hugo.
2 //
3 // Node's ESM resolver does not consult NODE_PATH, unlike CJS require().
4 // That breaks postcss.config.js / babel.config.js / etc. files written in
5 // ESM and loaded from outside the project tree (typically the Hugo module
6 // cache): bare imports like `import x from "postcss-import"` cannot be
7 // resolved by walking up from the file's location.
8 //
9 // This hook makes the ESM resolver fall back to NODE_PATH for bare
10 // specifiers when Node's normal resolution fails. It is a no-op for
11 // relative/absolute paths and URL-scheme specifiers, and it never fires
12 // unless Node would itself have thrown ERR_MODULE_NOT_FOUND or
13 // ERR_ACCESS_DENIED.
14 //
15 // ERR_ACCESS_DENIED is handled because Node's resolver walks up the
16 // directory tree looking for node_modules. Under the permission model that
17 // walk can hit a node_modules outside the allow-list (e.g. Netlify stores
18 // its node_modules cache in the same tree as the Hugo file cache), aborting
19 // resolution even though the package is reachable via NODE_PATH. If the
20 // NODE_PATH fallback also fails we re-throw the original error so the
21 // access-denied resource is still reported.
22 //
23 // Uses the synchronous registerHooks API so it runs on the main thread and
24 // does not require --allow-worker under the Node permission model.
25
26 import { registerHooks, createRequire } from 'node:module';
27 import { pathToFileURL } from 'node:url';
28
29 const resolvers = [];
30 const np = process.env.NODE_PATH;
31 if (np) {
32 const sep = process.platform === 'win32' ? ';' : ':';
33 for (const p of np.split(sep)) {
34 if (p) resolvers.push(createRequire(p + '/_'));
35 }
36 }
37
38 function isBareSpecifier(s) {
39 if (!s) return false;
40 if (s.startsWith('.') || s.startsWith('/') || s.startsWith('#')) return false;
41 if (/^[a-z][a-z0-9+.-]*:/i.test(s)) return false;
42 return true;
43 }
44
45 registerHooks({
46 resolve(specifier, context, nextResolve) {
47 try {
48 return nextResolve(specifier, context);
49 } catch (err) {
50 if (err?.code !== 'ERR_MODULE_NOT_FOUND' && err?.code !== 'ERR_ACCESS_DENIED') throw err;
51 if (!isBareSpecifier(specifier)) throw err;
52 for (const r of resolvers) {
53 try {
54 const resolved = r.resolve(specifier);
55 return { url: pathToFileURL(resolved).href, shortCircuit: true, format: null };
56 } catch (_) { /* try next */ }
57 }
58 throw err;
59 }
60 },
61 });