common/hexec: Make NODE_PATH a fallback for ESM bare imports

Node's ESM resolver does not consult NODE_PATH (unlike CJS require), so
an ESM postcss.config.js shipped by a Hugo theme fails when loaded from
the module cache: bare imports like `import x from "postcss-import"`
have no node_modules to walk up to.

Install a synchronous resolver hook (module.registerHooks) via
--import=data:... on every Node invocation. On ERR_MODULE_NOT_FOUND for
a bare specifier it resolves the package from each NODE_PATH entry via
createRequire().resolve(). No-op for relative, absolute, URL-scheme and
non-MODULE_NOT_FOUND failures. Synchronous hooks run on the main thread,
so no --allow-worker is needed under the Node permission model.

Fixes #13987

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Bjørn Erik Pedersen
2026-05-13 17:05:09 +02:00
parent 123018de21
commit ae7bf74b3e
4 changed files with 157 additions and 0 deletions
+30
View File
@@ -0,0 +1,30 @@
// Copyright 2026 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package hexec
import (
_ "embed"
"encoding/base64"
"sync"
)
//go:embed esmloader.mjs
var esmLoaderSource string
// nodeESMLoaderImportArg returns a "--import=data:..." argument that installs
// a Node.js ESM resolver hook making NODE_PATH a fallback for failed bare
// imports. See esmloader.mjs for the rationale.
var nodeESMLoaderImportArg = sync.OnceValue(func() string {
return "--import=data:text/javascript;base64," + base64.StdEncoding.EncodeToString([]byte(esmLoaderSource))
})
+52
View File
@@ -0,0 +1,52 @@
// Node.js ESM resolver hook installed by Hugo.
//
// Node's ESM resolver does not consult NODE_PATH, unlike CJS require().
// That breaks postcss.config.js / babel.config.js / etc. files written in
// ESM and loaded from outside the project tree (typically the Hugo module
// cache): bare imports like `import x from "postcss-import"` cannot be
// resolved by walking up from the file's location.
//
// This hook makes the ESM resolver fall back to NODE_PATH for bare
// specifiers when Node's normal resolution fails. It is a no-op for
// relative/absolute paths and URL-scheme specifiers, and it never fires
// unless Node would itself have thrown ERR_MODULE_NOT_FOUND.
//
// Uses the synchronous registerHooks API so it runs on the main thread and
// does not require --allow-worker under the Node permission model.
import { registerHooks, createRequire } from 'node:module';
import { pathToFileURL } from 'node:url';
const resolvers = [];
const np = process.env.NODE_PATH;
if (np) {
const sep = process.platform === 'win32' ? ';' : ':';
for (const p of np.split(sep)) {
if (p) resolvers.push(createRequire(p + '/_'));
}
}
function isBareSpecifier(s) {
if (!s) return false;
if (s.startsWith('.') || s.startsWith('/') || s.startsWith('#')) return false;
if (/^[a-z][a-z0-9+.-]*:/i.test(s)) return false;
return true;
}
registerHooks({
resolve(specifier, context, nextResolve) {
try {
return nextResolve(specifier, context);
} catch (err) {
if (err?.code !== 'ERR_MODULE_NOT_FOUND') throw err;
if (!isBareSpecifier(specifier)) throw err;
for (const r of resolvers) {
try {
const resolved = r.resolve(specifier);
return { url: pathToFileURL(resolved).href, shortCircuit: true, format: null };
} catch (_) { /* try next */ }
}
throw err;
}
},
});
+4
View File
@@ -234,6 +234,10 @@ func (e *Exec) newNode(name, scriptPath string, arg ...any) (Runner, error) {
for _, pa := range e.nodePermissionArgs(name, scriptPath) {
allArgs = append(allArgs, pa)
}
// Install an ESM resolver hook that makes NODE_PATH a fallback for failed
// bare imports, so postcss.config.js / babel.config.js / etc. written in
// ESM work when loaded from the Hugo module cache. See esmloader.mjs.
allArgs = append(allArgs, nodeESMLoaderImportArg())
allArgs = append(allArgs, scriptPath)
allArgs = append(allArgs, arg...)
// When the script lives outside the working dir (a globally installed