diff --git a/.gitmodules b/.gitmodules index 0170f4ed0..17e552aff 100644 --- a/.gitmodules +++ b/.gitmodules @@ -2,3 +2,6 @@ path = TestRunner/app/shared url = https://github.com/NativeScript/common-runtime-tests-app.git branch = master +[submodule "NativeScript/runtime-common"] + path = NativeScript/runtime-common + url = https://github.com/NativeScript/runtime-common.git diff --git a/NativeScript/NativeScript.mm b/NativeScript/NativeScript.mm index a660a6b64..3c5834f6b 100644 --- a/NativeScript/NativeScript.mm +++ b/NativeScript/NativeScript.mm @@ -7,7 +7,6 @@ #include "runtime/Console.h" #include "runtime/Helpers.h" #include "runtime/ModuleInternal.h" -#include "runtime/ModuleInternalCallbacks.h" #include "runtime/NativeScriptException.h" #include "runtime/Runtime.h" #include "runtime/RuntimeConfig.h" @@ -129,87 +128,10 @@ static void DestroyMainRuntime() { - (void)runMainApplication { runtime_->RunMainScript(); + // Outside the Locker: for a UI app this calls UIApplicationMain, which never + // returns. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, true); tns::Tasks::Drain(); - - // Async boot handoff. For UI apps Tasks::Drain() invokes UIApplicationMain - // and never returns — the app's main runloop services whatever is still in - // flight. When Drain returns, the entry has not reached UIApplicationMain, - // so pump a manual runloop until boot actually finishes, Node-like. A - // completion may itself register the UIApplicationMain task, so drain after - // each slice; if that drain calls UIApplicationMain it takes over and never - // returns. - // - // Two independent things can leave boot unfinished, and BOTH must hold the - // pump: an in-flight module-graph load, and an entry whose own evaluation - // promise is still pending — a top-level await parked on anything at all - // (a nested import() that does its own async work, a native init that will - // call UIApplicationMain later). Gating on graph work alone let the second - // case reach counter == 0 and fall off the end of main(). - std::string entryRejectionReason; - bool entryPending = runtime_->PollMainEntryEvaluation(&entryRejectionReason) == - tns::EntryEvaluationState::kPending; - bool entryRejected = false; - - if (entryPending || tns::HasPendingAsyncModuleGraphWork()) { - const CFAbsoluteTime deadline = - CFAbsoluteTimeGetCurrent() + 2 * tns::kModuleEvaluateDeadlineSeconds; - bool terminated = false; - for (;;) { - // Termination outranks everything, including an entry that settled in the - // same slice: boot must report the terminating fatal rather than take the - // normal exit and carry on into an app on a stopping isolate. Nothing - // pending can complete after this point either. Both signals: V8 reports - // only a materialized termination, which needs JS to run, and an entry - // parked on a promise nothing settles never runs any. - if (runtime_->IsExecutionTerminating() || runtime_->IsTerminationRequested()) { - terminated = true; - break; - } - if (!(entryPending || tns::HasPendingAsyncModuleGraphWork())) { - break; - } - if (CFAbsoluteTimeGetCurrent() >= deadline) { - break; - } - CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.01, true); - tns::Tasks::Drain(); - - if (entryPending) { - tns::EntryEvaluationState state = runtime_->PollMainEntryEvaluation(&entryRejectionReason); - // Once it settles, stop probing for good. - entryPending = state == tns::EntryEvaluationState::kPending; - if (state == tns::EntryEvaluationState::kRejected) { - entryRejected = true; - break; - } - } - } - tns::Tasks::Drain(); - - // A settled entry that never called UIApplicationMain is a script-style app - // finishing normally. The failures below are fatal in every build: each one - // evicts the entry first, so nothing can later import the half-evaluated - // module the failure left behind, and then throws rather than logging and - // returning into an app whose entry never ran. - std::string fatal; - if (terminated) { - fatal = "boot ended with execution terminating before the main entry settled"; - } else if (entryRejected) { - fatal = "the main entry module's evaluation rejected during boot: " + entryRejectionReason; - } else if (entryPending) { - char within[64]; - snprintf(within, sizeof(within), "%.0fs", 2 * tns::kModuleEvaluateDeadlineSeconds); - fatal = std::string("main entry never settled and UIApplicationMain was never reached " - "within ") + - within; - } - if (!fatal.empty()) { - runtime_->EvictMainEntry(); - Log(@"Fatal: %s", fatal.c_str()); - throw tns::NativeScriptException("Fatal: " + fatal); - } - } } - (bool)liveSync { @@ -246,11 +168,12 @@ - (instancetype)initializeWithConfig:(Config*)config { Runtime::Initialize(); StartStdioForwarding(); DestroyMainRuntime(); + RefreshLoaderConfig(); std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now(); runtime_ = new Runtime(); Isolate* isolate = runtime_->GetIsolate(); v8::Locker l(isolate); - runtime_->Init(); + runtime_->Init(nativescript::common::platform::LoaderSnapshot()); std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast(t2 - t1).count(); printf("Runtime initialization took %llims (version %s, V8 version %s)\n", duration, diff --git a/NativeScript/inspector/JsV8InspectorClient.h b/NativeScript/inspector/JsV8InspectorClient.h index fd4de2ca3..9090c803d 100644 --- a/NativeScript/inspector/JsV8InspectorClient.h +++ b/NativeScript/inspector/JsV8InspectorClient.h @@ -105,6 +105,9 @@ class JsV8InspectorClient : V8InspectorClient { tns::Runtime* runtime_; v8::Isolate* isolate_; tns::IsolateWrapper isolateWrapper_; + // The main isolate's loader configuration, for the threads that read file + // URLs without its Locker. + std::shared_ptr loaderConfig_; // The runtime's loop. Outlives the runtime, after which it drops posts. std::shared_ptr eventLoop_; // Work for the main isolate. Connect and disconnect go through the same diff --git a/NativeScript/inspector/JsV8InspectorClient.mm b/NativeScript/inspector/JsV8InspectorClient.mm index cd433198a..e509abb3c 100644 --- a/NativeScript/inspector/JsV8InspectorClient.mm +++ b/NativeScript/inspector/JsV8InspectorClient.mm @@ -12,6 +12,9 @@ #include "src/inspector/v8-runtime-agent-impl.h" #include "src/inspector/v8-stack-trace-impl.h" +#include "ns/JsError.h" +#include "ns/loader/LoaderState.h" + #include "Caches.h" #include "Helpers.h" #include "HttpLoader.h" @@ -69,7 +72,8 @@ bool ShouldRewriteSourceMapURLs() { // Debugger.scriptFailedToParse events from a file url (or a url relative to // the script's file url) to an absolute nsruntime:// url, so DevTools // requests the map through the target instead of the frontend host. -std::string MaybeRewriteSourceMapURL(const std::string& message) { +std::string MaybeRewriteSourceMapURL(const std::string& message, + const nativescript::common::LoaderConfig& config) { if (!ShouldRewriteSourceMapURLs()) { return message; } @@ -92,35 +96,32 @@ bool ShouldRewriteSourceMapURLs() { return message; } - std::string path; + std::optional path; if (sourceMapURL.rfind("file://", 0) == 0) { - path = tns::FileModulePath(sourceMapURL); + path = tns::OriginToPath(sourceMapURL, config); } else if (sourceMapURL[0] == '/') { - path = sourceMapURL; + path = tns::OriginToPath("file://" + sourceMapURL, config); } else { // Relative to the script url, e.g. "bundle.js.map". - std::string scriptUrl = params.value("url", ""); - if (scriptUrl.rfind("file://", 0) != 0) { - return message; - } - @autoreleasepool { - NSString* scriptPath = [NSString stringWithUTF8String:tns::FileModulePath(scriptUrl).c_str()]; - NSString* mapPath = [NSString stringWithUTF8String:sourceMapURL.c_str()]; - if (scriptPath != nil && mapPath != nil) { - NSString* resolved = [[[scriptPath stringByDeletingLastPathComponent] - stringByAppendingPathComponent:mapPath] stringByStandardizingPath]; - if (resolved != nil) { - path = [resolved UTF8String]; - } - } + const std::optional scriptPath = + tns::OriginToPath(params.value("url", ""), config); + if (scriptPath) { + path = tns::CanonicalFilePath( + scriptPath->substr(0, scriptPath->rfind('/') + 1) + sourceMapURL, config); } } - if (path.empty()) { + if (!path || path->empty()) { return message; } - params["sourceMapURL"] = kSourceMapScheme + path; + // Spelled as the script's own origin is (file:///app/... for an app file), + // which does not change between installs. + const std::string origin = tns::ReportedModuleUrl(*path, config); + if (origin.rfind("file://", 0) != 0) { + return message; + } + params["sourceMapURL"] = kSourceMapScheme + origin.substr(strlen("file://")); return parsed.dump(); } @@ -240,6 +241,7 @@ bool GetInt32(const json& value, long long& out) { : runtime_(runtime), isolate_(runtime_->GetIsolate()), isolateWrapper_(isolate_), + loaderConfig_(nativescript::common::loader::CaptureLoaderConfig(isolate_)), eventLoop_(runtime_->GetEventLoop()) { instance_ = this; } @@ -433,7 +435,7 @@ bool GetInt32(const json& value, long long& out) { } // Its Network.setCacheDisabled lasts only as long as the connection. - tns::SetModuleHttpCacheDisabledByInspector(connectionId, false); + tns::SetModuleHttpCacheDisabledBy(connectionId, false); // Free the process-global trace controller for other frontends. { @@ -520,15 +522,23 @@ bool GetInt32(const json& value, long long& out) { // DispatchFrontendMessage answers it when there is none. Worker sessions // have no JS domain handlers, so they are answered here. A sessionId that // names no worker of this frontend changes nothing and is left to - // RouteToWorker's "Session not found". + // RouteToWorker's "Session not found". A clear that failed is answered here + // for every session, since the domain handler cannot tell. if ((method == "Network.setCacheDisabled" || method == "Network.clearBrowserCache") && (sessionId.empty() || this->HasWorkerSession(connectionId, sessionId))) { const std::optional cacheDisabled = SetCacheDisabledParam(parsed); const bool valid = method == "Network.clearBrowserCache" || cacheDisabled.has_value(); if (method == "Network.clearBrowserCache") { - tns::ClearModuleHttpCache(); + const tns::CacheOpResult cleared = tns::ClearModuleHttpCache(); + if (!cleared.ok) { + if (msgId >= 0) { + json error = {{"id", msgId}, {"error", {{"code", -32000}, {"message", cleared.error}}}}; + this->SendRawToConnection(connectionId, WithSessionId(error, sessionId).dump()); + } + return; + } } else if (valid) { - tns::SetModuleHttpCacheDisabledByInspector(connectionId, *cacheDisabled); + tns::SetModuleHttpCacheDisabledBy(connectionId, *cacheDisabled); } if (!sessionId.empty()) { if (msgId >= 0) { @@ -844,7 +854,7 @@ bool GetInt32(const json& value, long long& out) { } void JsV8InspectorClient::SendToConnection(uint64_t connectionId, const std::string& message) { - this->SendRawToConnection(connectionId, MaybeRewriteSourceMapURL(message)); + this->SendRawToConnection(connectionId, MaybeRewriteSourceMapURL(message, *loaderConfig_)); } void JsV8InspectorClient::SendRawToConnection(uint64_t connectionId, const std::string& message) { @@ -1240,11 +1250,21 @@ bool GetInt32(const json& value, long long& out) { void JsV8InspectorClient::HandleLoadNetworkResource(uint64_t connectionId, int msgId, const std::string& url, const std::string& sessionId) { - std::string path; - if (url.rfind(kSourceMapScheme, 0) == 0) { - path = url.substr(strlen(kSourceMapScheme)); - } else if (url.rfind("file://", 0) == 0) { - path = tns::FileModulePath(url); + // DevTools percent-encodes the URLs it requests, while a legacy origin, and + // a source map URL rewritten from one, spell their path verbatim: try both + // readings. + std::vector candidates; + const bool sourceMap = url.rfind(kSourceMapScheme, 0) == 0; + if (sourceMap || url.rfind("file://", 0) == 0) { + const std::string fileUrl = sourceMap ? "file://" + url.substr(strlen(kSourceMapScheme)) : url; + std::optional verbatim = tns::OriginToPath(fileUrl, *loaderConfig_); + if (verbatim) { + candidates.push_back(*verbatim); + } + std::optional decoded = tns::FileUrlToPath(fileUrl, *loaderConfig_); + if (decoded && (!verbatim || *decoded != *verbatim)) { + candidates.push_back(*decoded); + } } else { // Reply with a protocol error (not success:false) so DevTools falls back // to loading the resource from the frontend host, which is the @@ -1257,35 +1277,18 @@ bool GetInt32(const json& value, long long& out) { std::string content; bool loaded = false; - - if (!path.empty()) { + for (const std::string& candidate : candidates) { @autoreleasepool { - NSString* urlPath = [NSString stringWithUTF8String:path.c_str()]; - if (urlPath != nil) { - // Script urls are built by stripping RuntimeConfig.BaseDir (see - // ModuleInternal::LoadClassicScript), so map the url path back to - // disk; fall back to the raw path for absolute urls, and to - // percent-decoded variants for urls the frontend encoded. - NSString* basePath = [NSString stringWithUTF8String:RuntimeConfig.BaseDir.c_str()]; - NSMutableArray* candidates = [NSMutableArray new]; - [candidates addObject:[basePath stringByAppendingPathComponent:urlPath]]; - [candidates addObject:urlPath]; - NSString* decoded = [urlPath stringByRemovingPercentEncoding]; - if (decoded != nil && ![decoded isEqualToString:urlPath]) { - [candidates addObject:[basePath stringByAppendingPathComponent:decoded]]; - [candidates addObject:decoded]; - } - - for (NSString* candidate in candidates) { - NSData* data = [NSData dataWithContentsOfFile:candidate]; - if (data != nil) { - content.assign(static_cast(data.bytes), data.length); - loaded = true; - break; - } - } + NSData* data = + [NSData dataWithContentsOfFile:[NSString stringWithUTF8String:candidate.c_str()]]; + if (data != nil) { + content.assign(static_cast(data.bytes), data.length); + loaded = true; } } + if (loaded) { + break; + } } json resource; @@ -1508,6 +1511,18 @@ bool GetInt32(const json& value, long long& out) { } } +// Inspector modules are optional tooling: a top-level await that rejects +// after registerModules returned is logged, like a failure before it. +static void InspectorModulesRejected(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + if (isolate->IsExecutionTerminating()) { + return; + } + TryCatch tc(isolate); + std::string reason = info.Length() > 0 ? tns::ToString(isolate, info[0]) : std::string(); + Log(@"Inspector modules failed to load: %s", reason.c_str()); +} + void JsV8InspectorClient::registerModules() { Isolate* isolate = isolate_; Local context = isolate->GetEnteredOrMicrotaskContext(); @@ -1554,11 +1569,19 @@ bool GetInt32(const json& value, long long& out) { } try { - runtime_->RunModule(modulePath); + Local pendingEntry; + Local onRejected; + if (runtime_->RunModule(modulePath).ToLocal(&pendingEntry) && + v8::Function::New(context, InspectorModulesRejected).ToLocal(&onRejected)) { + std::ignore = pendingEntry->Catch(context, onRejected); + } } catch (tns::NativeScriptException& ex) { // Inspector modules are optional tooling; a failure must not take the // app down, but it must be visible. Log(@"Inspector modules failed to load: %s", ex.getMessage().c_str()); + } catch (nativescript::common::JsError& ex) { + Log(@"Inspector modules failed to load: %s", ex.what()); + } catch (nativescript::common::Terminated&) { } // FIXME: This triggers some DCHECK failures, due to the entered v8::Context in // Runtime::init(). diff --git a/NativeScript/runtime-common b/NativeScript/runtime-common new file mode 160000 index 000000000..8c4e81dc4 --- /dev/null +++ b/NativeScript/runtime-common @@ -0,0 +1 @@ +Subproject commit 8c4e81dc443c3cc8a07a07061457f67591174c0e diff --git a/NativeScript/runtime/Base64.cpp b/NativeScript/runtime/Base64.cpp index 221ba91d2..0b13794d8 100644 --- a/NativeScript/runtime/Base64.cpp +++ b/NativeScript/runtime/Base64.cpp @@ -1,9 +1,8 @@ #include "Base64.h" -#include - #include "BuiltinLoader.h" #include "Helpers.h" +#include "ns/Base64Binding.h" using namespace v8; @@ -11,168 +10,13 @@ namespace tns { namespace { -constexpr char kAlphabet[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -// 6-bit value per ASCII byte; 0xFF marks everything outside the alphabet. -constexpr uint8_t kInvalid = 0xFF; - -uint8_t SixBits(uint8_t c) { - if (c >= 'A' && c <= 'Z') { - return static_cast(c - 'A'); - } - if (c >= 'a' && c <= 'z') { - return static_cast(c - 'a' + 26); - } - if (c >= '0' && c <= '9') { - return static_cast(c - '0' + 52); - } - if (c == '+') { - return 62; - } - if (c == '/') { - return 63; - } - return kInvalid; -} - -bool IsAsciiWhitespace(uint8_t c) { - return c == '\t' || c == '\n' || c == '\f' || c == '\r' || c == ' '; -} - -// The string's code units as bytes. Fails when any unit is above U+00FF, -// which neither op can represent. -bool GetLatin1Bytes(Isolate* isolate, Local value, - std::vector* out) { - if (!value->IsString()) { - return false; - } - Local str = value.As(); - if (!str->ContainsOnlyOneByte()) { - return false; - } - const int length = str->Length(); - out->resize(static_cast(length)); - if (length > 0) { - str->WriteOneByteV2(isolate, 0, static_cast(length), out->data()); - } - return true; -} - -// btoa: base64-encode the input's code units. -void BtoaCallback(const FunctionCallbackInfo& info) { - Isolate* isolate = info.GetIsolate(); - std::vector input; - if (!GetLatin1Bytes(isolate, info[0], &input)) { - info.GetReturnValue().SetNull(); - return; - } - - std::vector out; - out.reserve((input.size() + 2) / 3 * 4); - size_t i = 0; - for (; i + 3 <= input.size(); i += 3) { - const uint32_t group = (static_cast(input[i]) << 16) | - (static_cast(input[i + 1]) << 8) | - input[i + 2]; - out.push_back(kAlphabet[(group >> 18) & 0x3F]); - out.push_back(kAlphabet[(group >> 12) & 0x3F]); - out.push_back(kAlphabet[(group >> 6) & 0x3F]); - out.push_back(kAlphabet[group & 0x3F]); - } - const size_t remaining = input.size() - i; - if (remaining == 1) { - const uint32_t group = static_cast(input[i]) << 16; - out.push_back(kAlphabet[(group >> 18) & 0x3F]); - out.push_back(kAlphabet[(group >> 12) & 0x3F]); - out.push_back('='); - out.push_back('='); - } else if (remaining == 2) { - const uint32_t group = (static_cast(input[i]) << 16) | - (static_cast(input[i + 1]) << 8); - out.push_back(kAlphabet[(group >> 18) & 0x3F]); - out.push_back(kAlphabet[(group >> 12) & 0x3F]); - out.push_back(kAlphabet[(group >> 6) & 0x3F]); - out.push_back('='); - } - - if (out.empty()) { - info.GetReturnValue().Set(v8::String::Empty(isolate)); - return; - } - Local result; - if (v8::String::NewFromOneByte(isolate, out.data(), NewStringType::kNormal, - static_cast(out.size())) - .ToLocal(&result)) { - info.GetReturnValue().Set(result); - } -} - -// atob: forgiving-base64 decode -// (https://infra.spec.whatwg.org/#forgiving-base64-decode). -void AtobCallback(const FunctionCallbackInfo& info) { - Isolate* isolate = info.GetIsolate(); - std::vector raw; - if (!GetLatin1Bytes(isolate, info[0], &raw)) { - info.GetReturnValue().SetNull(); - return; - } - - std::vector data; - data.reserve(raw.size()); - for (uint8_t c : raw) { - if (!IsAsciiWhitespace(c)) { - data.push_back(c); - } - } - - if (data.size() % 4 == 0) { - size_t strip = 0; - while (strip < 2 && !data.empty() && data.back() == '=') { - data.pop_back(); - strip++; - } - } - if (data.size() % 4 == 1) { - info.GetReturnValue().SetNull(); - return; - } - - std::vector out; - out.reserve(data.size() / 4 * 3 + 2); - uint32_t accumulator = 0; - uint32_t bits = 0; - for (uint8_t c : data) { - const uint8_t value = SixBits(c); - if (value == kInvalid) { - info.GetReturnValue().SetNull(); - return; - } - accumulator = (accumulator << 6) | value; - bits += 6; - if (bits >= 8) { - bits -= 8; - out.push_back(static_cast((accumulator >> bits) & 0xFF)); - } - } - - if (out.empty()) { - info.GetReturnValue().Set(v8::String::Empty(isolate)); - return; - } - Local result; - if (v8::String::NewFromOneByte(isolate, out.data(), NewStringType::kNormal, - static_cast(out.size())) - .ToLocal(&result)) { - info.GetReturnValue().Set(result); - } -} - MaybeLocal CreateBinding(Local context) { Isolate* isolate = v8::Isolate::GetCurrent(); Local binding = Object::New(isolate); - tns::SetMethodNoSideEffect(context, binding, "btoa", BtoaCallback); - tns::SetMethodNoSideEffect(context, binding, "atob", AtobCallback); + tns::SetMethodNoSideEffect(context, binding, "btoa", + nativescript::common::base64::Btoa); + tns::SetMethodNoSideEffect(context, binding, "atob", + nativescript::common::base64::Atob); return binding; } diff --git a/NativeScript/runtime/EventLoop.h b/NativeScript/runtime/EventLoop.h index fc36a0264..39a1e9851 100644 --- a/NativeScript/runtime/EventLoop.h +++ b/NativeScript/runtime/EventLoop.h @@ -3,6 +3,8 @@ #include +#include +#include #include #include #include @@ -13,6 +15,7 @@ #include #include "Common.h" +#include "ns/Loop.h" #include "v8-platform.h" // 1: JS timers keep exact fire-date order with foreign runloop timers at the @@ -98,11 +101,11 @@ class OrderedTaskSource { * sibling, possibly on this loop), so Shutdown moves the lanes out and lets * them die after the unlock. */ -class EventLoop { +class EventLoop : public nativescript::common::Loop { public: explicit EventLoop(v8::Isolate* isolate) : isolate_(isolate) {} - ~EventLoop(); + ~EventLoop() override; /** * Attaches both lanes to the calling thread's CFRunLoop and flushes work @@ -153,8 +156,8 @@ class EventLoop { // internal lane: runs on the home thread as soon as the runloop polls. // Returns false if the post was dropped (loop already shut down). - bool PostInternal(std::function fn); - bool PostInternalDelayed(std::function fn, double delayMs); + bool PostInternal(std::function fn) override; + bool PostInternalDelayed(std::function fn, double delayMs) override; /** * Internal-lane post whose fn does its OWN isolate ceremony: RunEntry skips @@ -168,16 +171,17 @@ class EventLoop { /** * Posts a v8 foreground task into the internal lane. Called by the - * platform's per-isolate v8::TaskRunner adapter, from any thread. + * platform's per-isolate v8::TaskRunner adapter, from any thread. False + * when the loop has stopped and dropped the task. */ - void PostV8Task(std::unique_ptr task, bool nestable, - double delaySeconds); + bool PostV8Task(std::unique_ptr task, bool nestable, + double delaySeconds) override; /** * True once Shutdown ran. A stopped loop found in the platform registry for * a (reused) isolate pointer is stale and must be replaced. */ - bool IsStopped(); + bool IsStopped() override; /** * Runs the internal-lane v8 tasks that are due and nestable, bounded to the @@ -186,7 +190,30 @@ class EventLoop { * tasks and plain function posts stay queued and run from their own wakeups * after the loop unwinds. */ - void RunNestableV8Tasks(); + void RunNestableV8Tasks() override; + + /** + * See nativescript::common::Loop::PumpUntil. A kPlatformWork slice is a + * default-mode CFRunLoop slice, so it also runs non-nestable tasks, bare + * posts, ordered entries and JS timers. + */ + nativescript::common::PumpResult PumpUntil( + const nativescript::common::Deadline& deadline, + const std::function& settled, nativescript::common::PumpMode mode, + const std::function& idle = nullptr) override; + + /** + * Records that termination was requested for this loop's isolate. Called on + * the requesting thread before TerminateExecution: V8 reports a termination + * only once running JS materializes it, and a pump parked on a promise + * nothing settles runs none, so without the flag it would spend its whole + * deadline. One-way: a worker never un-terminates. + */ + void RequestTermination(); + bool TerminationRequested() const override; + + // False until BindToCurrentThread has run. + bool IsOnHomeThread() const override; /** * Runs at most one due ordered-lane item (an entry, a timer, or a @@ -271,6 +298,9 @@ class EventLoop { CFRunLoopSourceRef internalSource_ = nullptr; CFRunLoopTimerRef internalTimer_ = nullptr; bool stopped_ = false; + std::atomic terminationRequested_{false}; + // pthread_threadid_np of the bound thread; 0 while unbound + std::atomic homeThreadId_{0}; }; } // namespace tns diff --git a/NativeScript/runtime/EventLoop.mm b/NativeScript/runtime/EventLoop.mm index b1f67a595..7e327c44d 100644 --- a/NativeScript/runtime/EventLoop.mm +++ b/NativeScript/runtime/EventLoop.mm @@ -1,5 +1,10 @@ #include "EventLoop.h" +#include "ns/JsError.h" + +#include +#include + #include #include #include @@ -11,6 +16,9 @@ #include "NativeScriptException.h" using namespace v8; +using nativescript::common::Deadline; +using nativescript::common::PumpMode; +using nativescript::common::PumpResult; namespace { @@ -29,6 +37,10 @@ void RunGuarded(F&& body) { } catch (tns::NativeScriptException& ex) { Log(@"NativeScript: uncaught NativeScriptException in event loop task: %s", ex.getMessage().c_str()); + } catch (nativescript::common::JsError& ex) { + Log(@"NativeScript: uncaught error in event loop task: %s", ex.what()); + } catch (nativescript::common::Terminated&) { + // the isolate is terminating; there is nothing left to report to } catch (std::exception& ex) { Log(@"NativeScript: c++ exception in event loop task: %s", ex.what()); } @@ -97,6 +109,9 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { } loop_ = CFRunLoopGetCurrent(); + uint64_t threadId = 0; + pthread_threadid_np(nullptr, &threadId); + homeThreadId_.store(threadId, std::memory_order_release); CFRunLoopSourceContext sourceContext = { 0, this, nullptr, nullptr, nullptr, @@ -355,12 +370,13 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { timerSource_ = source; } -void EventLoop::PostV8Task(std::unique_ptr task, bool nestable, double delaySeconds) { +bool EventLoop::PostV8Task(std::unique_ptr task, bool nestable, double delaySeconds) { std::lock_guard lock(mutex_); if (stopped_) { - return; + return false; } PostInternalLocked(Entry{std::move(task), nullptr, nestable, false, 0}, delaySeconds * 1000.0); + return true; } bool EventLoop::IsStopped() { @@ -521,6 +537,85 @@ static CFAbsoluteTime FireDateFor(double dueMs, double nowMs) { } } +PumpResult EventLoop::PumpUntil(const Deadline& deadline, const std::function& settled, + PumpMode mode, const std::function& idle) { + // Short, so a completion posted during a wait is picked up promptly. The + // kV8Tasks wait must stay within the 10 ms Loop.h allows. + constexpr int kNestableOnlyIdleMs = 2; + constexpr useconds_t kV8TasksIdleMicros = 1000; + constexpr CFTimeInterval kPlatformSliceSeconds = 0.01; + + for (;;) { + if (TerminationRequested() || isolate_->IsExecutionTerminating() || IsStopped()) { + return PumpResult::kTerminated; + } + if (settled()) { + return PumpResult::kSettled; + } + if (nativescript::common::DeadlinePassed(deadline)) { + return PumpResult::kDeadline; + } + + switch (mode) { + case PumpMode::kNestableOnly: { + { + v8::Isolate::SuppressMicrotaskExecutionScope noMicrotasks(isolate_); + RunNestableV8Tasks(); + } + if (settled()) { + // back to the head, where termination outranks this settlement + continue; + } + if (idle != nullptr) { + idle(kNestableOnlyIdleMs); + } else { + usleep(kNestableOnlyIdleMs * 1000); + } + break; + } + case PumpMode::kV8Tasks: { + RunNestableV8Tasks(); + isolate_->PerformMicrotaskCheckpoint(); + if (settled()) { + continue; + } + usleep(kV8TasksIdleMicros); + break; + } + case PumpMode::kPlatformWork: { + RunNestableV8Tasks(); + isolate_->PerformMicrotaskCheckpoint(); + if (settled()) { + continue; + } + @autoreleasepool { + CFRunLoopRunInMode(kCFRunLoopDefaultMode, kPlatformSliceSeconds, true); + } + isolate_->PerformMicrotaskCheckpoint(); + break; + } + } + } +} + +void EventLoop::RequestTermination() { + terminationRequested_.store(true, std::memory_order_relaxed); +} + +bool EventLoop::TerminationRequested() const { + return terminationRequested_.load(std::memory_order_relaxed); +} + +bool EventLoop::IsOnHomeThread() const { + const uint64_t home = homeThreadId_.load(std::memory_order_acquire); + if (home == 0) { + return false; + } + uint64_t self = 0; + pthread_threadid_np(nullptr, &self); + return self == home; +} + void EventLoop::RunOrderedTask() { // one anonymous token = one due slot across the whole ordered domain: pick // the earliest due item among the ordered entries and the timer source, diff --git a/NativeScript/runtime/Helpers.h b/NativeScript/runtime/Helpers.h index 64ba155b1..3d6ae3cd9 100644 --- a/NativeScript/runtime/Helpers.h +++ b/NativeScript/runtime/Helpers.h @@ -265,16 +265,7 @@ inline bool ToBool(const v8::Local& value) { return result; } bool Exists(const char* fullPath); -v8::Local ReadModule(v8::Isolate* isolate, const std::string& filePath); std::string ReadText(const std::string& file); -// The whole file in a heap buffer the caller owns (delete[]); nullptr and a -// zero length when it cannot be read. -uint8_t* ReadBinary(const std::string& path, long& length); -// Replaces the file at `path` atomically: readers see the old contents or the -// new ones, never a partial write. A non-negative `modificationTime` stamps the -// file's mtime before it is published. -bool WriteBinary(const std::string& path, const void* data, long length, - time_t modificationTime = -1); void SetPrivateValue(const v8::Local& obj, const v8::Local& propName, const v8::Local& value); diff --git a/NativeScript/runtime/Helpers.mm b/NativeScript/runtime/Helpers.mm index e385cba67..e65ebd56b 100644 --- a/NativeScript/runtime/Helpers.mm +++ b/NativeScript/runtime/Helpers.mm @@ -69,52 +69,8 @@ return false; } -Local tns::ReadModule(Isolate* isolate, const std::string& filePath) { - static constexpr char prefix[] = "(function(module, exports, require, __filename, __dirname) { "; - static constexpr char suffix[] = "\n})"; - constexpr size_t prefixLength = sizeof(prefix) - 1; - constexpr size_t suffixLength = sizeof(suffix) - 1; - - int file = open(filePath.c_str(), O_RDONLY); - if (file < 0) { - throw NativeScriptException(isolate, "Cannot read module " + filePath); - } - - struct stat finfo; - if (fstat(file, &finfo) != 0) { - close(file); - throw NativeScriptException(isolate, "Cannot read module " + filePath); - } - size_t length = finfo.st_size; - - size_t sourceLength = prefixLength + length + suffixLength; - std::unique_ptr source(new char[sourceLength]); - memcpy(source.get(), prefix, prefixLength); - char* body = source.get() + prefixLength; - size_t bytesRead = 0; - while (bytesRead < length) { - ssize_t n = read(file, body + bytesRead, length - bytesRead); - if (n < 0 && errno == EINTR) { - continue; - } - if (n <= 0) { - break; - } - bytesRead += n; - } - close(file); - if (bytesRead != length) { - throw NativeScriptException(isolate, "Cannot read module " + filePath); - } - memcpy(body + length, suffix, suffixLength); - - return v8::String::NewFromUtf8(isolate, source.get(), NewStringType::kNormal, (int)sourceLength) - .ToLocalChecked(); -} - -// The file readers below run on the main thread and on every worker's thread -// at once (workers load shared modules and their code caches while starting), -// so each call reads into storage of its own; no scratch buffer is shared. +// Runs on the main thread and on every worker's thread at once, so each call +// reads into storage of its own; no scratch buffer is shared. std::string tns::ReadText(const std::string& filePath) { FILE* file = fopen(filePath.c_str(), "rb"); @@ -137,84 +93,6 @@ return result; } -uint8_t* tns::ReadBinary(const std::string& path, long& length) { - length = 0; - FILE* file = fopen(path.c_str(), "rb"); - if (!file) { - return nullptr; - } - - fseek(file, 0, SEEK_END); - long fileLength = ftell(file); - rewind(file); - if (fileLength <= 0) { - fclose(file); - return nullptr; - } - - uint8_t* data = new uint8_t[fileLength]; - size_t readBytes = fread(data, sizeof(uint8_t), fileLength, file); - fclose(file); - if (readBytes != static_cast(fileLength)) { - delete[] data; - return nullptr; - } - - length = fileLength; - return data; -} - -bool tns::WriteBinary(const std::string& path, const void* data, long length, - time_t modificationTime) { - // Written to a private temp file in the same directory, then renamed over the - // target: rename is atomic on the local file system, so a concurrent reader - // of `path` never observes a truncated or half-written file, and two writers - // racing on the same path leave whichever complete file landed last. - std::string tmpTemplate = path + ".XXXXXX"; - std::vector tmpPath(tmpTemplate.begin(), tmpTemplate.end()); - tmpPath.push_back('\0'); - int fd = mkstemp(tmpPath.data()); - if (fd < 0) { - return false; - } - - bool ok = true; - const uint8_t* cursor = static_cast(data); - long remaining = length; - while (remaining > 0) { - ssize_t written = write(fd, cursor, remaining); - if (written < 0) { - if (errno == EINTR) { - continue; - } - ok = false; - break; - } - cursor += written; - remaining -= written; - } - - if (ok && modificationTime >= 0) { - struct timespec times[2]; - times[0].tv_sec = time(nullptr); - times[0].tv_nsec = 0; - times[1].tv_sec = modificationTime; - times[1].tv_nsec = 0; - ok = futimens(fd, times) == 0; - } - - close(fd); - - if (ok && rename(tmpPath.data(), path.c_str()) != 0) { - ok = false; - } - if (!ok) { - unlink(tmpPath.data()); - } - - return ok; -} - Local tns::UnwrapProxyOrThrow(Isolate* isolate, Local value) { if (value.IsEmpty() || !value->IsProxy()) { return value; diff --git a/NativeScript/runtime/HttpLoader.h b/NativeScript/runtime/HttpLoader.h index 666765e8b..96e97bb31 100644 --- a/NativeScript/runtime/HttpLoader.h +++ b/NativeScript/runtime/HttpLoader.h @@ -1,176 +1,54 @@ #pragma once -#include -#include +#include #include #include -namespace tns { - -// HttpLoader: the native half of the NativeScript HTTP module-loader -// contract. -// -// The runtime deliberately exposes *mechanism* only: -// - the synchronous HTTP text fetch backing the HTTP ESM loader's -// fallback path (V8's ResolveModuleCallback is synchronous — still -// true as of 14.9.207.39 — so the fallback must be native), -// - the async NSURLSession fetch behind the phase-1 module-graph walk -// (StartModuleGraphLoad), which is how module bodies -// normally arrive, -// - the boot-evaluation flag that arms the cold-boot runloop pump only -// while an entry module is evaluating (derived by the runtime itself), -// - the remote-module security gate, seeded once from nativescript.config -// at boot and never exposed on ns:runtime getConfig/setConfig. +#include "ns/http/ModuleFetch.h" -// ───────────────────────────────────────────────────────────── -// HTTP loader helpers (used by dev/HMR and general-purpose HTTP module loading) +namespace tns { -// Canonicalization vocabulary (client-supplied policy). -// -// The canonical-key *mechanism* (fragment strip, cache-buster param drop, -// param sort) must be native because it keys the module registry inside -// V8's synchronous resolve walk. The *vocabulary* — which query params are -// pure cache busters, which path prefixes identify dev endpoints whose -// queries may be normalized, and which paths must keep their query verbatim -// because the query IS the identity — is server/framework policy, supplied -// by the dev client via -// ns:module `configureLoader({ canonicalization: {...} })` and consumed by -// `CanonicalizeHttpUrlKey`. It is per-isolate loader vocabulary — installed -// through SetCanonicalizationConfig in ModuleInternalCallbacks.h — so -// CanonicalizeHttpUrlKey runs on the isolate's own thread only. The transport -// never canonicalizes. +// The HTTP module loader: policy, fetch orchestration and the cache switch are +// the shared core's (ns/http/ModuleFetch.h); this runtime supplies the +// NSURLSession transport and the per-isolate canonicalization vocabulary. // -// When unconfigured, canonicalization is purely mechanical (fragment strip). -struct CanonicalizationConfig { - std::vector stripParams; // query param names to drop - std::vector devPathPrefixes; // StartsWith → normalize query - std::vector preserveQueryPrefixes; // contains → keep query -}; - -// Normalize an HTTP(S) URL into a stable module registry/cache key. -// - Always strips URL fragments. -// - For NativeScript dev endpoints, drops known cache busters (t/v/import) -// and sorts remaining query params for stability. -// - For non-dev/public URLs, preserves the full query string as part of the -// cache key. -// Module identity IS the (canonical) URL — the dev server serves every -// module under exactly one URL and never varies it for freshness. -std::string CanonicalizeHttpUrlKey(const std::string& url); - -// CanonicalizeHttpUrlKey for a URL already spelled by NormalizeHttpModuleUrl. +// V8's ResolveModuleCallback is synchronous (still true as of 14.9.207.39), so +// the fallback fetch HttpFetchModule has to block natively. Module bodies +// normally arrive through FetchModuleBodyAsync, driven by the module-graph walk +// (StartModuleGraphLoad in ns/loader/GraphLoad.h). + +using nativescript::common::http::CacheOpResult; +using nativescript::common::http::CanonicalizationConfig; +using nativescript::common::http::ClearModuleHttpCache; +using nativescript::common::http::FetchModuleBodyAsync; +using nativescript::common::http::HttpFetchModule; +using nativescript::common::http::IsRemoteModulesAllowed; +using nativescript::common::http::IsRemoteUrlAllowed; +using nativescript::common::http::ModuleFetchDeadline; +using nativescript::common::http::ModuleFetchResult; +using nativescript::common::http::ModuleHttpCacheEnabled; +using nativescript::common::http::ModuleResponseKind; +using nativescript::common::http::RemoteModuleAllowlist; +using nativescript::common::http::RemoteModuleAllowlistFromConfig; +using nativescript::common::http::RemoteUrlAllowedByAllowlist; +using nativescript::common::http::SetModuleHttpCacheDisabledBy; +using nativescript::common::http::SetModuleHttpCacheEnabled; + +// The module registry key of an HTTP(S) URL already spelled by +// NormalizeHttpModuleUrl, under the current isolate's vocabulary (ns:module +// `configureLoader({ canonicalization })`); without one only the fragment is +// stripped. Isolate thread only. std::string CanonicalizeNormalizedHttpUrlKey(const std::string& normalizedUrl); -// What a module response turned out to be. Decided once, by the shared -// classifier, for whichever transport produced the response. -enum class ModuleResponseKind { - kJavaScript, - kJson, -}; - -// The outcome of fetching one module over HTTP. Both transports produce this -// same verdict, so the synchronous fallback and the async graph walk cannot -// drift apart on what counts as a usable module. -struct ModuleFetchResult { - bool ok = false; - int status = 0; - ModuleResponseKind kind = ModuleResponseKind::kJavaScript; - // Normalized: an empty 2xx JavaScript body becomes the canonical empty - // module. Meaningful only when `ok`. - std::string body; - std::string contentType; // as received, parameters included - // Reader-facing explanation, non-empty exactly when `!ok`. This is the text - // that reaches the importer's rejection, so it names the URL and the cause. - std::string failureReason; -}; - -// Synchronous module fetch with one retry on transport error — the fallback -// path for anything the async module-graph walk missed. Blocks the calling -// thread, for at most a few seconds past the request timeout per attempt: a -// response that has not arrived by then fails the fetch. Uses the same HTTP -// cache as FetchModuleBodyAsync, through sessions (and so connections) of its -// own. Returns `result.ok`. -bool HttpFetchModule(const std::string& url, ModuleFetchResult& result); - -// Asynchronous single-URL module fetch — the I/O primitive behind the -// module-graph walk (see StartModuleGraphLoad in ModuleInternalCallbacks.h). -// Same response policy as HttpFetchModule, minus the JS-thread block: -// - security gate (IsRemoteUrlAllowed) checked up front, -// - an NSURLSession GET on a background queue with the same request shape -// as the sync path (no cookies, HTTP caching as the response headers -// allow) and one retry on transport error. -// `fetchDeadline` is the enclosing graph load's fetch budget as an absolute -// CFAbsoluteTime (double; 0 = unbounded): attempts clamp their request -// timeout to the time remaining and the transport-error retry is skipped -// once no budget is left, so a bounded fetch can never outlive the wait -// that is pumping for it. -// `completion(result)` is invoked exactly once, on an arbitrary thread — -// callers must hop to their JS thread before touching V8. -void FetchModuleBodyAsync( - const std::string& url, double fetchDeadline, - std::function completion); - -// ───────────────────────────────────────────────────────────── -// Remote-module security gate -// -// Seeded once from nativescript.config / package.json -// (`security.allowRemoteModules`, `security.remoteModuleAllowlist`) the first -// time a fetch is gated. Debug builds always allow. These values are not -// readable or writable through ns:runtime getConfig/setConfig — only -// nativescript.config at boot. - -// In debug mode (RuntimeConfig.IsDebug): always returns true. -// Otherwise returns the boot-time `security.allowRemoteModules` value. -bool IsRemoteModulesAllowed(); - -// Whether `url` may be fetched as a remote ES module. Debug builds always -// allow. Production requires allowRemoteModules, then an allowlist match -// (or all URLs if the allowlist is empty). -bool IsRemoteUrlAllowed(const std::string& url); - -// The allowlist IsRemoteUrlAllowed applies once remote modules are enabled. -struct RemoteModuleAllowlist { - // False only when `security.remoteModuleAllowlist` is absent, not an array, - // or an empty array: then every URL is allowed. - bool inForce = false; - // The usable items, each spelled the way the loader spells the URLs it - // fetches (NormalizeHttpModuleUrl) so path-scoped entries compare against - // resolved paths, or kept verbatim when it is not an http(s) URL. An item - // that is not a string, is empty or has no exact UTF-8 form is not here: it - // matches nothing but still keeps the list in force. - std::vector entries; -}; +// The NSURLSession transport, for platform::HttpTransport(). Process lifetime. +nativescript::common::http::ModuleTransport& ModuleHttpTransport(); #ifdef __OBJC__ -// The allowlist for the raw `security.remoteModuleAllowlist` config value. -RemoteModuleAllowlist RemoteModuleAllowlistFromConfig(id value); +// The raw `security.remoteModuleAllowlist` value as the core reads it: nullopt +// unless an NSArray; each item nullopt unless an NSString with an exact UTF-8 +// form. +std::optional>> +RemoteModuleAllowlistItems(id value); #endif -// Whether `url` (as fetched) passes `allowlist`: always when it is not in -// force, otherwise when one entry matches it by prefix with the match ending -// at a URL-component boundary. -bool RemoteUrlAllowedByAllowlist(const std::string& url, const RemoteModuleAllowlist& allowlist); - -// ───────────────────────────────────────────────────────────── -// Module HTTP cache controls -// -// Process-wide, shared by every isolate, callable from any thread. A fetch -// uses the cache when it is enabled and no inspector connection has it -// disabled; that is decided when the fetch is issued, so fetches in flight are -// unaffected. Disabled means nothing is read from or written to it. The launch -// arguments `--nativescript-no-module-cache` and -// `--nativescript-clear-module-cache` and the `moduleHttpCache` app config key -// are read once per process, before the first fetch. - -void SetModuleHttpCacheEnabled(bool enabled); - -// Records whether inspector connection `connectionId` has the cache disabled; -// false also forgets the connection. -void SetModuleHttpCacheDisabledByInspector(uint64_t connectionId, - bool disabled); - -// Empties the cache of every origin before returning, durably: a process -// killed right after the call does not find the old entries at its next -// launch. -void ClearModuleHttpCache(); - } // namespace tns diff --git a/NativeScript/runtime/HttpLoader.mm b/NativeScript/runtime/HttpLoader.mm index 638fb03fc..e548467b9 100644 --- a/NativeScript/runtime/HttpLoader.mm +++ b/NativeScript/runtime/HttpLoader.mm @@ -1,531 +1,58 @@ #include "HttpLoader.h" #import + #include #include -#include - -#include +#include +#include +#include +#include #include #include #include -#include #include +#include #include -#include "Caches.h" + #include "Helpers.h" -#include "ModuleInternal.h" -#include "ModuleInternalCallbacks.h" #include "ModuleUrl.h" -#include "Runtime.h" #include "RuntimeConfig.h" +#include "ns/http/ModuleTransport.h" +#include "ns/loader/LoaderState.h" namespace tns { -static inline bool StartsWith(const std::string& s, const char* prefix) { - size_t n = strlen(prefix); - return s.size() >= n && s.compare(0, n, prefix) == 0; -} - -// ───────────────────────────────────────────────────────────── -// Remote-module security gate -// -// Boot-time only: values come from nativescript.config / package.json -// (`security.allowRemoteModules`, `security.remoteModuleAllowlist`) and -// are never registered on ns:runtime getConfig/setConfig. - -static std::once_flag s_securityConfigInitFlag; -static bool s_allowRemoteModules = false; -static RemoteModuleAllowlist s_remoteModuleAllowlist; - -// Returns true when `url` is authorized by allowlist `entry`. -// -// This is intentionally stricter than a raw string-prefix test: after the -// matched entry text, the next character in `url` must be a URL-component -// boundary ('/', '?', or '#'), the URL must end exactly at the entry, or the -// entry must itself end in '/'. That refuses lookalike-host and lookalike-port -// bypasses — an entry of "https://cdn.example.com" must NOT authorize -// "https://cdn.example.com.attacker.com/x.js" or -// "https://cdn.example.com:9999/x.js". To allow a specific port, include it in -// the allowlist entry (deny-by-default for anything not explicitly listed). -static bool RemoteUrlMatchesAllowlistEntry(const std::string& url, const std::string& entry) { - if (entry.empty()) return false; - if (url.size() < entry.size()) return false; - if (url.compare(0, entry.size(), entry) != 0) return false; - if (url.size() == entry.size()) return true; // exact match - if (entry.back() == '/') return true; // entry ended at a boundary - const char next = url[entry.size()]; - return next == '/' || next == '?' || next == '#'; -} - -static std::string NormalizeRemoteModuleAllowlistEntry(const std::string& entry) { - const std::string url = NormalizeHttpModuleUrl(entry); - return url.empty() ? entry : url; -} - -RemoteModuleAllowlist RemoteModuleAllowlistFromConfig(id value) { - RemoteModuleAllowlist allowlist; - if (![value isKindOfClass:[NSArray class]] || [(NSArray*)value count] == 0) { - return allowlist; - } - allowlist.inForce = true; - for (id item in (NSArray*)value) { - if (![item isKindOfClass:[NSString class]]) { - continue; - } - const std::optional entry = ToExactUtf8((NSString*)item); - if (entry.has_value() && !entry->empty()) { - allowlist.entries.push_back(NormalizeRemoteModuleAllowlistEntry(*entry)); - } - } - return allowlist; -} - -bool RemoteUrlAllowedByAllowlist(const std::string& url, const RemoteModuleAllowlist& allowlist) { - if (!allowlist.inForce) { - return true; - } - for (const std::string& entry : allowlist.entries) { - if (RemoteUrlMatchesAllowlistEntry(url, entry)) { - return true; - } - } - return false; -} - -static void InitializeSecurityConfig() { - std::call_once(s_securityConfigInitFlag, []() { - @autoreleasepool { - id securityValue = Runtime::GetAppConfigValue("security"); - if (!securityValue || ![securityValue isKindOfClass:[NSDictionary class]]) { - return; - } - - NSDictionary* security = (NSDictionary*)securityValue; - - id allowRemote = security[@"allowRemoteModules"]; - if (allowRemote && [allowRemote respondsToSelector:@selector(boolValue)]) { - s_allowRemoteModules = [allowRemote boolValue]; - } - - s_remoteModuleAllowlist = RemoteModuleAllowlistFromConfig(security[@"remoteModuleAllowlist"]); - } - }); -} - -bool IsRemoteModulesAllowed() { - if (RuntimeConfig.IsDebug) { - return true; - } - - InitializeSecurityConfig(); - return s_allowRemoteModules; -} - -bool IsRemoteUrlAllowed(const std::string& url) { - if (RuntimeConfig.IsDebug) { - return true; - } - - InitializeSecurityConfig(); - if (!s_allowRemoteModules) { - return false; - } - - return RemoteUrlAllowedByAllowlist(url, s_remoteModuleAllowlist); -} - -// ───────────────────────────────────────────────────────────── -// Boot-evaluation flag -// -// ───────────────────────────────────────────────────────────── -// HTTP loader helpers - -// URLs touched before the client configures anything (the local trampoline's -// clean `/ns/core/*` imports) carry no query, so they canonicalize identically -// under any vocabulary. -std::string CanonicalizeHttpUrlKey(const std::string& url) { - const std::string normalizedUrl = NormalizeHttpModuleUrl(url); - return normalizedUrl.empty() ? url : CanonicalizeNormalizedHttpUrlKey(normalizedUrl); -} +using nativescript::common::http::AttemptOutcome; +using nativescript::common::http::AttemptRequest; +using nativescript::common::http::FetchPath; +using nativescript::common::http::ModuleTransport; std::string CanonicalizeNormalizedHttpUrlKey(const std::string& normalizedUrl) { - // Per-isolate vocabulary, so this runs on the isolate's own thread only. - const CanonicalizationConfig* canonConfig = CanonicalizationConfigForCurrentIsolate(); - // Drop fragment entirely - size_t hashPos = normalizedUrl.find('#'); - std::string noHash = - (hashPos == std::string::npos) ? normalizedUrl : normalizedUrl.substr(0, hashPos); - - // Locate path start and query start - size_t schemePos = noHash.find("://"); - if (schemePos == std::string::npos) { - // Unexpected shape; fall back to removing whole query - size_t q = noHash.find('?'); - return (q == std::string::npos) ? noHash : noHash.substr(0, q); - } - size_t pathStart = noHash.find('/', schemePos + 3); - if (pathStart == std::string::npos) { - // No path; nothing to normalize - return noHash; - } - size_t qPos = noHash.find('?', pathStart); - std::string originAndPath = (qPos == std::string::npos) ? noHash : noHash.substr(0, qPos); - std::string query = (qPos == std::string::npos) ? std::string() : noHash.substr(qPos + 1); - - // IMPORTANT: This function is used as an HTTP module registry/cache key. - // For general-purpose HTTP module loading (public internet), the query string - // can be part of the module's identity (auth, content versioning, routing, etc). - // Therefore query normalization (sorting/dropping) applies only to dev - // endpoints, per the client-supplied vocabulary above. - // - // The dev server serves every module under ONE canonical URL — module - // identity IS the URL string. Freshness after an HMR edit is handled by - // ns:module `invalidateModules` (registry evict) and the server's own - // response caching headers, never by URL variation. There is deliberately - // no path-tag vocabulary to collapse here. - // - // Why `preserveQueryFor` exists (and is checked BEFORE the dev-endpoint - // prefix test, so it covers endpoints nested under a dev prefix): for some - // endpoints the query IS the identity. A framework that fetches recompiled - // component metadata under a timestamped query is the motivating case — - // stripping that timestamp would collapse every HMR fetch onto the boot-time - // cache key, and the client would forever replay stale metadata. - // - // Until a client supplies that vocabulary, canonicalization is purely - // mechanical: the fragment is gone and the query stays, because which params - // are cache-busters and which paths are dev endpoints is knowledge only the - // client has. Guessing would silently collapse two distinct modules onto one - // registry key. - if (canonConfig == nullptr) { - return noHash; - } - - { - std::string pathOnly = originAndPath.substr(pathStart); - for (const auto& p : canonConfig->preserveQueryPrefixes) { - if (!p.empty() && pathOnly.find(p) != std::string::npos) { - return noHash; // query preserved verbatim (fragment already removed) - } - } - bool isDevEndpoint = false; - for (const auto& p : canonConfig->devPathPrefixes) { - if (!p.empty() && StartsWith(pathOnly, p.c_str())) { - isDevEndpoint = true; - break; - } - } - if (!isDevEndpoint) { - return noHash; - } - } - - if (query.empty()) return originAndPath; - - // Keep all params except the configured cache busters; sort for stability. - std::vector kept; - size_t start = 0; - while (start <= query.size()) { - size_t amp = query.find('&', start); - std::string pair = - (amp == std::string::npos) ? query.substr(start) : query.substr(start, amp - start); - if (!pair.empty()) { - size_t eq = pair.find('='); - std::string name = (eq == std::string::npos) ? pair : pair.substr(0, eq); - bool drop = std::find(canonConfig->stripParams.begin(), canonConfig->stripParams.end(), - name) != canonConfig->stripParams.end(); - if (!drop) kept.push_back(pair); - } - if (amp == std::string::npos) break; - start = amp + 1; - } - if (kept.empty()) return originAndPath; - std::sort(kept.begin(), kept.end()); - std::string rebuilt = originAndPath + "?"; - for (size_t i = 0; i < kept.size(); i++) { - if (i > 0) rebuilt += "&"; - rebuilt += kept[i]; - } - return rebuilt; -} - -// ============================================================================ -// HTTP module fetching -// ============================================================================ -// -// Two fetch primitives back the HTTP ESM loader: -// - `HttpFetchModule` — the synchronous fetch V8's ResolveModuleCallback -// falls back to for anything the module-graph walk missed -// (the callback is synchronous — still true as of 14.9.207.39 — so -// this fallback must be native and blocking). -// - `FetchModuleBodyAsync` — the primitive behind the module-graph walk -// (StartModuleGraphLoad), which fetches the transitive closure -// concurrently off the JS thread before instantiation begins. -// -// Both issue their requests through StartModuleFetchTask, so they share one -// HTTP cache and its switch, BuildModuleFetchRequest shapes every request, -// and ClassifyModuleResponse judges every response. Neither can drift into -// its own idea of what a valid module response is. -// -// Concurrent per-module fetches overlap with on-device compile, which -// measured fastest on real apps (HMR_API_NECESSITY_REVIEW.md §8.3). - -// Forward declarations — these helpers are defined below their first use, -// matching the existing convention in this file. -static bool PerformHttpFetchOnceSync(const std::string& url, std::string& out, - std::string& contentType, int& status, bool& waitExpired); - -// ── The module-fetch timeout policy ────────────────────────────────────────── -// -// One request timeout for every module-fetch attempt, read by every path: the -// synchronous fallback, each async attempt, and the session's own default. It -// MUST live in exactly one place — the async session once said 10s while every -// NSMutableURLRequest overrode it to 5s, so raising the session alone would -// have changed nothing. -// -// Debug runtimes get 30s: dev servers transform cold modules on demand, and -// real toolchain responses have been measured at 5–9s — comfortably past the -// old flat 5s, which expired mid-transform. A timed-out dependency fetch left -// the module absent from the registry, hid its subtree from the graph walk, -// and dumped it onto the blocking synchronous fallback (the "module graph -// walk missed" warnings). Release keeps 5s: remote module loading there is -// opt-in through the security gate, and nothing measured justifies relaxing -// its budget. -static NSTimeInterval ModuleFetchTimeoutInterval() { - return RuntimeConfig.IsDebug ? 30.0 : 5.0; -} - -// Transport-error retry delay, shared by the sync and async paths. Long enough -// to let a transient hiccup pass, short enough not to matter against the -// request timeout. -static constexpr double kModuleFetchRetryDelaySeconds = 0.12; - -// How long the synchronous fallback waits past the request timeout before it -// gives up on a task whose completion never arrived. The request timeout is an -// idle timeout, so a response still trickling in can legitimately outlast it; -// this margin is what makes the blocking wait finite regardless. -static constexpr double kModuleFetchSyncWaitMarginSeconds = 5.0; - -// synchronous-fetch timing histogram. -// -// The histogram is intentionally coarse — -// just three buckets — and we log a summary once per kFetchSyncSummaryEvery -// completions. That keeps the noise low (one line per ~100 fetches) while -// still surfacing tail behavior. The "fast" bucket means a request landed -// in <10ms (typical for a kept-alive HTTP/1.1 connection on loopback); -// "slow" means >100ms (which usually means a fresh TCP/TLS handshake or -// a large response body). If most fetches are "fast", keep-alive is -// working. If most are "slow", we still have churn to track down. -static std::atomic g_fetchSyncCount{0}; -static std::atomic g_fetchSyncTotalMs{0}; -static std::atomic g_fetchSyncFast{0}; // <10ms -static std::atomic g_fetchSyncMedium{0}; // 10–99ms -static std::atomic g_fetchSyncSlow{0}; // >=100ms -static constexpr size_t kFetchSyncSummaryEvery = 100; - -// ── The module response policy ─────────────────────────────────────────────── -// -// Module scripts are strict about MIME: the HTML spec's "fetch a single module -// script" fails the fetch outright for anything that is not a JavaScript or -// JSON MIME type, where a classic script would sniff and run it anyway. That -// strictness is the whole point — an SPA dev server answering an unknown path -// with `200 text/html` should say so, not hand HTML to the parser and produce -// `Unexpected token '<'` from somewhere deep in the graph. -// -// Both transports classify here, so the synchronous fallback and the async -// walk cannot disagree about what a response means. - -// "text/javascript; charset=utf-8" → "text/javascript": parameters stripped, -// trimmed, lowercased. -static std::string MimeEssence(const std::string& contentType) { - size_t semi = contentType.find(';'); - std::string essence = semi == std::string::npos ? contentType : contentType.substr(0, semi); - size_t begin = essence.find_first_not_of(" \t"); - if (begin == std::string::npos) { - return ""; - } - size_t end = essence.find_last_not_of(" \t"); - essence = essence.substr(begin, end - begin + 1); - for (char& c : essence) { - c = (char)tolower((unsigned char)c); - } - return essence; -} - -// The HTML spec's JavaScript MIME type essence list, verbatim. -static bool IsJavaScriptMimeEssence(const std::string& essence) { - static const char* const kJavaScriptEssences[] = {"application/ecmascript", - "application/javascript", - "application/x-ecmascript", - "application/x-javascript", - "text/ecmascript", - "text/javascript", - "text/javascript1.0", - "text/javascript1.1", - "text/javascript1.2", - "text/javascript1.3", - "text/javascript1.4", - "text/javascript1.5", - "text/jscript", - "text/livescript", - "text/x-ecmascript", - "text/x-javascript"}; - for (const char* candidate : kJavaScriptEssences) { - if (essence == candidate) { - return true; - } - } - return false; -} - -// A JSON MIME type is application/json, text/json, or any `+json` subtype. -static bool IsJsonMimeEssence(const std::string& essence) { - if (essence == "application/json" || essence == "text/json") { - return true; - } - const std::string suffix = "+json"; - return essence.size() > suffix.size() && - essence.compare(essence.size() - suffix.size(), suffix.size(), suffix) == 0; -} - -// `transportOk` means a response arrived at all; everything else about it — -// status, MIME, emptiness — is policy decided here. `body` is moved into the -// result on success. -static void ClassifyModuleResponse(const std::string& url, bool transportOk, int status, - const std::string& contentType, std::string& body, - ModuleFetchResult& result) { - result.status = status; - result.contentType = contentType; - - if (!transportOk) { - result.failureReason = "HTTP import failed: " + url + " (network error)"; - return; - } - if (status == 204 || status == 205) { - // "No content" carries no module, which the web treats as a network error - // for a module script rather than as an empty module. - result.failureReason = - "HTTP import failed: " + url + " (status=" + std::to_string(status) + ", no content)"; - return; - } - if (status < 200 || status >= 300) { - result.failureReason = - "HTTP import failed: " + url + " (status=" + std::to_string(status) + ")"; - return; - } - - const std::string essence = MimeEssence(contentType); - if (essence.empty()) { - result.failureReason = - "Expected a JavaScript module but '" + url + "' responded with no MIME type"; - return; - } - - if (IsJsonMimeEssence(essence)) { - if (body.empty()) { - result.failureReason = - "Expected a JSON module but '" + url + "' responded with an empty body"; - return; - } - result.kind = ModuleResponseKind::kJson; - } else if (IsJavaScriptMimeEssence(essence)) { - result.kind = ModuleResponseKind::kJavaScript; - // An empty 2xx JavaScript body is a valid module: type-only TypeScript - // modules transform to zero runtime code and dev servers serve them as - // empty 200s. Failing here would kill the whole graph with a misleading - // "status=200". - if (body.empty()) { - body = "export {};\n"; - TNS_DEBUG(Esm, "[http-loader] empty 2xx body for %s — serving canonical empty module", - url.c_str()); - } - } else { - result.failureReason = - "Expected a JavaScript module but '" + url + "' responded with MIME type '" + essence + "'"; - return; - } - - result.ok = true; - result.body = std::move(body); + return nativescript::common::http::CanonicalizeNormalizedHttpUrlKey( + normalizedUrl, + nativescript::common::loader::CanonicalizationConfigFor(v8::Isolate::TryGetCurrent())); } -bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { - result = ModuleFetchResult(); - - // Security gate: the single point of enforcement for all HTTP module - // loading, checked before any network turn. - if (!IsRemoteUrlAllowed(url)) { - result.status = 403; - result.failureReason = "HTTP import blocked: remote module loading is not allowed for " + url; - TNS_DEBUG(Esm, "[http-esm][security][blocked] %s", url.c_str()); - return false; - } - - // Hoist the category check once per call so the branches below share a - // single read. - const bool traceFetch = tns::LogCategoryEnabled(tns::LogCategory::Fetch); - - // Time the network branch end-to-end so the per-URL log can attribute - // milliseconds to each fetch. Measured here rather than inside - // PerformHttpFetchOnceSync so the retry interval is billed to the URL too — - // which is what the user sees as "this URL was slow". - const uint64_t netStartUs = - traceFetch ? (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0) : 0ull; - - std::string body; - std::string contentType; - int status = 0; - bool waitExpired = false; - bool transportOk = PerformHttpFetchOnceSync(url, body, contentType, status, waitExpired); - if (!transportOk && !waitExpired) { - // One retry, and only for a transport error: an HTTP status is an answer, - // not a failure to communicate, so asking again would just repeat it. An - // expired wait is not retried: it already blocked this thread for longer - // than a request may take. - TNS_DEBUG(Esm, "[http-loader] retrying %s after initial fetch error", url.c_str()); - usleep((useconds_t)(kModuleFetchRetryDelaySeconds * 1000.0 * 1000.0)); - transportOk = PerformHttpFetchOnceSync(url, body, contentType, status, waitExpired); - } - // NOTE: no long dev-server-startup retry loop here on purpose. The CLI's - // `compileWithWatch` gates app deploy/restart on its `vite serve` - // readiness probe (bundler-compiler-service), so a connection-refused at - // boot is a real failure, not a startup race — surface it immediately. - - ClassifyModuleResponse(url, transportOk, status, contentType, body, result); - if (waitExpired) { - result.failureReason = - "HTTP import failed: " + url + " (no response within " + - std::to_string((int)(ModuleFetchTimeoutInterval() + kModuleFetchSyncWaitMarginSeconds)) + - "s)"; +std::optional>> RemoteModuleAllowlistItems(id value) { + if (![value isKindOfClass:[NSArray class]]) { + return std::nullopt; } - - if (!result.ok) { - TNS_DEBUG(Esm, "[http-loader][fetch-sync][reject] %s", result.failureReason.c_str()); - return false; - } - - if (tns::LogCategoryEnabled(tns::LogCategory::Esm)) { - const char* ctstr = result.contentType.empty() ? "" : result.contentType.c_str(); - TNS_DEBUG(Esm, "[http-loader] fetched status=%d content-type=%s bytes=%llu", result.status, - ctstr, (unsigned long long)result.body.size()); - } - if (traceFetch) { - const uint64_t netEndUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); - const uint64_t netMs = netEndUs > netStartUs ? (netEndUs - netStartUs) / 1000ull : 0ull; - TNS_DEBUG(Fetch, "[http-loader][fetch][network] %s bytes=%lu ms=%llu", url.c_str(), - (unsigned long)result.body.size(), (unsigned long long)netMs); + std::vector> items; + for (id item in (NSArray*)value) { + items.push_back([item isKindOfClass:[NSString class]] ? ToExactUtf8((NSString*)item) + : std::nullopt); } - - return true; + return items; } // ───────────────────────────────────────────────────────────── // The module HTTP cache // // Module fetches use ephemeral sessions, so no cookies or credentials persist. -// While the cache is enabled each origin has an on-disk NSURLCache in its own +// Each origin fetched with the cache on has an on-disk NSURLCache in its own // directory, so one origin's cache can be dropped without touching another's; -// the app's shared NSURLCache is never read, replaced or resized. While it is -// disabled fetches go through sessions without a cache. +// the app's shared NSURLCache is never read, replaced or resized. Fetches with +// the cache off go through sessions without a cache. // // The graph walk and the synchronous fallback each have sessions of their // own, configured alike, so a blocking fallback fetch never waits for a @@ -537,7 +64,7 @@ bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { // queue, so a thread blocked waiting on one of its tasks does not hold up the // completion it waits for. // -// On disk, under Library/Caches/ns-module-http-cache: +// On disk, under AppCachesDirectory()/ns-module-http-cache: // origins/// one NSURLCache directory // trash/ deleted in the background // A cache is dropped by moving its directory into trash, which is atomic; its @@ -547,8 +74,10 @@ bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { // its highest generation, and removes the others when it does. At most // kModuleCacheMaxOrigins origin directories outlive a launch. // -// All of it is process-wide, guarded by one mutex: fetch threads, every -// isolate's thread and the inspector's socket thread read and change it. +// All of it is process-wide, guarded by one mutex: fetch completions, every +// isolate's thread and the inspector's socket thread read and change it. An +// attempt's outcome goes to the core, which may clear the cache in response, so +// nothing is delivered to the core while that mutex is held. static constexpr NSUInteger kModuleCacheMemoryCapacity = 8 * 1024 * 1024; static constexpr NSUInteger kModuleCacheDiskCapacity = 256 * 1024 * 1024; @@ -558,21 +87,16 @@ bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { // of the most recently opened ones. static constexpr NSUInteger kModuleCacheMaxOrigins = 8; -// Top-level app config key; `false` starts the process with the cache off. -static constexpr const char* kModuleHttpCacheConfigKey = "moduleHttpCache"; - namespace { -enum class ModuleFetchPath { kGraphWalk, kSynchronousFallback }; - // One session per path; the fallback's is created on first use, since most // processes never take the fallback. struct ModuleSessions { NSURLSession* graphWalk = nil; // retained NSURLSession* synchronousFallback = nil; // retained - NSURLSession*& For(ModuleFetchPath path) { - return path == ModuleFetchPath::kGraphWalk ? graphWalk : synchronousFallback; + NSURLSession*& For(FetchPath path) { + return path == FetchPath::kGraphWalk ? graphWalk : synchronousFallback; } }; @@ -586,8 +110,6 @@ bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { struct ModuleHttpCacheState { std::mutex mutex; bool initialized = false; - bool userEnabled = true; - std::set inspectorDisabledConnections; std::map partitions; // The generation each origin must open next, set when its cache is dropped // in this process. @@ -596,30 +118,18 @@ bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { NSURL* root = nil; // retained }; -ModuleHttpCacheState& CacheState() { - static auto* state = new ModuleHttpCacheState(); - return *state; -} - -} // namespace - -static NSURLSessionConfiguration* ModuleSessionConfiguration(NSURLCache* cache) { +NSURLSessionConfiguration* ModuleSessionConfiguration(NSURLCache* cache) { NSURLSessionConfiguration* config = [NSURLSessionConfiguration ephemeralSessionConfiguration]; // nil, not the ephemeral configuration's default in-memory cache: an // uncached session must not cache at all. config.URLCache = cache; config.HTTPShouldSetCookies = NO; - // Every module request overrides this (BuildModuleFetchRequest sets the - // same policy value); the session default exists so the two settings can - // never disagree about the budget again. - config.timeoutIntervalForRequest = ModuleFetchTimeoutInterval(); config.HTTPMaximumConnectionsPerHost = 32; return config; } // The session `path` uses with `cache` (nil: uncached), created on first use. -static NSURLSession* SessionLocked(ModuleSessions& sessions, ModuleFetchPath path, - NSURLCache* cache) { +NSURLSession* SessionLocked(ModuleSessions& sessions, FetchPath path, NSURLCache* cache) { NSURLSession*& session = sessions.For(path); if (session == nil) { session = [[NSURLSession sessionWithConfiguration:ModuleSessionConfiguration(cache)] retain]; @@ -628,7 +138,7 @@ bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { } // The sessions finish what they have in flight without being used again. -static void RetireSessions(ModuleSessions& sessions) { +void RetireSessions(ModuleSessions& sessions) { for (NSURLSession* session : {sessions.graphWalk, sessions.synchronousFallback}) { [session finishTasksAndInvalidate]; [session release]; @@ -636,17 +146,17 @@ static void RetireSessions(ModuleSessions& sessions) { sessions = ModuleSessions(); } -static NSURL* OriginsDirectory(ModuleHttpCacheState& state) { +NSURL* OriginsDirectory(ModuleHttpCacheState& state) { return [state.root URLByAppendingPathComponent:@"origins" isDirectory:YES]; } -static NSURL* TrashDirectory(ModuleHttpCacheState& state) { +NSURL* TrashDirectory(ModuleHttpCacheState& state) { return [state.root URLByAppendingPathComponent:@"trash" isDirectory:YES]; } // Moves `item` into trash under a fresh name. Returns false only when `item` -// still exists afterwards. -static bool MoveToTrash(ModuleHttpCacheState& state, NSURL* item) { +// still exists afterwards, with the reason in `error`. +bool MoveToTrash(ModuleHttpCacheState& state, NSURL* item, std::string* error = nullptr) { NSFileManager* fm = [NSFileManager defaultManager]; NSURL* trash = TrashDirectory(state); [fm createDirectoryAtURL:trash withIntermediateDirectories:YES attributes:nil error:nil]; @@ -657,10 +167,21 @@ static bool MoveToTrash(ModuleHttpCacheState& state, NSURL* item) { if (![fm fileExistsAtPath:item.path]) { return true; } - return [fm removeItemAtURL:item error:nil]; + NSError* removeError = nil; + if ([fm removeItemAtURL:item error:&removeError]) { + return true; + } + if (error != nullptr) { + NSString* description = removeError.localizedDescription + ?: [NSString stringWithFormat:@"could not remove %@", item.path]; + *error = description.UTF8String ?: "could not remove a cache directory"; + } + return false; } -static void PurgeTrashInBackground(ModuleHttpCacheState& state) { +// Only removes what is inside trash, so concurrent purges, and a purge racing +// a MoveToTrash, at worst both try to remove one item. +void PurgeTrashInBackground(ModuleHttpCacheState& state) { NSURL* trash = TrashDirectory(state); dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{ @autoreleasepool { @@ -677,7 +198,7 @@ static void PurgeTrashInBackground(ModuleHttpCacheState& state) { // "http://127.0.0.1:8080" → "http%3A%2F%2F127.0.0.1%3A8080": collision-free // and a single path component. -static NSString* OriginDirectoryName(const std::string& origin) { +NSString* OriginDirectoryName(const std::string& origin) { static const char kHex[] = "0123456789ABCDEF"; std::string name; for (unsigned char c : origin) { @@ -692,11 +213,16 @@ static void PurgeTrashInBackground(ModuleHttpCacheState& state) { return [NSString stringWithUTF8String:name.c_str()]; } +NSURL* OriginDirectory(ModuleHttpCacheState& state, const std::string& origin) { + return [OriginsDirectory(state) URLByAppendingPathComponent:OriginDirectoryName(origin) + isDirectory:YES]; +} + // Keeps the kModuleCacheMaxOrigins origin directories opened most recently // (PartitionLocked stamps each one's modification date) and trashes the rest; // one whose date cannot be read counts as the oldest. Only safe before any // partition is open. -static void PruneOriginsLocked(ModuleHttpCacheState& state) { +void PruneOriginsLocked(ModuleHttpCacheState& state) { NSArray* origins = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:OriginsDirectory(state) includingPropertiesForKeys:@[ NSURLContentModificationDateKey ] @@ -719,31 +245,26 @@ static void PruneOriginsLocked(ModuleHttpCacheState& state) { } } -static void InitializeModuleHttpCacheLocked(ModuleHttpCacheState& state) { +// Before the first fetch and the first clear in the process. +void InitializeModuleHttpCacheLocked(ModuleHttpCacheState& state) { if (state.initialized) { return; } state.initialized = true; - NSURL* caches = [[NSFileManager defaultManager] URLsForDirectory:NSCachesDirectory - inDomains:NSUserDomainMask] - .firstObject; + const std::string cachesDir = AppCachesDirectory(); + NSURL* caches = cachesDir.empty() ? nil + : [NSURL fileURLWithFileSystemRepresentation:cachesDir.c_str() + isDirectory:YES + relativeToURL:nil]; state.root = [[caches URLByAppendingPathComponent:@"ns-module-http-cache" isDirectory:YES] retain]; - NSArray* arguments = [NSProcessInfo processInfo].arguments; - id configured = Runtime::GetAppConfigValue(kModuleHttpCacheConfigKey); - if ([configured isKindOfClass:[NSNumber class]] && ![(NSNumber*)configured boolValue]) { - state.userEnabled = false; - } - if ([arguments containsObject:@"--nativescript-no-module-cache"]) { - state.userEnabled = false; - } - // Anything at the root besides the two directories above is not a cache // this runtime opens, so it goes too. NSFileManager* fm = [NSFileManager defaultManager]; - const bool clearAtLaunch = [arguments containsObject:@"--nativescript-clear-module-cache"]; + const bool clearAtLaunch = + [[NSProcessInfo processInfo].arguments containsObject:@"--nativescript-clear-module-cache"]; for (NSURL* item in [fm contentsOfDirectoryAtURL:state.root includingPropertiesForKeys:nil options:0 @@ -761,17 +282,14 @@ static void InitializeModuleHttpCacheLocked(ModuleHttpCacheState& state) { // The partition for `origin`, opened on first use in this process. Opening // reuses the origin's highest generation on disk unless its cache was dropped // in this process, and removes every other generation. -static ModuleCachePartition& PartitionLocked(ModuleHttpCacheState& state, - const std::string& origin) { +ModuleCachePartition& PartitionLocked(ModuleHttpCacheState& state, const std::string& origin) { auto it = state.partitions.find(origin); if (it != state.partitions.end()) { return it->second; } NSFileManager* fm = [NSFileManager defaultManager]; - NSURL* originDirectory = - [OriginsDirectory(state) URLByAppendingPathComponent:OriginDirectoryName(origin) - isDirectory:YES]; + NSURL* originDirectory = OriginDirectory(state, origin); uint64_t highest = 0; NSArray* entries = [fm contentsOfDirectoryAtURL:originDirectory includingPropertiesForKeys:nil @@ -814,16 +332,17 @@ static void InitializeModuleHttpCacheLocked(ModuleHttpCacheState& state) { // Drops the cache of one open partition: its directory moves to trash, an // empty directory for the next generation takes its place, and both sessions -// are retired. -static void DropPartitionLocked(ModuleHttpCacheState& state, const std::string& origin) { +// are retired. False when the old directory could not be removed. +bool DropPartitionLocked(ModuleHttpCacheState& state, const std::string& origin, + std::string* error) { auto it = state.partitions.find(origin); if (it == state.partitions.end()) { - return; + return true; } ModuleCachePartition partition = it->second; state.partitions.erase(it); - MoveToTrash(state, partition.directory); + const bool trashed = MoveToTrash(state, partition.directory, error); const uint64_t next = partition.generation + 1; state.reservedGenerations[origin] = next; NSURL* nextDirectory = [[partition.directory URLByDeletingLastPathComponent] @@ -837,427 +356,256 @@ static void DropPartitionLocked(ModuleHttpCacheState& state, const std::string& RetireSessions(partition.sessions); [partition.cache release]; [partition.directory release]; + return trashed; } -static void ClearModuleHttpCacheLocked(ModuleHttpCacheState& state) { - // Every origin at once, opened in this process or not; the open ones then - // get their next-generation directory back. - MoveToTrash(state, OriginsDirectory(state)); - std::vector open; - for (const auto& entry : state.partitions) { - open.push_back(entry.first); - } - for (const std::string& origin : open) { - DropPartitionLocked(state, origin); - } - PurgeTrashInBackground(state); -} - -void SetModuleHttpCacheEnabled(bool enabled) { - ModuleHttpCacheState& state = CacheState(); - std::lock_guard lock(state.mutex); - @autoreleasepool { - InitializeModuleHttpCacheLocked(state); - } - state.userEnabled = enabled; +nativescript::common::http::CacheOpResult CacheOpFailed(const std::string& error) { + return {false, "could not clear the module HTTP cache: " + error}; } -void SetModuleHttpCacheDisabledByInspector(uint64_t connectionId, bool disabled) { - ModuleHttpCacheState& state = CacheState(); - std::lock_guard lock(state.mutex); - if (disabled) { - state.inspectorDisabledConnections.insert(connectionId); - } else { - state.inspectorDisabledConnections.erase(connectionId); - } -} - -void ClearModuleHttpCache() { - ModuleHttpCacheState& state = CacheState(); - std::lock_guard lock(state.mutex); - @autoreleasepool { - InitializeModuleHttpCacheLocked(state); - ClearModuleHttpCacheLocked(state); - } -} - -// Whether a Clear-Site-Data value, a comma-separated list of quoted strings, -// holds "cache" or "*". -static bool ClearSiteDataClearsCache(NSString* value) { - NSCharacterSet* whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet]; - for (NSString* item in [value componentsSeparatedByString:@","]) { - NSString* directive = [item stringByTrimmingCharactersInSet:whitespace]; - if ([directive isEqualToString:@"\"cache\""] || [directive isEqualToString:@"\"*\""]) { - return true; +void ApplyRequestHeaders(NSMutableURLRequest* urlRequest, const AttemptRequest& request) { + for (const auto& header : request.headers) { + NSString* name = [NSString stringWithUTF8String:header.name.c_str()]; + NSString* value = [NSString stringWithUTF8String:header.value.c_str()]; + if (name != nil && value != nil) { + [urlRequest addValue:value forHTTPHeaderField:name]; } } - return false; } -// Clear-Site-Data "cache" drops the cache of the response URL's origin. The -// partition the response was fetched through goes too, which is the same one -// unless a redirect crossed origins: the carrier itself is stored there, and -// left in place it would be replayed from the cache and clear again on every -// hit. Plain http: origins are honoured as well. -static void ApplyClearSiteData(NSURLResponse* response, const std::string& fetchingOrigin) { - if (![response isKindOfClass:[NSHTTPURLResponse class]]) { - return; - } - NSString* value = [(NSHTTPURLResponse*)response valueForHTTPHeaderField:@"Clear-Site-Data"]; - if (value == nil || !ClearSiteDataClearsCache(value)) { - return; - } - const std::string responseOrigin = HttpUrlOrigin(response.URL.absoluteString.UTF8String ?: ""); - - ModuleHttpCacheState& state = CacheState(); - std::lock_guard lock(state.mutex); - std::vector origins{responseOrigin}; - // Each origin once: a second pass would also trash the next-generation - // directory the first one reserved. - if (fetchingOrigin != responseOrigin) { - origins.push_back(fetchingOrigin); +// Autoreleased; nil when NSURL cannot parse the URL. +NSMutableURLRequest* BuildModuleFetchRequest(const AttemptRequest& request) { + NSString* string = [NSString stringWithUTF8String:request.url.c_str()]; + NSURL* url = string != nil ? [NSURL URLWithString:string] : nil; + if (url == nil) { + return nil; } - for (const std::string& origin : origins) { - if (origin.empty()) { - continue; - } - if (state.partitions.count(origin) != 0) { - DropPartitionLocked(state, origin); - } else { - MoveToTrash(state, - [OriginsDirectory(state) URLByAppendingPathComponent:OriginDirectoryName(origin) - isDirectory:YES]); - } + NSMutableURLRequest* urlRequest = [NSMutableURLRequest requestWithURL:url]; + [urlRequest setHTTPMethod:@"GET"]; + ApplyRequestHeaders(urlRequest, request); + [urlRequest setTimeoutInterval:std::chrono::duration(request.timeout).count()]; + [urlRequest setHTTPShouldHandleCookies:NO]; + if (!request.useCache) { + [urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; } - PurgeTrashInBackground(state); + return urlRequest; } -// Shared request builder for every module fetch. Caching follows the protocol -// policy, so the server's response headers decide freshness. Returns an -// autoreleased NSMutableURLRequest (nil for unparseable URLs). -static NSMutableURLRequest* BuildModuleFetchRequest(const std::string& url) { - NSURL* u = [NSURL URLWithString:[NSString stringWithUTF8String:url.c_str()]]; - if (!u) { - return nil; - } - - NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:u]; - [request setHTTPMethod:@"GET"]; - [request setValue:@"application/javascript, text/javascript, */*;q=0.1" - forHTTPHeaderField:@"Accept"]; - [request setValue:@"identity" forHTTPHeaderField:@"Accept-Encoding"]; - [request setTimeoutInterval:ModuleFetchTimeoutInterval()]; - [request setHTTPShouldHandleCookies:NO]; - return request; +std::string Utf8(NSString* string) { + const char* utf8 = string.UTF8String; + return utf8 != nullptr ? std::string(utf8) : std::string(); } -// What a finished module fetch task produced, read off the NSURLResponse. -// `transportOk` means a response arrived at all; whether it is a usable module -// is ClassifyModuleResponse's call. -struct ModuleFetchOutcome { - bool transportOk = false; - int status = 0; - std::string contentType; - std::string body; -}; - -static ModuleFetchOutcome ReadModuleFetchOutcome(NSData* data, NSURLResponse* response, - NSError* error) { - ModuleFetchOutcome outcome; - outcome.transportOk = error == nil; +// What a finished task produced. NSURLSession reports a body that failed after +// the status line as an error alongside the response, so a response counts as +// arrived only without an error; its status and headers are still reported. +AttemptOutcome ReadModuleFetchOutcome(NSData* data, NSURLResponse* response, NSError* error) { + AttemptOutcome outcome; if ([response isKindOfClass:[NSHTTPURLResponse class]]) { - NSHTTPURLResponse* httpResp = (NSHTTPURLResponse*)response; - outcome.status = (int)[httpResp statusCode]; - NSString* ct = [httpResp allHeaderFields][@"Content-Type"]; - if (ct) { - const char* utf8 = [ct UTF8String]; - if (utf8) outcome.contentType = std::string(utf8); + NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; + outcome.arrived = error == nil; + outcome.status = (int)httpResponse.statusCode; + outcome.contentType = Utf8([httpResponse valueForHTTPHeaderField:@"Content-Type"]); + outcome.finalUrl = Utf8(httpResponse.URL.absoluteString); + NSString* clearSiteData = [httpResponse valueForHTTPHeaderField:@"Clear-Site-Data"]; + if (clearSiteData != nil) { + outcome.clearSiteData.push_back(Utf8(clearSiteData)); } } - if (data && [data length] > 0) { - outcome.body.assign(static_cast([data bytes]), static_cast([data length])); + if (data.length > 0) { + outcome.body.assign(static_cast(data.bytes), static_cast(data.length)); } - return outcome; -} - -// Every module request goes out through here, whichever path issued it: the -// cache switch is read now, so it decides this request alone. `handler` runs -// exactly once, on the session's delegate queue, after the response's -// Clear-Site-Data has taken effect, so nothing the loader requests from then on -// can come from the cleared cache. `path` picks which of the two paths' sessions -// carries it. Returns the resumed task, autoreleased. -static NSURLSessionDataTask* StartModuleFetchTask(ModuleFetchPath path, - NSMutableURLRequest* request, - void (^handler)(NSData*, NSURLResponse*, - NSError*)) { - ModuleHttpCacheState& state = CacheState(); - std::lock_guard lock(state.mutex); - InitializeModuleHttpCacheLocked(state); - - const bool enabled = state.userEnabled && state.inspectorDisabledConnections.empty(); - const std::string origin = - enabled ? HttpUrlOrigin(request.URL.absoluteString.UTF8String ?: "") : std::string(); - NSURLSession* session = nil; - if (!origin.empty()) { - ModuleCachePartition& partition = PartitionLocked(state, origin); - session = SessionLocked(partition.sessions, path, partition.cache); - } else { - [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; - [request setValue:@"no-cache" forHTTPHeaderField:@"Cache-Control"]; - [request setValue:@"no-cache" forHTTPHeaderField:@"Pragma"]; - session = SessionLocked(state.uncached, path, nil); + if (error != nil) { + NSString* description = error.localizedDescription ?: @""; + NSString* domain = error.domain ?: @""; + outcome.errorDescription = + Utf8(domain) + " code=" + std::to_string((long)error.code) + " " + Utf8(description); } - void (^delivered)(NSData*, NSURLResponse*, NSError*) = - ^(NSData* data, NSURLResponse* response, NSError* error) { - @autoreleasepool { - try { - ApplyClearSiteData(response, origin); - } catch (...) { - Log(@"NativeScript: could not apply Clear-Site-Data from a module response"); - } - } - handler(data, response, error); - }; - // Created and resumed under the lock: a cache dropped on another thread - // invalidates its session, which then refuses new tasks. - NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:delivered]; - [task resume]; - return task; + return outcome; } -// One blocking fetch attempt for the synchronous fallback, on the fallback's -// own session over the same cache as the async path. The wait is bounded: `waitExpired` reports a -// task that had not completed when it ran out, which is then cancelled. -static bool PerformHttpFetchOnceSync(const std::string& url, std::string& out, - std::string& contentType, int& status, bool& waitExpired) { - waitExpired = false; - @autoreleasepool { - NSMutableURLRequest* request = BuildModuleFetchRequest(url); - if (!request) { - status = 0; - return false; - } +class NSURLSessionModuleTransport final : public ModuleTransport { + public: + const char* Name() const override { return "nsurlsession"; } - // Shared with the completion handler, which can outlive this frame when - // the wait expires. - struct SyncFetchState { - dispatch_semaphore_t done = dispatch_semaphore_create(0); - ModuleFetchOutcome outcome; - std::string errorDescription; - ~SyncFetchState() { dispatch_release(done); } - }; - auto state = std::make_shared(); + bool SchedulesItself() const override { return true; } - const auto fetchStartUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); + AttemptOutcome FetchBlocking(const AttemptRequest& request) override { + @autoreleasepool { + NSMutableURLRequest* urlRequest = BuildModuleFetchRequest(request); + if (urlRequest == nil) { + return MalformedUrl(); + } - NSURLSessionDataTask* task = StartModuleFetchTask( - ModuleFetchPath::kSynchronousFallback, request, - ^(NSData* data, NSURLResponse* response, NSError* error) { - try { - state->outcome = ReadModuleFetchOutcome(data, response, error); - if (error != nil) { - NSString* desc = error.localizedDescription ?: @""; - NSString* domain = error.domain ?: @""; - state->errorDescription = std::string(domain.UTF8String) + - " code=" + std::to_string((long)error.code) + " " + - desc.UTF8String; + // Shared with the completion handler, which can outlive this frame when + // the wait expires. + struct SyncFetchState { + dispatch_semaphore_t done = dispatch_semaphore_create(0); + AttemptOutcome outcome; + ~SyncFetchState() { dispatch_release(done); } + }; + auto sync = std::make_shared(); + + NSURLSessionDataTask* task = + StartTask(request, urlRequest, ^(NSData* data, NSURLResponse* response, NSError* error) { + @autoreleasepool { + try { + sync->outcome = ReadModuleFetchOutcome(data, response, error); + } catch (...) { + sync->outcome = AttemptOutcome(); + } } - } catch (...) { - state->outcome = ModuleFetchOutcome(); - } - dispatch_semaphore_signal(state->done); - }); + dispatch_semaphore_signal(sync->done); + }); + if (task == nil) { + return NoTask(); + } - const double waitSeconds = request.timeoutInterval + kModuleFetchSyncWaitMarginSeconds; - if (dispatch_semaphore_wait( - state->done, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(waitSeconds * NSEC_PER_SEC))) != - 0) { - [task cancel]; - waitExpired = true; - status = 0; - Log(@"NativeScript: synchronous module fetch of %s got no response within %.0fs", url.c_str(), - waitSeconds); - return false; + const dispatch_time_t waitUntil = + request.waitBound.count() > 0 + ? dispatch_time( + DISPATCH_TIME_NOW, + std::chrono::duration_cast(request.waitBound).count()) + : DISPATCH_TIME_FOREVER; + if (dispatch_semaphore_wait(sync->done, waitUntil) != 0) { + [task cancel]; + AttemptOutcome expired; + expired.waitExpired = true; + return expired; + } + return std::move(sync->outcome); } + } - const auto fetchEndUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); - const uint64_t fetchMs = - fetchEndUs > fetchStartUs ? (fetchEndUs - fetchStartUs) / 1000ull : 0ull; - g_fetchSyncTotalMs.fetch_add(fetchMs, std::memory_order_relaxed); - if (fetchMs < 10) { - g_fetchSyncFast.fetch_add(1, std::memory_order_relaxed); - } else if (fetchMs < 100) { - g_fetchSyncMedium.fetch_add(1, std::memory_order_relaxed); - } else { - g_fetchSyncSlow.fetch_add(1, std::memory_order_relaxed); - } - const size_t syncCount = g_fetchSyncCount.fetch_add(1, std::memory_order_relaxed) + 1; - if (syncCount > 0 && syncCount % kFetchSyncSummaryEvery == 0 && - tns::LogCategoryEnabled(tns::LogCategory::Esm)) { - const size_t fast = g_fetchSyncFast.load(std::memory_order_relaxed); - const size_t medium = g_fetchSyncMedium.load(std::memory_order_relaxed); - const size_t slow = g_fetchSyncSlow.load(std::memory_order_relaxed); - const uint64_t totalMs = g_fetchSyncTotalMs.load(std::memory_order_relaxed); - const uint64_t avgMs = syncCount ? totalMs / (uint64_t)syncCount : 0; - TNS_DEBUG(Esm, - "[http-loader][fetch-sync][summary] count=%lu avg=%llums fast(<10ms)=%lu " - "medium=%lu slow(>=100ms)=%lu", - (unsigned long)syncCount, (unsigned long long)avgMs, (unsigned long)fast, - (unsigned long)medium, (unsigned long)slow); + void FetchAsync(AttemptRequest request, std::function done) override { + auto deliver = std::make_shared>(std::move(done)); + @autoreleasepool { + NSMutableURLRequest* urlRequest = BuildModuleFetchRequest(request); + if (urlRequest == nil) { + (*deliver)(MalformedUrl()); + return; + } + NSURLSessionDataTask* task = + StartTask(request, urlRequest, ^(NSData* data, NSURLResponse* response, NSError* error) { + // NSURLSession invokes this block, so an exception leaving it is an + // std::terminate rather than a failed fetch. + @autoreleasepool { + AttemptOutcome outcome; + try { + outcome = ReadModuleFetchOutcome(data, response, error); + } catch (...) { + outcome = AttemptOutcome(); + } + try { + (*deliver)(std::move(outcome)); + } catch (...) { + } + } + }); + if (task == nil) { + (*deliver)(NoTask()); + } } + } - ModuleFetchOutcome& outcome = state->outcome; - status = outcome.status; - contentType = outcome.contentType; - if (!outcome.transportOk) { - TNS_DEBUG(Esm, "[http-loader][fetch-error] url=%s %s status=%d bodyEmpty=%d ms=%llu", - url.c_str(), state->errorDescription.c_str(), outcome.status, - outcome.body.empty() ? 1 : 0, (unsigned long long)fetchMs); - return false; - } - out.swap(outcome.body); + bool PostDelayed(std::chrono::milliseconds delay, std::function task) override { + auto run = std::make_shared>(std::move(task)); + dispatch_after( + dispatch_time(DISPATCH_TIME_NOW, + std::chrono::duration_cast(delay).count()), + dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ + @autoreleasepool { + try { + (*run)(); + } catch (...) { + } + } + }); return true; } -} - -// One network attempt for FetchModuleBodyAsync. Takes ownership of -// `completionHeap` (heap-allocated so the ObjC block can carry the -// std::function across threads without ARC) and guarantees exactly one -// invocation + delete. Retries once on transport error, mirroring the -// single-retry policy of the synchronous path. -// -// `fetchDeadline` (absolute CFAbsoluteTime, 0 = unbounded) is the enclosing -// graph load's fetch budget. Two full policy attempts plus the retry delay -// can outlast the pumped wait's deadline (e.g. 30s + 0.12s + 30s vs a 60s -// graph budget), so a bounded attempt clamps its request timeout to the time -// remaining and the retry fires only while some budget is left. A fetch that -// lands late is still reported — a dep failure stays on the designed path — -// but no request is issued that could only complete past the deadline. -static void PerformModuleFetchAsyncAttempt( - const std::string& url, int attempt, CFAbsoluteTime fetchDeadline, - std::function* completionHeap) { - @autoreleasepool { - const double remaining = - fetchDeadline > 0 ? fetchDeadline - CFAbsoluteTimeGetCurrent() : 0; - if (fetchDeadline > 0 && remaining <= 0) { - ModuleFetchResult failed; - failed.failureReason = - "HTTP import failed: " + url + " (module graph fetch deadline exceeded)"; - (*completionHeap)(std::move(failed)); - delete completionHeap; - return; - } - NSMutableURLRequest* request = BuildModuleFetchRequest(url); - if (!request) { - ModuleFetchResult failed; - failed.failureReason = "HTTP import failed: " + url + " (malformed request URL)"; - (*completionHeap)(std::move(failed)); - delete completionHeap; - return; + nativescript::common::http::CacheOpResult ClearAll() override { + std::lock_guard lock(state_.mutex); + @autoreleasepool { + InitializeModuleHttpCacheLocked(state_); + // Every origin at once, opened in this process or not; the open ones + // then get their next-generation directory back. + std::string error; + const bool trashed = MoveToTrash(state_, OriginsDirectory(state_), &error); + std::vector open; + for (const auto& entry : state_.partitions) { + open.push_back(entry.first); + } + for (const std::string& origin : open) { + DropPartitionLocked(state_, origin, nullptr); + } + PurgeTrashInBackground(state_); + return trashed ? nativescript::common::http::CacheOpResult{} : CacheOpFailed(error); } + } - if (fetchDeadline > 0 && remaining < request.timeoutInterval) { - [request setTimeoutInterval:remaining]; + // Each call drops what the origin has now. Called twice for one origin, the + // second finds no open partition and trashes the origin's directory, the + // reserved next generation included; PartitionLocked recreates that + // generation's directory when it reopens the origin. + nativescript::common::http::CacheOpResult ClearOrigin(const std::string& origin) override { + std::lock_guard lock(state_.mutex); + @autoreleasepool { + InitializeModuleHttpCacheLocked(state_); + std::string error; + const bool trashed = state_.partitions.count(origin) != 0 + ? DropPartitionLocked(state_, origin, &error) + : MoveToTrash(state_, OriginDirectory(state_, origin), &error); + PurgeTrashInBackground(state_); + return trashed ? nativescript::common::http::CacheOpResult{} : CacheOpFailed(error); } + } - const std::string urlCopy = url; - const uint64_t startUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); - StartModuleFetchTask( - ModuleFetchPath::kGraphWalk, request, - ^(NSData* data, NSURLResponse* response, NSError* error) { - // NSURLSession invokes this block, so a C++ exception leaving it is - // an std::terminate rather than a failure anyone can report. Nothing - // here runs JS — the compile is posted to the isolate's own thread — - // so an escape could only come from an allocation failure, but the - // containment is structural on purpose: the graph load must hear - // back exactly once or it waits out its entire deadline. - bool retrying = false; - ModuleFetchResult result; - try { - ModuleFetchOutcome outcome = ReadModuleFetchOutcome(data, response, error); - int status = outcome.status; - std::string contentType = std::move(outcome.contentType); - std::string body = std::move(outcome.body); + private: + static AttemptOutcome MalformedUrl() { + AttemptOutcome outcome; + outcome.malformedUrl = true; + return outcome; + } - // Transport error → one retry while the enclosing load's budget - // can still fit the delay — the same single-retry policy the - // sync path applies, without blocking any thread. The retry's - // own request clamps to whatever remains when it fires. - const bool retryFitsDeadline = - fetchDeadline <= 0 || - fetchDeadline - CFAbsoluteTimeGetCurrent() > kModuleFetchRetryDelaySeconds; - if (error != nil && attempt == 0 && retryFitsDeadline) { - TNS_DEBUG(Esm, "[http-loader][fetch-async] retrying %s after transport error: %s", - urlCopy.c_str(), - (error.localizedDescription ?: @"").UTF8String); - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, - (int64_t)(kModuleFetchRetryDelaySeconds * NSEC_PER_SEC)), - dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ - PerformModuleFetchAsyncAttempt(urlCopy, 1, fetchDeadline, - completionHeap); - }); - // Set only once the retry is actually queued: it now owns the - // completion, and this attempt must not settle it too. - retrying = true; - } else { - ClassifyModuleResponse(urlCopy, error == nil, status, contentType, body, result); + static AttemptOutcome NoTask() { + AttemptOutcome outcome; + outcome.errorDescription = "NSURLSession created no task"; + return outcome; + } - if (!result.ok) { - TNS_DEBUG(Esm, "[http-loader][fetch-async][reject] attempt=%d %s", attempt, - result.failureReason.c_str()); - } else if (tns::LogCategoryEnabled(tns::LogCategory::Fetch)) { - const uint64_t endUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); - const uint64_t ms = endUs > startUs ? (endUs - startUs) / 1000ull : 0ull; - TNS_DEBUG(Fetch, "[http-loader][fetch][async] %s bytes=%lu ms=%llu", - urlCopy.c_str(), (unsigned long)result.body.size(), - (unsigned long long)ms); - } - } - } catch (...) { - if (retrying) { - // The retry owns the completion and will settle it; nothing to - // report from here. - return; - } - result = ModuleFetchResult(); - result.failureReason = - "HTTP import failed: " + urlCopy + " (internal error handling the response)"; - } + // Creates and resumes the task for `request` on the session its path and + // cache choice use; autoreleased, nil when the session would not create one. + // `handler` runs on the session's delegate queue. + NSURLSessionDataTask* StartTask(const AttemptRequest& request, NSMutableURLRequest* urlRequest, + void (^handler)(NSData*, NSURLResponse*, NSError*)) { + std::lock_guard lock(state_.mutex); + InitializeModuleHttpCacheLocked(state_); - if (retrying) { - return; - } - // Guarded for the same reason: the completion posts to the - // isolate's loop, and a throw on the way out would cross the - // ObjC boundary instead of failing the load. - try { - (*completionHeap)(std::move(result)); - } catch (...) { - Log(@"NativeScript: module fetch completion threw for %s", urlCopy.c_str()); - } - delete completionHeap; - }); + const std::string origin = request.useCache ? HttpUrlOrigin(request.url) : std::string(); + NSURLSession* session = nil; + if (!origin.empty()) { + ModuleCachePartition& partition = PartitionLocked(state_, origin); + session = SessionLocked(partition.sessions, request.path, partition.cache); + } else { + [urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; + session = SessionLocked(state_.uncached, request.path, nil); + } + // Created and resumed under the lock: a cache dropped on another thread + // invalidates its session, which then refuses new tasks. + NSURLSessionDataTask* task = [session dataTaskWithRequest:urlRequest completionHandler:handler]; + [task resume]; + return task; } -} -void FetchModuleBodyAsync(const std::string& url, CFAbsoluteTime fetchDeadline, - std::function completion) { - // Security gate: single point of enforcement, same as HttpFetchModule. - if (!IsRemoteUrlAllowed(url)) { - TNS_DEBUG(Esm, "[http-esm][security][blocked] %s", url.c_str()); - ModuleFetchResult blocked; - blocked.status = 403; - blocked.failureReason = "HTTP import blocked: remote module loading is not allowed for " + url; - completion(std::move(blocked)); - return; - } + ModuleHttpCacheState state_; +}; - auto* completionHeap = new std::function(std::move(completion)); - PerformModuleFetchAsyncAttempt(url, 0, fetchDeadline, completionHeap); -} +} // namespace -// Cold-boot JS-thread runloop pump. -// +ModuleTransport& ModuleHttpTransport() { + static auto* transport = new NSURLSessionModuleTransport(); + return *transport; +} } // namespace tns diff --git a/NativeScript/runtime/Interop.mm b/NativeScript/runtime/Interop.mm index 74cfe27ee..3ce056c82 100644 --- a/NativeScript/runtime/Interop.mm +++ b/NativeScript/runtime/Interop.mm @@ -1984,13 +1984,19 @@ throw NativeScriptException( ffi_call(parametrizedCall->Cif, FFI_FN(methodCall.functionPointer_), call.ResultBuffer(), call.ArgsArray()); } @catch (NSException* e) { + std::free(errorRef); + + // A call made with the isolate unlocked (UIApplicationMain, from Tasks) has + // no JS caller to hand the exception to, and V8 may not be touched here. + Isolate* isolate = v8::Isolate::TryGetCurrent(); + if (isolate == nullptr || !v8::Locker::IsLocked(isolate)) { + @throw; + } + // Preserve the original NSException: build a JS Error carrying its name and // reason, and attach the wrapped native object as `nativeException` (mirrors // the NSError-out path below). Throw it via NativeScriptException so the JS // catch handler receives exactly this object. - std::free(errorRef); - - Isolate* isolate = v8::Isolate::GetCurrent(); Local context = isolate->GetCurrentContext(); NSString* nsName = [e name]; diff --git a/NativeScript/runtime/ModuleInternal.h b/NativeScript/runtime/ModuleInternal.h index b2b81cf57..20fae3c27 100644 --- a/NativeScript/runtime/ModuleInternal.h +++ b/NativeScript/runtime/ModuleInternal.h @@ -2,210 +2,33 @@ #define ModuleInternal_h #include "Common.h" -#include "robin_hood.h" +#include "ns/loader/Boot.h" namespace tns { -// The single deadline for every module-graph settle wait: the entry -// top-level-await pump in LoadESModule, the pumped async graph walk, and -// (doubled, as the outermost backstop) the app-boot handoff in -// NativeScript.mm. One knob, so the waits stay ordered: transport timeouts -// < this < the boot backstop. -inline constexpr double kModuleEvaluateDeadlineSeconds = 60.0; - -// How a module graph's evaluation promise is settled. -// kSyncStrict - Node's `require(esm)`: an async graph is refused before it -// ever evaluates, and the capability promise must already be -// settled when Evaluate() returns. -// kSyncPumping - drive this thread in place until the promise settles or the -// window closes. Only legal while nothing else owns the loop -// (entry evaluation), and only nestable V8 tasks can run. -// kAsync - evaluate and hand the caller the capability promise. -enum class ModuleEvaluationPolicy { kSyncStrict, kSyncPumping, kAsync }; - -struct ModuleEvaluationOptions { - enum class TimeoutBehavior { kReturnPending, kThrow }; - - ModuleEvaluationPolicy policy = ModuleEvaluationPolicy::kSyncStrict; - // kSyncPumping only: how long the graph gets to settle in-pump. - double deadlineSeconds = 0.0; - // kSyncPumping only: what an expired window means. - TimeoutBehavior timeoutBehavior = TimeoutBehavior::kReturnPending; - // kSyncPumping only: also give the Cocoa runloop a slice per iteration, for - // graphs whose progress depends on native transports rather than V8 tasks. - bool pumpRunLoop = false; -}; - -// Evaluates an instantiated graph under `options`. Returns the capability -// promise for kAsync and an empty handle otherwise; the namespace always comes -// from the module itself. Throws NativeScriptException on failure, in every -// build. `canonicalPath` names the registry entry to evict on failure and -// labels the phase logs. -v8::MaybeLocal EvaluateModuleGraph( - v8::Isolate* isolate, v8::Local context, - v8::Local module, const std::string& canonicalPath, - const ModuleEvaluationOptions& options); - -// The state of an entry module's evaluation promise. kNone means the path -// names no registered ES module — a classic script settles synchronously and -// never has one, so it needs no boot backstop. -enum class EntryEvaluationState { kNone, kPending, kFulfilled, kRejected }; - -// The app's main entry, resolved from package.json's `main` (with the usual -// extension probing). Boot code needs the resolved path to ask about the -// entry's evaluation. -std::string ResolveMainEntryFromPackageJson(const std::string& baseDir); - class ModuleInternal { public: + // Installs the global require (loader::InstallCommonJs) on `context`. ModuleInternal(v8::Local context); - // Runs the entry module at `path` (main "./" or a worker entry). Throws - // NativeScriptException on failure — the exception carries the cause - // (compile/require error text, top-level-await rejection reason, or a - // directional hint for an empty namespace); callers translate at their - // boundary (workers re-arm it on the isolate for worker.onerror). - void RunModule(v8::Isolate* isolate, std::string path); + // The app's main entry: the app root resolved as a package directory + // (loader::ResolveMainEntry). Throws JsError when nothing is found. + std::string ResolveMainEntry(v8::Isolate* isolate); + // Boots `mainEntry`, ES module or CommonJS, through loader::RunMainEntry + // under `options`. Throws JsError or Terminated when the entry fails. + nativescript::common::loader::BootResult RunMainModule( + v8::Isolate* isolate, const std::string& mainEntry, + const nativescript::common::loader::BootOptions& options); + // Runs a worker's or a tool's entry module at the absolute `path` (or an + // http(s) URL). Returns the entry's evaluation promise while an ES module's + // top-level await is still running, for the caller to settle on its loop; + // empty otherwise. Throws JsError or Terminated when the entry fails. + v8::MaybeLocal RunModule(v8::Isolate* isolate, std::string path); void RunScript(v8::Isolate* isolate, std::string script); - static v8::Local LoadScript( - v8::Isolate* isolate, const std::string& path, - const ModuleEvaluationOptions& options); - // Installs `createRequire` on the `ns:module` binding object. Kept here - // rather than with the dev-loader members because it hands out the very - // require the CommonJS loader builds for every module. - static bool InstallCreateRequireBinding(v8::Local context, - v8::Local binding); - // Read + wrap + compile `path` as an ES module (consuming/producing the - // on-disk code cache) WITHOUT registering, instantiating, or evaluating it. - // On compile failure the exception is left pending on the isolate (or a - // NativeScriptException is thrown for setup failures) and the result is - // empty. This is the resolver's file loader: the resolver must only ever - // hand V8 a compiled module — evaluation order belongs to V8. `query` is - // the module key's query: it is part of the reported URL (script origin, - // import.meta.url), never of the file read or of the code cache's name. - static v8::MaybeLocal CompileFileEsModule( - v8::Isolate* isolate, const std::string& path, - const std::string& query = std::string()); - // The entry module's still-pending evaluation promise, or empty when - // evaluation has settled (classic scripts settle synchronously and always - // return empty). Callers use this after RunModule to observe a top-level - // await that outlived the settle window. Note a TLA-parked module reports - // kEvaluated while its capability promise is still pending, so this probes - // the promise (Evaluate() returns the same capability), not the status. - static v8::MaybeLocal PendingEntryEvaluation( - v8::Isolate* isolate, const std::string& path); - // The same probe, but reporting the promise's state rather than only - // "pending or not" — the boot backstop must tell a rejection from a - // successful settle. Cheap enough to call once per pump slice: a registry - // hit plus Evaluate(), which returns the existing capability promise. - // `rejectionReason` (when non-null) receives the reason's text on kRejected. - static EntryEvaluationState PollEntryEvaluation(v8::Isolate* isolate, - const std::string& path, - std::string* rejectionReason); - - // A code-cache blob is either a script blob or a module blob, and V8 rejects - // the wrong kind outright. One file compiled both ways — require('./x.js') - // and import './x.js' — would otherwise share a blob and each load would - // reject and overwrite the other's, so the two kinds get their own suffix - // and the cache actually hits. - enum class ScriptCacheKind { kClassicScript, kEsModule }; - // The blob for `path` when one was written for the file's modification time - // `sourceModifiedTime`, otherwise empty. Stats only; never reads the blob. - // Always empty in the development flavor, which never consumes a cache. - static std::string FreshScriptCachePath(const std::string& path, - ScriptCacheKind kind, - time_t sourceModifiedTime); - // Queues creation of the code cache for a script compiled from `path` as - // it was at `sourceModifiedTime`. Creation needs the isolate's thread and - // costs a fifth of a cold compile, so it runs later in short slices once - // loading goes quiet (or when the app moves to the background); the file is - // written off-thread, and skipped if the source changed since it was read. - // A no-op in the development flavor. Isolate thread only. - static void QueueScriptCache(v8::Isolate* isolate, - v8::Local script, - const std::string& path, - time_t sourceModifiedTime); - static void QueueScriptCache(v8::Isolate* isolate, - v8::Local script, - const std::string& path, - time_t sourceModifiedTime); - // Where the code cache for `path` (with its kind's suffix) lives. - static std::string GetCacheFileName(const std::string& path); private: - static void RequireCallback(const v8::FunctionCallbackInfo& info); - static void CreateRequireCallback( - const v8::FunctionCallbackInfo& 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. - v8::Local GetRequireFunction( - v8::Isolate* isolate, const std::string& dirName, - const ModuleEvaluationOptions& options); - v8::Local LoadImpl(v8::Isolate* isolate, - const std::string& moduleName, - const std::string& baseDir, bool& isData, - const ModuleEvaluationOptions& options); - // Compile (and cache) a classic script; returns the compiled Script handle. - static v8::Local LoadClassicScript(v8::Isolate* isolate, - const std::string& path); - - // Compile/link/evaluate an ES module; returns its namespace object. - static v8::Local LoadESModule( - v8::Isolate* isolate, const std::string& path, - const ModuleEvaluationOptions& options); - static v8::Local WrapModuleContent(v8::Isolate* isolate, - const std::string& path); - v8::Local LoadModule(v8::Isolate* isolate, - const std::string& modulePath, - const std::string& cacheKey, - const ModuleEvaluationOptions& options); - v8::Local LoadData(v8::Isolate* isolate, - const std::string& modulePath); - std::string ResolvePath(v8::Isolate* isolate, const std::string& baseDir, - const std::string& moduleName); - std::string ResolvePathFromPackageJson(const std::string& packageJson, - bool& error); - static v8::ScriptCompiler::CachedData* LoadScriptCache( - const std::string& path, ScriptCacheKind kind, time_t sourceModifiedTime); v8::MaybeLocal RunScriptString(v8::Isolate* isolate, v8::Local context, const std::string script); - - std::unique_ptr> requireFunction_; - std::unique_ptr> requireFactoryFunction_; - robin_hood::unordered_map>> - loadedModules_; - - struct TempModule { - public: - TempModule(ModuleInternal* module, std::string modulePath, - std::string cacheKey, - std::shared_ptr> poModuleObj) - : module_(module), - dispose_(true), - modulePath_(modulePath), - cacheKey_(cacheKey) { - module->loadedModules_.emplace(modulePath, poModuleObj); - module->loadedModules_.emplace(cacheKey, poModuleObj); - } - - ~TempModule() { - if (this->dispose_) { - this->module_->loadedModules_.erase(modulePath_); - this->module_->loadedModules_.erase(cacheKey_); - } - } - - void SaveToCache() { this->dispose_ = false; } - - private: - ModuleInternal* module_; - bool dispose_; - std::string modulePath_; - std::string cacheKey_; - }; }; } // namespace tns diff --git a/NativeScript/runtime/ModuleInternal.mm b/NativeScript/runtime/ModuleInternal.mm index 0ff16c827..b466b3601 100644 --- a/NativeScript/runtime/ModuleInternal.mm +++ b/NativeScript/runtime/ModuleInternal.mm @@ -1,1685 +1,65 @@ #include "ModuleInternal.h" -#import -#include -#include -#include -#include -#include -#include #include -#include "BuiltinLoader.h" #include "Caches.h" -#include "EventLoop.h" #include "Helpers.h" -#include "HttpLoader.h" -#include "ModuleInternalCallbacks.h" // for ResolveModuleCallback -#include "ModuleUrl.h" -#include "NativeScriptException.h" -#include "NsBuiltinModules.h" -#include "Runtime.h" #include "RuntimeConfig.h" -#include "napi/NapiModules.h" +#include "ns/loader/Boot.h" +#include "ns/loader/CommonJs.h" +#include "ns/loader/LoaderState.h" +#include "ns/loader/RequireResolver.h" using namespace v8; namespace tns { -// Helper function to check if a file path is an ES module (.mjs) but not a source map (.mjs.map) -bool IsESModule(const std::string& path) { - return path.size() >= 4 && path.compare(path.size() - 4, 4, ".mjs") == 0 && - !(path.size() >= 8 && path.compare(path.size() - 8, 8, ".mjs.map") == 0); -} - -// A package-style specifier: neither a path nor a scheme, so it may be claimed -// by a registry rather than resolved on disk. -static bool IsBareSpecifier(const std::string& specifier) { - if (specifier.empty() || specifier[0] == '.' || specifier[0] == '/' || - specifier[0] == '~') { - return false; - } - - return specifier.find(':') == std::string::npos; -} - -static std::string NormalizePath(const std::string& path); - -// How an entry module's graph settles. For local modules the bound is a yield, -// not a timeout: only nestable V8 tasks can run while these JS frames are on -// the stack, so a TLA parked on a non-nestable foreground task can never settle -// in-pump — give it one short window, then return and let the real event loop -// finish it after the turn (the Node shape; EventLoopTests pins this). HTTP -// entries must settle in-pump — the dev client needs the rejection reason -// synchronously — so they get the full deadline and the runloop slices their -// transport needs. -static ModuleEvaluationOptions BootEntryEvaluationOptions(bool isHttpModule) { - ModuleEvaluationOptions options; - options.policy = ModuleEvaluationPolicy::kSyncPumping; - options.deadlineSeconds = isHttpModule ? kModuleEvaluateDeadlineSeconds : 1.0; - options.timeoutBehavior = isHttpModule ? ModuleEvaluationOptions::TimeoutBehavior::kThrow - : ModuleEvaluationOptions::TimeoutBehavior::kReturnPending; - options.pumpRunLoop = isHttpModule; - return options; -} - -// How a graph reached through require() settles. A pumping require must settle -// or throw — handing back a half-initialized namespace is what the strict -// policy exists to prevent — so it gets the full deadline. It never slices the -// Cocoa runloop: outside boot the loop belongs to the app, and re-entering -// arbitrary runloop sources from the middle of a require would run UI callbacks -// underneath JS frames. -static ModuleEvaluationOptions RequireEvaluationOptions(ModuleEvaluationPolicy policy) { - ModuleEvaluationOptions options; - options.policy = policy; - if (policy == ModuleEvaluationPolicy::kSyncPumping) { - options.deadlineSeconds = kModuleEvaluateDeadlineSeconds; - options.timeoutBehavior = ModuleEvaluationOptions::TimeoutBehavior::kThrow; - options.pumpRunLoop = false; - } - return options; -} - -static bool IsHttpModulePath(const std::string& path) { - return !NormalizeHttpModuleUrl(path).empty(); -} - -static std::string CanonicalizeModulePath(const std::string& path) { - const std::string url = NormalizeHttpModuleUrl(path); - if (!url.empty()) { - return CanonicalizeNormalizedHttpUrlKey(url); - } - - return NormalizePath(path); -} - -// Normalize file system paths to a canonical representation so lookups in -// registry remain consistent regardless of how the path was provided. -static std::string NormalizePath(const std::string& path) { - if (path.empty()) { - return path; - } - - NSString* nsPath = [NSString stringWithUTF8String:path.c_str()]; - if (nsPath == nil) { - return path; - } - - NSString* standardized = [nsPath stringByStandardizingPath]; - if (standardized == nil) { - return path; - } - - return std::string([standardized UTF8String]); -} - -// Helper function to resolve main entry from package.json with proper extension handling -std::string ResolveMainEntryFromPackageJson(const std::string& baseDir) { - // Get the main value from package.json - id mainValue = Runtime::GetAppConfigValue("main"); - NSString* mainEntry = nil; - - if (mainValue && [mainValue isKindOfClass:[NSString class]]) { - mainEntry = (NSString*)mainValue; - } else { - // Fallback to "index" if no main field found - mainEntry = @"index"; - } - - // Try the main entry with different extensions - NSString* basePath = - [[NSString stringWithUTF8String:baseDir.c_str()] stringByAppendingPathComponent:mainEntry]; - - // Check if file exists as-is - if (tns::Exists([basePath fileSystemRepresentation])) { - return std::string([basePath UTF8String]); - } - // Try with .js extension - else if (tns::Exists( - [[basePath stringByAppendingPathExtension:@"js"] fileSystemRepresentation])) { - return std::string([[basePath stringByAppendingPathExtension:@"js"] UTF8String]); - } - // Try with .mjs extension - else if (tns::Exists( - [[basePath stringByAppendingPathExtension:@"mjs"] fileSystemRepresentation])) { - return std::string([[basePath stringByAppendingPathExtension:@"mjs"] UTF8String]); - } else { - // If none found, default to .js (let the loading system handle the error) - return std::string([[basePath stringByAppendingPathExtension:@"js"] UTF8String]); - } -} - -ModuleInternal::ModuleInternal(Local context) { - Isolate* isolate = v8::Isolate::GetCurrent(); - Local global = context->Global(); - TryCatch tc(isolate); - Local result; - if (!BuiltinLoader::RunBuiltin(context, BuiltinId::kRequireFactory).ToLocal(&result)) { - if (tc.HasCaught()) { - tns::LogError(isolate, tc); - } - Log(@"FATAL: Failed to run require factory script"); - return; - } - if (result.IsEmpty() || !result->IsFunction()) { - Log(@"FATAL: Require factory script did not return a function"); - return; - } - - this->requireFactoryFunction_ = - std::make_unique>(isolate, result.As()); - - Local requireFuncTemplate = FunctionTemplate::New( - isolate, RequireCallback, External::New(isolate, this, v8::kExternalPointerTypeTagDefault)); - this->requireFunction_ = std::make_unique>( - isolate, requireFuncTemplate->GetFunction(context).ToLocalChecked()); - - // Use shortened path for global require function to avoid V8 parsing issues - std::string globalRequirePath = "/app"; +namespace loader = nativescript::common::loader; - Local globalRequire = GetRequireFunction( - isolate, globalRequirePath, RequireEvaluationOptions(ModuleEvaluationPolicy::kSyncStrict)); - bool success = - global->Set(context, tns::ToV8String(isolate, "require"), globalRequire).FromMaybe(false); - if (!success) { - Log(@"FATAL: Failed to set global require function"); - } -} - -void ModuleInternal::RunModule(Isolate* isolate, std::string path) { - // The app entry arrives as "./"; resolve it before deciding how to run it so - // an ES module entry takes the module path instead of being require()d. A - // required entry would evaluate under the strict policy, which refuses a - // top-level-await graph outright — so this is what makes `import`/`export`, - // and a TLA entry, legal in an app's main module. Resolved with the same - // function the boot backstop's probe uses, so the evaluated module and the - // probe agree on the registry key. A CommonJS entry keeps "./" and the - // global-require route it has always taken. - if (path == "./") { - std::string mainEntry = ResolveMainEntryFromPackageJson(RuntimeConfig.ApplicationPath); - if (IsESModule(mainEntry) || IsHttpModulePath(mainEntry)) { - path = mainEntry; - } - } +ModuleInternal::ModuleInternal(Local context) { loader::InstallCommonJs(context); } - std::shared_ptr cache = Caches::Get(isolate); - Local context = cache->GetContext(); - // The ES module branch compiles and links against isolate->GetCurrentContext(), - // and a caller that enters the isolate through a fresh Isolate::Scope - // (RunMainScript) has no current context: the one Runtime::Init entered was - // popped with Init's own scope. The require branch never needed this because - // Function::Call enters the context it is handed. - Context::Scope context_scope(context); +// ES module and CommonJS shims read global.__dirname. +static void DefineGlobalDirname(Isolate* isolate, Local context) { Local globalObject = context->Global(); - bool isHttpModule = IsHttpModulePath(path); - // Ensure global.__dirname is defined so ESM/CommonJS shims relying on it work. - { - Local dirVal; - bool hasDir = globalObject->Get(context, ToV8String(isolate, "__dirname")).ToLocal(&dirVal); - if (!hasDir || dirVal->IsUndefined()) { - bool setDir = globalObject - ->Set(context, ToV8String(isolate, "__dirname"), - ToV8String(isolate, RuntimeConfig.ApplicationPath)) - .FromMaybe(false); - if (!setDir) { - Log(@"Warning: Failed to set __dirname on global object"); - } - } - } - - // ES module fast path - if (IsESModule(path) || isHttpModule) { - Local moduleNamespace; - if (isHttpModule) { - TNS_DEBUG(Esm, "run-module http-esm begin %s", NormalizeHttpModuleUrl(path).c_str()); - } - try { - // The entry runs before this thread's event loop does, so its graph can - // only make progress from the pump inside LoadESModule. - moduleNamespace = - ModuleInternal::LoadESModule(isolate, path, BootEntryEvaluationOptions(isHttpModule)); - } catch (const NativeScriptException& ex) { - Runtime* runtime = Runtime::GetRuntime(isolate); - bool terminating = isolate->IsExecutionTerminating() || - (runtime != nullptr && runtime->IsTerminationRequested()); - if (RuntimeConfig.IsDebug && !terminating) { - Log(@"***** JavaScript exception occurred *****"); - Log(@"Error loading ES module: %s", path.c_str()); - Log(@"Exception: %s", ex.getMessage().c_str()); - } - throw; - } - if (moduleNamespace.IsEmpty()) { - // `LoadESModule` returned an empty value without throwing. Provide a - // directional hint; this is the only case with no actual reason text. - throw NativeScriptException( - std::string("ES module returned empty namespace for ") + path + - " — likely a top-level await that never settled; check the device " - "console for the matching [esm][evaluate][promise-timeout] entry."); - } - if (isHttpModule) { - TNS_DEBUG(Esm, "run-module http-esm ok %s", NormalizeHttpModuleUrl(path).c_str()); - } - return; - } - - // For CommonJS modules (.js), use the traditional require() approach - Local requireObj; - bool success = globalObject->Get(context, ToV8String(isolate, "require")).ToLocal(&requireObj); - if (!success || !requireObj->IsFunction()) { - throw NativeScriptException("require function unavailable on globalThis"); - } - Local requireFunc = requireObj.As(); - Local args[] = {ToV8String(isolate, path)}; - Local result; - - TryCatch tc(isolate); - success = requireFunc->Call(context, globalObject, 1, args).ToLocal(&result); - - if (!success || tc.HasCaught()) { - // A termination is caught like an exception but carries no error value; - // naming it as the failure keeps it from being reported as one. All three - // signals, as in the settle pump: a native frame between here and the - // interrupted JS may have swallowed the sentinel on its way out. - Runtime* runtime = Runtime::GetRuntime(isolate); - if (tc.HasTerminated() || isolate->IsExecutionTerminating() || - (runtime != nullptr && runtime->IsTerminationRequested())) { - throw NativeScriptException("Module evaluation interrupted by isolate termination: " + path); - } - if (RuntimeConfig.IsDebug) { - Log(@"***** JavaScript exception occurred *****"); - Log(@"Error in require() call:"); - Log(@" Requested module: '%s'", path.c_str()); - Log(@" Called from: %s", RuntimeConfig.ApplicationPath.c_str()); - if (tc.HasCaught()) { - tns::LogError(isolate, tc); - } - } - // The TryCatch form captures the V8 exception, so a worker boundary can - // re-arm it on the isolate (ReThrowToV8) and route it to worker.onerror. - if (tc.HasCaught()) { - throw NativeScriptException(isolate, tc, std::string("require() failed for module ") + path); - } - throw NativeScriptException(std::string("require() failed for module ") + path); - } -} - -void ModuleInternal::CreateRequireCallback(const FunctionCallbackInfo& info) { - Isolate* isolate = info.GetIsolate(); - if (info.Length() < 1 || !info[0]->IsString()) { - isolate->ThrowException(Exception::TypeError( - tns::ToV8String(isolate, "createRequire expects a base directory string"))); - return; - } - - Runtime* runtime = Runtime::GetRuntime(isolate); - ModuleInternal* moduleInternal = runtime != nullptr ? runtime->GetModuleInternal() : nullptr; - if (moduleInternal == nullptr) { - isolate->ThrowException(Exception::Error(tns::ToV8String( - isolate, "createRequire is unavailable: this isolate has no module loader"))); - return; - } - - std::string dirName = tns::ToString(isolate, info[0].As()); - const bool pumping = info.Length() > 1 && info[1]->BooleanValue(isolate); - ModuleEvaluationOptions options = RequireEvaluationOptions( - pumping ? ModuleEvaluationPolicy::kSyncPumping : ModuleEvaluationPolicy::kSyncStrict); - - // ns-module.js validates these at mint time and passes undefined for - // anything the caller left out, so each present value simply overrides its - // default. The numeric one is re-checked here regardless: this binding is a - // boundary of its own, and a NaN or infinite deadline makes every deadline - // comparison in the pump false, which is an unbounded pump rather than a - // long one. - if (info.Length() > 2 && info[2]->IsNumber()) { - const double deadlineSeconds = info[2].As()->Value(); - if (!std::isfinite(deadlineSeconds) || deadlineSeconds <= 0) { - isolate->ThrowException(Exception::TypeError(tns::ToV8String( - isolate, "createRequire: 'deadlineSeconds' must be a positive finite number"))); - return; - } - options.deadlineSeconds = deadlineSeconds; - } - if (info.Length() > 3 && info[3]->IsBoolean()) { - options.timeoutBehavior = info[3]->BooleanValue(isolate) - ? ModuleEvaluationOptions::TimeoutBehavior::kThrow - : ModuleEvaluationOptions::TimeoutBehavior::kReturnPending; - } - if (info.Length() > 4 && info[4]->IsBoolean()) { - options.pumpRunLoop = info[4]->BooleanValue(isolate); - } - - info.GetReturnValue().Set(moduleInternal->GetRequireFunction(isolate, dirName, options)); -} - -bool ModuleInternal::InstallCreateRequireBinding(Local context, Local binding) { - Isolate* isolate = v8::Isolate::GetCurrent(); - Local fn; - if (!v8::Function::New(context, ModuleInternal::CreateRequireCallback).ToLocal(&fn)) { - return false; - } - fn->SetName(tns::ToV8String(isolate, "createRequire")); - return binding->CreateDataProperty(context, tns::ToV8String(isolate, "createRequire"), fn) - .FromMaybe(false); -} - -Local ModuleInternal::GetRequireFunction(Isolate* isolate, const std::string& dirName, - const ModuleEvaluationOptions& options) { - Local requireFuncFactory = requireFactoryFunction_->Get(isolate); - Local context = isolate->GetCurrentContext(); - Local requireInternalFunc = this->requireFunction_->Get(isolate); - Local args[6]{ - requireInternalFunc, - tns::ToV8String(isolate, dirName.c_str()), - Integer::New(isolate, static_cast(options.policy)), - v8::Number::New(isolate, options.deadlineSeconds), - v8::Boolean::New(isolate, - options.timeoutBehavior == ModuleEvaluationOptions::TimeoutBehavior::kThrow), - v8::Boolean::New(isolate, options.pumpRunLoop)}; - - Local result; - Local thiz = Object::New(isolate); - - TryCatch tc(isolate); - bool success = requireFuncFactory->Call(context, thiz, 6, args).ToLocal(&result); - if (!success || tc.HasCaught()) { - if (tc.HasCaught()) { - tns::LogError(isolate, tc); - } - Log(@"FATAL: Failed to call require factory function"); - // A require that cannot exist must throw when called, in every build. - result = v8::Function::New(context, [](const v8::FunctionCallbackInfo& info) { - info.GetIsolate()->ThrowException(v8::Exception::Error( - tns::ToV8String(info.GetIsolate(), "Require function unavailable"))); - }).ToLocalChecked(); - } - - if (result.IsEmpty() || !result->IsFunction()) { - Log(@"FATAL: Require factory did not return a function"); - result = v8::Function::New(context, [](const v8::FunctionCallbackInfo& info) { - info.GetIsolate()->ThrowException(v8::Exception::Error( - tns::ToV8String(info.GetIsolate(), "Require function unavailable"))); - }).ToLocalChecked(); - } - - return result.As(); -} - -// Node's `determineSpecificType` (lib/internal/errors.js), so an -// ERR_INVALID_ARG_TYPE-shaped message reads the same here as it does there. -// Deliberately side-effect free: no getter, no user `toString`, no `inspect`. -static std::string DescribeValueForTypeError(Isolate* isolate, Local value) { - if (value.IsEmpty() || value->IsUndefined()) { - return "undefined"; - } - if (value->IsNull()) { - return "null"; - } - - if (value->IsFunction()) { - std::string name = tns::ToString(isolate, value.As()->GetName()); - return name.empty() ? "an instance of Function" : "function " + name; - } - - if (value->IsObject()) { - std::string ctorName = tns::ToString(isolate, value.As()->GetConstructorName()); - return ctorName.empty() ? "an object" : "an instance of " + ctorName; - } - - // A primitive: `type ()`. - const char* typeName = "object"; - std::string rendered; - if (value->IsBoolean()) { - typeName = "boolean"; - rendered = value->IsTrue() ? "true" : "false"; - } else if (value->IsNumber()) { - typeName = "number"; - double number = value.As()->Value(); - // String(-0) is "0", but Node renders the sign, and losing it here would - // hide exactly the distinction the message is meant to surface. - rendered = (number == 0 && std::signbit(number)) ? "-0" : tns::ToString(isolate, value); - } else if (value->IsBigInt()) { - typeName = "bigint"; - rendered = tns::ToString(isolate, value) + "n"; - } else if (value->IsSymbol()) { - typeName = "symbol"; - Local description = value.As()->Description(isolate); - rendered = "Symbol(" + - (description->IsUndefined() ? std::string() : tns::ToString(isolate, description)) + - ")"; - } else { - rendered = tns::ToString(isolate, value); - } - - if (rendered.size() > 28) { - rendered = rendered.substr(0, 25) + "..."; - } - return "type " + std::string(typeName) + " (" + rendered + ")"; -} - -void ModuleInternal::RequireCallback(const FunctionCallbackInfo& info) { - Isolate* isolate = info.GetIsolate(); - - // Every path below assumes a string specifier — the builtin probe, the - // http(s) guard and the filesystem resolution all read it — so reject a - // non-string before any of them rather than casting one unchecked. - if (info.Length() < 1 || !info[0]->IsString()) { - Local received = info.Length() < 1 ? Local() : info[0]; - isolate->ThrowException(Exception::TypeError( - tns::ToV8String(isolate, "The \"id\" argument must be of type string. Received " + - DescribeValueForTypeError(isolate, received)))); - return; - } - - // Builtin modules resolve before any path handling, so they can never be - // shadowed by a file or a package, and an unknown one fails as a missing - // builtin rather than as a missing file. Only prefixed specifiers get here: - // a bare `util` still resolves through npm. - { - std::string specifier = tns::ToString(isolate, info[0].As()); - if (NsBuiltinModules::IsBuiltinScheme(specifier)) { - Local context = isolate->GetCurrentContext(); - Local exports; - if (NsBuiltinModules::GetExports(context, specifier).ToLocal(&exports)) { - info.GetReturnValue().Set(exports); - } else if (!NsBuiltinModules::IsRegistered(specifier)) { - isolate->ThrowException(Exception::Error( - tns::ToV8String(isolate, NsBuiltinModules::NotFoundMessage(specifier)))); - } - return; - } - - // Node-API addons claim a bare name only, so a path can never be diverted - // into the addon registry, and builtins keep priority over both. - if (IsBareSpecifier(specifier) && NapiModules::IsRegistered(specifier)) { - Local context = isolate->GetCurrentContext(); - Local exports; - if (NapiModules::GetExports(context, specifier).ToLocal(&exports)) { - info.GetReturnValue().Set(exports); - } else if (!isolate->HasPendingException()) { - // The addon is registered but failed to initialize. Returning - // undefined would hand the caller a module-shaped hole to trip over - // later; the failure belongs at the require() call. - isolate->ThrowException(Exception::Error( - tns::ToV8String(isolate, "Failed to initialize Node-API module '" + specifier + "'"))); - } - return; - } - } - - // Declare these outside try block so they're available in catch - std::string moduleName; - std::string callingModuleDirName; - NSString* fullPath = nil; - - try { - // Guard: URL-based modules must be loaded via dynamic import() in dev HTTP ESM mode. - moduleName = tns::ToString(isolate, info[0]); - if (!NormalizeHttpModuleUrl(moduleName).empty()) { - std::string msg = std::string("NativeScript: require() of URL module is not supported: ") + - moduleName + ". Use dynamic import() instead."; - throw NativeScriptException(msg.c_str()); - } - ModuleInternal* moduleInternal = static_cast( - info.Data().As()->Value(v8::kExternalPointerTypeTagDefault)); - - moduleName = tns::ToString(isolate, info[0].As()); - callingModuleDirName = tns::ToString(isolate, info[1].As()); - // The require factory forwards the options its require was minted with; - // an absent policy is the strict default every ordinary require uses. - ModuleEvaluationPolicy policy = ModuleEvaluationPolicy::kSyncStrict; - if (info.Length() > 2 && info[2]->IsInt32() && - info[2].As()->Value() == static_cast(ModuleEvaluationPolicy::kSyncPumping)) { - policy = ModuleEvaluationPolicy::kSyncPumping; - } - ModuleEvaluationOptions evaluationOptions = RequireEvaluationOptions(policy); - if (info.Length() > 3 && info[3]->IsNumber()) { - evaluationOptions.deadlineSeconds = info[3].As()->Value(); - } - if (info.Length() > 4 && info[4]->IsBoolean()) { - evaluationOptions.timeoutBehavior = - info[4]->BooleanValue(isolate) ? ModuleEvaluationOptions::TimeoutBehavior::kThrow - : ModuleEvaluationOptions::TimeoutBehavior::kReturnPending; - } - if (info.Length() > 5 && info[5]->IsBoolean()) { - evaluationOptions.pumpRunLoop = info[5]->BooleanValue(isolate); - } - - // Expand shortened paths back to full paths for file resolution - if (callingModuleDirName.length() > 0 && callingModuleDirName.substr(0, 4) == "/app") { - std::string expandedPath = RuntimeConfig.ApplicationPath + callingModuleDirName.substr(4); - callingModuleDirName = expandedPath; - } - - // Special handling for "./" - resolve to main entry point from package.json - if (moduleName == "./") { - std::string mainEntryPath = ResolveMainEntryFromPackageJson(RuntimeConfig.ApplicationPath); - fullPath = [NSString stringWithUTF8String:mainEntryPath.c_str()]; - } else if (moduleName.length() > 0 && moduleName[0] != '/') { - if (moduleName[0] == '.') { - NSString* callingDirNS = [NSString stringWithUTF8String:callingModuleDirName.c_str()]; - NSString* moduleNameNS = [NSString stringWithUTF8String:moduleName.c_str()]; - fullPath = - [[callingDirNS stringByAppendingPathComponent:moduleNameNS] stringByStandardizingPath]; - } else if (moduleName[0] == '~') { - // `~` is the app-root alias, so what follows it is a path relative to - // the app root whether or not the caller wrote the separator. - std::string relative = moduleName.substr(1); - size_t firstSegment = relative.find_first_not_of('/'); - relative = - firstSegment == std::string::npos ? std::string() : relative.substr(firstSegment); - fullPath = [[NSString stringWithUTF8String:RuntimeConfig.ApplicationPath.c_str()] - stringByAppendingPathComponent:[NSString stringWithUTF8String:relative.c_str()]]; - } else { - // Default: resolve in tns_modules (shared folder override removed) - NSString* tnsModulesPath = - [[NSString stringWithUTF8String:RuntimeConfig.ApplicationPath.c_str()] - stringByAppendingPathComponent:@"tns_modules"]; - fullPath = [tnsModulesPath - stringByAppendingPathComponent:[NSString stringWithUTF8String:moduleName.c_str()]]; - - const char* path1 = [fullPath fileSystemRepresentation]; - const char* path2 = - [[fullPath stringByAppendingPathExtension:@"js"] fileSystemRepresentation]; - const char* path3 = - [[fullPath stringByAppendingPathExtension:@"mjs"] fileSystemRepresentation]; - - if (!tns::Exists(path1) && !tns::Exists(path2) && !tns::Exists(path3)) { - fullPath = [tnsModulesPath stringByAppendingPathComponent:@"tns-core-modules"]; - fullPath = [fullPath - stringByAppendingPathComponent:[NSString stringWithUTF8String:moduleName.c_str()]]; - } - } - } else { - fullPath = [NSString stringWithUTF8String:moduleName.c_str()]; - } - - NSString* fileNameOnly = [fullPath lastPathComponent]; - NSString* pathOnly = [fullPath stringByDeletingLastPathComponent]; - - bool isData = false; - Local moduleObj = moduleInternal->LoadImpl( - isolate, [fileNameOnly UTF8String], [pathOnly UTF8String], isData, evaluationOptions); - - if (moduleObj.IsEmpty()) { - return; - } - - if (isData) { - // moduleObj is guaranteed to be non-empty here due to check above - info.GetReturnValue().Set(moduleObj); - } else { - Local context = isolate->GetCurrentContext(); - Local exportsObj; - bool success = - moduleObj->Get(context, tns::ToV8String(isolate, "exports")).ToLocal(&exportsObj); - if (success) { - info.GetReturnValue().Set(exportsObj); - } else { - Log(@"Warning: Failed to get exports from module object"); - } - } - } catch (NativeScriptException& ex) { - // Rethrown as-is. Wrapping it in a fresh Error erased the original's class - // and identity, so `catch (e) { e instanceof TypeError }` — and any - // reference comparison against a module's own exported error — silently - // stopped working for anything thrown through a require(). - TNS_DEBUG(Esm, "[require][fail] module=%s from=%s resolved=%s: %s", moduleName.c_str(), - callingModuleDirName.c_str(), - fullPath != nil ? [fullPath UTF8String] : "", ex.getMessage().c_str()); - ex.ReThrowToV8(isolate); - } -} - -Local ModuleInternal::LoadImpl(Isolate* isolate, const std::string& moduleName, - const std::string& baseDir, bool& isData, - const ModuleEvaluationOptions& options) { - // The specifier goes into the key verbatim. Stripping its extension made - // './config.js' and './config.json' the same key, so whichever loaded first - // answered for both. Specifier spellings that differ but resolve to one file - // ('./x' and './x.js') still share a module: they meet again at the - // resolved-path lookup below, which is the identity that matters. - std::string cacheKey = baseDir + "*" + moduleName; - auto it = this->loadedModules_.find(cacheKey); - - if (it != this->loadedModules_.end()) { - return it->second->Get(isolate); - } - - Local moduleObj; - std::string path; - - try { - path = this->ResolvePath(isolate, baseDir, moduleName); - } catch (NativeScriptException& ex) { - // Add context about the module resolution - std::string contextMsg = "Failed to resolve module: '" + moduleName + "'"; - contextMsg += "\n Base directory: " + baseDir; - contextMsg += "\n Module name: " + moduleName; - contextMsg += "\n\nOriginal error:\n" + ex.getMessage(); - - throw NativeScriptException(isolate, contextMsg, "Error"); - } - - if (path.empty()) { - throw NativeScriptException(isolate, "Cannot find module '" + moduleName + "'", "Error"); - } - - NSString* pathStr = [NSString stringWithUTF8String:path.c_str()]; - NSString* extension = [pathStr pathExtension]; - - if ([extension isEqualToString:@"json"]) { - isData = true; - } - - auto it2 = this->loadedModules_.find(path); - if (it2 != this->loadedModules_.end()) { - return it2->second->Get(isolate); - } - - if ([extension isEqualToString:@"mjs"] || [extension isEqualToString:@"js"]) { - moduleObj = this->LoadModule(isolate, path, cacheKey, options); - } else if ([extension isEqualToString:@"json"]) { - moduleObj = this->LoadData(isolate, path); - } else { - // Throw an error for unsupported file extension instead of crashing - std::string errorMsg = "Unsupported file extension: " + std::string([extension UTF8String]); - throw NativeScriptException(errorMsg); - } - - return moduleObj; -} - -static bool NamespaceHasOwn(Isolate* isolate, Local context, Local ns, - const char* name) { - return ns->HasOwnProperty(context, tns::ToV8String(isolate, name)).FromMaybe(false); -} - -// The live compiled module behind a registry key, or empty. -static Local RegisteredModuleForPath(Isolate* isolate, const std::string& canonicalPath) { - auto* registryPtr = ModuleRegistryFor(isolate); - if (registryPtr == nullptr) { - return Local(); - } - auto it = registryPtr->find(canonicalPath); - if (it == registryPtr->end()) { - return Local(); - } - return it->second.Get(isolate); -} - -// What `require()` of an ES module hands back, per Node's -// populateCJSExportsFromESM: an explicit `module.exports` export wins outright; -// a namespace with no default export, or one that already declares -// __esModule, passes through untouched; everything else gets the facade so -// transpiled consumers reading `_mod.__esModule ? _mod.default : _mod` find the -// default. Export names are arbitrary strings, hence the own-property probes. -static Local RequireExportsForNamespace(Isolate* isolate, Local context, - Local ns, const std::string& canonicalPath) { - TryCatch tc(isolate); - - if (NamespaceHasOwn(isolate, context, ns, "module.exports")) { - Local moduleExports; - if (!ns->Get(context, tns::ToV8String(isolate, "module.exports")).ToLocal(&moduleExports)) { - throw NativeScriptException(isolate, tc, - "Cannot read the 'module.exports' export of " + canonicalPath); - } - return moduleExports; - } - - bool hasDefault = NamespaceHasOwn(isolate, context, ns, "default"); - bool hasEsModuleMarker = NamespaceHasOwn(isolate, context, ns, "__esModule"); - if (!hasDefault || hasEsModuleMarker) { - return ns; - } - - Local target = RegisteredModuleForPath(isolate, canonicalPath); - if (target.IsEmpty()) { - // The load that produced this namespace registered the module under this - // very key, so a miss means the registry and the namespace disagree — - // returning the bare namespace would drop __esModule and misroute every - // transpiled consumer downstream. - throw NativeScriptException( - "require() cannot build the exports facade for " + canonicalPath + - ": the module evaluated but is absent from the registry under its canonical key"); - } - - Local facade; - if (!GetOrCreateRequireFacade(isolate, context, target, canonicalPath).ToLocal(&facade)) { - throw NativeScriptException("Cannot build the require() exports facade for " + canonicalPath); - } - return facade->GetModuleNamespace(); -} - -Local ModuleInternal::LoadModule(Isolate* isolate, const std::string& modulePath, - const std::string& cacheKey, - const ModuleEvaluationOptions& options) { - Local moduleObj = Object::New(isolate); - Local exportsObj = Object::New(isolate); - Local context = isolate->GetCurrentContext(); - bool success = - moduleObj->Set(context, tns::ToV8String(isolate, "exports"), exportsObj).FromMaybe(false); - if (!success) { - Log(@"Warning: Failed to set exports property on module object"); - } - - const PropertyAttribute readOnlyFlags = - static_cast(PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly); - - Local fileName = tns::ToV8String(isolate, modulePath); - success = - moduleObj->DefineOwnProperty(context, tns::ToV8String(isolate, "id"), fileName, readOnlyFlags) - .FromMaybe(false); - if (!success) { - Log(@"Warning: Failed to set id property on module object"); - } - - std::shared_ptr> poModuleObj = - std::make_shared>(isolate, moduleObj); - TempModule tempModule(this, modulePath, cacheKey, poModuleObj); - - // Compile/load the JavaScript/ESM source - Local scriptValue = LoadScript(isolate, modulePath, options); - - if (scriptValue.IsEmpty()) { - throw NativeScriptException(isolate, "Script loading failed for " + modulePath); - } - - // Check if this is an ES module - bool isESM = IsESModule(modulePath); - - if (isESM) { - // For ES modules, the returned value is the namespace object - - if (scriptValue.IsEmpty()) { - throw NativeScriptException(isolate, "ES module load returned empty value " + modulePath); - } - - if (!scriptValue->IsObject()) { - throw NativeScriptException(isolate, "Failed to load ES module " + modulePath); - } - - Local esmExports = RequireExportsForNamespace(isolate, context, scriptValue.As(), - CanonicalizeModulePath(modulePath)); - - bool succ = - moduleObj->Set(context, tns::ToV8String(isolate, "exports"), esmExports).FromMaybe(false); - if (!succ) { - Log(@"Warning: Failed to set exports property after module execution"); - } - - tempModule.SaveToCache(); - return moduleObj; - } - - // Check if this is the main application bundle (webpack-style IIFE) - std::string appPath = RuntimeConfig.ApplicationPath; - std::string bundlePath = appPath + "/bundle.js"; - - if (modulePath == bundlePath) { - // Main application bundle is a webpack-style IIFE that executes immediately - // It doesn't return a function, so we just create an empty exports object - tempModule.SaveToCache(); - return moduleObj; - } - - // Classic CommonJS path – expect a factory function. - if (!scriptValue->IsFunction()) { - throw NativeScriptException(isolate, - "Expected module factory to be a function for " + modulePath); - } - v8::Local moduleFunc = scriptValue.As(); - - { - TryCatch tc(isolate); - // moduleFunc = script->Run(context).ToLocalChecked().As(); - if (tc.HasCaught()) { - throw NativeScriptException(isolate, tc, "Error running script " + modulePath); - } - } - - std::string parentDir = [[[NSString stringWithUTF8String:modulePath.c_str()] - stringByDeletingLastPathComponent] UTF8String]; - - // Shorten the parentDir for GetRequireFunction to avoid V8 parsing issues with long paths - std::string shortParentDir; - if (parentDir.length() >= RuntimeConfig.ApplicationPath.length() && - parentDir.compare(0, RuntimeConfig.ApplicationPath.length(), RuntimeConfig.ApplicationPath) == - 0) { - shortParentDir = "/app" + parentDir.substr(RuntimeConfig.ApplicationPath.length()); - } else { - // Fallback: use the entire path if it doesn't start with ApplicationPath - shortParentDir = parentDir; - } - - // A module's own require inherits the options it was loaded under, so a - // pumping require stays pumping — with the same deadline and timeout - // behavior — all the way down its dependency tree. - Local require = GetRequireFunction(isolate, shortParentDir, options); - // Use full paths for __filename and __dirname to match module.id - Local requireArgs[5]{moduleObj, exportsObj, require, - tns::ToV8String(isolate, modulePath.c_str()), - tns::ToV8String(isolate, parentDir.c_str())}; - - success = moduleObj->Set(context, tns::ToV8String(isolate, "require"), require).FromMaybe(false); - if (!success) { - Log(@"Warning: Failed to set require property on module object"); - } - - { - TryCatch tc(isolate); - Local result; - Local thiz = Object::New(isolate); - - success = - moduleFunc->Call(context, thiz, sizeof(requireArgs) / sizeof(Local), requireArgs) - .ToLocal(&result); - if (!success || tc.HasCaught()) { - Runtime* runtime = Runtime::GetRuntime(isolate); - if (tc.HasTerminated() || isolate->IsExecutionTerminating() || - (runtime != nullptr && runtime->IsTerminationRequested())) { - throw NativeScriptException("Module evaluation interrupted by isolate termination: " + - modulePath); - } - throw NativeScriptException(isolate, tc, "Error calling module function"); - } - } - - tempModule.SaveToCache(); - return moduleObj; -} - -Local ModuleInternal::LoadData(Isolate* isolate, const std::string& modulePath) { - Local json; - - std::string jsonData = tns::ReadText(modulePath); - - Local jsonStr = tns::ToV8String(isolate, jsonData); - - Local context = isolate->GetCurrentContext(); - TryCatch tc(isolate); - MaybeLocal maybeValue = JSON::Parse(context, jsonStr); - if (maybeValue.IsEmpty() || tc.HasCaught()) { - std::string errMsg = "Cannot parse JSON file " + modulePath; - throw NativeScriptException(isolate, tc, errMsg); - } - - Local value = maybeValue.ToLocalChecked(); - if (!value->IsObject()) { - std::string errMsg = "JSON is not valid, file=" + modulePath; - throw NativeScriptException(errMsg); - } - - json = value.As(); - - this->loadedModules_.emplace(modulePath, std::make_shared>(isolate, json)); - - return json; -} - -Local ModuleInternal::LoadScript(Isolate* isolate, const std::string& path, - const ModuleEvaluationOptions& options) { - std::string canonicalPath = NormalizePath(path); - - if (IsESModule(canonicalPath)) { - // Treat all .mjs files as standard ES modules. require()'s default route - // cannot wait: an async graph is refused rather than pumped. - return ModuleInternal::LoadESModule(isolate, canonicalPath, options); - } - - Local