Skip to content
Open
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
16 changes: 11 additions & 5 deletions NativeScript/runtime/ModuleInternal.mm
Original file line number Diff line number Diff line change
Expand Up @@ -1840,15 +1840,21 @@ throw NativeScriptException(
return std::string();
}

NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
if (dic == nil) {
id json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
if (![json isKindOfClass:[NSDictionary class]]) {
error = true;
return std::string();
}

NSString* main = [dic objectForKey:@"main"];
if (main == nil) {
main = @"index"; // Fallback to "index" if no main field found
// As in Node, a `main` that is not a string is ignored.
id mainValue = [(NSDictionary*)json objectForKey:@"main"];
NSString* main = [mainValue isKindOfClass:[NSString class]] ? (NSString*)mainValue : @"index";
// The lookups below go through C strings, which would end the path at
// U+0000; a lone surrogate has no UTF-8 form at all.
const std::optional<std::string> mainUtf8 = tns::ToExactUtf8(main);
if (!mainUtf8.has_value() || mainUtf8->find('\0') != std::string::npos) {
error = true;
return std::string();
}

NSString* baseDir = [packageJsonStr stringByDeletingLastPathComponent];
Expand Down
64 changes: 51 additions & 13 deletions NativeScript/runtime/ModuleInternalCallbacks.mm
Original file line number Diff line number Diff line change
Expand Up @@ -1607,6 +1607,30 @@ static UrlSpecifier ResolveModuleSpecifierAgainstUrl(const std::string& spec,
reason;
}

// A specifier's exact UTF-8, or nullopt when it contains U+0000: the path and
// URL APIs behind resolution read C strings and would load whatever precedes it.
static std::optional<std::string> ModuleSpecifierUtf8(v8::Isolate* isolate,
v8::Local<v8::String> specifier) {
std::string spec = tns::ToString(isolate, specifier);
if (spec.find('\0') != std::string::npos) {
return std::nullopt;
}
return spec;
}

static std::string NulSpecifierMessage(v8::Isolate* isolate, v8::Local<v8::String> specifier) {
std::string shown;
for (char c : tns::ToString(isolate, specifier)) {
if (c == '\0') {
shown += "\\u0000";
} else {
shown += c;
}
}
return "Cannot resolve module specifier \"" + shown +
"\": a module specifier must not contain U+0000";
}

static bool IsRegularFile(const std::string& p) {
std::string normalized = NormalizePath(p);
struct stat st;
Expand Down Expand Up @@ -1907,9 +1931,9 @@ static void AsyncGraphWalkModuleRequests(const std::shared_ptr<AsyncGraphLoad>&
if (request.IsEmpty()) {
continue;
}
v8::Local<v8::String> specV8 = request->GetSpecifier();
v8::String::Utf8Value specUtf8(isolate, specV8);
if (!*specUtf8) {
// A specifier holding U+0000 is left for the resolver to refuse at link.
const std::optional<std::string> spec = ModuleSpecifierUtf8(isolate, request->GetSpecifier());
if (!spec.has_value()) {
continue;
}
// Builtins are served by the resolver from the builtin registry, and an
Expand All @@ -1919,7 +1943,7 @@ static void AsyncGraphWalkModuleRequests(const std::shared_ptr<AsyncGraphLoad>&
// message. An unmapped bare specifier's subtree is therefore not
// discovered here; any HTTP edge inside it is pathological and lands on
// the synchronous anomaly guard.
const ModuleResolution resolution = ResolveSpecifierToPath(*specUtf8, moduleKey);
const ModuleResolution resolution = ResolveSpecifierToPath(*spec, moduleKey);
if (resolution.kind == ModuleResolution::Kind::kBuiltin ||
resolution.kind == ModuleResolution::Kind::kUnresolved) {
continue;
Expand Down Expand Up @@ -2753,8 +2777,13 @@ static void RejectAndClearInvalidatedModuleState(v8::Isolate* isolate,
}
auto& registry = moduleState->registry;

v8::String::Utf8Value specUtf8(isolate, specifier);
const std::string rawSpec = *specUtf8 ? *specUtf8 : "";
const std::optional<std::string> spec = ModuleSpecifierUtf8(isolate, specifier);
if (!spec.has_value()) {
isolate->ThrowException(
v8::Exception::Error(tns::ToV8String(isolate, NulSpecifierMessage(isolate, specifier))));
return v8::MaybeLocal<v8::Module>();
}
const std::string& rawSpec = *spec;
if (rawSpec.empty()) {
return v8::MaybeLocal<v8::Module>();
}
Expand Down Expand Up @@ -2987,12 +3016,23 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local<v8::Context>
auto& registry = moduleState->registry;
auto& modulesInFlight = moduleState->modulesInFlight;
auto& httpDynamicWaiters = moduleState->httpDynamicWaiters;
// Diagnostic: log every dynamic import attempt.
v8::String::Utf8Value specUtf8(isolate, specifier);
const char* cSpec = (*specUtf8) ? *specUtf8 : "<invalid>";
NSString* specStr = [NSString stringWithUTF8String:cSpec];
const std::optional<std::string> specUtf8 = ModuleSpecifierUtf8(isolate, specifier);
if (!specUtf8.has_value()) {
v8::EscapableHandleScope nulScope(isolate);
v8::Local<v8::Promise::Resolver> nulResolver;
if (!v8::Promise::Resolver::New(context).ToLocal(&nulResolver)) {
return v8::MaybeLocal<v8::Promise>();
}
nulResolver
->Reject(context, v8::Exception::Error(
tns::ToV8String(isolate, NulSpecifierMessage(isolate, specifier))))
.FromMaybe(false);
return nulScope.Escape(nulResolver->GetPromise());
}
std::string rawSpec = *specUtf8;
NSString* specStr = tns::ToNSString(rawSpec);
if (tns::LogCategoryEnabled(tns::LogCategory::Esm)) {
TNS_DEBUG(Esm, "[dyn-import] → %s", cSpec);
TNS_DEBUG(Esm, "[dyn-import] → %s", rawSpec.c_str());
// Also log the referrer resource when available to correlate origin of dynamic imports
v8::Local<v8::Value> resName = resource_name;
if (!resName.IsEmpty() && resName->IsString()) {
Expand All @@ -3002,8 +3042,6 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local<v8::Context>
}
}
}
std::string rawSpec = cSpec ? std::string(cSpec) : std::string();

// Builtin modules never reach the loader below; the namespace comes straight
// from the realm's synthetic module.
if (NsBuiltinModules::IsBuiltinScheme(rawSpec)) {
Expand Down
37 changes: 7 additions & 30 deletions NativeScript/runtime/Runtime.mm
Original file line number Diff line number Diff line change
Expand Up @@ -88,40 +88,17 @@ static void InitializeImportMetaObject(Local<Context> context, Local<Module> mod
url)
.Check();

// Compute import.meta.dirname.
//
// Spec (Node.js): `import.meta.dirname` is the OS-path of the
// directory containing the module — equivalent to `path.dirname(
// fileURLToPath(import.meta.url))`. It only makes sense for modules
// backed by the local filesystem.
//
// For URL-backed modules (HTTP, blob, etc.) there is no
// filesystem directory. We return the URL with the final segment
// stripped — a best-effort answer that's stable across cycles and
// useful for log lines / source maps. Consumers that genuinely need
// a filesystem path should already be guarding on `meta.url`'s
// scheme before using `meta.dirname`.
// As in Node, import.meta.dirname exists only for a module loaded from the
// filesystem: path.dirname(fileURLToPath(import.meta.url)), taken from the
// same base-stripped path the url reports. A module whose key carries a URL
// scheme (http(s), blob:, builtins) has no directory and gets no property.
if (tns::HasUrlScheme(modulePath)) {
return;
}
std::string dirname;
if (modulePath.empty()) {
dirname = "/app";
} else if (tns::HasUrlScheme(modulePath)) {
size_t schemeEnd = modulePath.find("://");
size_t pathStart =
(schemeEnd == std::string::npos) ? std::string::npos : modulePath.find('/', schemeEnd + 3);
size_t lastSlash = modulePath.find_last_of('/');
if (pathStart != std::string::npos && lastSlash != std::string::npos && lastSlash > pathStart) {
dirname = modulePath.substr(0, lastSlash);
} else {
// No path beyond the host (`http://host`) or scheme without `//`
// (`node:fs`, `blob:abc`). Keep the identity intact.
dirname = modulePath;
}
} else {
// Derived from the same base-stripped path `import.meta.url` reports, so
// the documented equivalence holds: dirname is
// `path.dirname(fileURLToPath(import.meta.url))`. Taking it from the raw
// path instead reported a container-absolute directory for a module whose
// url said `file:///app/…`.
const std::string appRelative = tns::ReplaceAll(modulePath, RuntimeConfig.BaseDir, "");
size_t lastSlash = appRelative.find_last_of("/\\");
if (lastSlash != std::string::npos && lastSlash > 0) {
Expand Down
61 changes: 37 additions & 24 deletions NativeScript/runtime/Worker.mm
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#include "Helpers.h"
#include "ModuleBinding.hpp"
#include "ModuleInternalCallbacks.h"
#include "ModuleUrl.h"
#include "NativeScriptException.h"
#include "ObjectManager.h"
#include "Runtime.h"
Expand Down Expand Up @@ -384,35 +385,47 @@ throw NativeScriptException(
// Relative worker paths are resolved against the calling module's directory,
// matching the Android runtime and the legacy JSC iOS runtime. If no file is
// found there, fall back to app-root-relative resolution, which is what this
// runtime historically did.
// runtime historically did. A module loaded over HTTP resolves them against
// its URL instead and never reaches the app root.
if (workerPath.rfind("./", 0) == 0 || workerPath.rfind("../", 0) == 0) {
std::string callerScript;
Local<StackTrace> stack = StackTrace::CurrentStackTrace(isolate, 1);
if (!stack.IsEmpty() && stack->GetFrameCount() > 0) {
Local<v8::String> scriptName = stack->GetFrame(isolate, 0)->GetScriptName();
if (!scriptName.IsEmpty()) {
std::string callerScript = ToString(isolate, scriptName);
const std::string filePrefix = "file://";
if (callerScript.rfind(filePrefix, 0) == 0) {
callerScript = callerScript.substr(filePrefix.size());
}
// Script origins are relative to the app bundle root (BaseDir)
if (!callerScript.empty() && callerScript[0] == '/' &&
callerScript.rfind(RuntimeConfig.BaseDir, 0) != 0) {
callerScript = RuntimeConfig.BaseDir + callerScript;
}
if (!callerScript.empty() && callerScript[0] == '/') {
NSString* callerDir = [[NSString stringWithUTF8String:callerScript.c_str()]
stringByDeletingLastPathComponent];
NSString* candidate = [[callerDir
stringByAppendingPathComponent:[NSString stringWithUTF8String:workerPath.c_str()]]
stringByStandardizingPath];
if (tns::Exists([candidate fileSystemRepresentation]) ||
tns::Exists(
[[candidate stringByAppendingPathExtension:@"js"] fileSystemRepresentation]) ||
tns::Exists([[candidate stringByAppendingPathComponent:@"index.js"]
fileSystemRepresentation])) {
workerPath = [candidate UTF8String];
}
callerScript = ToString(isolate, scriptName);
}
}

if (IsHttpRegistryKey(callerScript)) {
const ModuleUrl resolved = ParseModuleUrl(workerPath, callerScript);
if (!resolved.parsed || !resolved.http) {
throw NativeScriptException("Cannot resolve worker path \"" + workerPath +
"\" against the calling module's URL " + callerScript);
}
workerPath = resolved.href;
} else if (!callerScript.empty()) {
const std::string filePrefix = "file://";
if (callerScript.rfind(filePrefix, 0) == 0) {
callerScript = callerScript.substr(filePrefix.size());
}
// Script origins are relative to the app bundle root (BaseDir)
if (!callerScript.empty() && callerScript[0] == '/' &&
callerScript.rfind(RuntimeConfig.BaseDir, 0) != 0) {
callerScript = RuntimeConfig.BaseDir + callerScript;
}
if (!callerScript.empty() && callerScript[0] == '/') {
NSString* callerDir = [[NSString stringWithUTF8String:callerScript.c_str()]
stringByDeletingLastPathComponent];
NSString* candidate = [[callerDir
stringByAppendingPathComponent:[NSString stringWithUTF8String:workerPath.c_str()]]
stringByStandardizingPath];
if (tns::Exists([candidate fileSystemRepresentation]) ||
tns::Exists(
[[candidate stringByAppendingPathExtension:@"js"] fileSystemRepresentation]) ||
tns::Exists([[candidate stringByAppendingPathComponent:@"index.js"]
fileSystemRepresentation])) {
workerPath = [candidate UTF8String];
}
}
}
Expand Down
Loading
Loading