Skip to content

Latest commit

 

History

History
932 lines (775 loc) · 52 KB

DESIGN.md

File metadata and controls

932 lines (775 loc) · 52 KB

A shared module-loader core for the iOS and Android runtimes

Status: proposal, 2026-12-04, updated 2026-12-05. Step 1 of §9 (this repository and its build wiring) is done, and step 5 (the HTTP policy core) is built in ns/http/. F3 (a submodule repository), F7 (the nativescript::common namespace) and D1–D10 are decided; the rest of §7 is open. iOS #622 has since merged (052675a1); its Android port is NativeScript/android #2177.

Baseline: NativeScript/ios origin/main 73c99f9f, NativeScript/android origin/main a80675dfb, open iOS PR #622, the in-progress Android port of #622 (uncommitted, snapshot of 2026-12-04), and open Android PR #2104.

Assumption, as stated in the request: both runtimes build against the same V8. They already do (14.9.207.39 headers on both). The only V8 config difference is pointer compression and Wasm: on for Android 64-bit, off on iOS. None of the loader code depends on it.

Scope: ES module loading, CommonJS require, the V8 code cache and the HTTP module loader. Other mirrored subsystems (URL, structured clone, messaging, builtin JS and so on) sit on the same foundation. They are ranked in §9 but not designed here.

Layering and direction

NativeScript has two layers, and this repository holds the first:

  1. The app runtime: what loading a NativeScript app needs from the ground up. Builtins, module loading, the code cache, the event loop, web globals.
  2. Native calling: the FFI that exposes platform APIs to JS. It is heading to an ns:native module that any engine can load.

NativeScript/runtimes covers only the second layer: native calling on several engines, through Node-API and its nativescript::engine layer. Its module loading does just enough to run code. This repository aims at a complete app runtime.

The order:

  1. Unify the app runtime across iOS and Android on V8 (this document).
  2. Shape and build ns:native.
  3. Port both to a common API that is engine-agnostic, and possibly platform-agnostic, with each engine and platform supplying its primitives. Where an existing engine API is too narrow it grows. nativescript::engine has no module records, code cache or off-thread compile today.
  4. Bring native calling to any engine, without the app-runtime parts other engines don't need.

Rules that follow from it:

  • Performance before neutrality. V8 is the target now, and no path gets slower to avoid a V8 type. Example: per-runtime state is reached from the v8::Isolate* that V8 hands every callback, through an isolate data slot, not looked up by an engine-neutral id on each call. Neutral shapes are taken where they are free; where they cost, the V8 type stays, inside the V8 layer.
  • V8 calls are confined. Policy (resolution, import maps, the graph walk, cache validity, the HTTP gate and retry) has no V8 dependency and is host-tested. V8 calls live in their own files. There is no virtual engine interface; step 3 adds a second implementation of those files, and until then they are the list of what an engine API has to provide.
  • Namespace: nativescript::common, subdivided by component (nativescript::common::base64, ::loader, ::platform, ::http). One sub-namespace stays clear of the flat nativescript:: names in NativeScript/runtimes. No nested namespace is called v8, because inside nativescript::common it would hide ::v8. Headers stay under ns/: a nativescript/ include root matches the NativeScript/ source folders of all three repositories on case-insensitive file systems.

1. Summary

  • The loader already exists twice as one design. Every unit has the same name and structure on both sides. Comments say "mirroring iOS" and "the iOS port of the Android EventLoop". The PRs come in pairs.

  • The code itself has drifted. After normalizing formatting and stripping comments, line overlap is 55% in ModuleInternalCallbacks, 34% in HttpLoader and 23% in ModuleInternal. That is not because the logic is platform specific. Most differences are helper names, state access, error plumbing and real behaviour drift.

  • Genuinely platform-specific code is small and easy to name:

    • how to read an app file (POSIX on iOS; on Android with #2104, layered files that can come from the APK);
    • how to pump the thread (CFRunLoop on iOS, ALooper on Android);
    • how to fetch a URL (NSURLSession on iOS, OkHttp or HttpURLConnection on Android);
    • how to start a background thread (QoS and autorelease pool on Apple);
    • where caches go;
    • how the app says "I went to the background";
    • where config, logging and the debug flag come from.
  • Porting is about half of all runtime work. Between 2026-09-04 and 2026-12-04:

    • 35 of 81 iOS runtime PRs and 27 of 66 Android runtime PRs were ports of each other;
    • that is ~15.0k and ~15.2k changed lines, about 57% and 51% of runtime churn;
    • the lag ran from same-day to 55 days.
  • #622 is the measuring stick. It adds 435 substantive lines on iOS.

    • 305 of them (70%) reappear verbatim, whitespace aside, in the Android port.
    • Of the rest, 25 iOS lines and 36 Android lines are platform calls.
    • 26 Android lines are a new pump primitive.
    • The remainder (102 iOS, 153 Android) are renames, plus #622 being threaded through code that had already diverged.

    With the core proposed here, the port would be a ~35-line Java/JNI lifecycle hook. The interface would have grown by a few generic primitives (§6.1).

  • Unifying finds bugs. The comparison turned up a dozen behaviour bugs that exist on only one side (§8). Several of them are worth fixing before or regardless of unification.


2. What is shared today (measured)

Metric: lines of the iOS file that diff matches to the Android file. Both sides first go through a comment-stripping pass that respects string literals, then one clang-format style (Google, 100 columns), with blank lines dropped. The numbers are rough, because diff alignment is not semantic, but they are much closer than raw diff -w. That is because iOS uses 2-space indents and 80 columns, while Android uses 4-space indents and 100 columns. (A first pass without string awareness under-counted the loader files.)

Pair Common lines Why the rest differs
NativeScriptPlatform 100% nothing; the .mm contains no ObjC
Base64, ModuleBinding ~99% one include
TextEncoding, StructuredSerialization, Messaging 92–97% helper names, state access, small drift
URL, URLSearchParams, URLPattern, BuiltinLoader 79–87% helper names, state access, three URL behaviour drifts
NsBuiltinModules ~65% platform registry rows, logging
ModuleInternalCallbacks (ESM) ~55% the same algorithm unit by unit, with drifted resolution, identity, pump and teardown (report A)
ModuleInternal (CJS + evaluation) ~23% ESM evaluation is near identical; CommonJS resolution diverged structurally, with a native resolver on iOS and Java Module.java on Android
HttpLoader ~34% policy is mirrored; the transport is genuinely different (report C)

Per unit, the ESM resolver/registry report counts about 85% of ModuleInternalCallbacks as "the same algorithm". The line overlap is low because names, state accessors and error types differ on almost every line.

Already identical in substance:

  • HTTP URL spelling and canonical keys;
  • response classification and its error texts;
  • the allowlist matcher;
  • the require(esm) facade, registry mutation and invalidation;
  • dynamic-import waiters;
  • the settle policies (kSyncStrict / kSyncPumping / kAsync);
  • the entry-evaluation probes;
  • the off-thread compile gate.

3. Shape of the proposal

 ┌───────────────────────────────────────────────────────────────┐
 │ builtin JS (ns-module.js, require-factory.js, …)  — shared    │
 ├───────────────────────────────────────────────────────────────┤
 │ common::loader  — the shared core                             │
 │   esm/   registry, identity, import maps, resolver, graph     │
 │          walk, dynamic import, import.meta, ns:module binding │
 │   cjs/   resolver (node_modules walk), wrapper, require cache │
 │   eval/  EvaluateModuleGraph, settle policies, entry probes,  │
 │          boot backstop loop                                   │
 │   cache/ code-cache format, naming, freshness, deferred       │
 │          creation queue (#622 shape)                          │
 │   http/  gate, canonicalization, classification, retry and    │
 │          deadline, cache switch, Clear-Site-Data, lanes       │
 │   jobs/  stream-compile pool, compile gate                    │
 ├───────────────────────────────────────────────────────────────┤
 │ common  foundation  — shared, bridge-free headers             │
 │   IsolateState<T>, V8Helpers, Check, TraceLog/Log, JsError,   │
 │   Deadline, EventLoop interface                               │
 ├───────────────────────────────────────────────────────────────┤
 │ common::platform  — implemented once per platform             │
 │   ios/ (ObjC++, CF, NSURLSession)   android/ (JNI, ALooper,   │
 │                                      OkHttp, AppFiles)        │
 └───────────────────────────────────────────────────────────────┘

The core never includes Caches.h, Helpers.h, Runtime.h, ArgConverter.h, RuntimeState.h or JEnv.h. Those headers pull in ObjC, libffi or JNI. This rule is the real prerequisite, more than any renaming.

Calls go in both directions:

  • Down: the core calls the platform for files, loop, transport, threads, config and logs (§4).
  • Up: the platform calls the core for V8 host callbacks, entry loading, teardown, lifecycle notifications, HTTP-cache controls and Java-facing resolution (§5).

4. The platform interface (what each runtime implements)

Every method below traces to a place where the two trees do the same abstract thing differently. Each one lists both current implementations.

4.1 Style

Recommended: link-time free functions for process-wide services, and small abstract classes only where more than one implementation lives at runtime.

  • HttpLoader.h already works link-time: one header, .mm on iOS and .cpp on Android. No vtables, and the linker catches a missing function.
  • The cost: a core PR that adds a platform function can't build until both platforms implement it. With a submodule and a core CI that builds both runtimes, a new primitive needs a protocol. Either the platforms land it first (unused), or it arrives as a defaulted virtual or weak default that the core can call before every platform has caught up. #622 would have added six such primitives (§6.1), so this comes up regularly.
  • The transport and the event loop are exceptions:
    • Android switches transport from OkHttp to the platform one on LinkageError.
    • Tests want fakes for both.
    • Host-side unit tests need a fake file system and a fake transport.

4.2 Config, logging, failure

namespace nativescript::common::platform {

// Filled at boot, before the first isolate. Immutable while any isolate is live
// (iOS restartWithConfig: rewrites it between runs).
struct LoaderConfig {
  std::string appRoot;                 // no trailing slash
  std::vector<std::string> appRootAliases;    // other spellings of appRoot that name the same
                                              // directory (Android /data/data/<pkg> vs
                                              // /data/user/0/<pkg>); the core maps them to
                                              // appRoot before keying, so one file has one key
  std::string reportedPathPrefix;      // stripped from script origins (iOS BaseDir; Android "")
  std::vector<std::string> virtualFileRoots;  // "/app/", "/android_asset/app/"
  std::vector<std::string> globalModuleRoots; // tns_modules lookups, in precedence order
  bool walkNodeModules;                // Android true; iOS opts in (decision C2)
  bool isDebug;                        // diagnostics only, never behaviour (except the remote gate)
  bool codeCacheEnabled;               // iOS: !isDebug; Android: android.codeCache
  std::string codeCacheDir;            // iOS: Caches dir; Android (#2104): code_cache/v8
  std::string v8Flags;                 // stream-compile eager/lazy + stack size come from here on both
  struct { bool allowRemoteModules;
           std::optional<std::vector<std::optional<std::string>>> allowlist; } security;
  struct { bool cacheAtStartup; bool clearAtLaunch;
           size_t laneCap[2]; } http;  // {loopback, remote}; 0 = default
};
const LoaderConfig& Loader();

void Log(LogLevel, std::string_view);            // iOS os_log chunking / Android logcat
void EmitTrace(LogCategory, std::string_view);   // sink for TNS_DEBUG (already the same API)
[[noreturn]] void Fatal(const char* where, std::string_view);

}  // namespace nativescript::common::platform

Today these values come from:

Value iOS Android
app root RuntimeConfig.ApplicationPath three spellings: APP_ROOT_FOLDER_PATH, GetApplicationPath() and Java; #2104 unifies them as AppFiles
debug flag RuntimeConfig.IsDebug isDebuggable passed to Runtime::Init, plus a second JNI read into s_isDebuggable
allowlist RemoteModuleAllowlistFromConfig(id) RemoteModuleAllowlistFromConfig(optional<vector<optional<string>>>)
config reads Runtime::GetAppConfigValue → id Java AppConfig → StartupOptions

Shared code never reads package.json and never sees id or jobject.

4.3 App files (driven by #2104)

namespace nativescript::common::platform {

// Logical paths (appRoot-based, as V8 and users see them). Any thread, no
// Locker, bounded time: pool threads call these inside the compile gate that
// teardown drains on the isolate thread.
struct FileInfo {
  bool isFile; uint64_t size;
  // Changes whenever the bytes may have changed, and identifies the serving
  // layer: mtime for a disk layer, APK version for an asset layer. The code
  // cache keys freshness on it (B2).
  std::string freshnessToken;
};
std::optional<FileInfo> Stat(std::string_view logicalPath);  // nullopt: no such file
bool ReadFile(std::string_view logicalPath, std::string& out);   // all-or-nothing

}  // namespace nativescript::common::platform
  • iOS: stat and read, the way Helpers.mm does it today.
  • Android: AppFiles from #2104, which serves layers: directory, APK asset and plugin map.

Report B argued file IO could be plain POSIX in the core, which is true on main. #2104 makes it false: Android sources may come from AAssetManager. Keeping reads behind this seam is what lets #2104 land without touching the core, and it gives iOS the same OTA/layering option later for free.

ReadFile must be callable from pool threads, because #622 reads files off-thread. #2104's AppFiles already is: it is documented "safe to call from any thread" (AppFiles.h:101), takes a mutex, and makes no JNI upcalls. So pool threads need no JVM attach.

#2104 does not yet provide this seam:

  • No Stat. It has IsFile, Open (a Reader with size()) and ReadText, but no size without opening and no freshness token. It would need to add a Stat.
  • Short reads are not failures. Its ReadText returns true and truncates on a short read (AppFiles.cpp:642-644). The platform adapter has to turn that into a failure.
  • No directories. It answers files only. #2104 rewrote the Java resolver to probe files only, while iOS probes directories. So the core CJS resolver should probe files only, such as dir/package.json and dir/index.js, and Stat never needs a directory answer.

The code-cache file store is not in this seam. It lives in a real writable directory on both platforms, so the core does it with POSIX: mkstemp + rename, per-call buffers, all-or-nothing reads. Those helpers are the same algorithm on both sides today (Helpers.mm ↔ File.cpp). #2104 deletes File.cpp and moves cache IO into its ScriptCache.cpp, so the core takes that role.

The in-progress #622 port calls stat() on the real path (diff line ~1036). Under #2104, that would silently send every APK-served .mjs down the inline path. That is the concrete reason the core must only ever ask Stat.

4.4 Event loop: the one real gap

namespace nativescript::common {

class Loop {   // the per-isolate EventLoop; any thread unless noted
 public:
  virtual bool PostInternal(std::function<void()>) = 0;            // false = dropped (stopped)
  virtual bool PostInternalDelayed(std::function<void()>, double ms) = 0;
  // V8 layer: V8's own task type, no wrapping. Another engine adds its counterpart.
  virtual void PostV8Task(std::unique_ptr<v8::Task>, bool nestable, double delaySec) = 0;
  virtual void RunNestableV8Tasks() = 0;                            // home thread

  enum class PumpMode {
    kNestableOnly,  // nestable v8 tasks only, microtasks suppressed, idle(waitMs) between
                    // slices (#622). idle must return within waitMs even if nothing signals it
    kV8Tasks,       // nestable v8 tasks + a microtask checkpoint per slice; no timers
    kPlatformWork,  // minimum guarantee: also delivers the platform work a pending fetch or
                    // worker reply can depend on (iOS: a CFRunLoop slice; Android: due timers
                    // and its filtered internal drain, never the looper itself)
  };
  enum class PumpResult { kSettled, kDeadline, kTerminated };   // termination outranks settled
  virtual PumpResult PumpUntil(Deadline, const std::function<bool()>& settled, PumpMode,
                               const std::function<void(int waitMs)>& idle = nullptr) = 0; // home thread

  virtual bool TerminationRequested() = 0;   // the non-V8 half of the three-signal check
  virtual bool IsOnHomeThread() const = 0;   // Android #622 port adds this; iOS has IsOnRuntimeThread
};

// For holders off the home thread; null once the loop is gone. Hot paths reach the
// loop through per-runtime state in an isolate data slot instead.
std::shared_ptr<Loop> LoopFor(v8::Isolate*);

using Deadline = std::optional<std::chrono::steady_clock::time_point>;

}  // namespace nativescript::common
  • Android has PumpUntil(deadline, settled, drainLooperWork) today. The #622 port adds PumpNestableV8TasksUntil(deadline, settled, idle) and IsOnHomeThread(). PumpMode folds the two pump functions into one.

  • iOS has no PumpUntil. It pumps ad hoc in at least three places:

    • ModuleInternal.mm:1340-1360: TLA evaluation;
    • ModuleInternalCallbacks.mm:2400-2431: the graph walk, with CFRunLoopRunInMode(…, 0.01, true);
    • NativeScript.mm:133-177: the boot backstop.

    #622 adds a fourth (the FileJobSignal sleep). iOS growing this one method is the largest single platform task in this proposal.

  • Deadlines become monotonic everywhere. iOS uses wall-clock CFAbsoluteTime for fetch and pump deadlines, so a clock change can stretch or cut short a module wait.

  • The Post* return type: iOS returns bool and Android returns void. Unify on bool.

  • Engine types stay. v8::Task and the v8::Isolate* key are used as is, per "Performance before neutrality" above. Comparing two runtimes for identity across threads still uses an id, because V8 reuses isolate addresses; that is a comparison, not a per-call lookup.

  • The iOS boot backstop has a special case: each slice also runs Tasks::Drain(), where UIApplicationMain may take over and never return (NativeScript.mm:175-176). The graph walk never does this. So the core owns the backstop loop (poll entry → pump slice → evict or throw), and the platform supplies a per-slice hook (§5). Invariant: the core holds no RAII state across that hook, because it may never come back.

  • The mode can change between slices. The Android #622 port's outer loop switches modes as pending HTTP fetches come and go (diff ~1437-1448). A fixed mode per PumpUntil call is enough.

4.5 HTTP transport (report C §3)

Built: ns/http/ModuleTransport.h (the seam) and ns/http/ModuleFetch.h (the loader's API). The cut is at one attempt. The core owns:

  • the gate and allowlist, re-checked against the URL a redirect ended at;
  • the header set, User-Agent: NativeScript-HTTP-ESM included;
  • the timeout, retry and deadline policy;
  • classification;
  • the cache switch and its holders;
  • Clear-Site-Data parsing and scope;
  • the fetch threads for transports that block, capped per host class.

The transport only performs attempts and stores the cache.

namespace nativescript::common::http {

struct AttemptRequest {
  std::string url;                  // gated, NormalizeHttpModuleUrl spelling, never canonicalized
  FetchPath path;                   // kGraphWalk | kSynchronousFallback (separate connections)
  std::chrono::milliseconds timeout;    // idle bound, > 0, clamped to the deadline
  std::chrono::milliseconds waitBound;  // sync only: timeout + 5 s, honoured if cancellable
  bool useCache;                    // sampled once per fetch, when it is issued
  std::vector<RequestHeader> headers;   // core-built, no-cache pair included when off
};
struct AttemptOutcome {
  bool arrived;                     // status line, and for a 2xx the whole body
  int status; std::string contentType, body;
  std::string finalUrl;             // after redirects, set whenever `arrived`
  std::vector<std::string> clearSiteData;   // raw; the core parses and applies
  bool malformedUrl, waitExpired;   // neither is retried
  std::string errorDescription;
};

class ModuleTransport {
 public:
  virtual const char* Name() const = 0;
  virtual AttemptOutcome FetchBlocking(const AttemptRequest&) = 0;
  virtual bool SchedulesItself() const { return false; }   // NSURLSession: true
  // Only used when SchedulesItself(); otherwise the core runs FetchBlocking on its
  // fetch threads (Android's lanes, moved).
  virtual void FetchAsync(AttemptRequest, std::function<void(AttemptOutcome)> anyThreadOnce);
  // The retry delay of a self-scheduling transport. Default: one core timer thread;
  // iOS overrides it with dispatch_after so each task gets an autorelease pool.
  virtual bool PostDelayed(std::chrono::milliseconds, std::function<void()>);
  virtual CacheOpResult ClearAll() = 0;
  virtual CacheOpResult ClearOrigin(const std::string& origin) = 0;
  virtual void OnFetchThreadStart() {}   // Android: JVM attach
  virtual void OnFetchThreadExit() {}    // Android: JVM detach
};

}  // namespace nativescript::common::http

namespace nativescript::common::platform {
http::HttpLoaderConfig ReadHttpLoaderConfig();   // once per process, before any cache setter
http::ModuleTransport& HttpTransport();
}
  • iOS keeps its NSURLSession partitions, NSURLCache generations, launch options and delegate queues inside the transport.
  • Android keeps OkHttp, HttpURLConnection, StrictMode and JNI frame handling inside it. Its transport cannot cancel a blocking attempt yet, so its synchronous fallback still has no total-wait bound (D7).
  • Both already satisfy this contract (report C §2): completion exactly once, on any thread, possibly inline; never canonicalize; the sync path never shares the walk's connections.
  • The retry delay of a self-scheduling transport runs through its PostDelayed, holding no connection. On the fetch threads it still sleeps, holding the slot for 120 ms (D1, v1).

4.6 Threads

namespace nativescript::common::platform {

struct ThreadSpec { const char* name; size_t stackBytes; ThreadPriority priority; };
// Detached thread; the platform applies name, QoS and (Apple) an autorelease pool per job.
bool StartThread(const ThreadSpec&, std::function<void()> body);   // false → caller falls back inline

}  // namespace nativescript::common::platform

Both sides run the stream-compile pool on dedicated pthreads. GCD and bionic default stacks are below what V8's background parser needs. iOS sets QoS + @autoreleasepool; Android sizes the stack from --stack-size.

The pool itself (grow on demand, gate, drain) moves to the core. #622 already reuses it for file modules. The #622 cache writer is the second user:

  • iOS uses a serial UTILITY GCD queue;
  • the Android port wrote a std::thread + condition-variable writer.

Both become one core serial worker on StartThread.

4.7 Per-isolate state

namespace nativescript::common {
template <class T> T* IsolateState::For(v8::Isolate*);        // creates; null after final Clear()
template <class T> T* IsolateState::ForExisting(v8::Isolate*); // never creates; off-home-thread
                                                               // reads while holding the Locker.
                                                               // Pool/transport threads never call it
}
namespace nativescript::common::platform { IsolateStateBag* StateBag(v8::Isolate*); }

The two contracts differ, and the core can't be written against both.

  • iOS Caches::StateFor goes null at the start of ~Runtime (Runtime.mm:318, before the loader quiesce).
    • The loader therefore reaches for ExistingStateFor during teardown.
    • Messaging keeps a process-wide Isolate* map to get around it.
  • Android RuntimeState::For stays live until the last teardown statement (Runtime.cpp:1372).

Recommended: Android semantics, plus ForExisting for the cross-thread reads. iOS moves "stop accepting new work" to a separate flag. That is an iOS behaviour change and should be its own PR (decision F1).

4.8 Optional hooks (no-ops by default)

Hook Why
LoadNativeModule(path) Android .so addons and system_lib://
ReportFatalToDeveloper(title, msg, stack) iOS error modal
TraceModuleLoad(path) → RAII scope Android profiler frames and crash breadcrumbs
SourceReadLock(isolate) Android debug LiveSync mutex around source reads (per Runtime)
ExternalMemoryCharge(isolate, bytes) iOS charges through its gate id; Android uses v8::ExternalMemoryAccounter. Same V8, so probably the plain accounter for both; needs a check against #507

5. The core's public API (what platforms call)

namespace nativescript::common::loader {

// Boot / per isolate
void InstallHostCallbacks(v8::Isolate*);   // resolve, import(), import.meta, ns:module binding
void RunEntry(v8::Isolate*, v8::Local<v8::Context>, const std::string& path,
              EntryKind /* main | worker */);            // throws JsError on failure
EntryEvaluationState PollEntry(v8::Isolate*, const std::string& path, std::string* reason);
bool HasPendingGraphWork();
// The boot backstop loop. `platformSlice` runs once per slice and may never
// return (iOS UIApplicationMain); throws JsError on a failed or timed-out entry.
void RunBootBackstop(v8::Isolate*, const std::string& entryPath,
                     const std::function<void()>& platformSlice);

// Teardown (isolate alive, locked, before the loop shuts down)
void Quiesce(v8::Isolate*);

// Lifecycle: any thread. The platform calls it for each runtime it wants
// flushed; today both flush the main isolate only.
void NotifyAppBackgrounded(v8::Isolate*);   // flush deferred code caches (#622)

// Workers
LoaderVocabulary CaptureVocabulary(v8::Isolate* parent);
void InstallVocabulary(v8::Isolate* worker, LoaderVocabulary);

// Java-facing resolution (replaces Module.java's resolver)
std::string ResolveMainEntry();                          // Module.bootstrapApp
std::string ResolveEntry(const std::string& spec);       // Module.resolveEntryPath

// HTTP cache controls (ns:module and the inspector)
void SetHttpCacheEnabled(bool);
void SetHttpCacheDisabledBy(uint64_t holderId, bool disabled);   // inspector connection
CacheOpResult ClearHttpCache();

}  // namespace nativescript::common::loader

Each platform keeps a thin binding layer:

  • iOS: NativeScript.mm, the Runtime.mm boot, and the UIApplicationDidEnterBackground observer.
  • Android: com_tns_Runtime.cpp, Module.java as JNI wrappers, and the onTrimMemory registration.

6. Stress test: how #622 and #2104 would land

6.1 #622, off-thread file-module loading (iOS open; Android port in progress)

Caveat on method. §4 was written after reading #622, so this is not a blind test. It is a measure of what #622 forced the interface to contain, and of how little of the port would have been platform work.

What the Android port is doing today, from the uncommitted diff (copy in SHARED_LOADER_CORE.reports/):

  • It edits 12 files.
  • ModuleInternalCallbacks.cpp alone is ~1,100 changed lines (insertions plus deletions).
  • Its substantive added lines, after whitespace normalization and excluding lines under 25 characters, are:
iOS #622 Android port
substantive added lines 435 520
verbatim in both 305 305
platform calls 25 (GCD queue, NSNotificationCenter, CFAbsoluteTime, CFRunLoopRunInMode, fopen/fread, Caches::Get) 36 (std::thread + condition-variable writer, steady_clock, JNI entry, gettid, setpriority, runtime->ReadFileText)
new pump primitive 3 26 (PumpNestableV8TasksUntil, IsOnHomeThread)
renames and pre-existing divergence 102 153

The last row is mostly helper and enum names (TryLoadScriptCache vs LoadScriptCache, Classic vs kClassicScript, robin_hood vs std:: maps). It also includes #622 being re-threaded through code that had already diverged, chiefly the dynamic-import() callback: Android's version handles NUL specifiers and builtins and keeps the real rejection reason, while iOS's builds generic messages.

A shared core removes that row entirely. Line-set counting is approximate.

#622 piece Lands in Interface need
File jobs (FileModuleJob, FileModuleCompile, fileJobs, fileCompiles) core esm/ ReadFile (any thread), StartThread
Walk parking (SyncModuleLoadScope, parkWalksBefore, parkedWalks) core esm/ + eval/ none
Async file import() (fileDynamicImports, SettleFileDynamicImport) core esm/ none
Off-thread cache consume (≥256 KiB) and streamed compile (≥32 KiB) core jobs/ StartThread
Idle wait on FileJobSignal, no microtasks core calls PumpUntil(kNestableOnly, idle) new pump mode. iOS used CFRunLoopRunInMode + CV; Android added PumpNestableV8TasksUntil
Deferred cache creation (0.5 s quiet, 16 ms slices) core cache/ PostInternalDelayed (exists)
Off-thread cache write, mtime re-check core cache/ StartThread (replaces GCD queue vs std::thread)
Flush when backgrounded core NotifyAppBackgrounded() platform wiring: UIApplicationDidEnterBackground ↔ onTrimMemory(UI_HIDDEN)
Republish rejected caches, Debug gate on save core cache/ codeCacheEnabled
Eager vs lazy compile core, from v8Flags iOS stops using IsDebug as a proxy
Gate-identity stale check on completion core LoopFor, IsolateState (no Isolate* identity)

Verdict: with the core in place, the Android-specific part of #622 would have been:

  • the ~35 lines of Java + JNI that register onTrimMemory and call NotifyAppBackgrounded();
  • once per platform, the kNestableOnly pump mode (26 lines on Android).

Everything else is core code written once.

#622 is also what forced these parts of the interface into existence. None of them existed in a common form before it:

Primitive Before #622
PumpMode::kNestableOnly + idle hook neither side had it; Android added PumpNestableV8TasksUntil, iOS a CV sleep
Loop::IsOnHomeThread iOS had IsOnRuntimeThread; Android added it for this
NotifyAppBackgrounded new on both
ReadFile callable from any thread both read on the JS thread only
a serial background writer (StartThread) iOS GCD queue vs Android hand-built thread
FileInfo.freshnessToken #622 reads mtime with raw stat

Each is generic, with no platform concept leaking into the core. So a feature of #622's size costs a handful of small, reusable primitives instead of a 1,000-line port. The next feature that needs a quiet pump or a background writer gets them for free.

Behaviour #622 changes, which a shared landing makes explicit instead of re-porting:

  • File import() stops pumping synchronously. Android main still pumps (ModuleInternalCallbacks.cpp:3830).
  • The iOS Debug-build cache-writing bug and the "never republish" bug go away.

6.2 Android #2104, layered app files + code cache in code_cache/v8

#2104 piece Lands in Effect on the core
AppFiles layers (directory, APK asset, plugin map) platform ReadFile/Stat #2104 must add Stat (§4.3)
/data/data/<pkg> ≡ /data/user/0/<pkg>, applied inside the ESM resolver through AppFiles::ToLogical (ModuleInternalCallbacks.cpp:120, 1518 on the branch) core identity Not platform-only: it changes registry keys. The core needs LoaderConfig.appRootAliases, or one file gets two keys when JS spells the other root
Lexical normalization (no symlink canonicalization) core identity rule matches the proposed choice (A1), with the alias mapping above
Cache location code_cache/v8/<hash(logical path)> LoaderConfig.codeCacheDir + core naming core naming changes for iOS too. Hashed names fix the iOS flattening collision (a/b-c.js ≡ a-b/c.js, ModuleInternal.mm:2008)
Header: magic, version, source length + crc32, payload crc32 core cache/ format conflicts with #622's stat-only freshness (decision B2)
Republish rejected caches on the CJS path too core cache/ same as #622; converges

Verdict: #2104 is mostly platform-side. It touches the core in two places: identity (the root alias) and cache freshness.

The freshness conflict is the larger one:

  • #622 chooses inline, stream or consume on the isolate thread from stat size and mtime, before any read, and only then creates the streaming task (ios622 ModuleInternalCallbacks.mm:2433-2473).
  • #2104 validates with the source's crc32, which needs the bytes, and APK assets have no meaningful mtime.

There are two ways out:

  1. (Recommended) Stat reports a freshness token: mtime on disk, APK version for assets. #622's shape survives unchanged, and the cache header carries the token instead of a crc.
  2. Always read before deciding. This reshapes #622's job: the read moves ahead of the decision, and large files are read on the isolate thread or in an extra pool hop. It needs a cost measurement before it can be chosen.

6.3 Retrospective on the last paired PRs

My estimates from the reports, not measured line by line:

Pair Where the change would land
#621 ↔ #2176 import() like static import, file-module query identity all core
#620 ↔ #2173 HTTP cache controls core (switch, inspector holders, Clear-Site-Data) + ClearAll/ClearOrigin per transport
#585 ↔ #2172 HTTP cache + persistent connections mostly transport (legitimately two implementations); timeout, header and retry policy core
#587 ↔ #2170 off-thread HTTP compile all core except thread setup
#586 ↔ #2168 resolve against importer URL all core

7. Decisions needed

Grouped by subsystem. "Rec" is a recommendation, and every row is your call.

Already agreed, carried over as core invariants rather than re-asked (from the #383/#444 ↔ android#1965/#2021 work):

  • The shared terminate rules: termination outranks settlement at every pump head, the termination path always throws, and a module is evicted only while its promise is still pending.
  • The three settle policies, with static createPumpingRequire defaults and no boot-aware defaults.
  • A local (non-HTTP) TLA settle window that stays short (1 s). The core's PumpUntil modes must not unify it with the 60 s deadline; EventLoopTests pins this.
  • Failures throw the same way in every build.
  • Loader vocabulary is per isolate and copied to workers.
  • Import maps are validated in full before they are swapped in.
  • The runtime exposes mechanism, never HMR policy.

A. Module identity and resolution

# Question iOS today Android today Rec
A1 Path normalization for registry keys Foundation stringByStandardizingPath (strips /private) ESM lexical; CJS Java getCanonicalPath (realpath); #2104 makes all lexical Lexical everywhere. Normalize the app root once at the boundary
A2 file:// with #, %, spaces NSURL (# is a fragment) verbatim (# stays in the path) Not NSURL: URL work in the core goes through the vendored ada parser (standing rule). A1 and A2 are the start of the deferred "canonical identity" sweep, so the HTTP-authority caveat from #586 still applies
A3 file:// to absolute device paths everything mapped under the app root allowed needs your call
A4 CJS bare-name precedence tns_modules/<n> first, then tns-core-modules/<n> tns-core-modules/<n> first, then node_modules walk Node order. Keep the legacy roots only as config
A5 node_modules walk on iOS none (5 shared specs xit) yes Turn on through walkNodeModules; the xits become the acceptance list
A6 Package main pointing at nothing returns the missing path falls back to index Android (Node)
A7 CJS wrapper prologue 61 chars ) { 60 chars ){ (stack columns corrected by length) Pick one. Invalidates one platform's classic caches once, which is safe only after B3
A8 import.meta.dirname file modules only (#614) always iOS
A9 Import-map targets naming builtins, blob: resolution kind yes no iOS

B. Code cache

# Question Rec
B1 Cache on by default in release? iOS yes, Android opt-in (android.codeCache) Keep it per platform as LoaderConfig.codeCacheEnabled. Note that unification makes it trivial to flip Android's default later
B2 Freshness: mtime stamp (main, #622) vs source length + crc32 header (#2104) A header with a version and source length on both, plus a per-source freshness token from Stat (mtime on disk, APK version for assets) instead of crc. Needs a joint call with whoever owns #2104
B3 Land the cache in #622's shape (deferred creation, off-thread write, republish on reject) Yes, as both investigations concluded
B4 Naming: flattened (iOS) / beside the source (Android main) / hashed (#2104) Hashed under codeCacheDir

C. Evaluation and loop

# Question Today Rec
C1 Pumped graph wait when terminating iOS: return false; Android: return *done (ModuleInternalCallbacks.cpp:2427-2433); one of its three callers re-checks termination itself (ModuleInternal.cpp:1466) Already settled. The shared terminate rules agreed on 2026-08-19 (#383/#444 ↔ android#2021) say termination outranks settlement at every pump head. Android has regressed; fix it now (§8)
C2 LoadESModule after a terminated pump iOS throws "interrupted by isolate termination"; Android returns the namespace Same rule: "the termination path always throws". Android regressed
C3 Deadline clock iOS wall clock; Android steady_clock steady_clock
C4 File import() pumping #622: async; Android main: sync pump #622
C5 Boot backstop: rejection on the first poll Android fatal; iOS not Android

D. HTTP (report C §3 D1–D10): decided 2026-12-05

All ten as report C recommends, built in ns/http/:

# Decision
D1 The retry delay runs off-thread on a core timer for self-scheduling transports. Fetch threads sleep through it for now.
D2 Queue time counts against the deadline: each attempt's timeout is computed when it starts.
D3 The cache switch is sampled once per fetch, when it is issued; a retry reuses it.
D4 Clear-Site-Data clears the response's origin plus the fetching origin, each once, before the fetch is reported.
D5 Failed cache clears are reported (CacheOpResult). JS throws and the inspector answers -32000.
D6 Cache holders are a set keyed by an opaque id (SetModuleHttpCacheDisabledBy), idempotent per id.
D7 The sync fallback's total wait is the attempt timeout + 5 s. Android cannot cancel an attempt yet, so its wait stays unbounded until its transport can.
D8 User-Agent: NativeScript-HTTP-ESM on both.
D9 Deadlines are optional<steady_clock::time_point> everywhere.
D10 The gate is re-checked against the final URL after redirects. A transport that does not report it fails closed while an allowlist is in force. The redirect is still followed first, so the request reaches the target before the check.

Also: a transport error is a response that did not arrive (Android's rule): a status-bearing answer never is, unless it is a 2xx whose body failed.

E. Error policy

  • Shared code throws JS errors in every build, per the standing "same errors in Debug and Release" rule. It never uses tns::Assert or NS_CHECK for anything JS can reach.
  • One JsError value type (message, stack, name, ThrowToV8). Each platform's NativeScriptException wraps it.

F. Structure

# Question Options Rec
F1 Per-isolate state contract iOS early-null vs Android live-until-last Android + ForExisting; iOS teardown PR first
F2 Seam style link-time functions / virtual interfaces / mixed Mixed, as in §4.1
F3 Packaging A submodule NativeScript/runtime-common / B vendored copy + CI staleness check / C monorepo Decided 2026-12-04: A, this repository, private for now
F4 Same-PR parity must every core change build both runtimes before merge? Yes for the core: its CI builds both runtimes at their main
F5 iOS source registration synchronized folder group (objectVersion 77) / static-lib target Static library with its own strict flags and no header map. At the project's current objectVersion 55 the target still lists each source file; zero per-file churn needs the synchronized-folder format, which is a separate project-format bump
F6 Order relative to #622 extract the core first, then land #622 once / land #622 on both, then extract Second: the Android port is already in progress and is 70% a verbatim re-port. Extract from the post-#622 state; that is the baseline both sides converge on anyway
F7 C++ namespace top-level ns:: / nativescript::common:: Decided 2026-12-05: nativescript::common, subdivided by component; see "Layering and direction"

On packaging (F3):

  • Submodule is how the shared tests already work, and the record is instructive. In the window the pointer moved in only 2 of 30 paired PRs, and it hid 55 days of skew instead of exposing it.
  • Vendored copies recreate exactly today's drift mechanism, since people patch the copy. ada and robin_hood.h already show independent fixes to the same warning.
  • A monorepo is the only option that makes drift impossible, and the largest migration: history, PR numbering, scripts/changelog.mjs, npm publishing, and two CI runners.

My recommendation is a submodule plus a core CI that builds both runtimes (macOS + NDK) on every core PR, and a required check in each runtime that its pin is not behind core main by more than N commits. A monorepo is worth revisiting once the core is most of the code.


8. Bugs found while comparing (independent of unification)

Each one exists on one side only. Fixing them in place first shrinks the reconciliation.

"Read" means I read the cited lines. "Reported" means an investigation report found it and I did not re-read it. Treat "reported" items as leads to confirm, not as facts.

Side Bug Where Status
Android Pumped graph wait reports success for a terminating isolate, so the caller instantiates and evaluates more JS. Regression of the agreed terminate rule ModuleInternalCallbacks.cpp:2427-2433 (iOS: .mm:2401-2415) read
Android LoadESModule returns the namespace after the pump reported termination, instead of throwing as the agreed rule says ModuleInternal.cpp:1344-1350, 1611 reported
Android Sync HTTP fallback has no total-wait bound (no counterpart to iOS waitExpired), so a trickling body could hold the JS thread past the deadline HttpLoader.cpp:579-612 vs iOS HttpLoader.mm:477-486 read (absence); the consequence is reported
Android Module.java resolution keeps mutable statics with no locking (possibleException, checkForExternalPath, folderAsModuleCache HashMap). After an IOException in the helper, file is null and file.getCanonicalPath() throws an NPE Module.java:23-27, 71-91 read; concurrent callers are reported
Android ~/x builds app//x ModuleInternal.cpp:692 (fixed by #2104) reported (#2104 says so too)
Android URL hash accessor registered twice URLImpl.cpp:69-71, 75-77 reported (spot-checked by report D)
iOS Writes ES-module code caches in Debug builds; never republishes a rejected cache ModuleInternal.mm:1045-1049, 1963-1976 (fixed by #622) reported
iOS ReadModule ignores read()'s result, so a short read compiles uninitialized bytes Helpers.mm:81 read
iOS Cache-name flattening collides (a/b-c.js vs a-b/c.js). With 1 s mtimes and V8 not hashing content, a same-length collision could load the wrong code (risk, not reproduced) ModuleInternal.mm:1999-2016 read (naming); the consequence is unproven
iOS Calling-dir check substr(0,4) == "/app" also rewrites /apple/... ModuleInternal.mm:545-548 read
iOS File import() evaluation failure rejects with a generic Error and drops the V8 exception (still in #622) ModuleInternalCallbacks.mm:3852-3858 read
iOS Module-load deadlines use wall-clock CFAbsoluteTime ModuleInternalCallbacks.mm:2386, 2419, HttpLoader.mm:1141, 1189, ModuleInternal.mm:1366, 1412 read (2419); the rest from the review
both The remote-module gate and allowlist are not re-checked after a redirect report C §2 reported

Line numbers refer to the baseline commits above.


9. Migration plan

Each step is suite-green on both platforms on its own. The shared common-runtime-tests-app suite is the conformance test.

The core also gets host-side unit tests, built with macOS and Linux clang using the core's flags, for the pure parts:

  • canonicalization;
  • classification;
  • import-map parsing and resolution;
  • the CJS resolver against a fake Stat/ReadFile;
  • retry and deadline policy against a fake transport;
  • cache naming and freshness.

These are cheap and catch most port-style regressions without a device.

  1. Fix the §8 bugs in place, one small PR per side, after confirming each "reported" item. No dependency on anything else.

  2. Plumbing, proven on leaves.

    • Create the core repo and wire both builds: an Android CMake subproject and an iOS static-lib target.
    • The core gets its own flags, written to the stricter side: C++20, -fno-rtti, exceptions, -Wall -Werror -Wshorten-64-to-32, and V8 deprecation warnings on.
    • Use a unique include root (#include "ns/…"). iOS header maps resolve by basename, so a shared EventLoop.h next to a platform one would be picked silently.
    • Prove it on one slice whose include closure is V8 and std only: the base64 codec and the atob/btoa natives (ns/Base64.h, ns/Base64Binding.h). Each runtime keeps its Base64.cpp for the builtin wiring (BuiltinLoader, SetMethodNoSideEffect).
    • The other units that looked identical are not leaves. NativeScriptPlatform constructs and calls the platform EventLoop, so it moves with step 3. ModuleBinding carries a per-platform binding list, so it needs that list injected first.
  3. Foundation headers and platform basics: ns/V8Helpers.h, ns/Check.h, ns/TraceLog.h (already identical), ns/Log.h, ns/JsError.h, ns/Deadline.h, ns/IsolateState.h, plus LoaderConfig and StartThread. The iOS teardown change (F1) goes in as its own PR here.

  4. Loop interface. iOS gains PumpUntil with the three modes, replacing its three ad hoc pumps. Android folds PumpNestableV8TasksUntil into it.

  5. Code cache + file seam, in #622's shape, with B2/B4 decided jointly with #2104. Move the shared file helpers, ReadFile/Stat, the cache queue, and CompileFileEsModule. The ESM core calls CompileFileEsModule, so it has to move before step 6.

  6. HTTP policy core + ModuleTransport. NSURLSession and OkHttp move behind the interface; the lanes move into the core.

  7. ESM core (ModuleInternalCallbacks): registry, identity (A1, A2, A8, A9), walk, dynamic import, facade, ns:module, stream pool. This is the largest step; land it as several PRs by unit. Until steps 7–8 land, the core calls back into each platform's ModuleInternal through two declared transitional up-calls:

    • InstallCreateRequireBinding (the ns:module binding);
    • LoadESModule, the evaluation entry for require(esm).

    Name them in a transitional.h so they are deleted on purpose.

  8. Evaluation layer: EvaluateModuleGraph, entry probes, boot backstop loop (C1, C2, C5).

  9. CJS core: the resolver (A4–A7), the require cache and wrapper. Module.java becomes JNI wrappers. iOS turns on walkNodeModules, and the shared-test xits must pass.

Follow-on, on the same foundation, from the infrastructure report's ranking, easiest first:

  1. TextEncoding, StructuredClone, StructuredSerialization.
  2. URL and URLSearchParams/URLPattern, after the three URL drifts and Android's deprecated setter overload are fixed.
  3. BuiltinLoader, LazyGlobals, IsolateTracked.
  4. The builtin js/: 14 of 28 files are already byte-identical, and both sides generate the same js2c output.
  5. Events, ErrorEvents, Performance, WeakRef.
  6. Messaging, after F1.
  7. The EventLoop queue bookkeeping.

The platform-owned subsystems do not move: wrapper lifetime and leak probe, console sinks, inspector transport, Runtime, and the body of NativeScriptException.


Not covered

These need their own pass before the matching steps:

  • Catalyst and visionOS builds of the core.
  • Android builds without OkHttp, beyond the existing platform-transport fallback.
  • The inspector, beyond its cache-control calls.
  • How workers start and stop their own loader state, beyond vocabulary copying.

Appendix: sources

An independent review (Fable, 2026-12-04) checked §4.4, §4.7, §6 and §8 against the source. Its corrections are folded in above: #2104 identity and Stat, the pump-mode semantics, the boot hook, the interface-growth protocol, migration order, the URL row (removed: iOS does throw), and the deadline cites.

Investigation reports (kept with the proposal's working notes, not in this repository). Their line numbers cite the baseline snapshots.

  • A-esm-callbacks.md: unit-by-unit ESM inventory, invariants 1–21, #622 mapping.
  • B-cjs-codecache.md: CJS, entry, code cache, the Module.java vs iOS resolver behaviour table, invariants I1–I29.
  • C-http.md: HTTP policy vs transport, ModuleTransport sketch, decisions D1–D10.
  • D-infra.md: state, loop, build flags, packaging, the porting-burden table (PR pairs and lag).

The #622 overlap metric is a set comparison of whitespace-normalized added lines of 25 characters or more. It is iOS origin/main...origin/perf/stream-compile-lazy-imports vs the uncommitted diff in the Android worktree perf/stream-compile-lazy-imports, as of 2026-12-04. It overcounts trivially common lines slightly and undercounts rewritten-but-equivalent ones.