nstdlib-nightly
Version:
Node.js standard library converted to runtime-agnostic ES modules.
72 lines (65 loc) • 2.34 kB
JavaScript
// Source: https://github.com/nodejs/node/blob/65eff1eb/lib/internal/main/eval_string.js
import {
prepareMainThreadExecution,
markBootstrapComplete,
} from "nstdlib/lib/internal/process/pre_execution";
import {
evalModuleEntryPoint,
evalScript,
} from "nstdlib/lib/internal/process/execution";
import {
addBuiltinLibsToObject,
stripTypeScriptTypes,
} from "nstdlib/lib/internal/modules/helpers";
import { getOptionValue } from "nstdlib/lib/internal/options";
// User passed `-e` or `--eval` arguments to Node without `-i` or
// `--interactive`.
prepareMainThreadExecution();
addBuiltinLibsToObject(globalThis, "<eval>");
markBootstrapComplete();
const code = getOptionValue("--eval");
const source = getOptionValue("--experimental-strip-types")
? stripTypeScriptTypes(code)
: code;
const print = getOptionValue("--print");
const shouldLoadESM =
getOptionValue("--import").length > 0 ||
getOptionValue("--experimental-loader").length > 0;
if (
getOptionValue("--input-type") === "module" ||
(getOptionValue("--experimental-default-type") === "module" &&
getOptionValue("--input-type") !== "commonjs")
) {
((...args) => globalThis.evalModuleEntryPoint(...args))(source, print);
} else {
// For backward compatibility, we want the identifier crypto to be the
// `node:crypto` module rather than WebCrypto.
const isUsingCryptoIdentifier =
getOptionValue("--experimental-global-webcrypto") &&
RegExp.prototype.exec.call(/\bcrypto\b/, source) !== null;
const shouldDefineCrypto =
isUsingCryptoIdentifier && require("binding/config").hasOpenSSL;
if (isUsingCryptoIdentifier && !shouldDefineCrypto) {
// This is taken from `addBuiltinLibsToObject`.
const object = globalThis;
const name = "crypto";
const setReal = (val) => {
// Deleting the property before re-assigning it disables the
// getter/setter mechanism.
delete object[name];
object[name] = val;
};
Object.defineProperty(object, name, { __proto__: null, set: setReal });
}
((...args) => globalThis.evalScript(...args))(
"[eval]",
shouldDefineCrypto
? print
? `let crypto=require("node:crypto");{${source}}`
: `(crypto=>{{${source}}})(require('node:crypto'))`
: source,
getOptionValue("--inspect-brk"),
print,
shouldLoadESM,
);
}