diff --git a/NativeScript/inspector/InspectorModule.h b/NativeScript/inspector/InspectorModule.h new file mode 100644 index 000000000..4a5a6023d --- /dev/null +++ b/NativeScript/inspector/InspectorModule.h @@ -0,0 +1,15 @@ +#ifndef InspectorModule_h +#define InspectorModule_h + +#include "include/v8.h" + +namespace v8_inspector { + +// The natives of the ns:inspector builtin module (runtime/js/ns-inspector.js). +// Built in every isolate; `available` is false where no frontend can attach: +// release builds and workers. +v8::MaybeLocal NsInspectorBinding(v8::Local context); + +} // namespace v8_inspector + +#endif /* InspectorModule_h */ diff --git a/NativeScript/inspector/InspectorModule.mm b/NativeScript/inspector/InspectorModule.mm new file mode 100644 index 000000000..401ca6ca9 --- /dev/null +++ b/NativeScript/inspector/InspectorModule.mm @@ -0,0 +1,347 @@ +#include "InspectorModule.h" + +#include + +#include +#include +#include +#include + +#include "Helpers.h" +#include "JsV8InspectorClient.h" +#include "include/inspector/Runtime.h" +#include "utils.h" +#include "third_party/inspector_protocol/crdtp/json.h" + +using namespace v8; + +namespace v8_inspector { + +namespace { + +StringView Make8BitStringView(const std::string& value) { + return StringView(reinterpret_cast(value.data()), value.size()); +} + +void ThrowError(Isolate* isolate, const std::string& message) { + isolate->ThrowException(Exception::Error(tns::ToV8String(isolate, message))); +} + +JsV8InspectorClient* ClientOrThrow(Isolate* isolate) { + JsV8InspectorClient* client = JsV8InspectorClient::ForIsolate(isolate); + if (client == nullptr) { + ThrowError(isolate, "The inspector is not available"); + } + return client; +} + +// The session of the frontend the first argument names, or null with an +// exception set. +V8InspectorSession* SessionOrThrow(const FunctionCallbackInfo& info, + JsV8InspectorClient* client) { + Isolate* isolate = info.GetIsolate(); + if (info.Length() < 1 || !info[0]->IsNumber()) { + ThrowError(isolate, "Invalid session"); + return nullptr; + } + auto connectionId = static_cast(info[0].As()->Value()); + V8InspectorSession* session = client->SessionFor(connectionId); + if (session == nullptr) { + ThrowError(isolate, "The session is closed"); + } + return session; +} + +// A protocol object as the JSON value a frontend would receive. V8 only +// serializes them to CBOR. +template +MaybeLocal ToValue(Local context, const T& object) { + std::vector cbor; + object.AppendSerialized(&cbor); + std::string json; + if (!v8_crdtp::json::ConvertCBORToJSON(v8_crdtp::SpanFrom(cbor), &json).ok()) { + return MaybeLocal(); + } + return JSON::Parse(context, tns::ToV8String(Isolate::GetCurrent(), json)); +} + +class FunctionInspectable final : public V8InspectorSession::Inspectable { + public: + FunctionInspectable(Isolate* isolate, Local getter) + : isolate_(isolate), getter_(isolate, getter) {} + + Local get(Local context) override { + EscapableHandleScope scope(isolate_); + TryCatch tc(isolate_); + Local value; + if (!getter_.Get(isolate_)->Call(context, Undefined(isolate_), 0, nullptr).ToLocal(&value)) { + return scope.Escape(Undefined(isolate_).As()); + } + return scope.Escape(value); + } + + private: + Isolate* isolate_; + Global getter_; +}; + +void AttachCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + JsV8InspectorClient* client = ClientOrThrow(isolate); + if (client == nullptr) { + return; + } + if (info.Length() < 1 || !info[0]->IsObject()) { + ThrowError(isolate, "attach expects a router"); + return; + } + client->SetJsDomainRouter(info[0].As()); +} + +void RegisterCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + JsV8InspectorClient* client = ClientOrThrow(isolate); + if (client == nullptr) { + return; + } + std::string name = tns::ToString(isolate, info[0]); + std::vector enabledBefore; + std::string error; + if (!client->RegisterJsDomain(name, enabledBefore, error)) { + ThrowError(isolate, error); + return; + } + Local context = isolate->GetCurrentContext(); + Local result = Array::New(isolate, static_cast(enabledBefore.size())); + for (size_t i = 0; i < enabledBefore.size(); i++) { + result + ->Set(context, static_cast(i), + Number::New(isolate, static_cast(enabledBefore[i]))) + .Check(); + } + info.GetReturnValue().Set(result); +} + +// Throws for a domain the runtime implements, with or without a client. +void CheckDomainCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + std::string name = tns::ToString(isolate, info[0]); + if (JsV8InspectorClient::IsRuntimeDomain(name)) { + ThrowError(isolate, "The " + name + " domain is implemented by the runtime"); + } +} + +void UnregisterCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + JsV8InspectorClient* client = JsV8InspectorClient::ForIsolate(isolate); + if (client == nullptr) { + return; + } + std::vector enabled; + if (info.Length() > 1 && info[1]->IsArray()) { + Local context = isolate->GetCurrentContext(); + Local ids = info[1].As(); + for (uint32_t i = 0; i < ids->Length(); i++) { + Local id; + if (ids->Get(context, i).ToLocal(&id) && id->IsNumber()) { + enabled.push_back(static_cast(id.As()->Value())); + } + } + } + client->UnregisterJsDomain(tns::ToString(isolate, info[0]), enabled); +} + +void ConnectionsCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + Local context = isolate->GetCurrentContext(); + std::vector connections; + if (JsV8InspectorClient* client = JsV8InspectorClient::ForIsolate(isolate)) { + connections = client->Connections(); + } + Local result = Array::New(isolate, static_cast(connections.size())); + for (size_t i = 0; i < connections.size(); i++) { + result + ->Set(context, static_cast(i), + Number::New(isolate, static_cast(connections[i]))) + .Check(); + } + info.GetReturnValue().Set(result); +} + +void SendCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + JsV8InspectorClient* client = JsV8InspectorClient::ForIsolate(isolate); + if (client == nullptr || info.Length() < 2 || !info[0]->IsNumber() || !info[1]->IsString()) { + return; + } + auto connectionId = static_cast(info[0].As()->Value()); + client->SendRawToConnection(connectionId, tns::ToString(isolate, info[1])); +} + +void WrapObjectCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + JsV8InspectorClient* client = ClientOrThrow(isolate); + if (client == nullptr) { + return; + } + V8InspectorSession* session = SessionOrThrow(info, client); + if (session == nullptr) { + return; + } + Local context = isolate->GetCurrentContext(); + std::string group = info.Length() > 2 && info[2]->IsString() ? tns::ToString(isolate, info[2]) + : std::string(); + bool preview = info.Length() > 3 && info[3]->BooleanValue(isolate); + std::unique_ptr remote = + session->wrapObject(context, info[1], Make8BitStringView(group), preview); + if (remote == nullptr) { + ThrowError(isolate, "The value cannot be wrapped"); + return; + } + Local result; + if (!ToValue(context, *remote).ToLocal(&result)) { + if (!isolate->IsExecutionTerminating()) { + ThrowError(isolate, "The value cannot be wrapped"); + } + return; + } + info.GetReturnValue().Set(result); +} + +void UnwrapObjectCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + JsV8InspectorClient* client = ClientOrThrow(isolate); + if (client == nullptr) { + return; + } + V8InspectorSession* session = SessionOrThrow(info, client); + if (session == nullptr) { + return; + } + if (info.Length() < 2 || !info[1]->IsString()) { + ThrowError(isolate, "Invalid remote object id"); + return; + } + std::string objectId = tns::ToString(isolate, info[1]); + std::unique_ptr error; + Local value; + Local context; + if (!session->unwrapObject(&error, Make8BitStringView(objectId), &value, &context, nullptr)) { + std::string message = error != nullptr ? ToStdString(error->string()) : std::string(); + ThrowError(isolate, message.empty() ? "Could not find object with given id" : message); + return; + } + info.GetReturnValue().Set(value); +} + +void ReleaseObjectGroupCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + JsV8InspectorClient* client = ClientOrThrow(isolate); + if (client == nullptr) { + return; + } + V8InspectorSession* session = SessionOrThrow(info, client); + if (session == nullptr) { + return; + } + session->releaseObjectGroup(Make8BitStringView(tns::ToString(isolate, info[1]))); +} + +void AddInspectedObjectCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + JsV8InspectorClient* client = ClientOrThrow(isolate); + if (client == nullptr) { + return; + } + V8InspectorSession* session = SessionOrThrow(info, client); + if (session == nullptr) { + return; + } + if (info.Length() < 2 || !info[1]->IsFunction()) { + isolate->ThrowException(Exception::TypeError( + tns::ToV8String(isolate, "addInspectedObject expects a function"))); + return; + } + session->addInspectedObject( + std::make_unique(isolate, info[1].As())); +} + +void CaptureStackTraceCallback(const FunctionCallbackInfo& info) { + Isolate* isolate = info.GetIsolate(); + JsV8InspectorClient* client = JsV8InspectorClient::ForIsolate(isolate); + if (client == nullptr) { + return; + } + std::unique_ptr trace = client->Inspector()->captureStackTrace(true); + if (trace == nullptr || trace->isEmpty()) { + return; + } + Local result; + if (ToValue(isolate->GetCurrentContext(), *trace->buildInspectorObject(0)).ToLocal(&result)) { + info.GetReturnValue().Set(result); + } +} + +// Network.MonotonicTime: seconds on the clock the platform's TimeTicks, and +// with them trace events, use on Darwin. +void MonotonicTimeCallback(const FunctionCallbackInfo& info) { + static mach_timebase_info_data_t timebase = [] { + mach_timebase_info_data_t value; + mach_timebase_info(&value); + return value; + }(); + double nanoseconds = + static_cast(mach_absolute_time()) * timebase.numer / timebase.denom; + info.GetReturnValue().Set(nanoseconds / 1e9); +} + +// Network.TimeSinceEpoch: seconds, fractional. +void WallTimeCallback(const FunctionCallbackInfo& info) { + info.GetReturnValue().Set(std::chrono::duration( + std::chrono::system_clock::now().time_since_epoch()) + .count()); +} + +void LogErrorCallback(const FunctionCallbackInfo& info) { + Log(@"ns:inspector: %s", tns::ToString(info.GetIsolate(), info[0]).c_str()); +} + +} // namespace + +MaybeLocal NsInspectorBinding(Local context) { + Isolate* isolate = Isolate::GetCurrent(); + Local binding = Object::New(isolate); + bool available = JsV8InspectorClient::ForIsolate(isolate) != nullptr; + if (!binding + ->Set(context, tns::ToV8String(isolate, "available"), v8::Boolean::New(isolate, available)) + .FromMaybe(false)) { + return MaybeLocal(); + } + + const std::pair natives[] = { + {"attach", AttachCallback}, + {"checkDomain", CheckDomainCallback}, + {"register", RegisterCallback}, + {"unregister", UnregisterCallback}, + {"connections", ConnectionsCallback}, + {"send", SendCallback}, + {"wrapObject", WrapObjectCallback}, + {"unwrapObject", UnwrapObjectCallback}, + {"releaseObjectGroup", ReleaseObjectGroupCallback}, + {"addInspectedObject", AddInspectedObjectCallback}, + {"captureStackTrace", CaptureStackTraceCallback}, + {"monotonicTime", MonotonicTimeCallback}, + {"wallTime", WallTimeCallback}, + {"logError", LogErrorCallback}, + }; + for (const auto& native : natives) { + Local function; + if (!Function::New(context, native.second).ToLocal(&function) || + !binding->Set(context, tns::ToV8String(isolate, native.first), function).FromMaybe(false)) { + return MaybeLocal(); + } + } + return binding; +} + +} // namespace v8_inspector diff --git a/NativeScript/inspector/InspectorSessions.h b/NativeScript/inspector/InspectorSessions.h index 1088fc0d3..5545ffd65 100644 --- a/NativeScript/inspector/InspectorSessions.h +++ b/NativeScript/inspector/InspectorSessions.h @@ -55,6 +55,9 @@ class InspectorSessions { bool Has(uint64_t connectionId) const; + // The frontend's session, or null once it is gone or closing. + V8InspectorSession* Find(uint64_t connectionId) const; + private: class Channel; struct Session { diff --git a/NativeScript/inspector/InspectorSessions.mm b/NativeScript/inspector/InspectorSessions.mm index a2a45af6c..e51628161 100644 --- a/NativeScript/inspector/InspectorSessions.mm +++ b/NativeScript/inspector/InspectorSessions.mm @@ -225,6 +225,11 @@ void flushProtocolNotifications() override {} return it != sessions_.end() && !it->second->closing; } +V8InspectorSession* InspectorSessions::Find(uint64_t connectionId) const { + auto it = sessions_.find(connectionId); + return it != sessions_.end() && !it->second->closing ? it->second->session.get() : nullptr; +} + void InspectorSessions::Destroy(uint64_t connectionId) { auto node = sessions_.extract(connectionId); if (node.empty()) { diff --git a/NativeScript/inspector/JsV8InspectorClient.h b/NativeScript/inspector/JsV8InspectorClient.h index dd1c2dd0f..c42c76f2b 100644 --- a/NativeScript/inspector/JsV8InspectorClient.h +++ b/NativeScript/inspector/JsV8InspectorClient.h @@ -67,6 +67,28 @@ class JsV8InspectorClient : V8InspectorClient { void registerModules(); + // For ns:inspector (InspectorModule.mm). All need the isolate's Locker. + // The client debugging `isolate`, which only the main isolate has. + static JsV8InspectorClient* ForIsolate(v8::Isolate* isolate); + // Receives the commands of the domains JS registers, and the departures of + // frontends: dispatch(connectionId, id, domain, command, params) returns + // whether it handled the command; closed(connectionId). + void SetJsDomainRouter(v8::Local router); + // Whether V8 or the runtime implements the domain. Needs no client. + static bool IsRuntimeDomain(const std::string& name); + // Fills `enabledBefore` with the frontends that enabled the domain while + // nothing handled it. False, with `error` set, for a domain V8 or the + // runtime implements, or one already registered. + bool RegisterJsDomain(const std::string& name, std::vector& enabledBefore, + std::string& error); + // `enabled`: frontends that still have it enabled, for a later + // registration of the name. + void UnregisterJsDomain(const std::string& name, const std::vector& enabled); + std::vector Connections(); + // Null once the frontend is gone or leaving. + V8InspectorSession* SessionFor(uint64_t connectionId); + V8Inspector* Inspector() { return inspector_.get(); } + void consoleLog(v8::Isolate* isolate, ConsoleAPIType method, const std::vector>& args); @@ -133,6 +155,17 @@ class JsV8InspectorClient : V8InspectorClient { nlohmann::json id; }; std::map pendingJsReplies_; + + // ns:inspector state; needs the isolate's Locker. + v8::Global jsDomainRouter_; + std::set jsDomains_; + // Frontends that sent .enable for a domain nothing handled yet. + std::map> rememberedEnables_; + // Whether the JS domain router handled the command. + bool DispatchToJsDomain(uint64_t connectionId, v8::Local context, + v8::Local message, const std::string& domain, + const std::string& command); + void NotifyJsDomainsClosed(uint64_t connectionId); int64_t lastJsRequestId_ = 0; // The process-global trace controller serves one frontend at a time. diff --git a/NativeScript/inspector/JsV8InspectorClient.mm b/NativeScript/inspector/JsV8InspectorClient.mm index 82743339b..97c4ed826 100644 --- a/NativeScript/inspector/JsV8InspectorClient.mm +++ b/NativeScript/inspector/JsV8InspectorClient.mm @@ -672,11 +672,17 @@ bool GetInt32(const json& value, long long& out) { for (auto& entry : this->jsDomainEnablers_) { entry.second.erase(item.connectionId); } + for (auto& entry : this->rememberedEnables_) { + entry.second.erase(item.connectionId); + } for (auto it = this->pendingJsReplies_.begin(); it != this->pendingJsReplies_.end();) { it = it->second.connectionId == item.connectionId ? this->pendingJsReplies_.erase(it) : std::next(it); } sessions_->Disconnect(item.connectionId); + // After the session: a hook that pauses must not hold the app for a + // frontend that is gone. + this->NotifyJsDomainsClosed(item.connectionId); this->StopHolding(item.connectionId, false); break; case InspectorQueue::Item::Kind::kMessage: @@ -904,6 +910,19 @@ bool GetInt32(const json& value, long long& out) { return; } + size_t dot = method.find('.'); + std::string domain = method.substr(0, dot); + std::string command = dot == std::string::npos ? std::string() : method.substr(dot + 1); + + // Domains registered through ns:inspector win over __registerDomainDispatcher, + // which still gets the commands their handlers do not define. The router + // answers enable and disable itself, so those never reach it. + bool jsDomain = this->jsDomains_.count(domain) != 0 && arg->IsObject(); + if (jsDomain && this->DispatchToJsDomain(connectionId, context, arg.As(), domain, + command)) { + return; + } + // Pass incoming message to a registerd domain handler if any if (!arg.IsEmpty() && arg->IsObject()) { Local domainDebugger; @@ -911,15 +930,14 @@ bool GetInt32(const json& value, long long& out) { Local domainMethodFunc = v8_inspector::GetDebuggerFunctionFromObject(context, argObject, domainDebugger); - size_t dot = method.find('.'); - std::string domain = method.substr(0, dot); - std::string command = dot == std::string::npos ? std::string() : method.substr(dot + 1); bool hasHandler = !domainMethodFunc.IsEmpty() && domainMethodFunc->IsFunction(); if (hasHandler && command == "disable") { auto& enablers = this->jsDomainEnablers_[domain]; enablers.erase(connectionId); if (!enablers.empty()) { + // Neither may a later registerDomain of the name find it enabled. + this->rememberedEnables_[domain].erase(connectionId); json response = {{"id", json_message["id"]}, {"result", json::object()}}; this->SendRawToConnection(connectionId, response.dump()); return; @@ -965,6 +983,9 @@ bool GetInt32(const json& value, long long& out) { } if (success) { + if (hasHandler && command == "disable") { + this->rememberedEnables_[domain].erase(connectionId); + } auto returnString = GetReturnMessageFromDomainHandlerResult(result, json_message["id"]); @@ -986,6 +1007,16 @@ bool GetInt32(const json& value, long long& out) { } } + // A domain JS registers later is told about this frontend then. + if (!jsDomain && (command == "enable" || command == "disable") && + !V8InspectorSession::canDispatchMethod(Make8BitStringView(method))) { + if (command == "enable") { + this->rememberedEnables_[domain].insert(connectionId); + } else { + this->rememberedEnables_[domain].erase(connectionId); + } + } + // if no handler handled the message successfully, fall-through to the default V8 implementation sessions_->Dispatch(connectionId, method, message); @@ -1001,6 +1032,148 @@ bool GetInt32(const json& value, long long& out) { } } +JsV8InspectorClient* JsV8InspectorClient::ForIsolate(Isolate* isolate) { + JsV8InspectorClient* client = instance_; + return client != nullptr && client->isolateWrapper_.BelongsTo(isolate) ? client : nullptr; +} + +void JsV8InspectorClient::SetJsDomainRouter(Local router) { + this->jsDomainRouter_.Reset(isolate_, router); +} + +bool JsV8InspectorClient::IsRuntimeDomain(const std::string& name) { + // The runtime answers these before any JS domain is asked. + static const char* kNativeDomains[] = {"IO", "Target", "Tracing"}; + bool native = std::any_of(std::begin(kNativeDomains), std::end(kNativeDomains), + [&](const char* domain) { return name == domain; }); + return native || V8InspectorSession::canDispatchMethod(Make8BitStringView(name + ".enable")); +} + +bool JsV8InspectorClient::RegisterJsDomain(const std::string& name, + std::vector& enabledBefore, + std::string& error) { + if (IsRuntimeDomain(name)) { + error = "The " + name + " domain is implemented by the runtime"; + return false; + } + if (!this->jsDomains_.insert(name).second) { + error = "The " + name + " domain is already registered"; + return false; + } + + std::set enabled; + auto remembered = this->rememberedEnables_.find(name); + if (remembered != this->rememberedEnables_.end()) { + enabled = std::move(remembered->second); + this->rememberedEnables_.erase(remembered); + } + // From here the JS domain keeps them; a later registration of the name + // gets them from UnregisterJsDomain. + auto legacy = this->jsDomainEnablers_.find(name); + if (legacy != this->jsDomainEnablers_.end()) { + for (const auto& entry : legacy->second) { + if (entry.second) { + enabled.insert(entry.first); + } + } + this->jsDomainEnablers_.erase(legacy); + } + for (uint64_t connectionId : enabled) { + if (sessions_->Has(connectionId)) { + enabledBefore.push_back(connectionId); + } + } + return true; +} + +void JsV8InspectorClient::UnregisterJsDomain(const std::string& name, + const std::vector& enabled) { + if (this->jsDomains_.erase(name) == 0) { + return; + } + for (uint64_t connectionId : enabled) { + if (sessions_->Has(connectionId)) { + this->rememberedEnables_[name].insert(connectionId); + } + } +} + +std::vector JsV8InspectorClient::Connections() { + std::vector connections; + std::lock_guard lock(this->frontendsMutex_); + for (const auto& entry : this->frontends_) { + if (sessions_->Has(entry.first)) { + connections.push_back(entry.first); + } + } + return connections; +} + +V8InspectorSession* JsV8InspectorClient::SessionFor(uint64_t connectionId) { + return sessions_->Find(connectionId); +} + +bool JsV8InspectorClient::DispatchToJsDomain(uint64_t connectionId, Local context, + Local message, const std::string& domain, + const std::string& command) { + if (this->jsDomainRouter_.IsEmpty()) { + return false; + } + Isolate* isolate = isolate_; + Local router = this->jsDomainRouter_.Get(isolate); + Local dispatch; + Local id; + Local params; + if (!router->Get(context, tns::ToV8String(isolate, "dispatch")).ToLocal(&dispatch) || + !dispatch->IsFunction() || + !message->Get(context, tns::ToV8String(isolate, "id")).ToLocal(&id) || + !message->Get(context, tns::ToV8String(isolate, "params")).ToLocal(¶ms)) { + return false; + } + + Local args[] = {Number::New(isolate, static_cast(connectionId)), id, + tns::ToV8String(isolate, domain), tns::ToV8String(isolate, command), + params}; + TryCatch tc(isolate); + Local handled; + bool called = dispatch.As()->Call(context, router, 5, args).ToLocal(&handled); + if (tc.HasCaught() && !tc.HasTerminated()) { + tns::LogError(isolate, tc); + } + // An async handler answers from a microtask. Not while paused: that would + // also run the app's own promise callbacks in the middle of paused JS. + if (!runningPauseLoop_) { + isolate->PerformMicrotaskCheckpoint(); + } + return !called || handled->BooleanValue(isolate); +} + +void JsV8InspectorClient::NotifyJsDomainsClosed(uint64_t connectionId) { + if (this->jsDomainRouter_.IsEmpty()) { + return; + } + Isolate* isolate = isolate_; + Isolate::Scope isolate_scope(isolate); + HandleScope handle_scope(isolate); + Local context = tns::Caches::Get(isolate)->GetContext(); + Context::Scope context_scope(context); + Local router = this->jsDomainRouter_.Get(isolate); + Local closed; + if (!router->Get(context, tns::ToV8String(isolate, "closed")).ToLocal(&closed) || + !closed->IsFunction()) { + return; + } + Local args[] = {Number::New(isolate, static_cast(connectionId))}; + TryCatch tc(isolate); + std::ignore = closed.As()->Call(context, router, 1, args); + if (tc.HasCaught() && !tc.HasTerminated()) { + tns::LogError(isolate, tc); + } + if (!runningPauseLoop_) { + isolate->PerformMicrotaskCheckpoint(); + } +} + void JsV8InspectorClient::HandleLoadNetworkResource(uint64_t connectionId, int msgId, const std::string& url, const std::string& sessionId) { diff --git a/NativeScript/runtime/NsBuiltinModules.cpp b/NativeScript/runtime/NsBuiltinModules.cpp index c55e859bf..b1f01f6f2 100644 --- a/NativeScript/runtime/NsBuiltinModules.cpp +++ b/NativeScript/runtime/NsBuiltinModules.cpp @@ -18,6 +18,7 @@ #include "URLSearchParamsImpl.h" #include "Worker.h" #include "WrapperLifetime.h" +#include "inspector/InspectorModule.h" using namespace v8; @@ -53,6 +54,7 @@ struct Registration { // distinct and the standard module never carries compatibility code. constexpr Registration kRegistry[] = { {"ns:interop", BuiltinId::kNsInterop, Interop::NsInteropBinding}, + {"ns:inspector", BuiltinId::kNsInspector, v8_inspector::NsInspectorBinding}, {"ns:interop/ios", BuiltinId::kNsInteropIos, Interop::NsInteropIosBinding}, {"ns:module", BuiltinId::kNsModule, NsModuleBinding}, {"ns:runtime", BuiltinId::kNsRuntime, NsRuntimeBinding}, diff --git a/NativeScript/runtime/js/ns-inspector.js b/NativeScript/runtime/js/ns-inspector.js new file mode 100644 index 000000000..8cc5aa106 --- /dev/null +++ b/NativeScript/runtime/js/ns-inspector.js @@ -0,0 +1,653 @@ +"use strict"; + +// The `ns:inspector` builtin module: JS domains for the inspector protocol. +// A domain registered here gets every command its name prefixes, from any +// connected frontend; the runtime keeps who enabled it, answers each frontend +// under its own ids, and tells the domain when a frontend leaves. See +// docs/ns-builtin-modules.md for the contract. +// +// The native side (inspector/InspectorModule.mm) routes commands here through +// the router passed to `attach`, and is the only way out to a frontend. It is +// inert in release builds and in workers, where `available` is false. + +const { + available, + attach, + checkDomain, + register, + unregister, + connections, + send, + wrapObject, + unwrapObject, + releaseObjectGroup, + addInspectedObject, + captureStackTrace, + monotonicTime, + wallTime, + logError, +} = binding; +const { + Error, + Map, + Set, + String, + TypeError, + ArrayIsArray, + ArrayPrototypePush, + ArrayPrototypeSlice, + ArrayPrototypeSplice, + FunctionPrototypeApply, + FunctionPrototypeCall, + JSONStringify, + MapPrototypeDelete, + MapPrototypeGet, + MapPrototypeSet, + NumberIsInteger, + ObjectCreate, + ObjectDefineProperty, + ObjectFreeze, + ObjectPrototypeHasOwnProperty, + PromisePrototypeThen, + PromiseResolve, + RegExpPrototypeTest, + SetIteratorPrototypeNext, + SetPrototypeAdd, + SetPrototypeDelete, + SetPrototypeHas, + SetPrototypeValues, +} = primordials; + +const kDomainName = /^[A-Z][A-Za-z0-9]*$/; +const kHooks = ["enabled", "disabled", "sessionEnabled", "sessionDisabled", "sessionClosed"]; +const kServerError = -32000; + +class ProtocolError extends Error { + constructor(code, message) { + if (!NumberIsInteger(code)) { + throw new TypeError("ProtocolError code must be an integer"); + } + super(message); + this.code = code; + } +} +ObjectDefineProperty(ProtocolError.prototype, "name", { + value: "ProtocolError", + writable: true, + configurable: true, +}); + +function setValues(set) { + const values = []; + const iterator = SetPrototypeValues(set); + for (;;) { + const entry = SetIteratorPrototypeNext(iterator); + if (entry.done) { + return values; + } + ArrayPrototypePush(values, entry.value); + } +} + +// Refused rather than coerced: a function is reserved for params built per session. +function checkParams(params) { + if (params !== undefined && + (params === null || typeof params !== "object" || ArrayIsArray(params))) { + throw new TypeError("emit expects params to be an object"); + } +} + +// Reads `then`, which may be a getter that throws. +function isThenable(value) { + return value !== null && (typeof value === "object" || typeof value === "function") && + typeof value.then === "function"; +} + +// The text of anything thrown, whatever it is. +function messageOf(error) { + try { + const message = error instanceof Error ? error.message : String(error); + return typeof message === "string" ? message : String(message); + } catch { + return ""; + } +} + +function report(error) { + try { + logError(error instanceof Error && typeof error.stack === "string" ? error.stack : `${error}`); + } catch { + // Reporting must not break the protocol bookkeeping around it. + } +} + +// Every hook is user code that may throw, or pause, during which the +// frontend may leave or another may change the domain: callers record their +// state before calling and check it again after. +function callHook(owner, name, ...args) { + try { + const hook = owner[name]; + if (typeof hook !== "function") { + return undefined; + } + return FunctionPrototypeApply(hook, owner, args); + } catch (error) { + report(error); + return undefined; + } +} + +// connectionId -> Session, for frontends that reached a JS domain. +const sessions = new Map(); +// name -> Domain +const domains = new Map(); + +class Session { + #connectionId; + #closed = false; + + constructor(connectionId) { + this.#connectionId = connectionId; + } + + get closed() { + return this.#closed; + } + + emit(method, params) { + if (typeof method !== "string") { + throw new TypeError("emit expects a method name"); + } + checkParams(params); + if (this.#closed) { + return; + } + send(this.#connectionId, JSONStringify({ method, params: params === undefined ? {} : params })); + } + + wrapObject(value, options) { + const objectGroup = options !== undefined && options !== null ? options.objectGroup : undefined; + const generatePreview = options !== undefined && options !== null && !!options.generatePreview; + this.#ensureOpen(); + return wrapObject(this.#connectionId, value, + typeof objectGroup === "string" ? objectGroup : "", generatePreview); + } + + unwrapObject(objectId) { + if (typeof objectId !== "string") { + throw new TypeError("unwrapObject expects an object id"); + } + this.#ensureOpen(); + try { + return unwrapObject(this.#connectionId, objectId); + } catch (error) { + throw new ProtocolError(kServerError, error instanceof Error ? error.message : `${error}`); + } + } + + releaseObjectGroup(objectGroup) { + if (typeof objectGroup !== "string") { + throw new TypeError("releaseObjectGroup expects a group name"); + } + this.#ensureOpen(); + releaseObjectGroup(this.#connectionId, objectGroup); + } + + addInspectedObject(get) { + if (typeof get !== "function") { + throw new TypeError("addInspectedObject expects a function"); + } + this.#ensureOpen(); + addInspectedObject(this.#connectionId, get); + } + + // Called by the router only. + static close(session) { + session.#closed = true; + } + + static connectionId(session) { + return session.#connectionId; + } + + #ensureOpen() { + if (this.#closed) { + throw new Error("The session is closed"); + } + } +} + +function sessionFor(connectionId) { + let session = MapPrototypeGet(sessions, connectionId); + if (session === undefined) { + session = new Session(connectionId); + MapPrototypeSet(sessions, connectionId, session); + } + return session; +} + +function reply(session, id, result) { + if (session.closed) { + return; + } + let message; + try { + message = JSONStringify({ id, result: result === undefined || result === null ? {} : result }); + } catch (error) { + replyError(session, id, error); + return; + } + send(Session.connectionId(session), message); +} + +function replyError(session, id, error) { + if (session.closed) { + return; + } + let isProtocolError = false; + try { + // Throws for a revoked proxy. + isProtocolError = error instanceof ProtocolError; + } catch { + // Not one of ours. + } + if (!isProtocolError) { + report(error); + } + let code = kServerError; + if (isProtocolError) { + try { + // `code` is writable, so it may no longer be an integer. + const candidate = error.code; + if (NumberIsInteger(candidate)) { + code = candidate; + } + } catch { + // Keep the default. + } + } + const message = messageOf(error); + send(Session.connectionId(session), JSONStringify({ + id, + error: { code, message: message || "Internal error" }, + })); +} + +// Answers once `value` settles, when it is a promise. +function whenSettled(value, onResult, onError) { + let thenable; + try { + thenable = isThenable(value); + } catch (error) { + onError(error); + return; + } + if (!thenable) { + onResult(value); + return; + } + try { + // Reads `constructor`, which may be a getter that throws. + PromisePrototypeThen(PromiseResolve(value), onResult, onError); + } catch (error) { + onError(error); + } +} + +class Domain { + #name; + #options; + #alwaysEnabled; + #registered = true; + // Sessions with the domain enabled, and those that enabled it or sent it a + // command, which get sessionClosed. + #enabled = new Set(); + #enabledCount = 0; + #touched = new Set(); + // Sessions whose sessionEnabled has not settled, with the replies to + // repeated enables that wait for it. + #initializing = new Map(); + + constructor(name, options, alwaysEnabled) { + this.#name = name; + this.#options = options; + this.#alwaysEnabled = alwaysEnabled; + } + + get name() { + return this.#name; + } + + get enabled() { + if (!this.#registered) { + return false; + } + return this.#alwaysEnabled ? connections().length > 0 : this.#enabledCount > 0; + } + + emit(event, params) { + if (typeof event !== "string") { + throw new TypeError("emit expects an event name"); + } + checkParams(params); + if (!this.#registered) { + return; + } + const message = JSONStringify({ + method: `${this.#name}.${event}`, + params: params === undefined ? {} : params, + }); + if (this.#alwaysEnabled) { + const ids = connections(); + for (let i = 0; i < ids.length; i++) { + send(ids[i], message); + } + return; + } + const enabled = setValues(this.#enabled); + for (let i = 0; i < enabled.length; i++) { + if (!enabled[i].closed) { + send(Session.connectionId(enabled[i]), message); + } + } + } + + unregister() { + if (!this.#registered) { + return; + } + this.#registered = false; + MapPrototypeDelete(domains, this.#name); + // Its clients still get sessionClosed when they leave. + if (setValues(this.#touched).length !== 0) { + ArrayPrototypePush(retired, this); + } + // A later registration of the name finds them enabled again. + const enabled = setValues(this.#enabled); + const stillEnabled = []; + for (let i = 0; i < enabled.length; i++) { + if (!enabled[i].closed) { + ArrayPrototypePush(stillEnabled, Session.connectionId(enabled[i])); + } + } + unregister(this.#name, stillEnabled); + } + + // The router's side. + + static dispatch(domain, session, id, command, params) { + return domain.#dispatch(session, id, command, params); + } + + static enableWithoutReply(domain, session) { + domain.#enable(session, undefined, () => {}); + } + + static close(domain, session) { + domain.#close(session); + } + + static isDone(domain) { + return setValues(domain.#touched).length === 0; + } + + #dispatch(session, id, command, params) { + if (command === "enable") { + SetPrototypeAdd(this.#touched, session); + if (this.#alwaysEnabled) { + reply(session, id); + } else { + this.#enable(session, params, () => reply(session, id)); + } + return true; + } + if (command === "disable") { + if (!this.#alwaysEnabled) { + this.#disable(session); + } + reply(session, id); + return true; + } + + const commands = this.#options.commands; + if (commands === undefined || commands === null || + !ObjectPrototypeHasOwnProperty(commands, command) || typeof commands[command] !== "function") { + return false; + } + SetPrototypeAdd(this.#touched, session); + let result; + try { + result = FunctionPrototypeCall(commands[command], commands, + params === undefined ? {} : params, session); + } catch (error) { + replyError(session, id, error); + return true; + } + whenSettled(result, (value) => reply(session, id, value), (error) => replyError(session, id, error)); + return true; + } + + #enable(session, params, done) { + if (SetPrototypeHas(this.#enabled, session)) { + const waiting = MapPrototypeGet(this.#initializing, session); + if (waiting !== undefined) { + ArrayPrototypePush(waiting, done); + } else { + done(); + } + return; + } + const first = this.#enabledCount === 0; + SetPrototypeAdd(this.#enabled, session); + this.#enabledCount++; + SetPrototypeAdd(this.#touched, session); + // Before any hook runs: a hook can pause, and the pause loop can hand + // this client's next enable to us meanwhile. + const waiting = [done]; + MapPrototypeSet(this.#initializing, session, waiting); + const settled = () => { + // Not a newer one: the client may have disabled and enabled it again. + if (MapPrototypeGet(this.#initializing, session) === waiting) { + MapPrototypeDelete(this.#initializing, session); + } + for (let i = 0; i < waiting.length; i++) { + waiting[i](); + } + }; + if (first) { + callHook(this.#options, "enabled"); + } + // The client may have left, or disabled it again, while `enabled` ran. + if (session.closed || !SetPrototypeHas(this.#enabled, session)) { + settled(); + return; + } + const result = callHook(this.#options, "sessionEnabled", session, params === undefined ? {} : params); + let thenable = false; + try { + thenable = isThenable(result); + } catch (error) { + report(error); + } + if (!thenable) { + settled(); + return; + } + whenSettled(result, settled, (error) => { + report(error); + settled(); + }); + } + + #disable(session) { + if (!SetPrototypeDelete(this.#enabled, session)) { + return; + } + this.#enabledCount--; + // A later enable starts over; replies already waiting still go out when + // the pending sessionEnabled settles. + MapPrototypeDelete(this.#initializing, session); + callHook(this.#options, "sessionDisabled", session); + if (this.#enabledCount === 0) { + callHook(this.#options, "disabled"); + } + } + + #close(session) { + this.#disable(session); + if (SetPrototypeDelete(this.#touched, session)) { + callHook(this.#options, "sessionClosed", session); + } + } +} + +const router = ObjectFreeze({ + __proto__: null, + dispatch(connectionId, id, domainName, command, params) { + const domain = MapPrototypeGet(domains, domainName); + if (domain === undefined) { + return false; + } + const session = sessionFor(connectionId); + try { + return Domain.dispatch(domain, session, id, command, params); + } catch (error) { + // The command was ours; it must not go unanswered. + replyError(session, id, error); + return true; + } + }, + closed(connectionId) { + const session = MapPrototypeGet(sessions, connectionId); + if (session === undefined) { + return; + } + Session.close(session); + MapPrototypeDelete(sessions, connectionId); + // Copies: a hook may register or unregister domains. + const names = ArrayPrototypeSlice(domainNames); + for (let i = 0; i < names.length; i++) { + const domain = MapPrototypeGet(domains, names[i]); + if (domain !== undefined) { + Domain.close(domain, session); + } + } + const retiredNow = ArrayPrototypeSlice(retired); + for (let i = 0; i < retiredNow.length; i++) { + Domain.close(retiredNow[i], session); + } + for (let i = retired.length - 1; i >= 0; i--) { + if (Domain.isDone(retired[i])) { + ArrayPrototypeSplice(retired, i, 1); + } + } + }, +}); + +// Registration order, for closing domains in a stable order. +const domainNames = []; +// Unregistered domains that some open session enabled or sent a command. +const retired = []; + +function validateOptions(options) { + if (options === undefined) { + return ObjectCreate(null); + } + if (options === null || typeof options !== "object") { + throw new TypeError("registerDomain expects an options object"); + } + for (let i = 0; i < kHooks.length; i++) { + const hook = kHooks[i]; + const value = options[hook]; + if (value !== undefined && typeof value !== "function") { + throw new TypeError(`'${hook}' must be a function`); + } + } + const commands = options.commands; + if (commands !== undefined && (commands === null || typeof commands !== "object")) { + throw new TypeError("'commands' must be an object"); + } + if (options.alwaysEnabled !== undefined && typeof options.alwaysEnabled !== "boolean") { + throw new TypeError("'alwaysEnabled' must be a boolean"); + } + return options; +} + +// Release builds and workers: the same checks, and nothing to serve. +const inertNames = new Set(); + +class InertDomain { + #name; + #registered = true; + + constructor(name) { + this.#name = name; + } + + get name() { + return this.#name; + } + + get enabled() { + return false; + } + + emit(event, params) { + if (typeof event !== "string") { + throw new TypeError("emit expects an event name"); + } + checkParams(params); + } + + unregister() { + if (this.#registered) { + this.#registered = false; + SetPrototypeDelete(inertNames, this.#name); + } + } +} + +function registerDomain(name, options) { + if (typeof name !== "string" || !RegExpPrototypeTest(kDomainName, name)) { + throw new TypeError("registerDomain expects a domain name such as 'Network'"); + } + options = validateOptions(options); + if (!available) { + checkDomain(name); + if (SetPrototypeHas(inertNames, name)) { + throw new Error(`The ${name} domain is already registered`); + } + SetPrototypeAdd(inertNames, name); + return new InertDomain(name); + } + + // Throws for a domain the runtime implements, or one already registered. + const enabledBefore = register(name); + const domain = new Domain(name, options, options.alwaysEnabled === true); + MapPrototypeSet(domains, name, domain); + for (let i = 0; i < domainNames.length; i++) { + if (domainNames[i] === name) { + ArrayPrototypeSplice(domainNames, i, 1); + break; + } + } + ArrayPrototypePush(domainNames, name); + if (options.alwaysEnabled !== true) { + for (let i = 0; i < enabledBefore.length; i++) { + Domain.enableWithoutReply(domain, sessionFor(enabledBefore[i])); + } + } + return domain; +} + +if (available) { + attach(router); +} + +exports.registerDomain = registerDomain; +exports.ProtocolError = ProtocolError; +exports.monotonicTime = monotonicTime; +exports.wallTime = wallTime; +// Native, so that the trace starts at its caller. +exports.captureStackTrace = captureStackTrace; +ObjectFreeze(exports); diff --git a/TestRunner/app/tests/NsInspectorTests.js b/TestRunner/app/tests/NsInspectorTests.js new file mode 100644 index 000000000..8640afb08 --- /dev/null +++ b/TestRunner/app/tests/NsInspectorTests.js @@ -0,0 +1,104 @@ +describe("ns:inspector", function () { + var nsInspector = require("ns:inspector"); + var registered = []; + + function register(name, options) { + var domain = nsInspector.registerDomain(name, options); + registered.push(domain); + return domain; + } + + afterEach(function () { + registered.forEach(function (domain) { + domain.unregister(); + }); + registered = []; + }); + + it("exposes frozen exports", function () { + expect(Object.isFrozen(nsInspector)).toBe(true); + }); + + // The export set is public API, declared in types/ns-inspector.d.ts and + // docs/ns-builtin-modules.md; all three must change together. + it("exposes exactly the declared surface", function () { + expect(Object.keys(nsInspector).sort()).toEqual( + ["ProtocolError", "captureStackTrace", "monotonicTime", "registerDomain", "wallTime"]); + }); + + it("is a singleton per realm", function () { + expect(require("ns:inspector")).toBe(nsInspector); + }); + + it("validates the domain name and options", function () { + expect(function () { nsInspector.registerDomain("lowercase"); }).toThrowError(TypeError); + expect(function () { nsInspector.registerDomain("Two words"); }).toThrowError(TypeError); + expect(function () { nsInspector.registerDomain("Valid", 5); }).toThrowError(TypeError); + expect(function () { nsInspector.registerDomain("Valid", { enabled: true }); }).toThrowError(TypeError); + expect(function () { nsInspector.registerDomain("Valid", { commands: 1 }); }).toThrowError(TypeError); + expect(function () { nsInspector.registerDomain("Valid", { alwaysEnabled: "yes" }); }).toThrowError(TypeError); + }); + + it("refuses the domains the runtime implements", function () { + ["Runtime", "Debugger", "Profiler", "HeapProfiler", "Target", "IO", "Tracing"].forEach(function (name) { + expect(function () { nsInspector.registerDomain(name); }).toThrowError(/implemented by the runtime/); + }); + }); + + it("registers a domain again after it unregisters", function () { + var domain = register("NsInspectorTestsOwner"); + expect(domain.name).toBe("NsInspectorTestsOwner"); + domain.unregister(); + expect(register("NsInspectorTestsOwner").name).toBe("NsInspectorTestsOwner"); + }); + + it("is not enabled without a client, and emits nowhere", function () { + var domain = register("NsInspectorTestsQuiet", { commands: {} }); + expect(domain.enabled).toBe(false); + domain.emit("event", { a: 1 }); + domain.emit("event"); + expect(function () { domain.emit(5); }).toThrowError(TypeError); + [null, 1, "x", [], function () {}].forEach(function (params) { + expect(function () { domain.emit("event", params); }).toThrowError(TypeError); + }); + }); + + it("builds protocol errors with a code", function () { + var error = new nsInspector.ProtocolError(-32602, "bad params"); + expect(error instanceof Error).toBe(true); + expect(error.name).toBe("ProtocolError"); + expect(error.code).toBe(-32602); + expect(error.message).toBe("bad params"); + expect(function () { return new nsInspector.ProtocolError("x", "y"); }).toThrowError(TypeError); + }); + + it("reads the clocks", function () { + var first = nsInspector.monotonicTime(); + var second = nsInspector.monotonicTime(); + expect(typeof first).toBe("number"); + expect(second >= first).toBe(true); + expect(Math.abs(nsInspector.wallTime() - Date.now() / 1000)).toBeLessThan(5); + }); + + it("captures the caller's stack when the inspector is available", function () { + var trace = nsInspector.captureStackTrace(); + if (trace !== undefined) { + expect(Array.isArray(trace.callFrames)).toBe(true); + expect(trace.callFrames.length).toBeGreaterThan(0); + } + }); + + it("is inert in a worker", function (done) { + var worker = new Worker("./nsInspectorWorker.js"); + worker.onmessage = function (event) { + expect(event.data).toEqual({ enabled: false, stack: "undefined", clock: "number" }); + worker.terminate(); + done(); + }; + worker.onerror = function (event) { + expect(String(event.message)).toBe(""); + worker.terminate(); + done(); + }; + }); +}); diff --git a/TestRunner/app/tests/index.js b/TestRunner/app/tests/index.js index 7be398e09..c8cb0b79e 100644 --- a/TestRunner/app/tests/index.js +++ b/TestRunner/app/tests/index.js @@ -135,6 +135,7 @@ require("./ProxyReceiverTests"); require("./InvalidReceiverTests"); require("./NsRuntimeTests"); require("./NsWorkerThreadsTests"); +require("./NsInspectorTests"); require("./NsUrlTests"); require("./NsInteropTests"); require("./GCFinalizerTests"); diff --git a/TestRunner/app/tests/nsInspectorWorker.js b/TestRunner/app/tests/nsInspectorWorker.js new file mode 100644 index 000000000..118e2dd9e --- /dev/null +++ b/TestRunner/app/tests/nsInspectorWorker.js @@ -0,0 +1,8 @@ +var nsInspector = require("ns:inspector"); +var domain = nsInspector.registerDomain("NsInspectorWorkerDomain", { commands: {} }); +domain.emit("event", {}); +postMessage({ + enabled: domain.enabled, + stack: typeof nsInspector.captureStackTrace(), + clock: typeof nsInspector.monotonicTime(), +}); diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 8aaf580ca..91862ffc2 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -918,6 +918,93 @@ New code should import from the modules. also what first builds the three modules in a realm that has not required them. +### `ns:inspector` + +Inspector protocol domains implemented in JavaScript, served to every +connected client (DevTools windows, CDP scripts). **Experimental, iOS-only** +until the Android runtime ships it. + +| export | description | +|---|---| +| `registerDomain(name, options?)` | Handles every command `name.*` from every client and returns the domain. Throws a `TypeError` for a name that is not a capitalized identifier or for malformed options, and an `Error` for a domain the runtime implements (`Runtime`, `Debugger`, `Profiler`, `HeapProfiler`, `Console`, `Schema`, `Target`, `IO`, `Tracing`) or, for now, one already registered. | +| `ProtocolError` | `new ProtocolError(code, message)`: thrown or rejected by a command to answer with that protocol error code. | +| `monotonicTime()` | Seconds on the monotonic clock trace events use, sub-millisecond (`Network.MonotonicTime`). | +| `wallTime()` | Seconds since the epoch, fractional (`Network.TimeSinceEpoch`). | +| `captureStackTrace()` | The caller's stack as a `Runtime.StackTrace` (`Network.Initiator.stack`). | + +`options`: the hooks `enabled()`, `disabled()`, `sessionEnabled(session, +params)`, `sessionDisabled(session)`, `sessionClosed(session)`; `commands`, +an object of command handlers `(params, session) => result`; and +`alwaysEnabled`, for domains with no `enable` command. + +```js +import { registerDomain } from "ns:inspector"; + +const network = registerDomain("Network", { + sessionEnabled(session) { + // replay state to a client that enabled the domain + }, + commands: { + async getResponseBody({ requestId }, session) { + return { body: await bodyOf(requestId), base64Encoded: false }; + }, + }, +}); + +if (network.enabled) { + network.emit("requestWillBeSent", params); +} +``` + +Rules: + +- **The runtime owns `enable` and `disable`.** It answers them, keeps which + clients enabled the domain, and runs the hooks; handlers never receive them. + `enabled` runs for the first client and `disabled` after the last. + `domain.emit` reaches the clients that enabled the domain, or every client + for an `alwaysEnabled` one. +- **A client that enabled a domain before it was registered** (or while it + was unregistered) is enabled at registration: `enabled` and + `sessionEnabled` run then. `params` may be `undefined` there instead of + what the client's `enable` carried. +- **Commands may be async.** The returned value, or what a returned promise + resolves to, answers the command; `undefined` answers `{}`. A throw or + rejection answers with an error whose code is the `ProtocolError`'s, or + -32000. A reply never reaches another client, and one for a client that + left is dropped. A command the handlers do not define goes on to the + domain's `__registerDomainDispatcher` handler if there is one, and + otherwise to V8, which does not know it. +- **Per client, messages go out in the order they are sent.** Events a + command emits precede its reply, and events `sessionEnabled` emits precede + the reply to `enable`, which waits for a promise `sessionEnabled` returns. +- **Disabling is not leaving.** `sessionClosed` runs once a client leaves, + for every client that enabled the domain or sent it a command, after + `sessionDisabled` if it had the domain enabled. Cleanup that must happen + belongs there. +- **Commands run while the app is paused.** A command that must work at a + breakpoint answers synchronously: promise callbacks, the handler's own + included, run only after the resume. +- **The `session` argument** stands for one client for as long as it is + connected: `closed`, `emit(method, params)`, and `wrapObject(value, + { objectGroup?, generatePreview? })`, `unwrapObject(objectId)`, + `releaseObjectGroup(objectGroup)` and `addInspectedObject(get)` for remote + objects. An object id belongs to the client it was made for, so wrapped + objects are never broadcast. `addInspectedObject` makes the getter's value + `$0` in that client's console. Once the client has left, `emit` does + nothing and the object methods throw. +- **Event params are an object.** `emit` throws a `TypeError` for any other + `params` but `undefined`, which sends `{}`. +- **The runtime sees some commands first.** It answers + `Network.loadNetworkResource`, `IO.*`, `Tracing.*` and `Target.*` itself, + and they reach no domain. It may also act on other commands natively before + passing them on to the domain. +- **A domain registered with `__registerDomainDispatcher` too** is handled + here; the dispatcher keeps the commands `commands` does not define, and + never receives `enable` or `disable`. +- **In release builds and in workers** the module loads, `registerDomain` + returns an inert domain (`enabled` is false, `emit` does nothing), and + `captureStackTrace` returns `undefined`. + ### `node:` compatibility shims The same registry serves the `node:` scheme with **compatibility shims** so @@ -1316,7 +1403,7 @@ resolvers read the same table differently: - The **`ns:`/`node:` resolver** — the app-facing one, behind `require()`, `import` and `import()` — serves only rows *not* marked internal-only. An internal-only specifier fails exactly as a name absent from the table does. - Eleven rows are public today: `ns:interop`, `ns:interop/ios`, `ns:module`, + Twelve rows are public today: `ns:inspector`, `ns:interop`, `ns:interop/ios`, `ns:module`, `ns:runtime`, `ns:url`, `ns:util`, `ns:worker_threads`, `node:module`, `node:url`, `node:util`, `node:worker_threads`. `ns:interop/visionos` and `ns:interop/macos` are aliases, canonicalized to `ns:interop/ios` before any diff --git a/download_v8.sh b/download_v8.sh index 1418fba91..5bb5e2fed 100755 --- a/download_v8.sh +++ b/download_v8.sh @@ -67,7 +67,8 @@ fi # checkout looking up to date. installed() { [ -f "$STAMP" ] && [ "$(cat "$STAMP")" = "$RELEASE" ] \ - && [ -f "$NS_DIR/include/v8.h" ] && [ -d "$NS_DIR/inspector" ] + && [ -f "$NS_DIR/include/v8.h" ] \ + && [ -f "$NS_DIR/inspector/third_party/inspector_protocol/crdtp/json.h" ] } if [ "$FORCE" = "0" ] && installed; then diff --git a/tools/js2c-inputs.xcfilelist b/tools/js2c-inputs.xcfilelist index ca3913c1d..61957e156 100644 --- a/tools/js2c-inputs.xcfilelist +++ b/tools/js2c-inputs.xcfilelist @@ -17,6 +17,7 @@ $(SRCROOT)/NativeScript/runtime/js/node-module.js $(SRCROOT)/NativeScript/runtime/js/node-url.js $(SRCROOT)/NativeScript/runtime/js/node-util.js $(SRCROOT)/NativeScript/runtime/js/node-worker-threads.js +$(SRCROOT)/NativeScript/runtime/js/ns-inspector.js $(SRCROOT)/NativeScript/runtime/js/ns-interop.js $(SRCROOT)/NativeScript/runtime/js/ns-interop-ios.js $(SRCROOT)/NativeScript/runtime/js/ns-module.js diff --git a/tools/v8/vendor_inspector_sources.py b/tools/v8/vendor_inspector_sources.py index c831d7baa..ede6ca0e5 100644 --- a/tools/v8/vendor_inspector_sources.py +++ b/tools/v8/vendor_inspector_sources.py @@ -21,6 +21,7 @@ "src/inspector/v8-stack-trace-impl.h", "src/inspector/v8-console-message.h", "src/inspector/v8-inspector-session-impl.h", + "third_party/inspector_protocol/crdtp/json.h", ] INCLUDE_RE = re.compile(r'^\s*#\s*include\s*[<"]([^>"]+)[>"]', re.MULTILINE) diff --git a/types/index.d.ts b/types/index.d.ts index 0bef9864c..b0ddfd2a1 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -26,6 +26,7 @@ // in docs/ns-builtin-modules.md, not something to restate in types that would // then conflict. +/// /// /// /// diff --git a/types/ns-inspector.d.ts b/types/ns-inspector.d.ts new file mode 100644 index 000000000..7a42ecb5b --- /dev/null +++ b/types/ns-inspector.d.ts @@ -0,0 +1,97 @@ +declare module "ns:inspector" { + /** + * One connected inspector client (a DevTools window, a CDP script). The + * object stays the same for as long as the client is connected, so it can + * key a map. Once the client has left, `closed` is true, `emit` does + * nothing, and the object methods throw. + */ + export interface InspectorSession { + readonly closed: boolean; + /** Sends an event to this client only, e.g. `"Network.dataReceived"`. */ + emit(method: string, params?: object): void; + /** + * A `Runtime.RemoteObject` for `value`, valid for this client only: an + * object id names nothing, or something else, in another client. The + * value is held until the client releases `objectGroup`, releases the + * object, or leaves. + */ + wrapObject(value: unknown, options?: { objectGroup?: string; generatePreview?: boolean }): object; + /** The value behind one of this client's object ids. Throws a `ProtocolError` for an unknown id. */ + unwrapObject(objectId: string): unknown; + releaseObjectGroup(objectGroup: string): void; + /** + * Makes the getter's value `$0` in this client's console, and moves the + * previous ones to `$1`..`$4`. Called on every read; a getter that + * throws reads as `undefined`. + */ + addInspectedObject(get: () => unknown): void; + } + + /** + * The value or promise a command returns becomes its result; `undefined` + * becomes `{}`. A throw or rejection answers with an error: a + * `ProtocolError`'s code, -32000 otherwise. + */ + export type InspectorCommand = (params: any, session: InspectorSession) => unknown; + + export interface DomainOptions { + /** The first client enabled the domain. */ + enabled?(): void; + /** The last client disabled it, or left. */ + disabled?(): void; + /** + * This client enabled it. Events sent from here reach the client before + * the reply to its `enable`, which waits for a returned promise. + */ + sessionEnabled?(session: InspectorSession, params: any): unknown; + /** This client disabled it, or left. It may enable it again. */ + sessionDisabled?(session: InspectorSession): void; + /** + * This client left, having enabled the domain or sent it a command: drop + * everything kept for it. + */ + sessionClosed?(session: InspectorSession): void; + /** By command name, without the domain: `{ getResponseBody(params, session) {} }`. */ + commands?: Record; + /** + * For domains without `enable` (`Input`, `Emulation`): events reach every + * client, and `enable`/`disable` are only acknowledged. + */ + alwaysEnabled?: boolean; + } + + export interface InspectorDomain { + readonly name: string; + /** Whether any client has it enabled. Always false in release builds and workers. */ + readonly enabled: boolean; + /** Sends `.` to every client that enabled the domain. */ + emit(event: string, params?: object): void; + /** Stops handling the domain; a later registration of the name takes over. */ + unregister(): void; + } + + /** + * Handles the commands of `name` from every connected client. Throws for + * a domain the runtime implements (`Runtime`, `Debugger`, `Target`, ...) and, + * for now, for one already registered. In release builds and in workers the + * domain is inert: `enabled` is false and `emit` does nothing. + */ + export function registerDomain(name: string, options?: DomainOptions): InspectorDomain; + + /** An error a command can throw to answer with a chosen protocol error code. */ + export class ProtocolError extends Error { + constructor(code: number, message: string); + readonly code: number; + } + + /** `Network.MonotonicTime`: seconds on the clock trace events use, sub-millisecond. */ + export function monotonicTime(): number; + /** `Network.TimeSinceEpoch`: seconds since the epoch, fractional. */ + export function wallTime(): number; + /** + * A `Runtime.StackTrace` of the caller's stack, for `Network.Initiator`. + * Script ids belong to the isolate, so it can go to every client. + * `undefined` in release builds and workers. + */ + export function captureStackTrace(): object | undefined; +} diff --git a/v8ios.xcodeproj/project.pbxproj b/v8ios.xcodeproj/project.pbxproj index 13721fbf5..cee09bfbd 100644 --- a/v8ios.xcodeproj/project.pbxproj +++ b/v8ios.xcodeproj/project.pbxproj @@ -350,8 +350,10 @@ A1B2C3D40000000000000004 /* WorkerInspectorClient.mm in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000002 /* WorkerInspectorClient.mm */; }; A1B2C3D40000000000000007 /* InspectorSessions.h in Headers */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000005 /* InspectorSessions.h */; }; A1B2C3D4000000000000000B /* InspectorQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000009 /* InspectorQueue.h */; }; + A1B2C3D4000000000000000F /* InspectorModule.h in Headers */ = {isa = PBXBuildFile; fileRef = A1B2C3D4000000000000000D /* InspectorModule.h */; }; A1B2C3D40000000000000008 /* InspectorSessions.mm in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000006 /* InspectorSessions.mm */; }; A1B2C3D4000000000000000C /* InspectorQueue.mm in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4000000000000000A /* InspectorQueue.mm */; }; + A1B2C3D40000000000000010 /* InspectorModule.mm in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4000000000000000E /* InspectorModule.mm */; }; F6191AB129C0FCE8003F588F /* InspectorServer.h in Headers */ = {isa = PBXBuildFile; fileRef = F6191AA929C0FCE7003F588F /* InspectorServer.h */; }; F6191AB229C0FCE8003F588F /* InspectorServer.mm in Sources */ = {isa = PBXBuildFile; fileRef = F6191AAA29C0FCE7003F588F /* InspectorServer.mm */; settings = {COMPILER_FLAGS = "-fobjc-arc"; }; }; F6191AB629C0FF87003F588F /* utils.h in Headers */ = {isa = PBXBuildFile; fileRef = F6191AB429C0FF86003F588F /* utils.h */; }; @@ -912,8 +914,10 @@ A1B2C3D40000000000000002 /* WorkerInspectorClient.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = WorkerInspectorClient.mm; sourceTree = ""; }; A1B2C3D40000000000000005 /* InspectorSessions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = InspectorSessions.h; sourceTree = ""; }; A1B2C3D40000000000000009 /* InspectorQueue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = InspectorQueue.h; sourceTree = ""; }; + A1B2C3D4000000000000000D /* InspectorModule.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = InspectorModule.h; sourceTree = ""; }; A1B2C3D40000000000000006 /* InspectorSessions.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = InspectorSessions.mm; sourceTree = ""; }; A1B2C3D4000000000000000A /* InspectorQueue.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = InspectorQueue.mm; sourceTree = ""; }; + A1B2C3D4000000000000000E /* InspectorModule.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = InspectorModule.mm; sourceTree = ""; }; F6191AA929C0FCE7003F588F /* InspectorServer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = InspectorServer.h; sourceTree = ""; }; F6191AAA29C0FCE7003F588F /* InspectorServer.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = InspectorServer.mm; sourceTree = ""; }; F6191AB429C0FF86003F588F /* utils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = utils.h; sourceTree = ""; }; @@ -1708,8 +1712,10 @@ A1B2C3D40000000000000002 /* WorkerInspectorClient.mm */, A1B2C3D40000000000000005 /* InspectorSessions.h */, A1B2C3D40000000000000009 /* InspectorQueue.h */, + A1B2C3D4000000000000000D /* InspectorModule.h */, A1B2C3D40000000000000006 /* InspectorSessions.mm */, A1B2C3D4000000000000000A /* InspectorQueue.mm */, + A1B2C3D4000000000000000E /* InspectorModule.mm */, F6191AA929C0FCE7003F588F /* InspectorServer.h */, F6191AAA29C0FCE7003F588F /* InspectorServer.mm */, 91B25A0829DAC83D00E3CE04 /* ns-v8-tracing-agent-impl.mm */, @@ -1764,6 +1770,7 @@ A1B2C3D40000000000000003 /* WorkerInspectorClient.h in Headers */, A1B2C3D40000000000000007 /* InspectorSessions.h in Headers */, A1B2C3D4000000000000000B /* InspectorQueue.h in Headers */, + A1B2C3D4000000000000000F /* InspectorModule.h in Headers */, 6573B9D0291FE29F00B0ED7C /* JSIV8ValueConverter.h in Headers */, C20AB5E726E1015300E2B41D /* OneByteStringResource.h in Headers */, C2DDEBAC229EAC8300345BFE /* ObjectManager.h in Headers */, @@ -2514,6 +2521,7 @@ A1B2C3D40000000000000004 /* WorkerInspectorClient.mm in Sources */, A1B2C3D40000000000000008 /* InspectorSessions.mm in Sources */, A1B2C3D4000000000000000C /* InspectorQueue.mm in Sources */, + A1B2C3D40000000000000010 /* InspectorModule.mm in Sources */, C2DDEB9C229EAC8300345BFE /* ClassBuilder.cpp in Sources */, C266569322AFFF7E00EE15CC /* Pointer.cpp in Sources */, F1CB51832D5C37100042555E /* URLPatternImpl.cpp in Sources */,