Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
7f898b5
build(runtime): take the base64 codec from the shared runtime-common …
edusperoni Dec 4, 2026
fba7f6b
feat(runtime): run the HTTP module loader on runtime-common
edusperoni Dec 5, 2026
eca54ca
build: pin runtime-common foundation and implement its platform funct…
edusperoni Dec 5, 2026
cae3f7f
feat(runtime): pump through Loop::PumpUntil
edusperoni Dec 5, 2026
9643abd
Merge remote-tracking branch 'origin/main' into feat/runtime-common
edusperoni Dec 5, 2026
35fdde5
build: pin runtime-common step 4 and implement the app-file and state…
edusperoni Dec 5, 2026
ddf63e4
feat(runtime): compile app files and keep their code caches through r…
edusperoni Dec 5, 2026
cd962c0
feat(runtime): delete the old flattened code caches once
edusperoni Dec 5, 2026
101f8ca
build: pin runtime-common at 6826386
edusperoni Dec 5, 2026
98d645a
fix(runtime): keep a non-sandboxed Catalyst app's code cache under it…
edusperoni Dec 5, 2026
141d243
fix(runtime): keep a non-sandboxed Catalyst app's HTTP module cache u…
edusperoni Dec 5, 2026
9f511e0
style: clang-format the app caches directory change
edusperoni Dec 5, 2026
9b0cf7d
build: pin runtime-common at 39e2174 and implement platform::ParseUrl
edusperoni Dec 5, 2026
8c80061
feat(runtime): take module identity from the runtime-common core
edusperoni Dec 5, 2026
ce21736
build: pin runtime-common at 3bcf603
edusperoni Dec 5, 2026
8cddd98
feat(runtime): take loader state, registry and resolution from the ru…
edusperoni Dec 5, 2026
f4a28d4
build: pin runtime-common at da7852d
edusperoni Dec 5, 2026
5cbb603
test(runtime): pin module resolution under the runtime-common core
edusperoni Dec 6, 2026
055b991
build: pin runtime-common at 8585d65
edusperoni Dec 6, 2026
b9ae5ab
feat(runtime): take the graph walk, file jobs, import callbacks and J…
edusperoni Dec 6, 2026
dbc010c
test(runtime): cover JSON module strictness and loader teardown under…
edusperoni Dec 6, 2026
4969897
build: pin runtime-common at f73c0f5
edusperoni Dec 6, 2026
510a459
test(runtime): pin a static import of '' and import JSON with its typ…
edusperoni Dec 6, 2026
14fedd9
build: pin runtime-common at ab7f353
edusperoni Dec 6, 2026
238d4b2
feat(runtime): take import.meta, the require(esm) facade and the ns:m…
edusperoni Dec 6, 2026
40bb311
test(runtime): cover import of .js, CommonJS and .cjs files and impor…
edusperoni Dec 6, 2026
12cd4fe
test(runtime): read code cache headers of format 2
edusperoni Dec 6, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
Expand Up @@ -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
59 changes: 42 additions & 17 deletions NativeScript/NativeScript.mm
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@
#include <mach-o/dyld.h>
#include <mach-o/getsect.h>
#include "inspector/JsV8InspectorClient.h"
#include "ns/Deadline.h"
#include "ns/Loop.h"
#include "ns/loader/GraphLoad.h"
#include "runtime/Caches.h"
#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"
Expand Down Expand Up @@ -151,28 +154,49 @@ - (void)runMainApplication {
tns::EntryEvaluationState::kPending;
bool entryRejected = false;

if (entryPending || tns::HasPendingAsyncModuleGraphWork()) {
const CFAbsoluteTime deadline =
CFAbsoluteTimeGetCurrent() + 2 * tns::kModuleEvaluateDeadlineSeconds;
if (entryPending || nativescript::common::loader::HasPendingGraphWork()) {
using nativescript::common::Deadline;
using nativescript::common::PumpMode;
using nativescript::common::PumpResult;
// Short, so a completion that registers the UIApplicationMain task gets to
// the Drain below promptly.
constexpr double kSliceSeconds = 0.01;

const Deadline deadline =
nativescript::common::DeadlineAfterSeconds(2 * tns::kModuleEvaluateDeadlineSeconds);
Isolate* isolate = runtime_->GetIsolate();
std::shared_ptr<tns::EventLoop> eventLoop = runtime_->GetEventLoop();
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;
PumpResult result;
{
v8::Locker locker(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
Context::Scope context_scope(Caches::Get(isolate)->GetContext());
Deadline slice = nativescript::common::DeadlineAfterSeconds(kSliceSeconds);
if (deadline.has_value() && slice.has_value() && *deadline < *slice) {
slice = deadline;
}
result = eventLoop->PumpUntil(
slice,
[&]() {
return !(entryPending || nativescript::common::loader::HasPendingGraphWork());
},
PumpMode::kPlatformWork);
}
if (!(entryPending || tns::HasPendingAsyncModuleGraphWork())) {
if (result == PumpResult::kTerminated) {
// Outranks 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 now.
terminated = true;
break;
}
if (CFAbsoluteTimeGetCurrent() >= deadline) {
if (result == PumpResult::kSettled || nativescript::common::DeadlinePassed(deadline)) {
break;
}
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.01, true);
// Outside every scope above: it may call UIApplicationMain and never
// return, and nothing held here may outlive that.
tns::Tasks::Drain();

if (entryPending) {
Expand Down Expand Up @@ -246,11 +270,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<std::chrono::milliseconds>(t2 - t1).count();
printf("Runtime initialization took %llims (version %s, V8 version %s)\n", duration,
Expand Down
3 changes: 3 additions & 0 deletions NativeScript/inspector/JsV8InspectorClient.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<const nativescript::common::LoaderConfig> loaderConfig_;
// The runtime's loop. Outlives the runtime, after which it drops posts.
std::shared_ptr<tns::EventLoop> eventLoop_;
// Work for the main isolate. Connect and disconnect go through the same
Expand Down
118 changes: 62 additions & 56 deletions NativeScript/inspector/JsV8InspectorClient.mm
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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;
}
Expand All @@ -92,35 +96,32 @@ bool ShouldRewriteSourceMapURLs() {
return message;
}

std::string path;
std::optional<std::string> 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<std::string> 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();
}

Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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.
{
Expand Down Expand Up @@ -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<bool> 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) {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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<std::string> 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<std::string> verbatim = tns::OriginToPath(fileUrl, *loaderConfig_);
if (verbatim) {
candidates.push_back(*verbatim);
}
std::optional<std::string> 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
Expand All @@ -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<NSString*>* 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<const char*>(data.bytes), data.length);
loaded = true;
break;
}
}
NSData* data =
[NSData dataWithContentsOfFile:[NSString stringWithUTF8String:candidate.c_str()]];
if (data != nil) {
content.assign(static_cast<const char*>(data.bytes), data.length);
loaded = true;
}
}
if (loaded) {
break;
}
}

json resource;
Expand Down Expand Up @@ -1559,6 +1562,9 @@ bool GetInt32(const json& value, long long& out) {
// 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().
Expand Down
1 change: 1 addition & 0 deletions NativeScript/runtime-common
Submodule runtime-common added at ab7f35
Loading
Loading