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.
NativeScript has two layers, and this repository holds the first:
- The app runtime: what loading a NativeScript app needs from the ground up. Builtins, module loading, the code cache, the event loop, web globals.
- Native calling: the FFI that exposes platform APIs to JS. It is heading
to an
ns:nativemodule 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:
- Unify the app runtime across iOS and Android on V8 (this document).
- Shape and build
ns:native. - 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::enginehas no module records, code cache or off-thread compile today. - 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 flatnativescript::names in NativeScript/runtimes. No nested namespace is calledv8, because insidenativescript::commonit would hide::v8. Headers stay underns/: anativescript/include root matches theNativeScript/source folders of all three repositories on case-insensitive file systems.
-
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% inHttpLoaderand 23% inModuleInternal. 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.
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.
┌───────────────────────────────────────────────────────────────┐
│ 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).
Every method below traces to a place where the two trees do the same abstract thing differently. Each one lists both current implementations.
Recommended: link-time free functions for process-wide services, and small abstract classes only where more than one implementation lives at runtime.
HttpLoader.halready works link-time: one header,.mmon iOS and.cppon 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.
- Android switches transport from OkHttp to the platform one on
Built: ns/LoaderConfig.h (LoaderConfig, platform::Loader()),
ns/Platform.h (Log, TraceEnabled, Trace), ns/Trace.h (Tracef,
Logf, NS_TRACE) and ns/V8Flags.h. LoaderConfig holds only fields the
loader reads today: appRoot, reportedPathPrefix, isDebug,
codeCacheEnabled, codeCacheDir and v8Flags. HTTP settings stay in
http::HttpLoaderConfig. These join it when their step lands:
appRootAliases(other spellings ofappRoot, such as Android's/data/data/<pkg>vs/data/user/0/<pkg>) andvirtualFileRootswith the resolver (step 6);globalModuleRootsandwalkNodeModuleswith the CJS core (step 8);Fatalwhen the first core caller needs it.
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.
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:
statandread, the wayHelpers.mmdoes it today. - Android:
AppFilesfrom #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 hasIsFile,Open(aReaderwithsize()) andReadText, but no size without opening and no freshness token. It would need to add aStat. - Short reads are not failures. Its
ReadTextreturns 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.jsonanddir/index.js, andStatnever 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.
Built: ns/Loop.h (Loop, PumpMode, PumpResult, platform::LoopFor) and
ns/Deadline.h. The header is normative; in short:
-
each runtime's
EventLoopimplementsLoop; -
PumpUntil(deadline, settled, mode, idle)checks termination, thensettled, then the deadline, before every slice, so termination outranks a state that settled during the slice; -
termination is the loop's flag (set before
TerminateExecution), the isolate terminating, or the loop stopped; -
settledmust not throw or run JS; a caller whose condition can fail records it and throws afterkSettled. Android's TLA probe throws from inside the pump today, which lets a same-slice rejection outrank termination; -
kPlatformWorkis a minimum (Android's set). iOS's CFRunLoop slice also runs non-nestable tasks and bare posts, which the contract allows; -
two waits stay off
PumpUntil: the synchronous HTTP fallback (a blocking wait bounded bywaitBound) and the teardown drain of streamed compiles, which must keep running on a terminated isolate and usesRunNestableV8Tasksdirectly. -
Android has
PumpUntil(deadlineSeconds, settled, drainLooperWork),PumpNestableV8TasksUntil(deadlineSeconds, settled, idle)andIsOnHomeThread()(#2177).PumpModefolds the two pump functions into one. -
iOS has no
PumpUntil. It pumps ad hoc in at least three places:ModuleInternal.mm:1345-1452: TLA evaluation (NSDatedeadline);ModuleInternalCallbacks.mm:2902-2985: the graph walk, withCFRunLoopRunInMode(…, 0.01, true)and, for file jobs only, theFileJobSignalwait;NativeScript.mm:129-212: the boot backstop (CFAbsoluteTimedeadline).
iOS growing this one method is the largest single platform task in this proposal.
-
Deadlines become monotonic everywhere. iOS still uses the wall clock for the TLA and backstop deadlines, so a clock change can stretch or cut short a module wait.
-
The
Post*return type: iOS returnsbooland Android returnsvoid. Unify onbool. -
Engine types stay.
v8::Taskand thev8::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(), whereUIApplicationMainmay 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
PumpUntilcall is enough.
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-ESMincluded; - 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).
Built: ns/Thread.h. The core creates the pthread itself (detached, sized,
named) and calls two platform functions: ApplyThreadPriority first on the
new thread (iOS QoS, Android setpriority) and RunJob around each unit of
work (iOS @autoreleasepool). BackgroundCompileStackBytes(v8Flags) sizes a
compile thread from --stack-size on both platforms; iOS currently hardcodes
2 MB and infers --no-lazy from the debug flag.
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.
Built: ns/IsolateStateBag.h (the storage, V8-free) and ns/IsolateState.h
(For, ForExisting, platform::StateBag(isolate)). Each runtime owns one
bag per runtime, reached through an isolate data slot, and closes it at the
end of teardown.
The two contracts differ, and the core can't be written against both.
- iOS
Caches::StateForgoes null at the start of~Runtime(Runtime.mm:318, before the loader quiesce).- The loader therefore reaches for
ExistingStateForduring teardown. - Messaging keeps a process-wide
Isolate*map to get around it.
- The loader therefore reaches for
- Android
RuntimeState::Forstays live until the last teardown statement (Runtime.cpp:1372).
Decided (F1): Android semantics, plus ForExisting for the cross-thread
reads. iOS moves "stop accepting new work" to a separate flag, in its own PR;
iOS adopts IsolateState only after that lands.
| 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 |
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::loaderEach platform keeps a thin binding layer:
- iOS:
NativeScript.mm, theRuntime.mmboot, and theUIApplicationDidEnterBackgroundobserver. - Android:
com_tns_Runtime.cpp,Module.javaas JNI wrappers, and theonTrimMemoryregistration.
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.cppalone 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
onTrimMemoryand callNotifyAppBackgrounded(); - once per platform, the
kNestableOnlypump 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.
| #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
statsize and mtime, before any read, and only then creates the streaming task (ios622ModuleInternalCallbacks.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:
- (Recommended)
Statreports 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. - 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.
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 |
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
createPumpingRequiredefaults and no boot-aware defaults. - A local (non-HTTP) TLA settle window that stays short (1 s). The core's
PumpUntilmodes must not unify it with the 60 s deadline;EventLoopTestspins 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.
| # | 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 |
Decided 2026-12-05: lexical everywhere. Normalize the app root once at the boundary |
| A2 | file:// with #, %, spaces |
NSURL (# is a fragment) |
verbatim (# stays in the path) |
Decided 2026-12-05: 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 | Decided 2026-12-05: allowed (Android, Node and browser semantics). An absolute file:// path loads that file |
| 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 | Decided 2026-12-05: iOS (file modules only, as in Node) |
| A9 | Import-map targets naming builtins, blob: resolution kind |
yes | no | Decided 2026-12-05: iOS |
| A10 | Script origins and import.meta of app files |
file:///app/<rel> for both (BaseDir stripped) |
file://<absolute path> for both |
Decided 2026-12-05: see "App origins" below |
App origins (A10). A script origin (stack traces, DevTools, error
messages, crash reporters) and import.meta serve different readers, so the
core spells them separately:
- Origin of a file under the app root:
LoaderConfig.appRootOrigin+/+ the path relative to the app root. The core default isapp://, givingapp:///foo.mjs. A scheme cannot collide with a real path on any OS (a Linux runtime can have a real/app). It stays the same across installs and platforms, which keeps crash-reporter grouping stable (Sentry matches it as~/foo.mjs, React Native's convention). DevTools also loads the side resources of a non-file:script, such as a relative source map, through the target, with nosourceMapURLrewrite. - Origin of a file outside the app root:
file://<absolute path>. import.meta.url,.filename,.dirname: the real absolute path, sofileURLToPath(import.meta.url) === import.meta.filenameholds as in Node, and the values work with file APIs and with absolutefile://imports (A3).- Resolver aliases:
app:///<rel>always resolves to the app root, so code written for the new scheme works whatever a platform reports. One function in the core maps an origin back to a path, for both the resolver and the inspectors'loadNetworkResource.
Rollout. Each platform keeps today's behaviour by default and offers an
opt-in app config flag (proposed name appSchemeOrigins: true) that removes
its override:
- iOS:
appRootOrigin = "file:///app",import.meta= the origin, and the/app/resolver alias stays. - Android:
appRootOrigin = "file://" + appRoot,import.meta= the origin.
The flag switches to the whole model above: origins and import.meta
together. Once plugins and tools that parse stack traces handle app:///,
the default flips (or the override is kept), decided then.
| # | 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) | Decided 2026-12-05: 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. #2104 adapts to it |
| B3 | Land the cache in #622's shape (deferred creation, off-thread write, republish on reject) | Yes, as both investigations concluded |
| B5 | Re-check freshness after reading the source (Android's cacheMatchesBody) |
Decided 2026-12-05: yes. V8 checks a cache only against the source's length, so a same-length change between the dispatch-time Stat and the read would consume a cache that describes other bytes. One extra Stat per cached load, on the pool thread |
| B4 | Naming: flattened (iOS) / beside the source (Android main) / hashed (#2104) | Decided 2026-12-05: hashed under codeCacheDir |
| # | 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 | Decided 2026-12-05: Android |
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.
- Shared code throws JS errors in every build, per the standing "same errors
in Debug and Release" rule. It never uses
tns::AssertorNS_CHECKfor anything JS can reach. - One
JsErrorvalue type (message, stack, name,ThrowToV8). Each platform'sNativeScriptExceptionwraps it.
| # | Question | Options | Rec |
|---|---|---|---|
| F1 | Per-isolate state contract | iOS early-null vs Android live-until-last | Decided 2026-12-05: Android's (live until the last teardown statement, plus a separate stop-accepting-work flag) + ForExisting. The iOS teardown change lands as its own PR before the core relies on it |
| 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.halready 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.
Each one existed on one side only. Rechecked on 2026-12-05 against both
runtimes' main and the draft adoption PRs (iOS #625, Android #2179); line
numbers refer to those. "Fixed by" names the §9 step that retires the code
when the fix does not come sooner: fixing it once in the core beats fixing it
twice in place.
Open
| Side | Bug | Where | Fixed by |
|---|---|---|---|
| Android | When the pumped graph wait reports termination it returns *done, so a walk that finished still counts as success and the caller goes on to instantiate. The agreed rule is that termination outranks settlement. Its two callers (ModuleInternal.cpp:1478, 1555) re-check only IsExecutionTerminating(), not the loop's flag, and then return empty without throwing |
ModuleInternalCallbacks.cpp:3002 |
step 3/6: one shared PumpUntil caller |
| Android | When the top-level-await pump reports termination, EvaluateModuleGraph returns empty without throwing, and LoadESModule ignores that and returns the namespace; its CJS caller then caches the module |
ModuleInternal.cpp:1357-1361, 1628-1630 |
step 7 |
| Android | The entry Load discards an empty LoadESModule result silently |
ModuleInternal.cpp:605 |
step 7 |
| Android | The sync HTTP fallback has no total-wait bound. The core passes waitBound, but the transport cannot cancel an attempt, so a trickling body can hold the JS thread |
HttpLoader.cpp transport |
in place: OkHttp callTimeout or a watchdog calling Call.cancel() / disconnect() (D7) |
| Android | Module.java resolution keeps mutable statics with no locking (possibleException, checkForExternalPath, folderAsModuleCache). After an IOException in the helper, file is null and file.getCanonicalPath() throws an NPE |
Module.java:23-27, 85 |
step 8: the CJS resolver moves to the core |
| 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 GetCacheFileName |
step 4: hashed cache names in the core |
| iOS | Calling-dir check substr(0,4) == "/app" also rewrites /apple/... |
ModuleInternal.mm:547 |
step 8 |
| iOS | File import() evaluation failure rejects with a generic "Evaluation failed" Error and drops the V8 exception |
ModuleInternalCallbacks.mm:3797 |
step 6 |
| iOS | The top-level-await evaluation deadline is wall-clock (NSDate) |
ModuleInternal.mm:1371 |
step 3 |
| iOS | The boot backstop deadline is wall-clock (CFAbsoluteTime) |
NativeScript.mm:155-156 |
step 3 |
| iOS | tns::ReadText aborts the process (Assert → Fatal) when a file it was told exists can't be opened; reachable from ES-module compiles and JSON modules |
Helpers.mm:110-114 |
step 4: ReadFile is all-or-nothing and the caller throws |
Fixed
| Side | Bug | Fixed in |
|---|---|---|
| Android | LoadESModule returned the namespace after the graph-walk pump reported termination (the top-level-await path is still open, above) |
main: returns empty (ModuleInternal.cpp:1479, 1557) |
| Android | URL hash accessor registered twice |
android#2180 |
| iOS | ReadModule ignored read()'s result, so a short read compiled uninitialized bytes |
ios#626 |
| Android | ~/x built app//x |
main (ModuleInternal.cpp:698) |
| iOS | Wrote ES-module code caches in Debug builds; never republished a rejected cache | #622 |
| iOS | Graph-walk and HTTP fetch deadlines used wall-clock CFAbsoluteTime |
iOS #625 (steady_clock) |
| both | The remote-module gate and allowlist were not re-checked after a redirect | core #2, adopted by iOS #625 and Android #2179 |
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.
-
Fix the §8 bugs marked "in place", one small PR per side. The others go away with the step named in their row.
-
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 sharedEventLoop.hnext 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 itsBase64.cppfor the builtin wiring (BuiltinLoader,SetMethodNoSideEffect). - The other units that looked identical are not leaves.
NativeScriptPlatformconstructs and calls the platformEventLoop, so it moves with step 3.ModuleBindingcarries a per-platform binding list, so it needs that list injected first.
-
Foundation headers and platform basics, scoped by what the code moving in steps 4–8 uses:
ns/V8Helpers.h,ns/Trace.h,ns/JsError.h,ns/Deadline.h,ns/IsolateState.h,ns/LoaderConfig.h,ns/Thread.h,ns/V8Flags.h,ns/Utf8.handns/RuntimeAccess.h(IsRuntimeAlive,MainContext).ns/Check.hwaits for a first caller. The runtimes implement the platform functions; their own code keeps its helpers until it moves. The iOS teardown change (F1) goes in as its own PR.Before the core throws
JsError, every platform catch ladder learnscatch (JsError&)andcatch (Terminated&)ahead of its generic clauses: iOSRequireCallbackandRunMainScripthave nocatch (...), so an unknown type ends instd::terminate. -
Loop interface. Both
EventLoops implementLoop. iOS gainsPumpUntilwith the three modes, replacing its three ad hoc pumps, and its deadlines go monotonic; the 1 s local TLA window stays separate from the 60 s one. Android foldsPumpNestableV8TasksUntilinto it and moves its TLA probe's throw after the pump. -
Code cache + file seam, in #622's shape, with B2/B4 as decided (#2104 adapts to it). Move the shared file helpers,
ReadFile/Stat, the cache queue, andCompileFileEsModule. The ESM core callsCompileFileEsModule, so it has to move before step 6. -
HTTP policy core +
ModuleTransport. NSURLSession and OkHttp move behind the interface; the lanes move into the core. -
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'sModuleInternalthrough two declared transitional up-calls:InstallCreateRequireBinding(thens:modulebinding);LoadESModule, the evaluation entry for require(esm).
Name them in a
transitional.hso they are deleted on purpose. -
Evaluation layer:
EvaluateModuleGraph, entry probes, boot backstop loop (C1, C2, C5). -
CJS core: the resolver (A4–A7), the require cache and wrapper.
Module.javabecomes JNI wrappers. iOS turns onwalkNodeModules, and the shared-testxits must pass.
Follow-on, on the same foundation, from the infrastructure report's ranking, easiest first:
TextEncoding,StructuredClone,StructuredSerialization.- URL and
URLSearchParams/URLPattern, after the three URL drifts and Android's deprecated setter overload are fixed. BuiltinLoader,LazyGlobals,IsolateTracked.- The builtin
js/: 14 of 28 files are already byte-identical, and both sides generate the same js2c output. Events,ErrorEvents,Performance,WeakRef.Messaging, after F1.- The
EventLoopqueue bookkeeping.
The platform-owned subsystems do not move: wrapper lifetime and leak probe,
console sinks, inspector transport, Runtime, and the body of
NativeScriptException.
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.
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, theModule.javavs iOS resolver behaviour table, invariants I1–I29.C-http.md: HTTP policy vs transport,ModuleTransportsketch, 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.