Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions NativeScript/runtime/ModuleInternal.h
Original file line number Diff line number Diff line change
Expand Up @@ -101,15 +101,21 @@ class ModuleInternal {

private:
static void RequireCallback(const v8::FunctionCallbackInfo<v8::Value>& info);
// The global require's native half in debug builds: RequireCallback plus a
// one-time warning per ES module that passes it a relative specifier.
static void DebugGlobalRequireCallback(
const v8::FunctionCallbackInfo<v8::Value>& info);
static void CreateRequireCallback(
const v8::FunctionCallbackInfo<v8::Value>& info);
// A require bound to `dirName`, whose ES module loads evaluate under
// `options`. The options ride along as trailing arguments to the require
// factory, so nothing about them is ambient — and they are resolved once at
// mint time, never per require() call.
// mint time, never per require() call. `requireInternal` defaults to the
// RequireCallback function every module-scoped require shares.
v8::Local<v8::Function> GetRequireFunction(
v8::Isolate* isolate, const std::string& dirName,
const ModuleEvaluationOptions& options);
const ModuleEvaluationOptions& options,
v8::Local<v8::Function> requireInternal = v8::Local<v8::Function>());
v8::Local<v8::Object> LoadImpl(v8::Isolate* isolate,
const std::string& moduleName,
const std::string& baseDir, bool& isData,
Expand Down
90 changes: 87 additions & 3 deletions NativeScript/runtime/ModuleInternal.mm
Original file line number Diff line number Diff line change
Expand Up @@ -173,8 +173,21 @@ static bool IsHttpModulePath(const std::string& path) {
// Use shortened path for global require function to avoid V8 parsing issues
std::string globalRequirePath = "/app";

// The bound directory cannot tell the global require apart (a CommonJS
// module in the app root is bound to "/app" too), so debug builds give it a
// native half of its own.
Local<v8::Function> globalRequireInternal;
if (RuntimeConfig.IsDebug) {
globalRequireInternal =
FunctionTemplate::New(isolate, DebugGlobalRequireCallback,
External::New(isolate, this, v8::kExternalPointerTypeTagDefault))
->GetFunction(context)
.ToLocalChecked();
}

Local<v8::Function> globalRequire = GetRequireFunction(
isolate, globalRequirePath, RequireEvaluationOptions(ModuleEvaluationPolicy::kSyncStrict));
isolate, globalRequirePath, RequireEvaluationOptions(ModuleEvaluationPolicy::kSyncStrict),
globalRequireInternal);
bool success =
global->Set(context, tns::ToV8String(isolate, "require"), globalRequire).FromMaybe(false);
if (!success) {
Expand Down Expand Up @@ -360,10 +373,12 @@ throw NativeScriptException(
}

Local<v8::Function> ModuleInternal::GetRequireFunction(Isolate* isolate, const std::string& dirName,
const ModuleEvaluationOptions& options) {
const ModuleEvaluationOptions& options,
Local<v8::Function> requireInternal) {
Local<v8::Function> requireFuncFactory = requireFactoryFunction_->Get(isolate);
Local<Context> context = isolate->GetCurrentContext();
Local<v8::Function> requireInternalFunc = this->requireFunction_->Get(isolate);
Local<v8::Function> requireInternalFunc =
requireInternal.IsEmpty() ? this->requireFunction_->Get(isolate) : requireInternal;
Local<Value> args[6]{
requireInternalFunc,
tns::ToV8String(isolate, dirName.c_str()),
Expand Down Expand Up @@ -453,6 +468,75 @@ throw NativeScriptException(
return "type " + std::string(typeName) + " (" + rendered + ")";
}

namespace {
// The ES modules (by registry key) already warned about a relative specifier
// passed to the global require. Keyed by registry key rather than script id so
// an HMR recompile of the same module does not warn again.
struct GlobalRequireWarningState {
robin_hood::unordered_set<std::string> warnedModuleKeys;
};
} // namespace

// The specifiers the resolver joins onto the bound directory. Exactly "./" is
// left out: every require resolves it to the app's main entry.
static bool IsDirectoryRelativeSpecifier(const std::string& specifier) {
return specifier == "." || specifier == ".." || specifier.rfind("../", 0) == 0 ||
(specifier.rfind("./", 0) == 0 && specifier != "./");
}

// Never runs JS and never throws: it may only add a log line to a require().
static void WarnIfRelativeGlobalRequireFromEsModule(Isolate* isolate, Local<Value> specifierValue,
int requireFactoryScriptId) {
if (!specifierValue->IsString()) {
return;
}
const std::string specifier = tns::ToString(isolate, specifierValue);
if (!IsDirectoryRelativeSpecifier(specifier)) {
return;
}

// The require() closure is the top frame; the caller is the first frame
// from any other script.
HandleScope handleScope(isolate);
Local<StackTrace> stack = StackTrace::CurrentStackTrace(isolate, 3);
int callerScriptId = v8::Message::kNoScriptIdInfo;
for (int i = 0; i < stack->GetFrameCount(); i++) {
int scriptId = stack->GetFrame(isolate, i)->GetScriptId();
if (scriptId != requireFactoryScriptId) {
callerScriptId = scriptId;
break;
}
}
if (callerScriptId == v8::Message::kNoScriptIdInfo) {
return;
}

const std::string moduleKey = LookupModuleKeyForScriptId(isolate, callerScriptId);
if (moduleKey.empty()) {
return;
}
auto* state = Caches::StateFor<GlobalRequireWarningState>(isolate);
if (state == nullptr || !state->warnedModuleKeys.insert(moduleKey).second) {
return;
}

Log(@"NativeScript: require(\"%s\") in ES module %s resolves against the app root, not the "
@"module's folder. Use createRequire(import.meta.url) from \"ns:module\" (from a module "
@"loaded over http(s): createRequire with an app file path).",
specifier.c_str(), tns::ReportedModuleUrl(moduleKey).c_str());
}

void ModuleInternal::DebugGlobalRequireCallback(const FunctionCallbackInfo<Value>& info) {
Isolate* isolate = info.GetIsolate();
if (info.Length() > 0) {
ModuleInternal* moduleInternal = static_cast<ModuleInternal*>(
info.Data().As<External>()->Value(v8::kExternalPointerTypeTagDefault));
WarnIfRelativeGlobalRequireFromEsModule(
isolate, info[0], moduleInternal->requireFactoryFunction_->Get(isolate)->ScriptId());
}
RequireCallback(info);
}

void ModuleInternal::RequireCallback(const FunctionCallbackInfo<Value>& info) {
Isolate* isolate = info.GetIsolate();

Expand Down
5 changes: 5 additions & 0 deletions NativeScript/runtime/ModuleInternalCallbacks.h
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,11 @@ void RemoveModuleFromRegistry(v8::Isolate* isolate,
std::string LookupModuleKeyForModule(v8::Isolate* isolate,
v8::Local<v8::Module> mod);

// The registry key of the live source-text module compiled as script
// `scriptId` (a StackFrame's GetScriptId()), or empty when no registered ES
// module has that script. A linear scan of the registry: diagnostics only.
std::string LookupModuleKeyForScriptId(v8::Isolate* isolate, int scriptId);

// Record `mod` in the identity-hash index under `canonicalKey`. Call alongside
// every registry insert performed outside ModuleInternalCallbacks.mm.
void IndexModuleForIsolate(v8::Isolate* isolate,
Expand Down
22 changes: 22 additions & 0 deletions NativeScript/runtime/ModuleInternalCallbacks.mm
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,28 @@ void IndexRegisteredModule(ModuleLoaderState& state, const std::string& key,
return FindKeyForModule(*state, isolate, mod);
}

std::string LookupModuleKeyForScriptId(v8::Isolate* isolate, int scriptId) {
auto* state = ModuleLoaderStateFor(isolate);
if (state == nullptr) {
return std::string();
}
for (const auto& entry : state->registry) {
if (entry.second.IsEmpty()) {
continue;
}
v8::Local<v8::Module> mod = entry.second.Get(isolate);
// ScriptId() aborts on anything else.
if (!mod->IsSourceTextModule() || mod->GetStatus() == v8::Module::kErrored) {
continue;
}
if (mod->ScriptId() == scriptId) {
std::string key = FindKeyForModule(*state, isolate, mod);
return key.empty() ? entry.first : key;
}
}
return std::string();
}

namespace {
// The single module request in the facade source, and the source itself. Both
// match Node's required_module_facade_source_string so the semantics (live
Expand Down
80 changes: 80 additions & 0 deletions TestRunner/app/tests/CreateRequireTests.js
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,86 @@ describe("createRequire", function () {
});
});

// An ES module has no require of its own, so a bare `require` in one is the
// global require, bound to the app root. Debug builds log a one-time warning
// per ES module for a relative specifier passed to it; the fixtures split the
// callers so each one's warning (or its absence) shows up separately in the
// device log.
describe("the global require in an ES module", function () {
var fixtures = "~/tests/esm/global-require/sub/";

function withModule(name, done, fn) {
import(fixtures + name).then(function (mod) {
fn(mod);
done();
}).catch(function (e) {
expect("rejected: " + ((e && e.message) || e)).toBe("resolved");
done();
});
}

function errorOf(fn) {
try {
fn();
} catch (e) {
return String((e && e.message) || e);
}
return "<no error thrown>";
}

function expectResolvedAgainstAppRoot(message, specifier) {
expect(message).toContain("Cannot find module '" + specifier + "'");
expect(message).toMatch(/Base directory: [^\n]*\/app\n/);
expect(message).not.toContain("global-require/sub");
}

it("resolves a relative specifier against the app root, not the module's folder",
function (done) {
withModule("relative.mjs", done, function (mod) {
expectResolvedAgainstAppRoot(
errorOf(function () { mod.load("./global-require-sibling.js"); }),
"global-require-sibling.js");
// Repeated and different relative specifiers behave the same.
expectResolvedAgainstAppRoot(
errorOf(function () { mod.load("./global-require-sibling.js"); }),
"global-require-sibling.js");
expect(errorOf(function () { mod.load("../sub/global-require-sibling.js"); }))
.toContain("Cannot find module");
});
});

it("resolves a non-relative specifier as any other require does", function (done) {
withModule("non-relative.mjs", done, function (mod) {
expect(mod.load("~/tests/esm/global-require/sub/global-require-sibling.js").tag)
.toBe("global-require-sibling");
expect(mod.load("ns:module")).toBe(require("ns:module"));
});
});

it("leaves createRequire(import.meta.url) resolving against the module's folder",
function (done) {
withModule("create-require.mjs", done, function (mod) {
expect(mod.load("./global-require-sibling.js").tag).toBe("global-require-sibling");
});
});

it("resolves against the app root from a classic script an ES module created",
function (done) {
withModule("classic-caller.mjs", done, function (mod) {
expectResolvedAgainstAppRoot(
errorOf(function () { mod.load("./global-require-from-classic.js"); }),
"global-require-from-classic.js");
});
});

it("resolves against the app root from a CommonJS module", function () {
var caller = require("./esm/global-require/sub/commonjs-caller.js");
expectResolvedAgainstAppRoot(
errorOf(function () { caller.load("./global-require-from-commonjs.js"); }),
"global-require-from-commonjs.js");
});
});

// `~` marks the app root; the separator after it is optional.
describe("app-root specifiers", function () {
it("resolves ~/path", function () {
Expand Down
26 changes: 26 additions & 0 deletions TestRunner/app/tests/HttpEsmLoaderTests.js
Original file line number Diff line number Diff line change
Expand Up @@ -2098,6 +2098,32 @@ describe("HTTP ESM Loader", function() {
done();
});
});

it("leaves the global require resolving relative specifiers against the app root",
function (done) {
var origin = getHostOrigin();
if (!origin) {
pending("REPORT_BASEURL not set; skipping host HTTP tests");
done();
return;
}
import(origin + "/esm/global-require.mjs").then(function (mod) {
var message = "<no error thrown>";
try {
mod.load("./global-require-from-http.js");
} catch (e) {
message = String((e && e.message) || e);
}
expect(message).toContain("Cannot find module 'global-require-from-http.js'");
expect(message).toMatch(/Base directory: [^\n]*\/app\n/);
expect(mod.load("~/tests/esm/global-require/sub/global-require-sibling.js").tag)
.toBe("global-require-sibling");
done();
}).catch(function (error) {
expect("rejected: " + formatError(error)).toBe("resolved");
done();
});
});
});

describe("an import-map entry keyed by a file module's own URL", function () {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// The require() call sits in a classic script (a Function body) that this ES
// module merely creates and exports.
export const load = new Function("specifier", "return require(specifier);");
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// A CommonJS module calling the global require rather than its own.
exports.load = function (specifier) {
return globalThis.require(specifier);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { createRequire } from "ns:module";

const moduleRequire = createRequire(import.meta.url);

export function load(specifier) {
return moduleRequire(specifier);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
exports.tag = "global-require-sibling";
5 changes: 5 additions & 0 deletions TestRunner/app/tests/esm/global-require/sub/non-relative.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// The global require, reached from an ES module that only ever passes it
// non-relative specifiers.
export function load(specifier) {
return require(specifier);
}
4 changes: 4 additions & 0 deletions TestRunner/app/tests/esm/global-require/sub/relative.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// An ES module has no require of its own: `require` here is the global one.
export function load(specifier) {
return require(specifier);
}
8 changes: 8 additions & 0 deletions TestRunnerTests/TestRunnerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,14 @@ class TestRunnerTests: XCTestCase {
return
}

// A served ES module whose `load(spec)` calls the global require.
if path == "/esm/global-require.mjs" {
let body = "export function load(spec) { return require(spec); }\n"
startResponse("200 OK", [("Content-Type", "application/javascript; charset=utf-8")])
sendBody(body.data(using: .utf8) ?? Data())
return
}

// ── MIME-gate routes ──────────────────────────────
if path == "/esm/html-fallback.mjs" {
// The SPA-fallback shape: an unknown path answered with the
Expand Down
8 changes: 8 additions & 0 deletions docs/ns-builtin-modules.md
Original file line number Diff line number Diff line change
Expand Up @@ -1022,6 +1022,14 @@ The "id" argument must be of type string. Received <what>
`<what>` follows Node's `determineSpecificType`: `undefined`, `null`,
`type number (42)`, `an instance of Object`, `function foo`, and so on.

An ES module has no `require` of its own; the global `require` is available
there for compatibility and resolves a relative specifier (`./x`, `../x`)
against the app root, whichever module calls it. An ES module that needs
module-relative resolution uses `createRequire(import.meta.url)`, or, when it
was loaded over http(s), `createRequire` with an app file path. Debug builds
log a warning once per ES module that passes a relative specifier to the
global `require`.

### `require()` of an ES module

`require()` of an ES module works, under Node's `require(esm)` rule: the graph
Expand Down
3 changes: 3 additions & 0 deletions types/ns-module.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,9 @@ declare module "ns:module" {
*
* `require.resolve`, `require.cache` and `require.main` are not
* implemented and are absent from the returned function.
*
* In an ES module, `createRequire(import.meta.url)` is the module-relative
* `require`: the global one resolves relative specifiers against the app root.
*/
export function createRequire(
filenameOrURL: string | URL,
Expand Down
Loading