Review r1 finding 4: the imports step held a fixed list of Node 22's builtin modules (principle 11). It now reads module.builtinModules from the installed Node at each step, and fails loud when it cannot. Builds: design 47 H2 H-A-523, H-A-532 (DQ-6)
49 lines
1.5 KiB
Go
49 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"os/exec"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// ProbeTimeout bounds `node --version`.
|
|
const ProbeTimeout = 15 * time.Second
|
|
|
|
// ProbeNode reads the installed Node version: what `node --version` prints ("v26.10.0"), as the toolchains state holds it.
|
|
func ProbeNode(ctx context.Context) (string, error) {
|
|
ctx, cancel := context.WithTimeout(ctx, ProbeTimeout)
|
|
defer cancel()
|
|
out, err := exec.CommandContext(ctx, "node", "--version").Output()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return parseNodeVersion(string(out))
|
|
}
|
|
|
|
// ProbeBuiltins reads the installed Node's own modules, its module.builtinModules, so the imports step leaves out exactly
|
|
// what the probed toolchain holds (principle 11: read, never a fixed list).
|
|
func ProbeBuiltins(ctx context.Context) ([]string, error) {
|
|
ctx, cancel := context.WithTimeout(ctx, ProbeTimeout)
|
|
defer cancel()
|
|
out, err := exec.CommandContext(ctx, "node", "-p", "JSON.stringify(require('module').builtinModules)").Output()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("node's builtinModules cannot be read: %w", err)
|
|
}
|
|
var names []string
|
|
if err := json.Unmarshal(out, &names); err != nil || len(names) == 0 {
|
|
return nil, fmt.Errorf("node's builtinModules answered %q", strings.TrimSpace(string(out)))
|
|
}
|
|
return names, nil
|
|
}
|
|
|
|
func parseNodeVersion(out string) (string, error) {
|
|
v := strings.TrimSpace(out)
|
|
if len(v) < 2 || v[0] != 'v' || v[1] < '0' || v[1] > '9' || strings.ContainsAny(v, " \n\t") {
|
|
return "", fmt.Errorf("`node --version` answered %q", v)
|
|
}
|
|
return v, nil
|
|
}
|