Skip to content

Latest commit

 

History

History
3640 lines (3391 loc) · 220 KB

DESIGN.md

File metadata and controls

3640 lines (3391 loc) · 220 KB

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

Status: proposal, 2026-12-04, updated 2026-12-06. Steps 1–6 of §9 are built and adopted by both runtimes' draft PRs: the build wiring, the foundation headers, the loop interface, the app-file seam and code cache (ns/AppFiles.h, ns/loader/), the HTTP policy core (ns/http/) and the ESM core (ns/loader/). Step 7, the evaluation layer and main-entry boot, is built in ns/loader/Evaluate.h and ns/loader/Boot.h. Step 8, the CommonJS core, has its questions decided. F3 (a submodule repository), F7 (the nativescript::common namespace), D1–D10, A1–A10 and C1–C5 are decided. 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, main-entry     │
 │          boot (a pumping require of the entry)                │
 │   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

Built: ns/LoaderConfig.h (LoaderConfig, platform::LoaderSnapshot()), 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. Step 6.1 adds the module-identity fields:

  • appRootAliases: pairs of another spelling of appRoot (or of an ancestor) and the one appRoot uses. Examples are Android's /data/data/<pkg> for /data/user/0/<pkg>, and iOS's /private/var for /var, which stringByStandardizingPath used to fold;
  • virtualFileRoots: file:// path prefixes that name the app root;
  • appRootOrigin;
  • legacyOrigins (A10).

reportedPathPrefix goes once both runtimes adopt 6.1 (Q5).

These join it when their step lands:

  • globalModuleRoots and walkNodeModules with the CJS core (step 8);
  • Fatal when 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.

4.3 App files (driven by #2104)

Built: ns/AppFiles.h.

namespace nativescript::common {

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). Empty: the file never gets a cache.
  std::string freshnessToken;
};

namespace platform {
// Logical paths (absolute, 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.
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
  • 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.

Built: the code cache, in nativescript::common::loader.

  • ns/loader/CodeCache.h, V8-free and host-tested:
    • Name: <codeCacheDir>/<16 hex digits>.mcache (or .cache for a classic script). The digits are the 64-bit FNV-1a hash of the key. The key is the source's path relative to appRoot, or its absolute path outside it. A relative key keeps names stable when the iOS bundle path changes on an app update.
    • File: a header (magic NSCC, format version, kind, key, source size, freshness token, payload length, module format), then V8's cached data. The header must match exactly, so a hash collision reads as a miss. V8 validates its own version and flags. Format version 2 (6.6) added the module format, which records how import takes a .js file (Q13): an ES module file carries kEsModule and its payload; a CommonJS marker carries kCommonJs and no payload. A classic script's file carries kNone. FreshModuleFormat reads it from the header alone; LoadCodeCache never returns a marker. Version 1 files read as stale, so each app recompiles once after the update.
    • CodeCacheEntryFor(path, kind, stat) names the file and records the Stat it was decided on. It returns nullopt when caching is off: codeCacheEnabled false, no codeCacheDir, or no freshness token. It takes the LoaderConfig it applies (6.2), the isolate's LoaderConfigFor.
    • HasFreshCodeCache reads the header only (decide-before-read). LoadCodeCache returns the whole payload or nothing, checking the header again. WriteCodeCache creates the directory and renames into place.
    • SourceUnchanged(path, stat) is the B5 re-check: a second Stat after the read, comparing size and token.
    • PostCodeCacheWrite hands the bytes to one serial writer thread (StartThread, kUtility). The writer skips a source that changed.
  • ns/loader/CodeCacheQueue.h: QueueCodeCache defers creation per isolate (IsolateState), 0.5 s after the last queued cache and then 16 ms apart, through Loop::PostInternalDelayed. NotifyAppBackgrounded creates everything queued in one loop task.
  • ns/loader/FileCompile.h: CompileFileEsModule and CompileFileClassicScript. Each does Stat, then ReadFile, consumes a fresh cache, compiles, and queues creation when there was no cache or V8 rejected it. Only a debug build re-checks SourceUnchanged before it consumes the cache (B5). A missing file throws JsError "Cannot find module", an unreadable one "Cannot read module". A compile error returns empty with the exception pending. The caller passes the script origin (A10) and, for a classic script, the wrapper (A7) as parameters. 6.6 added CompileFileModule, which picks how import takes a file (Q13).

The pool-thread consumer of #622 (step 6) uses the same calls: CodeCacheEntryFor and HasFreshCodeCache at dispatch, then ReadFile, SourceUnchanged and LoadCodeCache on the pool, and QueueCodeCache when it finalizes.

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

Built: ns/Loop.h (Loop, PumpMode, PumpResult, platform::LoopFor) and ns/Deadline.h. The header is normative; in short:

  • each runtime's EventLoop implements Loop;

  • PumpUntil(deadline, settled, mode, idle) checks termination, then settled, 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;

  • settled must not throw or run JS; a caller whose condition can fail records it and throws after kSettled. Android's TLA probe throws from inside the pump today, which lets a same-slice rejection outrank termination;

  • kPlatformWork is 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 by waitBound) and the teardown drain of streamed compiles, which must keep running on a terminated isolate and uses RunNestableV8Tasks directly.

  • Android has PumpUntil(deadlineSeconds, settled, drainLooperWork), PumpNestableV8TasksUntil(deadlineSeconds, settled, idle) and IsOnHomeThread() (#2177). PumpMode folds 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 (NSDate deadline);
    • ModuleInternalCallbacks.mm:2902-2985: the graph walk, with CFRunLoopRunInMode(…, 0.01, true) and, for file jobs only, the FileJobSignal wait;
    • NativeScript.mm:129-212: the boot backstop (CFAbsoluteTime deadline).

    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 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.

  • iOS boot hands off to UIApplicationMain, which never returns. A JS call to it only queues a task that Tasks::Drain() runs once the boot call has returned, outside the Locker. The core's boot call takes a hand-off predicate instead of a per-slice hook (step 7): it stops pumping when the predicate says the task is queued, so the core holds nothing when UIApplicationMain takes over.

  • 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

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.

4.7 Per-isolate state

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::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).

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.

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
LoaderConfig::moduleRunScope(name, body, data) (built in step 8, replaces TraceModuleLoad): calls body(data) inside the runtime's per-module scope. The loader brackets each CommonJS module's function call (named by its path) and each ES module evaluation it starts (named by the root's registry key; V8 evaluates the root's whole graph inside it, and a CommonJS module imported there gets a nested scope). Null by default, so a runtime without one pays one pointer test Android profiler frames (instrumentation::Frame) and crash breadcrumbs (CrashBreadcrumbs::ModuleScope)
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 {

// Per isolate
void InstallHostCallbacks(v8::Isolate*);   // resolve, import(), import.meta

// Boot (ns/loader/Boot.h). Each throws JsError or Terminated and never
// asserts; whether that is fatal is the runtime's call.
struct BootOptions {
  std::function<bool()> handOff;   // asked before each slice; null = strict
  double deadlineSeconds = kModuleSettleSeconds;   // 60
};
enum class BootOutcome { kSettled, kHandedOff };
struct BootResult { BootOutcome outcome; v8::Local<v8::Promise> pendingEntry; };
// The app's ES module main entry: load, evaluate, then pump kPlatformWork
// until it settled and this isolate's graph walks ended, or handOff().
BootResult RunMainEntry(v8::Local<v8::Context>, const std::string& pathOrUrl,
                        const BootOptions&);
// The same hold after a CommonJS main entry the runtime ran (until step 8).
BootOutcome HoldBoot(v8::Local<v8::Context>, const BootOptions&);
// Worker and tooling entries: a local one returns its pending promise at
// once; an http(s) one is waited for (60 s) and throws.
v8::MaybeLocal<v8::Promise> RunEsModuleEntry(v8::Local<v8::Context>,
                                             const std::string& pathOrUrl);
bool IsEsModuleEntry(std::string_view pathOrUrl);   // .mjs or http(s)
bool HasPendingGraphWork(v8::Isolate*);   // this isolate's walks

// Evaluation (ns/loader/Evaluate.h, ns/loader/EvaluationPolicy.h)
v8::MaybeLocal<v8::Promise> EvaluateModuleGraph(
    v8::Local<v8::Context>, v8::Local<v8::Module>, const std::string& key,
    const ModuleEvaluationOptions&);
v8::Local<v8::Object> LoadEsModule(v8::Local<v8::Context>,
                                   const std::string& pathOrUrl,
                                   const ModuleEvaluationOptions&);
v8::Local<v8::Value> RequireEsModule(v8::Local<v8::Context>,
                                     const std::string& path,
                                     const ModuleEvaluationOptions&);

// 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

Step 8 (built: 8.1–8.5 core). These replace the ResolveMainEntry() / ResolveEntry(spec) sketch above, and the HoldBoot line: RunMainEntry now runs a CommonJS entry too. See §9 step 8.

namespace nativescript::common::loader {

// require() resolution, V8-free (ns/loader/RequireResolver.h)
RequireResolution ResolveRequire(std::string_view specifier,
                                 std::string_view fromDir,
                                 const LoaderConfig&, PackageJsonCache&);
std::vector<std::string> RequireLookupPaths(std::string_view fromDir,
                                            const LoaderConfig&);
std::string RequireErrorMessage(const RequireResolution&);
std::string_view RequireErrorCode(const RequireResolution&);
RequireResolution ResolveMainEntry(const LoaderConfig&, PackageJsonCache&);
RequireResolution ResolveEntry(std::string_view specifier,
                               std::string_view fromDir,
                               const LoaderConfig&, PackageJsonCache&);
class RequireResolveCache;   // found resolutions by (fromDir, specifier)

// package.json, V8-free (ns/loader/PackageJson.h)
PackageInfo ParsePackageJson(std::string_view text);
class PackageJsonCache;      // one Stat per use, read again when it changed

// Per isolate (ns/loader/CommonJs.h)
const RequireResolution* CachedRequireResolution(v8::Isolate*,
                                                 std::string_view specifier,
                                                 std::string_view fromDir);
RequireResolution ResolveRequireFor(v8::Isolate*, std::string_view specifier,
                                    std::string_view fromDir);
JsError RequireError(v8::Isolate*, const RequireResolution&);

// require() itself (ns/loader/CommonJs.h)
void InstallCommonJs(v8::Local<v8::Context>);   // the global require
v8::Local<v8::Function> RequireFunctionFor(v8::Local<v8::Context>,
                                           std::string_view dir,
                                           const ModuleEvaluationOptions&);
v8::Local<v8::Value> RequireFile(v8::Local<v8::Context>,
                                 const std::string& path);   // import of CJS
// ns/loader/ModuleIdentity.h: a file: URL's path, virtual roots mapped
// (ns:module's createRequire uses it; require directories are canonical
// paths, never mapped).
std::string FileUrlPathToPath(std::string_view path, const LoaderConfig&);
// ns/loader/RequireResolver.h: the format require() gives a resolved path
// (RunCommonJsEntry dispatches on it).
RequireResolution::Format RequireFormatOf(std::string_view path,
                                          const LoaderConfig&);

// Entries (ns/loader/Boot.h): RunMainEntry takes a CommonJS entry too;
// HoldBoot is gone. A .mjs entry runs as an ES module; a JSON or addon
// entry throws "Cannot run <path> as an entry: it is not a JavaScript
// module".
v8::MaybeLocal<v8::Promise> RunCommonJsEntry(v8::Local<v8::Context>,
                                             const std::string& path);

// CommonJS compile (ns/loader/FileCompile.h)
inline constexpr std::array<std::string_view, 5> kCommonJsParameters;
v8::MaybeLocal<v8::Function> CompileFileCommonJs(
    v8::Isolate*, v8::Local<v8::Context>, const std::string& logicalPath,
    const std::string& scriptOrigin);
RequiredSource CompileFileForRequire(   // the same, or "an ES module" (Q13)
    v8::Isolate*, v8::Local<v8::Context>, const std::string& logicalPath,
    const std::string& scriptOrigin);

// Import-map scopes (ns/loader/ImportMap.h): now takes the config
std::string ImportMapScopePrefix(std::string_view scopeKey,
                                 const LoaderConfig&);

}  // namespace nativescript::common::loader

namespace nativescript::common::platform {
// ns/RuntimeAccess.h: a Node-API name or a native addon path; nullopt when
// the runtime does not load it.
std::optional<v8::MaybeLocal<v8::Value>> RequireNativeAddon(
    v8::Local<v8::Context>, const std::string& request,
    v8::Local<v8::Object> module);
}  // namespace nativescript::common::platform

LoaderConfig gains walkNodeModules, globalModuleRoots, nativeLibraryScheme, nativeAddonExtensions, commonJsThisHasExtends and the optional hook (§4.8)

// On the isolate's thread, under its Locker; `name` lives until the call
// returns; `body` throws no C++ exception and may leave a V8 exception
// pending. Null for none.
void (*moduleRunScope)(const char* name, void (*body)(void* data),
                       void* data) = nullptr;

CodeCacheKind gains kCommonJsFunction. ns/loader/Transitional.h is gone: platform::RequireFileForImport and platform::InstallCreateRequireBinding are no longer up-calls.

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.
  • No local (non-HTTP) entry waits in place for its top-level await: the main entry boots as a pumping require, and a worker or tool entry returns its pending promise to its own event loop (decided 2026-12-06; this replaced the 1 s local window).
  • 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 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 Decided 2026-12-06: Node order. node_modules from the requiring file's directory up to and including <appRoot>/node_modules (up to / for a file outside the app root), then the legacy roots as config (globalModuleRoots): <appRoot>/tns_modules, then <appRoot>/tns_modules/tns-core-modules
A5 node_modules walk on iOS none (5 shared specs xit) yes Decided 2026-12-06: turn on through walkNodeModules (core config only); 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 ){ Decided 2026-12-06: no text prologue. Compile with ScriptCompiler::CompileFunction and Node's parameters (exports, require, module, __filename, __dirname), so line-1 columns are exact, under a new code-cache kind and format version. Every classic cache is rejected once. If V8's code cache or the inspector's script reporting does not work for such a function, fall back to one text prologue for both. Neither side corrects error-stack columns for the prologue today; only Android's extend() class naming (MetadataNode) subtracts it
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-root forms and .. (A1, A3). A ~/, root-absolute or bare specifier names a path below the app root, so its tail is normalized as an app-root-relative path first, a .. at the root dropped as at a URL's root, and only then prefixed with the app root: /../../etc/x.mjs, ~/../../etc/x.mjs and lib/../../../etc/x.mjs all name <appRoot>/etc/x.mjs, as /etc/x.mjs does. A root-absolute path already under the app root is kept as it is (Q7). Only a relative specifier, joined with its importer's directory, and an absolute file:// URL (A3) reach files outside the app root.

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 is app://, giving app:///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 no sourceMapURL rewrite.
  • Origin of a file outside the app root: file://<absolute path>.
  • import.meta.url, .filename, .dirname: the real absolute path, so fileURLToPath(import.meta.url) === import.meta.filename holds as in Node, and the values work with file APIs and with absolute file:// 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, appSchemeOrigins: true (named and wired in 6.6), 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. The LoaderConfig defaults are that model, so the core has no code for the flag: a runtime that reads it set skips its appRootOrigin and legacyOrigins override. The virtual roots stay either way (Q10). Once plugins and tools that parse stack traces handle app:///, the default flips (or the override is kept), decided then.

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) 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. No payload checksum: atomic rename plus the exact-size check guard the file, as both runtimes' main do today
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. The inline compile (CompileFile*) re-checks only in debug builds, so a Release boot pays no extra Stat on the isolate thread
B4 Naming: flattened (iOS) / beside the source (Android main) / hashed (#2104) Decided 2026-12-05: hashed under codeCacheDir, keyed by the path relative to appRoot (the absolute path outside it), so names survive the iOS bundle path changing on update. #2104 adapts to it

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 Decided 2026-12-05: Android. Step 7 replaced the backstop: boot is a pumping require of the main entry that throws on any rejection, and each runtime makes that fatal

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 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.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)

Most 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 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 once adopted: hashed names, and the header holds the key
iOS Calling-dir check substr(0,4) == "/app" also rewrites /apple/..., through createRequire too ModuleInternal.mm:548 step 8
iOS require("./") from any module loads the app's main entry instead of the calling directory as a package ModuleInternal.mm:554 step 8
both "main": "." (or "./", "") in a package.json recurses without end: iOS reads the same package.json again, Android loops through loadAsDirectory. Node resolves it to ./index.js (by reading) iOS ModuleInternal.mm:1773-1778; Android Module.java:270-274 step 8: main naming a directory loads its index and never reads a nested package.json
Android ~/x builds <appRoot>//x: APP_ROOT_FOLDER_PATH ends in / and the resolver appends "/" + tail. For .mjs the doubled string is the path and the registry key ModuleInternal.cpp:743, Runtime.cpp:238 step 8
Android A bare-name require-cache key ignores the requiring directory, so two packages with different nested node_modules/<n> get whichever loaded first ModuleInternal.cpp:720 step 8: keyed by directory and specifier
both A CommonJS file reached through require() and through import can run twice. The require cache keys by the platform's normalizer: iOS Foundation stringByStandardizingPath, which resolves a symlink followed by .. and keeps /private for a path that does not exist; Android Java getCanonicalPath, a realpath. RequireFileForImport keys by the core's lexical canonical path, so a file whose two spellings differ misses and runs again. Only on the adoption branches: before 6.6, import never shared the require cache iOS ModuleInternal.mm:648, 681; Android ModuleInternal.cpp:385, 771, Module.java:85 step 8: one canonical require-cache key
core The classic code cache's header and name do not record the wrapper prologue, and V8 checks a cache only against the source length, so a same-length prologue change would consume caches compiled for other positions (latent) CodeCache.cpp header, FileCompile.cpp step 8: a new cache kind and format version with A7
iOS File import() evaluation failure rejects with a generic "Evaluation failed" Error and drops the V8 exception ModuleInternalCallbacks.mm:3829 step 6.5 once adopted (built: "Evaluation failed for module: — ")
iOS tns::ReadText aborts the process (Assert → Fatal) when a file it was told exists can't be opened; reachable from ES-module compiles, JSON modules and require() of a .json file (LoadData, ModuleInternal.mm:902) Helpers.mm:110-114 step 4 once adopted for compiles (CompileFile* throw "Cannot read module"); step 6.5 once adopted for JSON modules (built: platform::ReadFile, Error "Cannot read module "); step 8 for require()

Fixed

Side Bug Fixed in
Android LoadESModule returned the namespace after the graph-walk pump reported termination 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
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
Android The pumped graph wait returned *done on termination, and its callers returned empty without throwing android#2179
Android A terminated top-level-await pump let LoadESModule return the namespace android#2179
Android The entry Load discarded an empty LoadESModule result android#2179
iOS The top-level-await deadline was wall-clock (NSDate) ios#625 (Loop::PumpUntil)
iOS The boot backstop deadline was wall-clock (CFAbsoluteTime) ios#625 (Loop::PumpUntil)
both import() of a module whose evaluation was on the stack (a self-import, or a cycle back to a module being evaluated) hit V8's CHECK in Module::Evaluate core fix/evaluating-import (settles after the evaluation, §9 6.5), once adopted
both import() once loader::Quiesce had run returned an empty promise with no exception pending, and V8 aborted the process in Isolate::UnwindAndFindHandler core 6.5 (decided 2026-12-05: a promise that never settles), once adopted. A runtime wrapper that checks its own teardown state first must return such a promise too

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 marked "in place", one small PR per side. The others go away with the step named in their row.

  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, 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.h and ns/RuntimeAccess.h (IsRuntimeAlive, MainContext). ns/Check.h waits 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 learns catch (JsError&) and catch (Terminated&) ahead of its generic clauses: iOS RequireCallback and RunMainScript have no catch (...), so an unknown type ends in std::terminate.

  4. Loop interface. Both EventLoops implement Loop. iOS gains PumpUntil with 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 folds PumpNestableV8TasksUntil into it and moves its TLA probe's throw after the pump.

  5. Code cache + file seam, in #622's shape, with B2/B4 as decided (#2104 adapts to it). The ESM core calls CompileFileEsModule, so it has to move before step 6. Built in the core (§4.3); the runtimes adopt it next:

    • Both: implement platform::Stat and platform::ReadFile. Set codeCacheDir to a directory of the cache's own. Replace LoadScriptCache/TryLoadScriptCache, QueueScriptCache, FreshScriptCachePath and ReadBinary/WriteBinary with the core's calls. Call CompileFile* with today's origin and wrapper. Have the background hook call NotifyAppBackgrounded(isolate).
    • iOS: the token is the source's mtime. The UIApplicationDidEnterBackground observer moves to the platform. Before using IsolateState, it needs the F1 teardown change.
    • Android: the token is the mtime on disk; with #2104, the APK version for asset layers. codeCacheDir is new on Android, which writes caches beside the source today. The debug LiveSync lock that Runtime::ReadFileText takes per runtime becomes one process-wide lock, debug only, taken inside Android's platform::ReadFile. The core has no hook for it.
    • Old cache files (iOS's flattened names in Caches, Android's .cache/.mcache beside the sources) are never read again. Delete them once.
  6. HTTP policy core + ModuleTransport. NSURLSession and OkHttp move behind the interface; the lanes move into the core.

  7. ESM core (ModuleInternalCallbacks). The largest step, landed as six units in the order below. Each one is suite-green on both platforms on its own, and each runtime deletes its copy of the unit in the same adoption. Baseline: both runtimes' feat/runtime-common branches (steps 1–4 adopted). #622 is on both sides there: file jobs, walk parking and asynchronous file import(). Both pumps already run through Loop::PumpUntil, and both return false on termination.

    Three calls cross from the callbacks into each runtime's ModuleInternal:

    • InstallCreateRequireBinding(context, binding), from the ns:module binding (6.6);
    • EvaluateModuleGraph(…, kSyncStrict), from the require(esm) facade (6.6);
    • ModuleInternal::CompileFileEsModule(isolate, path, query), from the walk and the static resolver. It is the runtime's wrapper around the core's CompileFileEsModule, and it adds the origin and, on iOS, the CommonJS wrap for a .js file. 6.4 and 6.5 retire it: the core passes ModuleOrigin, and the wrap follows Q13.

    The first two stay until steps 7–8. They are declared in ns/loader/Transitional.h, which each runtime implements, so they are deleted on purpose. The third goes there too if Q13 is still open when 6.4 lands.

    As built: 6.4 retired the third into platform::FileModuleSourceWrap, and 6.6 deleted it: import takes a file as an ES module or as CommonJS, never wrapped. 6.6 never added the second: the core evaluates the facade itself, so the facade needs no up-call. Q13 added platform::RequireFileForImport. The two left (InstallCreateRequireBinding, RequireFileForImport) go with step 8's CommonJS core.

    LoadESModule is not an up-call. The callbacks never call it. It is ModuleInternal's driver of the walk (SyncModuleLoadScope, RunModuleGraphLoadPumped, LoadHttpModuleForUrl, ResolveModuleCallback), and it calls the core's API once 6.4 lands. It moves with step 7.

    Until a unit lands, the runtime code that is still local calls the core units that already moved. Each unit below lists that surface.

    6.1 Module identity. V8-free, in ns/loader/ModuleIdentity.h. Built (see "Built" below).

    • Core API:

      • NormalizePath (A1);
      • ModuleQuery;
      • KeyPath;
      • CanonicalizeModuleKey;
      • ModuleOrigin and ReportedModuleUrl, the A10 origins;
      • ImportMetaFor, the import.meta strings;
      • OriginToPath, the inverse of ModuleOrigin;
      • FileUrlToPath, a file: or app: URL the runtime did not write (A2, A3).

      None of them read a global config. Each takes the LoaderConfig it applies.

    • Config: LoaderConfig gains appRootOrigin (default app://), legacyOrigins, appRootAliases and virtualFileRoots (§4.2). reportedPathPrefix goes once both runtimes have adopted this unit.

    • Platform: platform::ParseUrl, WHATWG parsing through each runtime's ada (Q12).

    • Runtimes delete:

      • from ModuleUrl: ReportedModuleUrl, ModuleQuery and FileModulePath;
      • iOS NormalizePath and FileURLToPath, which are Foundation code;
      • Android NormalizeDotSegments;
      • the bodies of CanonicalizeRegistryKey. iOS keeps a wrapper for its filePathByKey short-circuit until 6.2;
      • the string work in both import.meta callbacks;
      • the path mapping in both inspectors' loadNetworkResource and source-map rewrite, along with iOS's BaseDir candidates.
    • Settles:

      • A1: lexical everywhere, with the app root's spelling fixed through appRootAliases;
      • A2: the file:// branch of canonicalization goes through ada;
      • A8 and A10: the strings.

      Under each platform's override (legacyOrigins), every origin and import.meta string stays byte-identical to today, except Q5.

    6.2 Loader state and the registry. Built (see "Built: 6.2" below).

    • Core API:

      • a core ModuleLoaderState in IsolateState, holding the registry, the module → key index and iOS's key → path record;
      • SetRegisteredModule(key, module, path) as the only write. It unindexes the previous occupant;
      • RemoveModuleFromRegistry, FindKeyForModule, ModuleFilePathForKey, GetLoadedModuleUrls and InvalidateModules;
      • the per-isolate config snapshot (see "Liveness and config snapshot" below);
      • a closing flag that loader::Quiesce sets first. This is F1's "stop accepting new work", owned by the core, which replaces iOS's Caches::IsTearingDown test in ModuleLoaderStateFor.
    • Platform: platform::LoaderSnapshot() replaces platform::Loader().

    • Still local: the walk, file jobs and vocabulary keep the runtime's own loader state and reach the registry through the core API. Both ModuleInternals call SetRegisteredModule and RemoveModuleFromRegistry.

    • Runtimes delete:

      • the registry, keysByModuleHash, filePathByKey and requireFacadesByTargetHash fields, with the Index/Unindex helpers, DropRequireFacadesForTarget and ModuleRegistryFor;
      • Android's open-coded unindex sites (seven);
      • IndexModuleForIsolate, UnindexModuleForIsolate, SetRegisteredFileModule and the bodies of FindKeyForModule, GetLoadedModuleUrls and InvalidateModules.

      RemoveModuleFromRegistry shrinks to the file-job step around the core's.

    • Settles:

      • the write-path shape (iOS's);
      • Q6.

      It also covers iOS ModuleInternal.mm:1561. That line looks as though it overwrites a key without unindexing it when the entry there is still evaluating, because such an entry is neither reused nor removed. This is from reading the code, not a reproduction.

    6.3 Vocabulary, import maps and the resolver. Built (see "Built: 6.3" below). Policy is V8-free; the JSON parse is in a V8 file.

    • Core API:
      • LoaderVocabulary;
      • ParseImportMap through v8::JSON::Parse, validated in full before install;
      • LookupImportMap(map, spec, referrerPath), which takes the map explicitly (Android's shape);
      • CaptureLoaderVocabulary and InstallLoaderVocabulary, which Worker.mm and WorkerWrapper call;
      • ResolveSpecifier(spec, referrer, vocabulary, config, ImportMapLookup), returning ModuleResolution with kBuiltin, kHttp, kFile, kBlob or kUnresolved. It probes files only, through platform::Stat, and builds the same attempted text, which the tests pin.
    • Platform:
      • none for builtins: IsBuiltinModuleSpecifier(spec) is a core prefix check, since both runtimes' scheme tests are the same. Each runtime keeps its NsBuiltinModules rows;
      • the ada-backed helpers the resolver calls, ParseModuleUrl (authority as written) and BlobStoreUrl. They move from ModuleUrl to platform functions beside NormalizeHttpModuleUrl until Q12. ParseModuleUrl needs component offsets that UrlParts does not expose.
    • Runtimes delete:
      • both resolvers and both import-map parsers, including iOS's NSJSONSerialization;
      • ImportMapScopePrefix.
    • Settles:
      • A3: an absolute file:// path loads that file. The iOS expectation at DynamicImportTests.js:159 flips;
      • A9: builtin targets, kBlob and kSkip;
      • A10: app:/// always resolves to the app root;
      • A1: the relative join is lexical;
      • Q7–Q10.

    6.4 Graph walk, file jobs and the stream-compile pool. These land together. The walk dispatches file jobs to the pool, and parking ties the jobs to SyncModuleLoadScope.

    • Core API:

      • StartModuleGraphLoad with the typed ModuleGraphRoot (iOS's);
      • RunModuleGraphLoadPumped, SyncModuleLoadScope, HasPendingGraphWork and LoadHttpModuleForUrl;
      • loader::Quiesce, which kills walks and file jobs (marking jobs superseded, as Android does) and then drains the pool under SuppressMicrotaskExecutionScope and DisallowJavascriptExecutionScope (invariant 11);
      • the pool on StartThread, BackgroundCompileStackBytes and the eager option from V8FlagsDisableLazyCompile;
      • file jobs, through CodeCacheEntryFor, HasFreshCodeCache, SourceUnchanged, LoadCodeCache and QueueCodeCache;
      • the liveness token (see "Liveness and config snapshot").
    • Platform: none new. Q15 settles the external memory charge.

    • Transitional: if Q13 is still open, CompileFileEsModule's SourceWrap for a .js reached through import comes from a Transitional.h up-call (it was; 6.6 settled Q13).

    • Runtimes delete:

      • StreamCompilePool, StreamFeed and BodySourceStream;
      • FileModuleJob and its functions;
      • AsyncGraphLoad and both copies of the walk.

      LoadESModule calls the core.

    • Settles:

      • the monotonic start stamp;
      • Android's drain scopes, superseded on kill, and its home-thread check before waiting on file jobs;
      • Q13 and Q14, the two items carried over from step 4.

      The pool keeps the SourceUnchanged re-check unconditionally.

    6.5 Static and dynamic import, JSON modules. Built (see "Built: 6.5" below). (Found in 6.4: both runtimes build a JSON module as "export default " + text + ";", so a served body is compiled as JavaScript, not validated as JSON. 6.5's JSON module should parse it with v8::JSON::Parse into a synthetic module.)

    • Core API:
      • ResolveModuleCallback, ImportModuleDynamicallyCallback, FinishHttpDynamicImport and the settling of a file import();
      • blob import();
      • the dynamic-import waiters and BuildModuleFailureReason;
      • JSON modules.
    • Platform: a blob-store lookup. Today it is per runtime, beside URL.createObjectURL.
    • Runtimes delete: both callbacks and DynamicImportReferrerKey.
    • Settles:
      • A9: builtins are matched after the single resolution (iOS);
      • invariant 19: Android's rejection reasons. This fixes the §8 iOS "Evaluation failed" bug and iOS's generic blob failure messages;
      • Then(...) through FromMaybe;
      • the referrer is read with OriginToPath;
      • JSON modules read through platform::ReadFile. This is the step 4 carry-over and retires iOS tns::ReadText for modules.

    6.6 import.meta, the require(esm) facade and ns:module.

    • Core API:
      • InstallHostCallbacks(isolate), which installs the resolve, import() and import.meta callbacks;
      • InitializeImportMetaObject, built on ImportMetaFor;
      • GetOrCreateRequireFacade;
      • the ns:module binding, with Android's C++ exception barrier on every callback and its rejection of a function-valued importMap.
    • Transitional: both up-calls named above.
    • Runtimes delete: both import.meta callbacks (iOS's is in Runtime.mm), the facade, and BuildNsModuleBinding.
    • Settles:
      • A8;
      • wiring the appSchemeOrigins app-config flag on both platforms;
      • Q11, Q16 and Q17.

    Built (see "Built: 6.6" below), with Q13.

    Liveness and config snapshot. Decided 2026-12-05: both are accepted as written here. The core needs them before it posts work that outlives a call, so the snapshot lands with 6.2 and the token with 6.4. 6.1 needs neither.

    • Liveness (6.4). Today both IsRuntimeAlive implementations read the isolate's data slot. That read is itself a use-after-free once the isolate is disposed, and Android never clears its slot. The core never calls IsRuntimeAlive. Background work instead holds two things, captured on the isolate thread when the work is dispatched:

      • a liveness token: std::shared_ptr to a core RuntimeLiveness { std::atomic<bool> alive; std::weak_ptr<Loop> loop; }, created when the loader is installed and set false first thing in loader::Quiesce;
      • the loop's weak_ptr.

      A completion posts only while alive, through the weak_ptr, and re-checks alive when it runs on the isolate thread before it touches the isolate. No isolate address is ever dereferenced or compared.

      Step 4's code-cache code splits two ways:

      • Tasks that CodeCacheQueue posts to the isolate's own loop keep their [isolate] capture. They run only on that loop, and the loop is shut down before the isolate is disposed.
      • NotifyAppBackgrounded(isolate) is called from any thread and looks the loop up by isolate. It moves to the token: the platform holds the main runtime's token and passes that instead.

      The existing load->dead flag and StreamCompileGate identity are two ad hoc copies of this pattern, and the token replaces both. A gate-id registry would also work, but it costs a lookup under a mutex on every check and still needs the id captured at dispatch.

      IsRuntimeAlive leaves ns/RuntimeAccess.h. MainContext stays, for the isolate thread.

    • Config snapshot (6.2). platform::Loader() becomes std::shared_ptr<const LoaderConfig> platform::LoaderSnapshot(). iOS's RefreshLoaderConfig publishes a new snapshot with std::atomic_store instead of rewriting the static in place. (The free functions compile clean under C++20 on Apple clang 17 and NDK 27 and 29; libc++ has no std::atomic<std::shared_ptr>.) The core copies the snapshot into the isolate's loader state when the loader is installed. A worker takes its parent's snapshot, as it does the vocabulary. Every core reader uses the per-isolate copy: CodeCacheEntryFor, FileCompile's debug check, and the identity functions' callers. A worker of the previous run then keeps that run's values, and no thread reads a struct that is being rewritten.

    Decisions. Every question below was decided on 2026-12-05. Q1–Q5, Q12 and Q18 shape 6.1 and are built. The others are applied by the unit named in each.

    • Q1. Legacy round trip. Legacy origins spell the path verbatim, so a file whose name contains # or a %XX sequence does not survive A2's ada parse. The options were to accept that, to percent-encode legacy origins too (which changes today's stack text), or to read the runtime's own strings back verbatim.

      Decided (c): strings the runtime minted (the import() referrer, inspector URLs) are read back verbatim in legacy mode, and everything else goes through ada. OriginToPath is that inverse. Node never parses its CommonJS frame paths as URLs either, and a legacy origin is a path written in file:// syntax, not a URL.

      A runtime-minted origin can also come back through JS, as invalidateModules(import.meta.url) does. So under legacyOrigins the registry reads a file: URL back verbatim first (OriginToPath, with the query kept as written) and uses that key when it names a registered module. Any other string still goes through ada. RegistryKeyFor, RemoveModuleFromRegistry and InvalidateModules all go through this (RegistryTable::CanonicalKey). Opt-in mode needs none of it: Q2 encodes its origins, and ada round-trips them.

    • Q2. Encoding in opt-in mode. Decided: opt-in origins and import.meta.url are percent-encoded as Node's pathToFileURL does, and import.meta.filename is the decoded path. A10's fileURLToPath(import.meta.url) === import.meta.filename holds only this way. ModuleOrigin does it.

    • Q3. Hosts and encoded separators in a file:// URL. Today Android drops the host, and iOS's resolver reads it as a path segment under the app root.

      Decided (b), strict. FileUrlToPath rejects:

      • a host other than empty or localhost;
      • %2F and %5C, in either case. Node's ESM resolver rejects both with ERR_INVALID_MODULE_SPECIFIER;
      • %00. This is stricter than Node, which does not reject NUL by name but can never load such a path.

      The runtime's own node:url fileURLToPath already rejects hosts and %2F. OriginToPath reads strings the runtime minted, so it still decodes %5C: a file whose name contains \ keeps its inspector URL and import() referrer, but, as in Node, it cannot be imported through its own opt-in import.meta.url.

    • Q4. ModuleQuery when the parser rejects the specifier. Decided: iOS's fallback, which keeps the text from ? to #, so two queries stay two modules. That is #621's stated intent, and the #2176 port dropped it. Android changes.

    • Q5. iOS files in the bundle but outside the app root. Under the iOS override, their origin changes from file:///<path relative to the bundle> to file://<abs>, which is what A10 says for files outside the app root. No ES module can live there today (A3), so only classic scripts outside app/ see it, and iOS's stack-text BaseDir stripping hides it there. Decided: accept it, and drop reportedPathPrefix.

    • Q6. File names containing ?. iOS's key → path record reads them correctly. Android cuts the key at the first ?. Decided: the record (6.2).

    • Q7. A root-absolute specifier already under the app root. iOS prefixes the app root again. Android uses it as is. Decided: Android (6.3).

    • Q8. A specifier that is empty after the query is stripped. Android returns unresolved early; iOS falls through. Decided: Android (6.3).

    • Q9. The import-map scope prefix. iOS trims the trailing / whenever the key has none. Android trims it only for a key written with no path (#2169). Decided: Android (6.3).

    • Q10. Virtual roots under the opt-in. Decided: file:///app/ (both platforms) and file:///android_asset/app/ (Android) stay virtualFileRoots in both modes (6.3). No such device path exists on either OS, and the shared tests use file:///app/… throughout. Retiring them is its own deprecation.

    • Q11. import.meta.filename. Neither runtime sets it today. Decided: set it only under the opt-in, as A10 lists (6.6). In legacy mode, iOS's dirname is not a real path, so a filename there would not be one either. Done in 6.6.

    • Q12. Ada in the core. Decided: keep ada behind platform::ParseUrl for step 6, and move it into the core with the URL follow-on. Both runtimes link their own ada today (iOS hides its symbols, #589). The move also retires the NormalizeHttpModuleUrl and HttpUrlOrigin platform functions.

    • Q13. A .js file reached through import (carried over from step 4). iOS wraps it in the CommonJS wrapper; Android compiles it as is. Still settled in 6.4, with the require(esm) interop rules. CompileFileEsModule keeps SourceWrap until then.

      Decided 2026-12-06: Node's detection (shouldRetryAsESM, containsModuleSyntax). A .js file is an ES module when it has module syntax, and otherwise CommonJS: a synthetic module whose default is module.exports, loaded by the runtime's require(). Any other extension (.cjs included) is CommonJS, never detected, as Node reads .cjs. Named exports: default and 'module.exports' only; a CommonJS lexer (merve, as in Node) is a later unit. Built in 6.6, with the format recorded in the code cache file so the hot path parses once; see "Built: 6.6".

    • Q14. When the off-thread consume did not run (carried over from step 4). Android loads the cache synchronously; iOS compiles without it. Decided: Android, since a consume is cheaper than a compile, once a measurement on a large .mjs confirms it. Settled in 6.4.

      Measured 2026-12-05. The branch is reached only for a job in consume mode (a fresh cache and at least 256 KiB), when V8 declined to start the consume task or LoadCodeCache failed on the pool. A smaller file with a fresh cache never becomes a job. The setup:

      • the 14.9 Mac Catalyst static libraries, --jitless (as on a device) on an M-series Mac;
      • a fresh isolate per sample, the median of 15;
      • prettier's self-contained plugin bundles;
      • the cache made after evaluation, as CodeCacheQueue makes it;
      • no cache rejected in any sample.

      Each cell is compile, then instantiate plus evaluate, in ms. "Sync" includes reading the cache file. "Pool" is the finalize after a consume that ran on another thread.

      File, flags Lazy, no cache Eager, no cache Sync consume Pool
      babel 311 KiB, Debug 2.36 + 0.74 5.88 + 0.64 0.28 + 0.52 0.00 + 0.56
      typescript 880 KiB, Debug 6.78 + 2.02 12.90 + 1.46 1.34 + 1.34 0.00 + 1.43
      flow 1.06 MiB, Debug 2.32 + 3.61 4.62 + 0.65 0.27 + 0.56 0.00 + 0.57
      babel, Release --no-lazy 5.91 + 0.66 5.93 + 0.64 0.71 + 0.55 0.00 + 0.54
      typescript, Release --no-lazy 12.68 + 1.47 12.67 + 1.46 1.90 + 1.36 0.03 + 1.40
      flow, Release --no-lazy 4.64 + 0.67 4.72 + 0.66 0.92 + 0.56 0.00 + 0.63

      Counting evaluation too, the sync consume is 3.3 to 7 times cheaper than iOS's compile at every size, so Android's branch stands. Absolute times won't carry over to a device; the ratios should.

    • Q15. External memory charge. iOS uses its gate-id charge; Android uses v8::ExternalMemoryAccounter. Decided: the plain accounter on both, after a check against #507's backoff (§4.8), in 6.4.

    • Q16. createRequire's JS signature. The headers disagree: (baseDir, pumping) vs (path). Decided: reconcile in 6.6.

      Done in 6.6. The native binding is the same on both platforms, createRequire(baseDir, pumping, deadlineSeconds, throwOnTimeout, pumpRunLoop), and so are both ns-module.js halves, which validate the arguments first. The (path) header was stale. The one difference is in native code JS cannot reach through ns-module.js: iOS throws on a bad deadline, Android ignores it.

    • Q17. Android-only ns:module debug calls. These are httpFetchDiagnostics, streamedCompileStats and forcePlatformHttpTransport. Decided: the first two become core and debug-only, and the third stays a platform row (6.6). Done in 6.6: Android adds forcePlatformHttpTransport to the binding after the core fills it.

    • Q18. Virtual roots in key canonicalization. Both runtimes key file:///app/x.mjs as /app/x.mjs today. That matches no module, so invalidateModules with an app file's legacy import.meta.url misses. The resolver, meanwhile, maps the same URL to the app root, which gives one file two spellings (invariant 16).

      Decided (a): canonicalization maps virtual roots onto the app root too. It is JS-visible: such an invalidation starts to hit.

    Built: 6.1.

    • Normalization and keys:

      • NormalizePath is Android's NormalizeDotSegments, except that a relative path keeps its leading ... Keys are always absolute.

      • CanonicalFilePath normalizes a path, then rewrites it from one of the appRootAliases (pairs of alias and spelling) onto the spelling appRoot uses.

      • CanonicalizeModuleKey routes keys by kind:

        • http(s): through NormalizeHttpModuleUrl and CanonicalizeNormalizedHttpUrlKey;
        • blob: and custom schemes: kept verbatim;
        • file: and app:, in any case and with or without // (the resolver's own scheme test): FileUrlToPath plus ModuleQuery;
        • a plain path: normalized and aliased, followed by the ModuleQuery of the text from its first ?, so the query is encoded and its fragment dropped as the resolver keys it. The query's slashes and dot segments are not path syntax.

        An absolute spelling of a file (a file: or app: URL, or a path already under the app root) canonicalizes to the key the resolver gives it; tests/ResolverTest.cpp checks every such spelling it resolves. A path spelling with a # and no ? keeps the #, since a key cannot tell a fragment from a file name.

        The file: branch maps virtual roots onto the app root (Q18).

    • Origins (ModuleOrigin):

      • A file under appRoot gets appRootOrigin + its path relative to the root.
      • Any other file gets file:// + its absolute path.
      • Under legacyOrigins, both are verbatim and import.meta is the origin.
      • Otherwise, both are percent-encoded (Q2), and import.meta.url, .filename and .dirname are the real path.

      The override values:

      • iOS: appRootOrigin = "file://" + (appRoot without BaseDir), which is file:///app for the usual layout, with legacyOrigins = true;
      • Android: appRootOrigin = "file://" + appRoot, with legacyOrigins = true.
    • Reading back:

      • OriginToPath is the inverse of ModuleOrigin. It is verbatim in legacy mode and ada in opt-in mode (Q1), and it always accepts app:///.
      • FileUrlToPath serves URLs from outside the runtime. It parses with ada, refuses what Q3 rejects, and percent-decodes. Then:
        • app: names the app root;
        • an appRootOrigin prefix and the virtualFileRoots map onto the app root;
        • anything else is the absolute path (A3).
    • Decided behaviour. The code follows the decisions for Q1–Q4 and Q18, and the host tests pin each one. Nothing reaches JS before the runtimes adopt it.

    • Legacy spellings. A scratch harness linked the core against each runtime's own ModuleUrl.cpp and ada. It compared ReportedModuleUrl, the path read back from each origin, and ModuleQuery over the same inputs. iOS showed no difference. Android showed one, Q4, which is decided in iOS's favour. The import.meta strings were checked against both callbacks by reading.

    • Host tests: tests/ModuleIdentityTest.cpp, against tests/FakeUrl.cpp, a hand-written parser. With -DNS_ADA_DIR=<a runtime's ada folder> they run against the real ada instead (tests/AdaUrl.cpp). That file is also the reference implementation of platform::ParseUrl. Built: 6.2.

    • Config snapshot (ns/loader/LoaderState.h):

      • platform::LoaderSnapshot() replaces platform::Loader().
      • InstallLoader(isolate, config) gives an isolate the snapshot it keeps for its life: platform::LoaderSnapshot() for a main runtime, CaptureLoaderConfig(parent), taken on the parent's thread, for a worker. It aborts on a null config and on a second call for the same isolate: LoaderConfigFor's callers hold the snapshot by reference.
      • LoaderConfigFor(isolate) is the per-isolate read. It aborts when InstallLoader never ran, rather than guessing at a config that may belong to another run.
      • CodeCacheEntryFor takes the config it applies, and FileCompile passes LoaderConfigFor.
    • Closing: loader::Quiesce(isolate) sets the flag and, for now, does nothing else; 6.4 adds the kills and the drain behind it. IsClosing(isolate) is the gate for work that would outlive the call. Under F1, the registry stays readable and writable through teardown; only new work checks the flag.

    • Registry (ns/loader/ModuleRegistry.h):

      • SetRegisteredModule(isolate, key, module, filePath) is the only write. The previous occupant leaves the index under that key, and loses its facades once no other key holds it. The path record follows the occupant: an empty filePath clears it.
      • Reads: FindRegisteredModule, IsModuleRegistered, RegisteredModuleCount, FindKeyForModule, ModuleFilePathForKey and GetLoadedModuleUrls.
      • RegistryKeyFor(isolate, keyOrUrl) is CanonicalizeModuleKey under the isolate's config, except that a registered file module's key is kept as it is (Q6), and a legacy origin that reads back verbatim as a registered key names it (Q1).
      • RemoveModuleFromRegistry(isolate, keyOrUrl) returns the key it removed.
      • InvalidateModules(isolate, urls, beforeRemove): each key once, beforeRemove(key) just before it goes.
      • FindRequireFacade and AddRequireFacade: the facade table moves now, because it has to empty as the registry does. Building a facade stays local until 6.6.
      • 6.3 moved the vocabulary into the loader state, and these functions lost their vocabulary parameter.
    • Still local, reached through the API above:

      • Superseding a file job on removal. The runtime's RemoveModuleFromRegistry wrapper marks the job for the key the core returns, until 6.4. Since 6.4, the core's removal and InvalidateModules do it.
      • Rejecting HTTP waiters and clearing modulesInFlight on invalidation. The runtime passes this as beforeRemove, together with the file-job step, until 6.5.
    • Host tests: tests/ModuleRegistryTest.cpp runs the V8-free table (src/loader/RegistryTable.h) with fake handles whose identity hashes collide. It pins the write path, facade release, the path record, ModuleFilePathForKey's fallback and GetLoadedModuleUrls' filter, and that only Find and FindFacade, which return a module, make a v8::Local: the writes and FindKey compare Global == Local and read a hash in a HandleScope of their own, so a large invalidation does not grow the caller's scope. Both use iOS's FileModulePath for a key with no record. Android's also drops a host from file://host/…. No registered key can differ: a file: key stays verbatim only when FileUrlToPath refuses it, and such a specifier resolves to nothing, so nothing registers under it. The V8 instantiation (src/loader/ModuleRegistry.cpp, LoaderState.cpp) is only syntax-checked, against iOS's and Android's V8 headers, until a runtime adopts it. Built: 6.3.

    • Vocabulary (ns/loader/ImportMap.h, ns/loader/LoaderState.h):

      • LoaderVocabulary (import map, canonicalization config and whether one was supplied, volatile patterns) lives in the core ModuleLoaderState.
      • CaptureLoaderVocabulary(parent) and InstallLoaderVocabulary(worker, copy) replace the runtimes' worker inheritance.
      • InstallImportMap, SetVolatilePatterns, SetCanonicalizationConfig, CanonicalizationConfigFor, IsVolatileModuleUrl and VocabularyFor are the per-isolate accessors. InstallImportMap fails with "the isolate is shutting down" once the state is gone.
    • Import maps:

      • ParseImportMap(isolate, json, out, error) is Android's parser over v8::JSON::Parse, with its error texts, in the isolate's current context, which must be entered. It reads own keys only and installs nothing. It reads an index-like key ("404") as the string it is in the JSON. Android's parser kept it a number and rejected it as "every key must be a string"; iOS accepted it.
      • AddImportMapEntry, ImportMapScopePrefix (Q9), FinishImportMap and LookupImportMap are V8-free. A map built by hand needs FinishImportMap before its first lookup, or its prefix keys never match.
      • A section keeps its exact keys in a hash map with transparent lookup and its '/'-terminated keys in a vector, longest first. A lookup allocates only on a hit, and scans only the prefix keys.
      • Scopes are sorted most specific first, and every matching scope is tried before "imports". As in the import-map spec, a scope matches a referrer equal to its key, or below a key that ends in /: the scope /data/app/pkg does not apply to /data/app/pkgs/x.mjs. Q9's path-less http(s) key still matches as a prefix.
    • Resolver (ns/loader/Resolver.h):

      • ResolveSpecifier(spec, {key, path}, vocabulary, config, lookup) is V8-free. ResolveModuleSpecifier(isolate, spec, referrerKey, lookup) reads the referrer's recorded file from the registry.
      • The order: builtins; the import map (unless kSkip), whose target may be a builtin (A9); blob: as kBlob (A9); an http(s) importer's browser rules; http(s) URLs; file: and app: URLs through FileUrlToPath (A3, A10, Q3, Q10); then paths: relative (lexical join, A1), ~/, root-absolute (Q7, then without /app), and bare names under appRoot, the last three with .. clamped at appRoot (see "App-root forms" under A). A specifier that is empty before its query or fragment resolves to nothing (Q8).
      • Q7's "already under appRoot" is a path-segment test: with appRoot /data/app, /data/appx/y.mjs is not under it and is looked up as /data/app/data/appx/y.mjs. Android's raw string prefix used it as is.
      • A file:///app/x specifier names <appRoot>/x only. iOS also tried <appRoot>/app/x, a leftover of reading every file:// URL as app-relative, which A3 retires. Decided 2026-12-05: it stays dropped.
      • An http(s) importer can now reach an app: URL as well as a file: one, because A10 says app:/// always resolves.
      • Probes: as written, .mjs, .js, /index.mjs, /index.js. A candidate that already ends in .mjs or .js is not probed a second time with that extension.
      • Platform: ParseModuleUrl (authority as written) and BlobStoreUrl. tests/AdaUrl.cpp is their reference implementation.
    • Allocations per resolve, under libc++ (both runtimes' standard library; its short-string buffer holds 22 bytes) with tracing off, against a realistic app root. tests/ResolverTest.cpp pins each count under libc++, the rows that parse a URL against ada only; the platform's Stat is not counted. Debug with ASan and Release agree:

      • a relative, bare, ~/ or root-absolute file hit: 2, the candidate, which becomes path, and key;
      • each probe past the first: 1 more in total, since every extension and index probe shares one buffer;
      • a miss: 2, the probe buffer and the last candidate, kept as attempted;
      • a ~/ hit on its second candidate (<appRoot>/app/…): 4. The second candidate is built only once the first has missed;
      • an import-map hit: the target string as well, when it is longer than the short-string buffer;
      • a specifier longer than the buffer: 1 more, for ModuleResolution::specifier; a query longer than it, 1 more for query. ModuleQuery returns the text as written when the parser would copy it unchanged, and parses only when a byte needs encoding or stripping;
      • a name that starts with h or b: nothing more. The http(s) and blob: tests read the whole scheme, as the parser does, before anything is copied or parsed;
      • a path with dot segments: NormalizePath's segment list, which grows as it fills, and its output (11 in all for ./lib/../lib/./../lib/util.mjs);
      • an http(s) URL: 3, with the host tests' stand-in NormalizeHttpModuleUrl; a relative specifier from an http(s) importer: 3, most of them in the URL parser;
      • a file: URL: 7, a file:///app/… URL: 5, an app:///… URL: 3, most of them in FileUrlToPath's parse and decode;
      • a builtin: none.
    • Host tests: tests/ImportMapTest.cpp pins entry validation and its errors, scope prefixes and lookup precedence. tests/ResolverTest.cpp pins every branch above against fake files, including the attempted and blocked texts. ParseImportMap is only syntax-checked, like the other V8 files.

    • Deviations from the plan: IsBuiltinModuleSpecifier is in the core, not the platform. The import map's JSON errors now come from V8 on iOS too (the plan's v8::JSON::Parse), so iOS's detail text changes, and a lone surrogate in a key or target is rejected as "must be a string", as on Android. ParseModuleUrl's authority-as-written branch is ported from iOS but no host test reaches it. Built: 6.4.

    • Liveness (ns/RuntimeLiveness.h, a token per runtime):

      • loader::LivenessFor(isolate) creates it the first time a walk needs it and the platform has a loop for the isolate (null until then). It holds a weak_ptr<Loop> and the isolate pointer. The pointer is used by a task the token ran, on the isolate's thread, and by a pool job inside a section (StartConsumingCodeCacheOnBackground finds the isolate's heap through it), where the isolate cannot be disposed. NotifyAppBackgrounded(token) reads it off the thread only to hand it to its task.
      • The token keeps the loop it was created with. LivenessFor aborts, with a message, when the isolate's loop is no longer that loop: work posted through the token would go to a loop nobody runs.
      • Post(task) posts a nestable V8 task while the token is open, and the task re-checks the token before it runs. It returns false when the token is closed or the loop is gone or stopped; for the last, Loop::PostV8Task reports the drop. The weak loop is locked and released inside a section, so no other thread ever drops the last loop reference.
      • Enter/Leave bracket background use of isolate-owned state. CloseAndDrain(service) closes the token and waits out the sections, running service first and between 2 ms waits.
      • The token merges the plan's two pieces: the alive flag and the stream gate's in-flight count. A plain flag cannot stop a thread that checked it a moment before teardown, and that thread could then become the loop's last owner; the count can. It replaces load->dead, StreamCompileGate and its identity check, and every LookupEventLoop(isolate) on these paths.
      • platform::IsRuntimeAlive is no longer declared. MainContext stays.
      • NotifyAppBackgrounded(const std::shared_ptr<RuntimeLiveness>&) is the token overload (a shared_ptr, since Post needs shared_from_this). The isolate overload stays for callers that keep the runtime alive across the call: iOS pins the isolate gate, and Android calls it on the runtime's own thread. Both runtimes call that overload at 3bcf603, so neither has to change.
    • Compile pool (src/loader/CompilePool.h): one per process, at most clamp(cpus - 1, 1, 4) threads. Threads start lazily through StartThread ("ns-esm-compile", kUserInitiated, a stack of BackgroundCompileStackBytes(config.v8Flags)), and each job runs through platform::RunJob, which on iOS gives it an autorelease pool. Jobs carry an owner, the token. Discard(owner) calls that owner's queued jobs with run == false, so a teardown never waits behind another isolate's compile. iOS's pool used a hard-coded 2 MiB stack. Known and left as is: the queue is FIFO across isolates, so one isolate's burst of file jobs delays another's.

    • Graph walk (ns/loader/GraphLoad.h):

      • ModuleGraphRoot is iOS's, plus FromResolution. A FilePath root's path is canonicalized (CanonicalFilePath) when the walk starts, and is also its key. It is then read, cached and reported under the resolver's spelling, as iOS's dispatch and its CompileFileEsModule wrapper did.
      • StartModuleGraphLoad, SyncModuleLoadScope (parking), RunModuleGraphLoadPumped, HasPendingGraphWork (process-wide, as both runtimes have it) and LoadHttpModuleForUrl. HasPendingGraphWork counts walks from their start until they complete or Quiesce kills them; fetch threads that still hold a finished walk no longer count.
      • GraphLoadCompletion runs at most once: never for a walk started after Quiesce, and not when the runtime is torn down first. It carries the exception a JSON root failed with (6.5).
      • FinalizeFinishedFileModule(isolate, context, key) is the resolver's step for a finished job until 6.5 moves the resolver in.
      • Edges resolve through ResolveModuleSpecifier. Thresholds and routing are unchanged: 32 KiB to stream or to make a file job, 256 KiB with a fresh cache, and file jobs for .mjs only.
      • Walks and jobs own no V8 state. A walk's context lives in GraphLoaderState::walkContexts, keyed by its start sequence, so a walk's last reference may drop on a transport or pool thread. Both runtimes kept a Global<Context> in the walk and relied on reset ordering.
      • The start stamp is steady_clock (iOS used wall-clock time).
      • Eager streaming follows V8FlagsDisableLazyCompile(config.v8Flags). On iOS that reproduces IsDebug ? lazy : eager, because iOS adds --no-lazy outside Debug.
      • A file job's script origin is ModuleOrigin(path, query). Both runtimes used ReportedModuleUrl(path + query), and the two agree unless the file name contains '?'.
      • An http(s) edge in an isolate without a loop is not fetched by the walk. The resolver fetches it synchronously and logs the miss. On Android, such a walk instead never completed.
      • RunModuleGraphLoadPumped pumps at least once, so termination outranks a walk that completed inline (iOS). Android skipped the pump, and returned true, when the walk completed inline. A walk started on a closing loader returns false at once. It pumps the token's loop, the one the walk's completions go to.
      • Off the loop's home thread (multithreaded JavaScript) RunModuleGraphLoadPumped never pumps, since its caller holds the Locker the loop needs: it returns whether the walk completed inside the call, and false when termination was requested (ns/loader/GraphLoad.h).
      • A file job that lands while platform::MainContext is empty still continues its waiters, each in its own walk context. Only the finalize waits: the result stays with the job, for the resolver or the next walk that reaches the key.
    • The walk's public functions open their own handle scopes and escape what they return. Only the isolate's thread reads LoaderConfigFor or the vocabulary. The pool and transport paths work on copies taken at dispatch: the CodeCacheEntry, the path and the pool's stack size.

    • Settles:

      • Android's drain scopes;
      • superseded on kill and on the core's removals (RemoveModuleFromRegistry and InvalidateModules);
      • CanWaitForFileJobs (a loop that is on its home thread);
      • Q14: a synchronous LoadCodeCache consume at finalize, after the measurement above;
      • Q15: the plain v8::ExternalMemoryAccounter, increased under a handle and decreased in Unaccount. On the check against #507's backoff, see below.
    • Q15 and the #507 backoff, checked by reasoning and Android's shipped use of the accounter, not measured. The backoff comes from charges that a finalizer drops after V8 has recomputed its limits within the GC pause, so dead bytes still count toward the next limit. An external string's resource is different: V8 releases it while it processes its external-string table inside the collection, through Unaccount, not a finalizer. Module sources also live as long as their module, and only an invalidated module's source dies at all. Neither part of the backoff applies.

    • Q13 stays open. 6.4 did not force a choice. A .js file never becomes a file job, and the inline compile takes its wrap from the platform::FileModuleSourceWrap(path) up-call (ns/loader/Transitional.h). iOS returns its CommonJS wrapper there, and Android returns none. (Settled in 6.6: CompileFileModule detects a .js file's format, any other extension is CommonJS, and the up-call is deleted.)

    • JSON modules reached by an http(s) edge or LoadHttpModuleForUrl compile through the platform::CompileJsonModule up-call until 6.5. The runtimes' versions instantiate with ResolveModuleCallback, which is 6.5's.

    • Threads and teardown, per handoff. Nothing a background thread holds owns V8 state. V8 tasks and StreamedSources live in GraphLoaderState, which only the isolate's thread creates, finalizes and destroys.

      Handoff Holds Cancelled by
      Fetch completion, transport thread to isolate thread walk, ticket, token, the fetched body (ModuleFetchResult) refused once the token closes; dropped by the re-check if already queued
      Large HTTP body, transport thread to pool a token section; the ticket's raw stream and task pointers Discard if queued; Quiesce waits if running; the job skips its work once the token is closed
      Pool completion back to the isolate thread job or ticket, posted from inside the section refused, or dropped by the re-check
      File job, isolate thread to pool a token section; job->compile raw as for the large HTTP body
      Parked walk, released when the outermost SyncModuleLoadScope closes the walk's continuation posted through the token; the task takes the Locker
      File job's notify, pool to a synchronous wait shared_ptr<FileJobSignal> (a counter and a condition variable) nothing: shared ownership keeps it alive on both sides
      NotifyAppBackgrounded(token), any thread to isolate thread the isolate pointer, read only by the task refused, or dropped by the re-check
      onComplete of a walk, run on the isolate thread whatever the caller captured destroyed unrun, on any thread, when the walk dies with the runtime; never run for a walk started after Quiesce

      So an onComplete owns no V8 state. All four runtime callers comply: the import() ones keep their resolvers in loader state by id or key and capture strings, and the pumped wait captures a shared_ptr<bool>.

      loader::Quiesce runs on the isolate's thread, under its Locker, before the loop shuts down:

      1. It marks the walks killed, resets their contexts and root exceptions, supersedes the jobs still in fileJobs and drops their waiters, and clears the parked walks. A job superseded earlier is no longer in fileJobs and keeps its waiters until its completion is dropped; they are walks, which hold no V8 state.
      2. It closes the token and drains under SuppressMicrotaskExecutionScope and DisallowJavascriptExecutionScope. The drain's service discards this token's queued pool jobs and runs RunNestableV8Tasks, where a background compile's GC request waits. When the loop is gone or stopped, no V8 task runs: the service then logs once, runs LowMemoryNotification at most every 100 ms (any full GC on the isolate's thread releases a waiting background compile), and aborts with a message after 10 s.
      3. It destroys the streamed compiles and file-job compiles that will never be finalized.

      Step 1 precedes step 2, so a task the token refuses never holds the last reference to anything with a V8 handle.

    • Host tests: tests/CompilePoolTest.cpp runs the token's sections and drain, the pool's run-once and discard rules, the teardown pattern (a drain does not wait for another owner's running job), and FileJobSignal. It also runs a concurrent close-and-drain stress (5,000 rounds under a sanitizer, 20,000 without; an Enter that checks the flag before taking the mutex showed 100 to 300 violations in 2,000 rounds), a post that lands after the drain's first Discard, and a job taken off the queue but not yet run when Discard runs. It runs clean under ASan/UBSan (all three lanes) and under TSan.

    • V8-linked tests (opt-in, never in CI): configured with NS_V8_LIB_DIR and NS_V8_INCLUDE_DIR, the build links the whole core against a V8 build and runs tests/v8. CMakeLists.txt documents a configure against iOS's Mac Catalyst libraries. LoaderHostTest runs synchronous and asynchronous file and HTTP graphs, streamed compiles, parking, supersession, the resolver racing the pool, termination during a pump and while parked, a walk without a main context, a replaced loop and a closed state bag (in a child process), a load off the home thread, and concurrent teardown of runtimes mid-walk on several threads. LoaderHostTestShutdownFirst stops the loop before loader::Quiesce, under a 9 MB heap. ModuleImportTest is 6.5's.

    • Adoption (on top of 6.2 and 6.3), current at the 6.5 tip. When 6.5 is adopted in the same change, read its list too: some items here fall away (marked "until 6.5").

      • Platform functions to implement:
        • platform::FileModuleSourceWrap (iOS: today's ModuleSourceWrap; Android: {}). 6.6 deletes it; see its adoption list.
        • platform::CompileJsonModule (today's CompileJsonTextAsEsModule), until 6.5, which removes it.
      • Interfaces that change:
        • Loop::PostV8Task returns bool: false when the loop has stopped and dropped the task. Both runtimes' EventLoop::PostV8Task and the NativeScriptPlatform forwarding change with it.
        • GraphLoadCompletion is void(bool ok, const std::string& errorMessage, v8::Local<v8::Value> exception, v8::Local<v8::Context> context). exception is set only for a JSON root that did not parse. Any runtime caller of StartModuleGraphLoad adds the parameter.
      • Delete:
        • StreamCompilePool, StreamCompileGate, StreamFeed, FeedSourceStream and BodySourceStream;
        • StreamTicket, StreamedModuleCompile, FileModuleCompile, FileModuleJob, FileJobSignal and AsyncGraphLoad;
        • OwnedAsciiSource;
        • both walks, ModuleGraphRoot, ResolutionForRoot, SyncModuleLoadScope and RunModuleGraphLoadPumped;
        • LoadHttpModuleForUrl and HasPendingAsyncModuleGraphWork;
        • QuiesceModuleLoadsForIsolate and NoteAppliedV8Flags;
        • the runtime's fileJobs step in the RemoveModuleFromRegistry wrapper and in beforeRemove;
        • the platform::IsRuntimeAlive definitions;
        • the matching ModuleLoaderState fields.
      • Call sites:
        • Call loader::Quiesce(isolate) where QuiesceModuleLoadsForIsolate was called.
        • Boot backstops call loader::HasPendingGraphWork(): Android's Runtime.cpp and iOS's runMainApplication.
        • The resolvers' "finalize a finished job" block becomes FinalizeFinishedFileModule, until 6.5 replaces the resolvers.
        • Android's streamedCompileStats reads GetStreamedCompileStats().
        • Android's import() file path passes ModuleGraphRoot::FromResolution(resolution) instead of the key string, and its HTTP path passes ModuleGraphRoot::HttpUrl(url), until 6.5 replaces import().
      • Ordering, which the core now checks:
        • The loader's token keeps the loop it finds on first use, and LivenessFor aborts the process when the isolate's loop has been replaced since. Both runtimes replace a stopped loop in RefreshEventLoop right after Isolate::New; nothing may call a loader function that walks or posts before that, and neither runtime does today.
        • Every teardown path calls loader::Quiesce before the loop shuts down and before the state bag closes: the main runtime, workers, and failed or aborted initializations. A debug build aborts when the bag closes for an isolate whose loader was installed and never quiesced.
        • loader::Quiesce after the loop stopped is a backstop, not a supported order: it logs once, collects garbage on the calling thread for the background compiles waiting on a GC, and aborts the process after 10 s.
      • Optional: hold the token from LivenessFor and call the token overload NotifyAppBackgrounded(const std::shared_ptr<RuntimeLiveness>&), retiring iOS's gate pin there. Neither runtime calls it yet.
      • Behavior that may move expectations:
        • iOS's eager-compile choice now comes from the flag string (the same in practice), and iOS's pool threads follow --stack-size instead of 2 MiB.
        • HasPendingGraphWork turns false as soon as the walks complete or are killed, so the boot backstops may stop pumping sooner.
        • RunModuleGraphLoadPumped called off the loop's home thread (multithreaded JavaScript) never pumps: it returns whether the walk completed inside the call.

    Built: 6.5.

    • Core API (ns/loader/ModuleImport.h): ResolveModuleCallback and ImportModuleDynamicallyCallback, which each runtime installs or passes to InstantiateModule. Both resolve once, through ResolveModuleSpecifier, and load what the resolution names. Behind them, in src/loader/ModuleImport.cpp: the http(s) and blob: waiters, the top-level-await continuations, the settling of a file import() (Android's SettleDynamicImport) and FinishHttpImport. The waiters, the file imports' resolvers (by id, so a walk's onComplete holds no V8 state) and the JSON values live in ImportState, in the core ModuleLoaderState.

    • Platform: a new platform::BuiltinModule(context, specifier) (ns/RuntimeAccess.h) returns the builtin's module, already evaluated, or empty with an exception pending ("No such built-in module: X" for an unknown name). Both runtimes have it as NsBuiltinModules::GetModule plus NotFoundMessage. platform::CompileJsonModule is gone from ns/loader/Transitional.h.

    • Departures from the plan:

      • BuiltinModule is a new up-call. The plan had none, but the builtin registry is per runtime until the builtins move (follow-on 3).
      • No blob-store platform lookup. Both runtimes' store is JS beside URL.createObjectURL, and both read it as URL.InternalAccessor.getData(url).blob.text(), so the core reads the same accessor.
      • InvalidateModules(isolate, context, urls) takes the context and drops beforeRemove. It rejects the import()s still waiting on a key it removes with "Module invalidated during dev reload: ", which is what both runtimes' beforeRemove did.
      • Quiesce drops all import state. An import() still pending then stays pending, as before. A new import() after it returns a promise that never settles and runs nothing (decided below; it aborted the process before, §8).
    • Settles:

      • A9: a builtin is matched after the single resolution, for import() too (Android matched the raw specifier before it). Any kBlob resolution takes the blob path, as on iOS; Android took it only for the blob:nativescript/ prefix, and rejected any other blob: URL with "Cannot find module '' (tried )". Such a URL now loads when the store has it, and otherwise rejects with "Blob not found: ".
      • Invariant 19: Android's reasons, listed below.
      • The Then(...) results are ignored, as FromMaybe does; no ToLocalChecked. The continuations keep their state in the function's data array, not in a heap block a never-settling promise would leak.
      • The import() referrer key comes from OriginToPath (Android's ReferrerKeyFromOrigin), and falls back to RegistryKeyFor.
      • A .json file is read through platform::ReadFile; a failed read throws Error "Cannot read module ".
    • Rejection reasons. <stage>: <url or key> — <V8 message> is Android's BuildModuleFailureReason; the message comes from TryCatch::Message(), so it starts with "Uncaught ". A module that throws while it evaluates rejects V8's evaluation promise, so its exception reaches JS as it is; the "Evaluation failed …" stages are left for an Evaluate that returns empty, which only termination does.

      Path Failure Reason
      any NUL in the specifier Error Cannot resolve module specifier "<spec, \u0000 escaped>": a module specifier must not contain U+0000
      any unresolved, or blocked by a rule Error from UnresolvedModuleMessage; import('') gives "Cannot find module '' (tried )"
      builtin unknown name BuiltinModule's exception
      file load (read, compile, JSON parse) the exception itself
      file link Error "Failed to instantiate module: — "
      file evaluation, or its top-level await the exception itself (V8 rejects the evaluation promise)
      http(s) fetch or compile in the walk Error with the walk's message, as in 6.4; a JSON root that does not parse rejects with its SyntaxError
      http(s) load after the walk the exception itself, or "HTTP fetch/compile failed: "
      http(s) link Error "Instantiation failed (http-loader): — " ("(http-cache hit)" on a registered module)
      http(s) evaluation, or its top-level await the exception itself
      blob: lookup Error "URL constructor not available", "URL.InternalAccessor not available", "URL.InternalAccessor.getData not available", "Blob not found: ", "Invalid blob data", "Blob object not found", "Blob.text() not available", "Blob.text() threw[: ]", "Blob.text() did not return a thenable", "Blob text is not a string"
      blob: compile Error "Failed to compile blob module: (line L:C)"
      blob: link Error "Failed to instantiate blob module: — "
      blob: evaluation, or its top-level await the exception itself
      http(s), blob: waiting on an evaluation that ended unevaluated Error "Module did not finish evaluation: "
      any, import() import attributes, with enforceImportAttributes TypeError Module "<url>" needs an import attribute of "type: json", Module "<url>" is not of type "json", or Import attribute "<key>" with value "<v>" is not supported in <url> (Node's texts)
      any, static the same the importer's link fails: "Failed to instantiate module: — TypeError: …" under a file import()

      Rows that change, from grepping both test trees at bae0c78e (iOS) and 1ee254f22 (Android) for every reason above and the texts they replace: one iOS row. import('') from a module rejected with "Module resolution failed for dynamic import: " and now gets Android's "Cannot find module '' (tried )" (the ["esm", "", …] row of DynamicImportTests.js). No test checks a JSON failure text or a blob failure other than "Blob not found", and every .json fixture and JSON test-server response in both trees is strict JSON.

    • JSON modules (src/loader/JsonModule.cpp): a synthetic module whose only export, default, is JSON.parse of the text, BOM dropped. The value is parsed when the module is created, and kept in ImportState::pendingJson until the evaluation steps set the export. Text that is not JSON throws SyntaxError ": <V8's JSON.parse message>", e.g. "app:///x.json: Expected double-quoted property name in JSON at position 8 (line 1 column 9)". Every path that loads JSON goes through it: a file (ReadFile), and an http(s) response served as JSON, in the walk and in LoadHttpModuleForUrl.

      Differences JS can see, compared with both runtimes' `"export default "

      • text + ";"`:
      Text Before Now
      JS that is not JSON: trailing commas, comments, unquoted keys, single quotes, hex, .5, Infinity, undefined, \x41, 1+1, a raw tab in a string, a vertical tab or NBSP between tokens loaded SyntaxError
      Code after the value, {"a":1};globalThis.x=1 loaded, and ran the code SyntaxError; nothing runs
      {"__proto__": {…}} set the object's prototype an own __proto__ property
      __proto__ twice SyntaxError (compile) loaded, last one wins
      Empty or whitespace only SyntaxError (compile) SyntaxError "Unexpected end of JSON input"
      Other invalid text (leading zero, two values, a line break in a string) SyntaxError "Failed to compile JSON module" SyntaxError with V8's JSON message
      Nesting deep enough to exhaust the compiler (3000 levels and up) RangeError, reported as "Failed to compile JSON module" loads
      BOM, U+2028 in a string, -0, a lone surrogate escape, null, a trailing newline same same

      Timing. The parse happens where the compile did, when the module is loaded and before it is linked, so an invalid file fails the same step it failed before. The old module was also instantiated and evaluated right after its compile; the synthetic module is linked and evaluated with its importer's graph. Its evaluation only sets the export, so the order is invisible except through code after the value, which no longer runs. Settling, measured in a V8 harness against the old module registered under the same key:

      • a file import(): 2 microtask turns, before and now;
      • a registered http(s) module: 1 turn, before and now;
      • the first import() whose root is an http(s) JSON module: one turn later than before, inside the same checkpoint. The old module was already evaluated, so its waiters resolved at once; now the import waits on the evaluation's promise, as it does for any module (by reading the code; the harness cannot count across the fetch).

      Which paths hand the SyntaxError object to JS:

      Where the bad JSON is What JS gets
      import() of the file the SyntaxError
      a static import, under a file import() Error "Failed to instantiate module: — SyntaxError: : …"
      import() of the http(s) URL the SyntaxError (decided below; the walk hands its JSON root's exception to onComplete)
      a static import, under an http(s) import() Error "Instantiation failed (http-loader): — Uncaught SyntaxError: : …"
    • Import attributes. A module is JSON when its path ends in .json or its response is served as JSON, as in both runtimes today, never because of an attribute. Static imports and import() then check the type attribute against it (ResolveModuleCallback per edge, so registry hits are checked too):

      • a JSON module imported without type: "json";
      • type: "json" on a module that is not JSON (JavaScript, a builtin, a blob);
      • a type other than "json", "javascript" included, as in Node and browsers;
      • any key other than type, reported before the type, as Node does. With LoaderConfig::enforceImportAttributes (default false) the import rejects with Node's TypeError before anything is linked or evaluated, so import('./m.mjs', { with: { type: 'json' } }) never runs m.mjs. File, builtin and blob imports are refused before the load starts, and an http(s) import with an unsupported key or type before its fetch. An http(s) module's type is known only after the fetch, so each waiter is checked against its own attributes once the module has loaded; when every waiter is refused, nothing links or evaluates. With enforcement off, the import goes on, and a debug build (LoaderConfig.isDebug) logs each mismatch once per module URL, naming the specifier and the importer: NativeScript: Module "app:///x.json" needs an import attribute of "type: json" ("./x.json" imported from app:///main.mjs). Import attributes will be enforced in a future release. V8 refuses a non-string value itself. assert { … } in a static import is a SyntaxError ("Unexpected identifier 'assert'"), and V8 ignores an assert key in import()'s options, so that import has no attributes.
    • Decided 2026-12-05:

      • JSON errors: the walk passes its failing JSON root's exception through onComplete, so import() of an http(s) JSON URL rejects with the SyntaxError itself, as a local file does. Failures deeper in the graph keep Android's wrapped messages.
      • import() after loader::Quiesce returns a promise that never settles, as the imports in flight at teardown do. It runs no JS.
      • Import attributes: warn now, enforce later, as above. The default flips to enforcement once tooling and plugins write the attributes, like the appSchemeOrigins rollout. assert { … } stays a SyntaxError, as V8 decides.
      • Keys other than type: warned in debug builds once per module, and rejected under enforceImportAttributes with Node's Import attribute "<key>" with value "<value>" is not supported in <url>, as for type.
      • An http(s) JavaScript root that does not compile keeps its wrapped rejection, Error "HTTP import compile failed: — …": V8's SyntaxError does not name the module, and iOS's HttpEsmLoaderTests checks the message for the name. Only JSON roots reject with the exception itself.
      • type: "javascript" is unsupported, as in Node and browsers: a warning by default, a rejection under enforcement.
      • A module whose static import breaks the attribute rule keeps the wrapped outer rejection, "Failed to instantiate module: — TypeError: …", as other failures deeper in the graph do. A direct import() rejects with the TypeError itself.
      • After loader::Quiesce, ResolveModuleCallback throws Error "The module loader is shutting down", so an instantiate a runtime runs then fails cleanly instead of returning empty with no exception pending.
    • import '' in a static import throws Error "Cannot find module '' (tried )", the message import('') rejects with. Both runtimes failed the link with no exception pending. Under a file import() the reason is "Failed to instantiate module: — Error: Cannot find module '' (tried )".

    • import() of a module being evaluated. V8 CHECKs (Module::Evaluate on a kEvaluating module) when an import() names a module whose evaluation is on the stack: a module that imports itself, or B, statically imported by A, calling import('./A.mjs'). Both runtimes crashed this way inside the import() call (iOS d888aad5, Android 83a72561f and a12106397), and so did the core through 6.5.

      • Such an import is parked and settles from a microtask after the evaluation returns, as in Node: with the namespace once the evaluation has finished, following its top-level await, or with its error. Awaiting it inside that evaluation never settles (A awaits B, which awaits A), as in Node.
      • When a microtask checkpoint nested in the evaluation runs it, the module is still evaluating, and the retry goes to a 4 ms delayed loop task, never to another microtask, so the checkpoint cannot spin. Inside a kPlatformWork pump within that evaluation it polls at that interval until the evaluation returns.
      • Decided 2026-12-06: an http(s) import() of a module a static import is evaluating waits the same way. Both runtimes resolved it with the namespace at once ("avoiding re-entrant Evaluate"), and so did the core: reading an export could hit its temporal dead zone, and a module that went on to throw, or was still in its top-level await, was handed over as evaluated.
      • JS-visible, both runtimes: a crash becomes a settlement after the evaluation, for a file import(); an immediate namespace becomes one after the evaluation, for an http(s) import().
      • Known difference from Node, decided 2026-12-06 to stay: an import(), made during an evaluation, of a module not yet loaded whose static graph reaches the module being evaluated. reach-a.mjs is import './reach-b.mjs'; export const a = 'A';, reach-b.mjs is globalThis.reach = import('./reach-c.mjs');, and reach-c.mjs is import { a } from './reach-a.mjs'; export const seen = a;. Node gives seen === 'A'. When the walk for reach-c.mjs completes synchronously (a small file), the core evaluates it inside the import() call and it rejects with ReferenceError "Cannot access 'a' before initialization"; when it completes through a background job (an .mjs file of 32 KiB or more, 256 KiB with a fresh code cache), it evaluates after A and gives 'A'. Both runtimes evaluate inside the call too, so this is no regression. Matching Node would defer the evaluation of every import() made during an evaluation, which changes the timing of all of them.
      • Open:
        • A blob import() of a blob module that something other than an import() is evaluating queues a waiter that nothing settles.
        • LinkAndEvaluateForWaiters returns, leaving its waiters pending, when the module is being evaluated by someone else. That needs an http(s) walk to complete inside a pump nested in that module's evaluation.
    • Verification: ModuleImport.cpp has no V8-free part. It is syntax-checked against iOS's and NDK 27's V8 headers, and tests/v8/ModuleImportTest.cpp (the opt-in V8-linked lane) asserts the rows above under the default, iOS and Android configurations: JSON (file and http(s), static and dynamic, BOM, __proto__, the injection text), file, http(s) and blob import() with link, evaluation and top-level-await failures, coalesced imports, builtins, NUL and empty specifiers, invalidation of an import in flight, import() of a module being evaluated (itself, back through a cycle, throwing, with top-level await, under a nested checkpoint, awaited, and an http(s) module a file's static import is evaluating), import() and a runtime's own instantiate after Quiesce, and every attribute case in both modes (JSON without the attribute, type: "json" on JavaScript and builtins, unsupported types including "javascript", unknown keys, static and dynamic, file and http(s)), with the warnings logged once each and none in a release build.

    • Adoption (on top of 6.4), current at the 6.5 tip:

      • Implement platform::BuiltinModule: NsBuiltinModules::GetModule, throwing NotFoundMessage when it returns empty with no exception pending.
      • Config: LoaderConfig::enforceImportAttributes is new and defaults to false. A platform may map an app config flag to it; nothing has to set it. The attribute warnings follow LoaderConfig::isDebug.
      • Install the core's ImportModuleDynamicallyCallback, and pass the core's ResolveModuleCallback wherever a runtime instantiates.
        • A runtime that keeps a wrapper around import() must not return an empty MaybeLocal when its loader state is closing or gone, as both runtimes' callbacks do today when ModuleLoaderStateFor is null: call the core's callback, which then returns a promise that never settles. An empty result with no exception pending aborts V8 (§8).
        • After loader::Quiesce, ResolveModuleCallback throws Error "The module loader is shutting down", so an instantiate a runtime runs then fails with that exception pending. Run it under a TryCatch, as for any other link failure.
      • The dev invalidateModules binding calls the core's InvalidateModules(isolate, context, urls).
      • Delete:
        • both callbacks and everything only they use: the waiters, FinishHttpDynamicImport, SettleDynamicImport / SettleFileDynamicImport, BuildModuleFailureReason, AdoptThenable, the blob path, LoadResolvedFileModule;
        • DynamicImportReferrerKey and ReferrerKeyFromOrigin;
        • the JSON code (CompileJsonTextAsEsModule) and the platform::CompileJsonModule definitions;
        • the runtimes' InvalidateModules wrappers and RejectAndClearInvalidatedModuleState;
        • the matching ModuleLoaderState fields.
      • Adopted with 6.4 in one change, these 6.4 items fall away: platform::CompileJsonModule, the resolvers' FinalizeFinishedFileModule block (unless something else in the runtime finalizes file jobs), and Android's ModuleGraphRoot arguments in import().
      • Expectations that move:
        • the iOS import('') row above;
        • any JSON file or response that is not strict JSON (none in either test tree);
        • import() of an http(s) JSON URL that does not parse rejects with the SyntaxError instead of an Error wrapping its text; a search of both test trees for "failed to compile" found no test of that text;
        • debug builds log a warning once per module for each attribute mismatch: a JSON module imported without with { type: "json" }, type: "json" on a module that is not JSON, any other type ("javascript" included), and any key other than type. Both runtimes' HTTP loader tests import data.json without the attribute: they log it and, with the default, still pass. No import in either test tree passes attributes (with or assert, static or in import()'s options), checked at iOS d888aad5 with the shared tests at 2cb9c23 and Android a12106397.

    Built: 6.6.

    • Core API:

      • ns/loader/ModuleImport.h: InitializeImportMetaObject, on ImportMetaFor, and InstallHostCallbacks(isolate), which installs it with ImportModuleDynamicallyCallback. ResolveModuleCallback is not an isolate callback and is still passed to every InstantiateModule.
      • ns/loader/RequireEsm.h: GetOrCreateRequireFacade(context, target, label), Node's facade source (re-exports and __esModule = true), returned instantiated and evaluated, one per target. It throws JsError or Terminated; the runtime's require() catches them.
      • ns/loader/NsModuleBinding.h: BuildNsModuleBinding(context, binding, diagnostics). configureLoader, invalidateModules, getLoadedModuleUrls, setHttpCacheEnabled, clearHttpCache, then createRequire from the platform. With diagnostics: canonicalizeHttpUrlKey, remoteUrlMatchesAllowlist, httpFetchDiagnostics and streamedCompileStats. Every member runs inside Android's barrier: JsError, Terminated, any std::exception ("C++ exception: ") and anything else become a JS exception. diagnostics is a parameter, not LoaderConfig::isDebug, which must never change what JS observes.
      • ns/loader/FileCompile.h: CompileFileModule(isolate, context, path, origin), the file module import loads, by extension: .mjs an ES module, .js detected (Q13 below), anything else CommonJS. The walk and both import callbacks call it. CompileFileEsModule lost its SourceWrap parameter.
      • The code cache's module format (§4.3).
    • Platform (ns/loader/Transitional.h, all deleted by step 8):

      • InstallCreateRequireBinding(context, binding), as before.
      • RequireFileForImport(context, path), new: module.exports of a CommonJS file through the runtime's require() and its cache. Empty with an exception pending on failure; never throws C++.
      • FileModuleSourceWrap is deleted.
    • Departures from the plan:

      • No EvaluateModuleGraph(…, kSyncStrict) up-call. The facade only re-exports an evaluated target, so the core evaluates it: a rejected evaluation is marked handled and its value thrown; a pending one (a target that has not finished evaluating, which the header rules out) throws "The require() facade for did not evaluate synchronously". After loader::Quiesce it throws "The module loader is shutting down".
      • RequireFileForImport is a new up-call, for Q13.
      • A synthetic module other than JSON that throws while it evaluates (the CommonJS leaf) rejects import() with the thrown value, as an ES module does, not with "Evaluation failed …".
    • Settles:

      • A8: one import.meta callback, on ImportMetaFor, which both runtimes already called.
      • Q11: filename under the opt-in only, from ImportMetaFor.
      • Q13: below.
      • Q16 and Q17: in their entries above.
      • appSchemeOrigins: see "Rollout" in §7 A. The core has nothing to wire; each runtime skips its override when the flag is set (adoption below).
    • Q13, as built. CompileFileModule on a .js file:

      1. It Stats the file. A format remembered for that Stat (size and freshness token) skips detection: first the isolate's memo (ModuleLoaderState::detectedFormats), then the code cache header (FreshModuleFormat).
      2. Otherwise it reads the file and compiles it with ScriptCompiler::CompileFunction and the CommonJS parameters (exports, require, module, __filename, __dirname). Success means CommonJS. A failure is ES module syntax when V8's message is one of Node's three ESM-only messages ("Cannot use import statement outside a module", "Unexpected token 'export'", "Cannot use 'import.meta' outside a module"). When it is one of Node's maybe-ESM messages (the five "Identifier '' has already been declared", the top-level await message, "missing ) after argument list", "SyntaxError: Unexpected"), it compiles as a module, as Node's ShouldRetryAsESM does, and success means ES module; that module is the one returned. Anything else is CommonJS, so the syntax error surfaces when require() compiles it.
      3. An ES module compiles with its code cache as .mjs does, and queues a cache when there was none. A CommonJS file becomes a synthetic module with two exports, default and 'module.exports' (as in Node 24), both RequireFileForImport's value when it evaluates; the source is not read again. The cache writer gets a CommonJS marker for it.

      Any other extension (.cjs, .ts, none) goes straight to the CommonJS module after the Stat: no detection, no read, no marker.

      So with the code cache on, a .js file parses once on every boot but its first: an ES module consumes its cache; a CommonJS file reads a 36-byte header and is compiled only by require(), which has its own classic cache. With the code cache off, each isolate detects once per file.

      Named exports from CommonJS: decided 2026-12-06, default and 'module.exports' only. A lexer is a later unit: merve (nodejs/merve, the lexer Node uses since PR 61456; MIT or Apache-2.0, C++20). Its costs: the names stored with the marker (the marker path never reads the source), a CommonJS-resolve up-call for re-exports, a check of -fno-rtti and -Werror builds, and its binary size.

      Detection cost, measured 2026-12-06 with raw V8 calls (not CompileFileModule), as for Q14: the 14.9 Mac Catalyst static libraries on an M-series Mac, a fresh isolate per sample, the median of 15, prettier's plugin bundles (the ESM build's only module syntax is a trailing export{}, so its CommonJS compile fails at the end). In ms:

      File, flags ES module compile Failed CommonJS compile + module compile CommonJS detection compile require()'s own compile
      babel 311 KiB, --jitless 2.35 2.01 + 2.25 1.90 1.87
      typescript 880 KiB, --jitless 6.34 5.16 + 6.05 4.25 4.10
      flow 1.06 MiB, --jitless 2.18 2.04 + 2.06 1.95 1.91
      babel, --jitless --no-lazy 5.68 2.45 + 5.55 5.88 5.68
      typescript, --jitless --no-lazy 12.09 5.87 + 11.66 12.31 11.74
      flow, --jitless --no-lazy 4.44 2.42 + 4.34 4.58 4.38

      Reading the header on the remembered path costs 0.014 to 0.036 ms. A cold detection about doubles a .js file's compile: a failed CommonJS compile before an ES module's, a second compile before require()'s. Under --no-lazy the CommonJS detection is a full eager compile. Only the first boot with the cache on, and every isolate with it off, pays.

    • A webpack bundle.js with no module syntax, reached by import (a require() of it, the usual entry, is unchanged):

      • iOS: it was compiled as a strict ES module, unwrapped, beside and apart from require(), so it could run a second time. It is now CommonJS: require() runs it once, as its unwrapped sloppy classic script (top-level vars become globals, this is the global object), and default is {}, as require('./bundle.js') returns.
      • Android: it was a strict ES module, where module and exports are undefined. It is now the CommonJS file require() loads, with the same cache.
    • JS-visible changes, iOS:

      • A .js file reached by import with module syntax, top-level await or a redeclared CommonJS name was a SyntaxError (it was wrapped in the CommonJS function), and loads as an ES module.
      • A .js file without module syntax compiled as an ES module wrapping a function that never ran: nothing ran, import() gave an empty namespace and a default import failed to link. It now runs through require() and its cache, exports default and 'module.exports', and a throw rejects import() with the thrown value.
      • bundle.js, above.
      • Any other extension (.cjs, .ts, none) reached by import was an ES module wrapping a CommonJS function that never ran, like a .js file. It now runs through require(), as a .js file without module syntax does; ES module syntax in it is a SyntaxError from the CommonJS compile.
      • configureLoader with a function importMap, or one whose toJSON returns undefined, throws TypeError "configureLoader: importMap must be an object or a JSON string" instead of a parse error.
      • Debug builds gain httpFetchDiagnostics and streamedCompileStats once ns-module.js forwards them. A remoteUrlMatchesAllowlist entry holding a lone surrogate is dropped, as the app config's array drops one (ToExactUtf8); iOS read it through NSString.
      • createRequire("file://…#…") keeps the # in the path, as Android does; iOS cut the path at the #. A URL object's fragment is still dropped.
      • A C++ exception in a binding member is a JS exception, not a crash.
      • The facade after loader::Quiesce throws "The module loader is shutting down", and a facade that cannot be built throws the core's texts ("Cannot compile/link/evaluate the require() facade for ").
      • Once the isolate's loader state is gone, import.meta is left empty instead of getting the app root's strings.
      • Every cache file is stale once (format version 2).
    • JS-visible changes, Android:

      • A .js file without module syntax was a strict ES module: module and exports were undefined, a default import failed to link, and it ran apart from require(). It now runs through require(), as on iOS.
      • A .js file that parses neither way reports the CommonJS compile's SyntaxError, as Node does.
      • Any other extension (.cjs, .ts, none) reached by import was an unwrapped ES module, so ES module syntax in a .cjs file worked. It is now CommonJS through require(): such syntax is a SyntaxError, and module, exports and require work.
      • The facade texts and the Quiesce error, as on iOS.
      • import.meta is filled after loader::Quiesce (Android's callback left it empty once the loader was closing), until the state bag closes.
      • Every cache file is stale once, which also drops .mcache files compiled from CommonJS .js files as ES modules.
    • Verification:

      • tests/CodeCacheTest.cpp (host): the format field, markers, and corrupt headers (a marker with a payload, an ES module file with no format, an unknown format).
      • tests/v8/ModuleImportTest.cpp, under the default, iOS and Android configurations: import.meta strings, with a query and over http; every detection row (ESM-only messages, top-level await in three positions, redeclared names, return, await as an identifier, import() in CommonJS, syntax errors, a file that parses neither way, throws, cycles through require(), the memo per Stat, other extensions); the facade (live bindings, dropped with its target, after Quiesce); every binding member, error and barrier, with and without diagnostics; and a code cache mode that checks the marker and the ES module cache, then reads the marker from a new isolate.
      • Lanes: host ASan+UBSan (fake and ada), V8-linked ASan, and TSan on CodeCacheTest, ModuleImportTest and LoaderHostTest; syntax-checked against iOS's and NDK 27's headers.
    • Adoption, iOS (on top of 6.5):

      • Add CommonJsModule.cpp, NsModuleBinding.cpp and RequireEsm.cpp to the RuntimeCommon target in the Xcode project.
      • Runtime.mm: replace the two Set…Callback calls with loader::InstallHostCallbacks(isolate) and delete the static InitializeImportMetaObject.
      • ModuleInternalCallbacks.mm: delete GetOrCreateRequireFacade and BuildNsModuleBinding. NsBuiltinModules.cpp calls loader::BuildNsModuleBinding(context, binding, RuntimeConfig.IsDebug).
      • ModuleInternal.mm's require(esm) path calls the core's facade and turns JsError and Terminated into its own exceptions.
      • Implement platform::InstallCreateRequireBinding with ModuleInternal::InstallCreateRequireBinding.
      • Implement platform::RequireFileForImport with LoadImpl and the require cache, converting NativeScriptException to a pending exception. A module still loading gives its exports so far; bundle.js gives {}. The path is canonical and names an existing file, so skip ResolvePath. It can end in anything but .mjs and .json: LoadImpl throws "Unsupported file extension: " for anything but .js, .mjs and .json (an extensionless path included), so load such a file as a CommonJS script (LoadModule's classic path, with the CommonJS wrapper) under its path in the require cache. require('./x.cjs') itself still throws until step 8.
      • Delete platform::FileModuleSourceWrap (ModuleInternal.mm's definition). LoadClassicScript takes its wrap from a private helper, today's ModuleSourceWrap body: no wrap for bundle.js or an ES module path, the CommonJS wrapper otherwise.
      • ModuleInternal::CompileFileEsModule, used by LoadESModule, calls CompileFileModule (or serves .mjs only) and passes no wrap: a .js or .cjs entry would otherwise skip detection, and a .js one overwrite its marker.
      • js/ns-module.js forwards httpFetchDiagnostics and streamedCompileStats, and its fileUrlToPath keeps a # in the path, as Android's does (decided 2026-12-06).
      • RefreshLoaderConfig skips its appRootOrigin and legacyOrigins override when the app config sets appSchemeOrigins: true.
    • Adoption, Android (on top of 6.5):

      • The core's sources come in through add_subdirectory; nothing to list.
      • Runtime.cpp: loader::InstallHostCallbacks(isolate) replaces the two Set…Callback calls. Delete InitializeImportMetaObject, GetOrCreateRequireFacade and BuildNsModuleBinding from ModuleInternalCallbacks.cpp.
      • NsBuiltinModules.cpp calls loader::BuildNsModuleBinding(context, binding, <debuggable>), then adds forcePlatformHttpTransport inside its own barrier.
      • ModuleInternal.cpp's require(esm) path calls the core's facade and turns JsError and Terminated into its own exceptions.
      • Implement platform::RequireFileForImport (the require() cache, a pending exception on failure) and platform::InstallCreateRequireBinding. As on iOS, the path is canonical and can end in anything but .mjs and .json: neither Module.java's resolution (it appends .js or .mjs to an unknown extension) nor LoadImpl (it throws "Unsupported file extension: " for anything but .js, .mjs, .json and .so) takes it, so load the file by path as a CommonJS script (LoadScript). A .so path: LoadModule's addon path gives the addon's exports, as require() does; refusing it instead is the alternative.
      • Delete platform::FileModuleSourceWrap (RuntimeCommonPlatform.cpp).
      • ModuleInternal::CompileFileEsModule: as on iOS.
      • InitLoaderConfig skips its override under appSchemeOrigins.
    • Expectations that move: none found, searching both test trees at iOS dbc010c5 and Android 9768a8a4c. No test imports an existing local .js file with import (the shared tests reach sibling-cjs.js only through createRequire; iOS's /nonexistent-module-404.js row only checks that it rejects), and none checks the facade's texts. No import in either tree (the shared tests included) names a local file other than .mjs, .js or .json. The shared Import/ImportCommonJS test has import file from './file', but inside a .js file that require() loads, which this unit does not change (it is xit on iOS). Android's testEsmHttpLoader.js already expects "importMap must be an object or a JSON string"; iOS has no such row.

    • Cached import() trims. Android's 6.4/6.5 adoption measured a cached import() 8–12% slower than before. Three changes:

      • The replaced-loop check (LivenessFor, a platform::LoopFor and shared_ptr traffic) runs where a walk hands work to the loop: file jobs, fetches, parked walks, the pumped wait, and the file-job wait check. A walk only creates the token, once. A walk that only meets registered modules posts nothing, so it is not checked; one that posts after a replacement still aborts.
      • A file import() moves its resolution and specifier into the walk's completion, and the walk moves a FromResolution root's strings instead of copying them. StartModuleGraphLoad takes its root by value (source-compatible).
      • A file import() whose module is registered and neither uninstantiated nor errored settles without a walk: the walk would stop at that root and complete inside StartModuleGraphLoad, so SettleFileImport runs as its completion would, in the same call. Attribute checks run before, as they did. Settling takes 2 microtask turns with and without the walk (tested, top-level await included).

      Measured with ModuleImportTest bench (opt-in, never in all): the V8-linked lane built Release, the Android configuration, 20,000 sequential awaited import()s of an evaluated module per sample, the median of 15 samples per run, then the median of 5 runs with the builds interleaved. Microseconds per import:

      Specifier Before Liveness + moves + no walk
      bare, import-mapped 4.04 3.97 3.70 2.57 (−36%)
      ./ relative 3.55 3.55 3.41 2.09 (−41%)
      file:// URL 4.66 4.68 4.30 3.32 (−29%)

      The liveness change is within noise on the host loop, whose LoopFor is cheap; the profile's 1% was Android's.

    • Decided 2026-12-06 (the questions this unit raised):

      • With the code cache off (Android's default, debug builds), every boot detects again. Accepted.
      • Named exports: default and 'module.exports' only; merve is a later unit (above).
      • Any other extension is CommonJS, and FileModuleSourceWrap is deleted (above).
      • invalidateModules on a CommonJS module leaves the require() cache alone, so the next import gets the old exports, until step 8 owns that cache.
      • One .js file under two queries is two modules and one require() entry. Accepted: require() has no queries.
      • The detection compile reports scriptParsed or scriptFailedToParse to the inspector, as Node's does. Accepted.
      • An ES module .js stays an inline compile, never a file job: apps put ES modules in .mjs.
      • fileUrlToPath in ns-module.js keeps a # in the path (Android's): the runtime's own file: URLs never carry a fragment, and legacy ones spell a # in the path verbatim (Q1).
      • Confirmed as built: the 'module.exports' export, a throwing CommonJS module rejecting import() with the thrown value, the facade's texts and its throw after loader::Quiesce.
  8. Evaluation layer: EvaluateModuleGraph, LoadESModule and the main-entry boot (C1, C2, C5). Planned as units 7.1–7.4; the boot model below, decided 2026-12-06, replaced 7.3 and 7.4 (the boot backstop). Built (see "Built: 7").

    Decided 2026-12-06.

    • Boot is a pumping require of the main entry: one call that returns only after everything the entry loads has settled, or throws. The core throws JsError (a rejection at any poll, the deadline, a load, link or evaluate failure) or Terminated (termination outranks settlement, C1/C2), or returns kSettled or kHandedOff with the pending entry promise. It never asserts, aborts or logs a fatal error: C5 (a boot rejection is fatal) and Q2 (termination at boot is fatal on Android too) live in each runtime's catch at its boot call.
    • The hold pumps PumpMode::kPlatformWork, so timers run, for up to kModuleSettleSeconds (60 s), and settles when the entry's evaluation is no longer pending and this isolate has no graph walk running (Q11): an import() nobody awaited must not be dropped when iOS's main() falls through to UIApplicationMain.
    • Hand-off: a runtime-supplied predicate, asked before each slice. Null is strict. Android passes null. iOS passes "the UIApplicationMain task is queued" (!Tasks::Empty()); that is a runtime choice, and strict is the alternative, a one-line change at the iOS call. After a hand-off the runtime attaches a rejection handler to the returned promise; it runs as a microtask under the UI run loop, so it routes to the runtime's uncaught-error path and never throws C++ through V8.
    • Main entry only: Android's later runModule calls (@JavaScriptImplementation classes, inspector_modules) lose the boot hold (B5, Q10). A CommonJS main entry stays in the runtime until step 8 and gets the same hold through HoldBoot.
    • The 1 s local window (kLocalEntryYieldSeconds) is gone, for every entry. A local worker or tooling entry is not pumped in place: the walk runs as before, then the evaluation promise comes back at once and the worker's own loop settles it, the worker enabling its message queue and reporting a rejection from that promise's handlers. An http(s) entry keeps its in-pump settle with the 60 s deadline: the dev client needs its failure synchronously.
    • A nested boot call throws JsError.
    • Q3 a rejection that becomes a throw is marked handled; Q4 iOS's Debug-only error modal leaves evaluation; Q5 a file root is keyed by CanonicalFilePath; Q6 a link failure evicts the root; Q7 "The module loader is shutting down"; Q8 a pumping require waits for a module whose top-level await is still running; Q9 Node's ERR_REQUIRE_CYCLE_MODULE, as its own change; Q12 never pump off the loop's home thread; Q13 CommonJS entries stay in the runtimes until step 8; Q14 deadlines keep counting while a debugger holds the isolate paused; Q15 one timeout text, the core's; Q16 time limits are core constants.

    Built: 7.

    • Core API:
      • ns/loader/EvaluationPolicy.h (V8-free): ModuleEvaluationPolicy (kSyncStrict 0, kSyncPumping 1, kAsync 2, the integers the require factory's JS passes), ModuleEvaluationOptions (policy, deadlineSeconds, timeoutBehavior, pumpPlatformWork) with Require(policy), kModuleSettleSeconds (60) and IsEsModuleEntry.
      • ns/loader/Evaluate.h: EvaluateModuleGraph(context, module, key, options), LoadEsModule(context, pathOrUrl, options) and RequireEsModule(context, path, options), which shapes the result as Node's require(esm) does: the 'module.exports' export, else the namespace when it has no default or exports __esModule, else the facade's namespace.
      • ns/loader/Boot.h: RunMainEntry, HoldBoot, RunEsModuleEntry, BootOptions, BootOutcome, BootResult.
      • ns/loader/GraphLoad.h: HasPendingGraphWork(isolate), this isolate's walks only. The global overload stays for the runtimes' backstops until they adopt.
      • No up-call. The hand-off predicate is a parameter, evaluated during the pump; iOS's Tasks::Drain() runs after RunMainEntry returns, outside the Locker.
    • Texts (each header lists its own):
      • the strict refusal, the microtask refusal and "Top-level await timed out for ES module ", as Android spells them today;
      • "Module evaluation promise rejected: — ", thrown as the reason itself (JsError::FromValue);
      • "Cannot evaluate/compile/instantiate module ", "Cannot load ES module " (an http root, with the loader's reason), "Cannot find module ";
      • "The module loader is shutting down";
      • "Cannot require() ES Module in a cycle." with code ERR_REQUIRE_CYCLE_MODULE;
      • "The main entry module '' never settled within 60s", and "The main entry module '' is still evaluating, and a boot off the event loop's home thread cannot wait for it";
      • "A boot call is already running on this isolate".
    • Behaviour as built:
      • Pumping happens on the loop's home thread only. Elsewhere a wait ends at once, as a deadline that has passed (Q12).
      • EvaluateModuleGraph never calls Evaluate() on a module that is evaluating (V8 CHECK-fails on it): it returns empty, and a load throws ERR_REQUIRE_CYCLE_MODULE instead (Q9).
      • A registered root is reused by status: errored is evicted and loaded again; instantiated or uninstantiated is linked and evaluated; an evaluated graph whose top-level await is still running is refused under kSyncStrict, waited for under kSyncPumping (Q8) and returned under kAsync. The Q8 wait holds no SyncModuleLoadScope: the walk it waits on (an import() inside the awaited module) must keep running. From a microtask, a pumping load is refused only while that evaluation is pending or before it starts; a settled one returns its namespace.
      • A call owns the evaluation it started (the module was instantiated when it called Evaluate()). Only the owner evicts on a failed Evaluate(), a termination or a deadline (kThrow, the boot), and only while the key still maps to that module instance; an evaluation started by an import() stays registered for the next caller. A rejection evicts the instance whoever started it, so the next load evaluates it again.
      • Termination is checked before and after Evaluate() under every policy, pumped or not, and before a rejection is thrown.
      • A promise whose rejection the core turns into a throw is marked handled before any pump (kThrow, the boot hold, an http entry), so a late rejection is never also an unhandled one. kReturnPending leaves it unmarked: the caller gets it back.
      • One deadline covers an http(s) graph walk and the settle, for a pumping load and for the boot.
      • loader::Quiesce ends any wait: a pumping load or the boot hold with the entry pending throws "The module loader is shutting down"; the hold over walks only returns kSettled.
      • RequireEsModule of a module still evaluating (kAsync, or past a kReturnPending deadline) returns its namespace unshaped: reading the default export would throw a TDZ ReferenceError.
      • The boot's ladder after the pump: termination (evict if still pending), then a rejection (also when the hand-off is true), then settled, then handed off (the promise if still pending), then, with the entry pending, loader::Quiesce ("The module loader is shutting down"), a boot off the home thread (its own text, no eviction), and the deadline (evict, throw). The boot evicts on termination or the deadline only an evaluation it started. A deadline that passes with only walks running returns kSettled: each walk ends on its own transport deadline and reports to its own importer.
      • RunMainEntry keeps the evaluation promise Evaluate() returned, so a late rejection is observed (B1); a caught require() of a throwing module is not also an unhandled rejection (B2); an http failure carries the loader's reason (B3).
      • RunEsModuleEntry: a local entry is evaluated without a pump. Empty when it fulfilled, the pending promise (unhandled, for the caller to report) while its top-level await runs, a throw (marked handled, evicted) when it rejected inside the call: a body that threw before its first await, or a top-level await that resumed through microtasks alone. An http(s) entry pumps platform work, with one 60 s deadline for the fetch and the settle, and throws at the deadline, as today.
      • Known, as the code being replaced behaves:
        • Indirect cycles: a nested load whose graph imports a module still evaluating up the stack, without its root being that module, evaluates and sees that module's bindings in their TDZ. Only a root evaluating up the stack throws ERR_REQUIRE_CYCLE_MODULE.
        • A registered, uninstantiated file root with an http(s) import is linked without a walk: each http edge falls back to the blocking synchronous fetch and logs "module graph walk missed".
        • A failing http(s) root is fetched twice, by the walk and then by the blocking fallback, which logs "module graph walk missed" for an ordinary 404.
    • JS-visible changes, both:
      • A boot rejection is fatal on both, at any poll; the boot deadline is 60 s instead of 120 s; timers run while the main entry boots.
      • A pumping require() of a module whose top-level await is still running waits for it instead of returning a namespace in its TDZ.
      • A require() of a module still evaluating up the stack throws ERR_REQUIRE_CYCLE_MODULE instead of returning a partial namespace.
      • After loader::Quiesce every load throws "The module loader is shutting down", replacing the four "empty namespace" texts.
      • A local worker entry whose top-level await waits on a task (a timer, I/O, a message) always returns before it settles, so messages wait for it in the queue and its rejection reaches the parent through the entry promise's handler, where one that settled within 1 s did both inside the entry call. One that resumes through microtasks alone still settles inside the entry call. iOS EventLoopTests "runs an ES module worker entry whose top-level await parks past the yield window" and the "outlived the settle window" spec must still pass on adoption; their names may need rewording.
      • A local worker entry whose top-level await rejects within 1 s after waiting on a task took the synchronous error route and now takes the one a later rejection already takes. iOS: the worker's own onerror runs first and the worker keeps running, where before the parent got the error with its line and the worker was terminated. Android: the worker's onerror gets "Unhandled promise rejection: " instead of the error. A body that throws before its first await, or a rejection reached through microtasks alone, keeps the synchronous route. No test pins the task-waiting case.
    • JS-visible changes, iOS: a late main-entry rejection is fatal (it was missed, B1); a failing http entry reports the loader's reason inside "Cannot load ES module" (B3); an ES main entry has no 1 s window before UIApplicationMain, it hands off as soon as UIApplicationMain is queued.
    • JS-visible changes, Android: a link failure evicts the root, so the next require() recompiles it (Q6); a path containing ? is one file (Q5); termination at boot is fatal (Q2); @JavaScriptImplementation and inspector_modules loads no longer get the boot hold (B5).
    • Verification: tests/EvaluationPolicyTest.cpp (host: the Require() factory, the policy integers, IsEsModuleEntry) and tests/v8/EvaluateTest.cpp under the default, iOS and Android configurations: every refusal, rejection shape, timeout and termination order of EvaluateModuleGraph; file and http roots, registry hits in each status, Q5–Q9, the three export shapes and the unregistered-facade throw; boot settle, rejection at the first poll and later, rejection over hand-off, deadline, termination over settlement and before boot, hand-off with the loop reference count back where it was, null predicate is strict, the graph-walk hold for an un-awaited import() (both entry kinds) and its deadline, nested boot calls, B2, and worker entries (pending at once, a synchronous throw, http). Ownership: a Q8 wait on an import()-started evaluation whose own walk must finish, no eviction of it at a deadline or termination, eviction by instance, a settled async graph loaded from a microtask, termination where nothing pumps (every policy, worker entries, a registered root), no TDZ throw from RequireEsModule of a pending module, no unhandled-rejection event for a pumped or boot late rejection, one deadline over walk and settle, a non-root dependency's top-level await, ERR_REQUIRE_CYCLE_MODULE under kSyncStrict. Boot edges: off the home thread, after Quiesce, termination with the entry pending, an http main entry and its 404, Quiesce inside the hold and inside a pumping load. Lanes: host ASan+UBSan (fake and ada), V8-linked ASan and plain, TSan on CodeCacheTest, ModuleImportTest, LoaderHostTest and EvaluateTest, clang-format 22.1.8; syntax-checked against iOS's and NDK 27's headers.
    • Adoption, iOS (paths under NativeScript/, lines at both runtimes' feat/runtime-common, iOS 12cd4fe0):
      • Add Boot.cpp, Evaluate.cpp and EvaluationPolicy.cpp to the RuntimeCommon target.
      • runtime/Tasks.h/.cpp: add static bool Empty().
      • runtime/Runtime.mm RunMainScript (461-482): resolve the main entry; an ES entry (loader::IsEsModuleEntry) calls loader::RunMainEntry(context, entry, {handOff = [] { return !tns::Tasks::Empty(); }}); a CommonJS one runs today's require, then loader::HoldBoot with the same options. On kHandedOff with a pending entry, attach the rejection handler (above). JsError and Terminated stay fatal there. Delete PollMainEntryEvaluation (491-508), EvictMainEntry (510-525) and their declarations (Runtime.h:83-87, 96-99).
      • NativeScript.mm runMainApplication (132-237): delete the backstop (152-236: the first poll, the for (;;) loop at 170-211, the fatal assembly at 219-235); keep RunMainScript, then Tasks::Drain().
      • runtime/ModuleInternal.h: delete kModuleEvaluateDeadlineSeconds, ModuleEvaluationPolicy, ModuleEvaluationOptions, EvaluateModuleGraph and EntryEvaluationState (9-52), CompileFileEsModule (91-93), PendingEntryEvaluation (100-101), PollEntryEvaluation (107-109) and LoadESModule (131-133); use the core's types.
      • runtime/ModuleInternal.mm: delete BootEntryEvaluationOptions (54-70), CanonicalizeModulePath (93-100), NamespaceHasOwn, RegisteredModuleForPath and RequireExportsForNamespace (699-759), CompileFileEsModule (999-1006), the entry probes (1011-1065), LogEsmPhase and the throw helpers (1068-1189), EvaluateModuleGraph (1191-1372), ThrowIfLoadInterruptedByTermination and LoadESModule (1377-1598), and IsModuleLoaderClosed (104-106) if nothing else uses it. IsESModule (38-41) becomes loader::IsEsModuleEntry. LoadModule's ES branch (809) calls loader::RequireEsModule; LoadScript (934) calls loader::LoadEsModule. RequireEvaluationOptions (78-87) builds the core's options (pumpRunLoop becomes pumpPlatformWork at 68, 84, 348, 377, 544; the JS argument keeps its name). RunModule's ES branch (222-263) serves workers and tooling through loader::RunEsModuleEntry.
      • Worker.mm (570-628): use the promise RunEsModuleEntry returned instead of the PendingEntryEvaluation re-probe (576); the handlers stay.
      • inspector/JsV8InspectorClient.mm (1560): inspector_modules.mjs through RunEsModuleEntry; its catches (1561-1568) already cover JsError and Terminated.
    • Adoption, Android (paths under test-app/runtime/src/main/, lines at 80193feec):
      • Nothing to list in the build.
      • java/com/tns/Runtime.java run() (922-930): call a new main-only JNI method. Its C++ side calls loader::RunMainEntry(context, path, {}) (null hand-off: strict) for an ES entry, or today's Load then loader::HoldBoot(context, {}) for a CommonJS one, and makes JsError and Terminated fatal (C5, Q2): runModule's ladder in cpp/com_tns_Runtime.cpp (222-258) swallows Terminated (247-248).
      • cpp/Runtime.cpp: delete HoldBootBackstop (342-419) and its calls in RunModule (429, 435). runModule keeps serving @JavaScriptImplementation (Runtime.java:1077) and inspector_modules without a hold.
      • cpp/ModuleInternal.h: delete 20-68 (the deadline constant, policy, entry state, options and EvaluateModuleGraph), IsESModule (96), LoadESModule (112-113), CompileFileEsModule (142-143), PendingEntryEvaluation (154-155) and PollEntryEvaluation (164-166).
      • cpp/ModuleInternal.cpp: delete RejectionDetail and PromiseRejectionMessage (51-115), BootEntryEvaluationOptions (229-241), NamespaceHasOwn, RegisteredModuleForPath and RequireExportsForNamespace (798-856), CompileFileEsModule (1085-1091), LogEsmPhase, DescribeModuleStatus, ClassifyV8Failure and the anonymous namespace (1094-1233), EvaluateModuleGraph (1235-1368), the entry probes (1373-1436) and LoadESModule (1443-1617). LoadModule's ES branch (884, 898-900) calls loader::RequireEsModule; RequireEvaluationOptions (247-258) builds the core's options (pumpRunLoop at 236, 253, 270, 298, 358, 595). Load's ES branch (633-649) serves the worker through loader::RunEsModuleEntry. inspector_modules is loaded by bare name through require(), not as an entry. A @JavaScriptImplementation .mjs (Runtime.java:1077) must define its class before createJSInstance goes on, so it loads through loader::LoadEsModule with Require(kSyncPumping), which pumps V8 tasks only: one whose top-level await waits on a timer is unsupported, and throws the timeout after 60 s.
      • cpp/WorkerWrapper.cpp (641-690): use the promise RunEsModuleEntry returned instead of the re-probe (642); the handlers stay.
      • cpp/JsV8InspectorClient.cpp init() (1218-1246): catch JsError and Terminated around registerModules(); it catches only NativeScriptException (1242-1245).
    • Specs to add on adoption (shared tests, both runtimes): one module instance for import() then require() of the same .mjs, and the reverse, which gates Q5; a createPumpingRequire of a module whose top-level await is still running gets its settled exports (Q8); a require() cycle through a static import throws ERR_REQUIRE_CYCLE_MODULE (Q9). Comments that describe the entry pump go stale: Android esmEntryTimerWorker.mjs (its timer now fires in the worker's loop), esmEntryNeverSettlesWorker.mjs and the terminate spec in testWorkerEsmEntry.js, iOS workerTerminate/parkedEntryWorker.mjs and the "any point of its startup" spec in WorkerTerminateTests.js; their expectations hold.
    • Left for step 8: the CommonJS main entry moves into RunMainEntry, and HoldBoot loses its last caller; require()'s resolver, cache and wrapper; the createRequire binding and require-factory.js's policy plumbing (Transitional.h).
  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.

    Units: 8.1 import-map scope keys (ESM), 8.2 the resolver and entry resolution, 8.3 the CommonJS compile and its code cache, 8.4 the require cache, module object and require() itself, 8.5 the Node surface. 8.4 and 8.5 wait for step 7. Every question of the step 8 plan (Q1–Q27) was decided on 2026-12-06 as recommended; 8.1 ships on its own. Q18 went further, the same day: __nativeRequire goes as well as __requireOverride, and @nativescript/vite, its only user, moves to ns:module's createRequire.

    Built: 8.1.

    • Core API: ImportMapScopePrefix(scopeKey, config) (ns/loader/ImportMap.h) takes the isolate's LoaderConfig; ParseImportMap passes LoaderConfigFor(isolate).
    • Scope keys: a file importer is matched by its path, so a key is turned into the path it names:
      • a file: or app: key: the path FileUrlToPath gives (virtual roots and appRootAliases included), plus the trailing / the key was written with. A key FileUrlToPath refuses stays verbatim and matches nothing;
      • a ~/ key: the path a ~/ specifier names, .. stopping at appRoot, plus its trailing /;
      • http(s) keys as before; root-absolute and bare keys unchanged (Q21). Four spellings of one directory (app:///lib/, file:///app/lib/, ~/lib/, <appRoot>/lib/) are one scope, and the last one written wins, as for any duplicate key.
    • ESM only: require() never reads the import map (Q20).
    • Runtimes adopt by the submodule bump; neither builds scopes itself. A bump to 155e262 carries 8.1 alone. A bump past 8.3 also brings code cache format version 3 (every existing cache is stale once) and the detection's kept CommonJS functions, which nothing takes until the runtime calls CompileFileCommonJs: up to 16 functions and their source stay alive until Quiesce.
    • Tests: tests/ImportMapTest.cpp (every spelling, refused URLs, the collapse), tests/ResolverTest.cpp (scoped lookups from file importers), tests/v8/ModuleImportTest.cpp (configureLoader with app: and ~/ scope keys, end to end).

    Built: 8.2 (core).

    • Core API (V8-free unless noted):
      • ns/loader/RequireResolver.h: ResolveRequire(specifier, fromDir, config, packages) returns a RequireResolution (kind: unresolved, invalid package, file, native addon, or URL and invalid entry path from ResolveEntry only; format: CommonJS, JSON, ES module or native addon; path, specifier, attempted, packageJson, packageError). RequireLookupPaths(fromDir, config), RequireErrorMessage, RequireErrorCode, ResolveMainEntry(config, packages), ResolveEntry(specifier, fromDir, config, packages) and RequireResolveCache.
      • ns/loader/PackageJson.h: ParsePackageJson(text) and PackageJsonCache (Q22).
      • ns/loader/CommonJs.h (V8): CachedRequireResolution(isolate, specifier, fromDir), ResolveRequireFor(isolate, specifier, fromDir) and RequireError(isolate, resolution).
      • LoaderConfig: walkNodeModules (default true; config only, Q14), globalModuleRoots, nativeLibraryScheme, nativeAddonExtensions. Both runtimes set globalModuleRoots to {<appRoot>/tns_modules, <appRoot>/tns_modules/tns-core-modules}; Android sets nativeLibraryScheme "system_lib://" and nativeAddonExtensions {".so"}, iOS leaves both empty.
    • The algorithm (decided 2026-12-06):
      • Empty, or holding a NUL: unresolved, nothing tried.
      • nativeLibraryScheme + name: a native addon, the name verbatim.
      • ./, ../, ., ..: joined to fromDir lexically (A1). .foo is a package name, as in Node.
      • ~ and ~/: below appRoot, .. stopping there (Q21).
      • /x: a device path (Q21), never moved under appRoot, so /apple and /app/x are themselves (B3).
      • Package names: <d>/node_modules for fromDir and each ancestor d, nearest first, skipping a d named node_modules, up to and including <appRoot>/node_modules for a fromDir under appRoot and up to /node_modules otherwise; then globalModuleRoots in order (A4, Q3). walkNodeModules false leaves only the global roots.
      • A candidate X is tried as a file (X, X.js, X.mjs, X.json; Q5, any extension as written, Q6), then as a directory: a valid package.json main M as a file and then as M/index.*, then X/index.js, X/index.mjs, X/index.json. A package.json below M is never read (Q8), so "main": "." ends at the index (B6). A specifier ending in /, . or .. names a directory only, so require("./") is the requiring directory's package, not the app's main (Q11).
      • The first package.json on the path that is not valid JSON, not an object, or whose main is a lone surrogate, U+0000 or ill-formed UTF-8 ends the lookup as an invalid package (Q9). A main that is not a non-empty string is no main.
      • The format follows the extension: .json, .mjs, nativeAddonExtensions, else CommonJS (Q6), so .cjs, LICENSE and .ts load as CommonJS.
      • Every path is CanonicalFilePath, so a file reached by require and by import under the same spelling has one path (B1).
      • Only files are probed (§4.3), plus one Stat per package-name lookup directory (<dir>/node_modules and each global root): one that is not a directory is skipped without probing inside it.
    • Errors (Q9, Q10): "Cannot find module '' (tried )", the parenthesis omitted when nothing was tried, with code: 'MODULE_NOT_FOUND' and requireStack: []; "Unable to locate main entry in <package.json>: " with code: 'ERR_INVALID_PACKAGE_CONFIG'. RequireError builds the error object the same way in Debug and Release.
    • Memos (Q4, Q23): each ModuleLoaderState keeps a PackageJsonCache (one Stat per use; a package.json is read again when its size or freshness token changed, and a missing one is dropped, never remembered) and a RequireResolveCache keyed by fromDir '\0' specifier (an empty fromDir keys as appRoot), holding found resolutions only. A lookup is heterogeneous: no allocation, no Stat. InvalidateModules clears both. The runtime checks a hit's path against its own require cache and resolves again with ResolveRequireFor when the module is gone.
    • Boot cost. A missing candidate costs four file probes, plus one package.json probe and three index probes when it is tried as a directory: eight per node_modules directory walked that exists, one per missing one (the review round's directory Stat). A package name served from tns-core-modules three directories below appRoot cost 46 Stats on its first resolution per (directory, specifier) as first built; a relative ./x that names x.js, 2. The timings below predate the directory Stat and the package.json Stat per use. Measured on an M-series Mac, Release, real APFS stat (RequireResolverTest bench has the fake-FS variant), per resolution: ./x → x.js 2.3–3 µs; an exact file 1.7–2.5 µs; a package main 15 µs cold, 5 µs once its package.json is remembered; a nearest-node_modules name 8 µs; the tns-core-modules name 32–40 µs; a memo hit 19–20 ns. On-device Stat (APK assets in particular) is not measured.
    • Departures from the plan:
      • The V8-free functions return a RequireResolution, not a string and a thrown JsError (JsError holds a v8::Global). RequireError is the V8 half.
      • ResolveEntry follows Node's Worker (decided 2026-12-06): a URL (://) passes through as kUrl; ./, ../, ~/ and / names resolve as require() resolves them; any other name, bare and empty ones included, is kInvalidEntryPath, which RequireError throws as Node's TypeError with code ERR_WORKER_PATH and Node v24's text (The worker script or module filename must be an absolute path or a relative path starting with './' or '../'. Received "<name>", plus Node's data: hint). Nothing is probed for it: no node_modules lookup and no caller-directory join. Absolute paths are canonicalized and probed (/abs/worker finds worker.js) where the plan let them pass through.
      • Documented difference from Node (decided 2026-12-06): ./ and ../ worker names resolve against the calling file's directory first, the browser's rule, and when nothing is found there, against the app root, which stands in for Node's cwd (an app has none). Both runtimes do this today; the core's ResolveEntry now does it for both. When neither finds the file, the error is the caller-directory attempt's; a broken package.json next to the caller (kInvalidPackage) is reported, not retried. ~/ is NativeScript's app-root form and stays.
      • nativeAddonExtensions is new: the plan's "explicit .so or .node" needs a per-platform list.
      • ~x is an app-root form, as in ESM, not a package name.
    • Host tests: tests/PackageJsonTest.cpp (strict grammar, main rules, 200 000-deep nesting, the cache's reads), tests/RequireResolverTest.cpp (the §1.3 cases, the five node_modules cases, B3, B6, Q5–Q11, Q21, the texts, lookup paths, addons, entry resolution, agreement with ResolveSpecifier, Stat counts, memo allocations). tests/v8/CommonJsTest.cpp: ParsePackageJson against JSON.parse on 38 000 mutated texts, the error objects, and the per-isolate memos with InvalidateModules.
    • Runtimes adopt (lines as of the runtime-common worktrees, 2026-12-06):
      • iOS (NativeScript/runtime/ModuleInternal.mm unless noted):
        • RefreshLoaderConfig (RuntimeCommonPlatform.mm:387-424) sets globalModuleRoots and walkNodeModules (true, so the shared node_modules xits at Require/index.js:318-349 become it).
        • RequireCallback: delete the /app expansion (:448-452), the "./" app-main case (:454-457, Q11), the ./.. standardization (:458-463), the ~ branch (:464-472) and the tns_modules probes (:473-491); call CachedRequireResolution / ResolveRequireFor and throw RequireError. The builtin, Node-API and HTTP checks (:357-419) stay ahead of it.
        • LoadImpl (:541-598): the baseDir*name key (:549-554) becomes the memo, the "Failed to resolve module" and "Cannot find module" texts (:561-573) become RequireError, and the extension switch (:575-595) becomes format, so .cjs and unknown extensions load as CommonJS instead of throwing "Unsupported file extension".
        • Delete ResolvePath (:842-925), ResolvePathFromPackageJson (:927-1010), ResolveMainEntryFromPackageJson (:43-76; boot at :137-142 uses ResolveMainEntry), the shortParentDir shortening (:668-680) and the global require's "/app" directory (:103-106); ModuleInternal.h:13, :69, :71.
        • LoadData reads JSON through platform::ReadFile, not tns::ReadText (:722), which aborts on a failed read.
        • Worker.mm: the caller-relative probe (:388-424, on the caller's thread) calls ResolveEntry, and kInvalidEntryPath throws RequireError's TypeError from the constructor, as Node's does. Today a bare name skips the caller-directory join and reaches the worker thread unresolved; it now throws. Delete the app-root fallback (:426-431): ResolveEntry retries from the app root itself. The ~ expansion (:482-489) and the existence probe (:518-532), on the worker thread, become ResolveEntry there and still report through onerror (Q25: no resolution moves threads).
        • The plan's CanonicalizeModulePath does not exist; iOS already calls the core's CanonicalFilePath (:748, :790).
      • Android:
        • RuntimeCommonPlatform.cpp:88-107 sets globalModuleRoots, nativeLibraryScheme and nativeAddonExtensions.
        • Module.java: delete resolvePath, resolvePathHelper, prepareRelativeOrAbsoluteDir, resolveFromFileOrDirectory, loadAsFile, loadAsDirectory, nodeModulesPaths, isFileExternal, possibleException, folderAsModuleCache and checkForExternalPath (:17-27, :68-346); init keeps ApplicationFilesPath only; bootstrapApp (:348-382) and resolveEntryPath (:58-66) become JNI wrappers over ResolveMainEntry and ResolveEntry. bootstrapApp's "Application entry point file not found" text and its ./bootstrap fallback stay in the wrapper, whose error names the last candidate tried (the ./bootstrap resolution's attempted). ResolveMainEntry's attempted is the package.json main it tried.
        • ModuleInternal.cpp: delete the MODULE_CLASS, RESOLVE_PATH_METHOD_ID and GET_APPLICATION_FILES_PATH_METHOD_ID lookups (:91-100, :905-907; ModuleInternal.h:156-158). LoadImpl (:597-677): the name-only key of bare names (:601, B7) becomes the memo, system_lib:// (:613-618) becomes kNativeAddon, the ~ rewrite with its double slash (:619-624, B4) and the JNI calls (:631-648) go, and the extension switch (:655-664) becomes format.
        • CheckFileExists (ModuleInternal.cpp:569-581) resolves through Module.resolvePath, so a bare worker name today takes the node_modules lookup; it and the worker entry code (CallbackHandlers.cpp:1775-1843) call ResolveEntry instead, and a bare name throws ERR_WORKER_PATH from the constructor. Delete the retry against the app root (:1834-1842): ResolveEntry retries from the app root itself. Module.resolveEntryPath's other callers: Runtime.java:929 with bootstrapApp's path and :936 with RuntimeHelper.java:211's app/tns-java-classes.js pass absolute paths, which ResolveEntry now probes (they passed verbatim); createJSInstance passes a @JavaScriptImplementation's javaScriptFile, a relative or bare name, which the Java wrapper prefixes with ./ unless it starts with ./, ../ or ~/. The wrapper keeps that prefix: ResolveEntry rejects a bare name.
        • The order changes: Android searched tns-core-modules first and read app/tns_modules in place of app/node_modules (Module.java:134-160, :336-338). No shared spec pins either (§1.3 of the plan).
      • Tests that move: Android requireExceptionTests.js:58, :85, :94, :113, :132 pin "Failed to find module: … relative to: …" and take the Q10 text. iOS NsUtilTests.js:89 and LoaderHardeningTests.js:154-185 match substrings that the core's texts keep. Shared Require/index.js:222 (index.json) resolves now, and becomes it with Q7's JSON primitives in 8.4.

    Built: 8.3 (core).

    • Core API (ns/loader/FileCompile.h, ns/loader/CodeCache.h, ns/loader/CodeCacheQueue.h):
      • kCommonJsParameters: exports, require, module, __filename, __dirname, Node's order; callers pass arguments in it.
      • CompileFileCommonJs(isolate, context, path, origin): the file compiled with ScriptCompiler::CompileFunction and those parameters, no text added (A7), so line-1 columns in Error.stack, stack frames, messages and the inspector are the file's. It Stats, reads, consumes a fresh cache, compiles and queues a cache when there was none or V8 rejected it, like the other file compiles; "Cannot find module" and "Cannot read module" are JsErrors, a compile error is left pending.
      • CodeCacheKind::kCommonJsFunction (3), in .fcache files, module format kNone; QueueCodeCache(isolate, function, entry) creates it with CreateCodeCacheForFunction. Every kind is an explicit switch: an unknown kind has no file name or entry, reads as stale and is never written.
      • kCodeCacheFormatVersion 3 (B10): every version 2 file reads as stale once.
    • Q13 reuse: the .js detection compiles through the same helper. When it finds CommonJS, the function is kept in ModuleLoaderState (path, size, freshness token, origin; at most 16, oldest evicted; none without a freshness token or after Quiesce), and CompileFileCommonJs takes it once when its Stat, origin and context match. EraseKey (so InvalidateModules and RemoveModuleFromRegistry), a new detection of the path and Quiesce drop it. When the reuse hits, the file is compiled once; a miss (the cap, no freshness token, another origin) compiles it again. Whether the inspector then sees one script per URL, which the spike showed setBreakpointByUrl needs, was not checked. Release, --jitless, require's compile right after detection: 0.000 / 0.002 ms kept, 0.047 / 1.39 ms dropped (V8's compilation cache), 1.98 / 46.8 ms dropped after a full GC, for babel.js / typescript.js.
    • A7 spike (V8 14.9.207.39, Mac Catalyst libraries):
      • A function cache is consumed across processes; a different-length source rejects it; a classic cache offered to CompileFunction is rejected; a same-length edit is accepted with stale code, as for every kind (B5).
      • scriptParsed reports the file's URL, start 0:0, the file's length and hash, hasSourceURL false, cold and consumed; getPossibleBreakpoints and setBreakpoint use file columns.
      • Line-1 errors report file columns (test.js:1:64, wrapped 1:125); import() inside the function sees the file's URL.
      • Cost: at parity under lazy compilation (cold 1.85 vs 1.85 ms, consume 0.037 vs 0.042 ms for babel.js); under --no-lazy, +1–3 % cold, up to +9 % to consume and +4–11 % cache bytes.
    • Tests: tests/CodeCacheTest.cpp (version 3, the new kind, kinds never read as each other); tests/v8/CommonJsCompileTest.cpp (parameters and this, line-1 columns, missing and unreadable files, the cache across isolates, the detection reuse and its mismatches, cap, invalidation, Quiesce; a bench mode). The V8 host's RequireFileForImport compiles through CompileFileCommonJs. ModuleImportTest's same-size, same-token edit of a CommonJS .js now runs the old code: require's function cache is consumed, as any cache is when the platform reports the file unchanged.
    • Runtimes adopt:
      • iOS: LoadClassicScript (ModuleInternal.mm:788-810) calls CompileFileCommonJs; LoadScript (:747-776) loses its run step; delete ClassicScriptWrap (:778-786), the factory check (:653-666); the arguments (:687) take Node's order. bundle.js (:643-652, :782) runs unwrapped today and needs its own path or Q18's change.
      • Android: LoadScript (ModuleInternal.cpp:827-847) calls CompileFileCommonJs; the run step at :716-721 goes; delete MODULE_PROLOGUE, MODULE_EPILOGUE and MODULE_PROLOGUE_LENGTH (:909-911, ModuleInternal.h:82, :159-160) and the line-1 column correction in MetadataNode.cpp:2499-2579. The arguments (:795) take Node's order for scripts only: .so addons receive the same array through NSMain (:762-773) and read it by index, so they keep module, exports, require, …. this stays {__extends} (Q12 (d)) until 8.4.
      • Both: the detection reuse hits only when require passes the path the registry recorded and ReportedModuleUrl(path) as the origin; anything else recompiles.

    Built: 8.4 (core).

    • Core API (ns/loader/CommonJs.h, ns/loader/Boot.h, ns/RuntimeAccess.h, ns/LoaderConfig.h):
      • InstallCommonJs(context): global require (appRoot, Require(kSyncStrict)). There is no __nativeRequire, and __requireOverride is not read (Q18).
      • RequireFunctionFor(context, dir, options): one native function per (canonical dir, policy, deadline, timeout behaviour, pump) per isolate (Q24) while anything holds it, name "require", length 1, not a constructor. module.require === require inside a module, and two modules in one directory share it. ns:module's binding createRequire(baseDir, pumping, deadlineSeconds, throwOnTimeout, pumpRunLoop) returns it for FileUrlPathToPath(baseDir): a directory below virtualFileRoots (/app) is under appRoot, as in a file: URL, since ns-module.js hands the binding a file: URL's path and iOS's legacy import.meta.url is file:///app/…. A runtime calling RequireFunctionFor with such a path maps it itself.
      • RequireFile(context, path): import of a CommonJS file, through the same cache.
      • RunMainEntry runs a CommonJS entry itself (no HoldBoot); RunCommonJsEntry(context, path) serves worker and tooling entries. Both run a file as require() does, so a file already in the require cache does not run again. The main entry becomes require.main, cached or not; until it runs, the first RunCommonJsEntry is.
      • platform::RequireNativeAddon(context, request, module) (Q19): a bare Node-API name with module empty, or a kNativeAddon path with the module object, cached before the call; nullopt means "not mine".
      • LoaderConfig::commonJsThisHasExtends (Q12 (d)): false (iOS), this is a fresh empty object; true (Android), a fresh object holding global.__extends. Node's module.exports stays a later deprecation.
      • ns/loader/Transitional.h is deleted; RequireFileForImport and InstallCreateRequireBinding are no longer up-calls.
    • Behaviour:
      • The require cache holds one module object per canonical path (CommonJS, JSON, addon). A cycle sees the exports so far; a module whose code throws leaves the cache. Import of a CommonJS file and a query-less import of a JSON file read the same entry, in either order (Q7); a query keeps its own value, as in Node.
      • invalidateModules drops the entries of the paths it names, and of a CommonJS file every import of it (Q17); Quiesce drops all of them, the require functions and require.main.
      • Builtins: ns:/node: names return platform::BuiltinModule's default. Both runtimes already export the frozen exports object there, so no BuiltinExports up-call was added.
      • Errors (same in Debug and Release):
        • a non-string id: Node's ERR_INVALID_ARG_TYPE TypeError, the text CreateRequireTests.js:137-161 pins;
        • nothing found: 8.2's RequireError;
        • an http(s) id: "NativeScript: require() of URL module is not supported: . Use dynamic import() instead.";
        • a compile error or a module's own throw: rethrown as it is, no wrapper text (the Cannot compile / Error calling module function prefixes stay in the C++ log message only);
        • JSON: any JSON value, primitives included; a parse error is the SyntaxError ": <V8's message>";
        • a Node-API name that fails: "Failed to initialize Node-API module ''" when the addon left nothing pending; an addon path on a runtime without addons: "Cannot load native addon : this runtime loads none";
        • new require() throws (not a constructor).
    • JS protocol: ns-module.js is unchanged: the binding keeps createRequire's five arguments and meanings. The runtimes delete require-factory.js and BuiltinId::kRequireFactory. Android drops two globals, each needing a release note: __requireOverride (only Android's require-factory.js reads it, and neither runtime's sources nor tests set it) and __nativeRequire (iOS never had it; createRequire(dir) from ns:module replaces it).
    • bundle.js (Q18): the core has no bundle.js case: an app's bundle.js is an ordinary CommonJS module, called with the five arguments, this per the flag. iOS ran it as a plain script, where top-level this is the global, top-level vars become globals, and module, exports and require are the globals (or undefined). As a module they are locals, so typeof module / typeof exports checks take the CommonJS branch and module.exports is real. iOS adoption must check a @nativescript/webpack 5 build (the bundle.js entry and every chunk it loads) for any of these reliances, and that its chunk loading works through the core's require.
    • Tests: tests/v8/RequireTest.cpp (shape, module object, cache and aliases, cycles, throw rollback, syntax errors, not found, packages, URLs, invalidation, this both ways, JSON and its sharing with import, builtins, addons, require(esm), import of the cached CommonJS, createRequire errors, no __nativeRequire, require after Quiesce); EvaluateTest holds on a CommonJS main entry; ModuleImportTest's CommonJS-to-ESM cycle now throws Node's ERR_REQUIRE_CYCLE_MODULE text. The V8 host's own require is gone.
    • Runtimes adopt (iOS paths under NativeScript/runtime/, Android under test-app/runtime/src/main/cpp/; lines at the runtime-common worktrees of 2026-12-06):
      • iOS:
        • Delete js/require-factory.js and its line in tools/js2c-inputs.xcfilelist:30.
        • ModuleInternal::Init's require-factory run and global require (ModuleInternal.mm:83-113, the global's base was a literal /app) become loader::InstallCommonJs(context); DefineGlobalDirname (:117) stays.
        • Delete CreateRequireCallback and InstallCreateRequireBinding (:202-261), GetRequireFunction (:263-306), DescribeValueForTypeError (:308-355), RequireCallback (:357-539), LoadImpl (:540-598), LoadModule (:600-717, the bundle.js branch :642-652 with it), LoadData (:719-745), RequireFileForImport and the Transitional.h up-calls (:1012-1062). In ModuleInternal.h: InstallCreateRequireBinding through LoadImpl (:33-58), requireFactoryFunction_, loadedModules_ and TempModule (to :110); RunMainModule's comment (:18-21) loses HoldBoot.
        • The Node-API branch (ModuleInternal.mm:389-404, NapiModules::IsRegistered / GetExports) moves to platform::RequireNativeAddon in RuntimeCommonPlatform.mm; paths return nullopt.
        • RunMainModule (:132-146) calls loader::RunMainEntry for every entry; Runtime.mm:544 keeps its outcome handling. RunModule (:148-200, Runtime.mm:567, Worker.mm:538) calls loader::RunCommonJsEntry for a CommonJS file.
      • Android:
        • Delete js/require-factory.js (runtime/CMakeLists.txt:110) and the kRequireFactory run (ModuleInternal.cpp:109).
        • The global require install (:131-140) becomes loader::InstallCommonJs(context); the __nativeRequire install (:124-130) and RequirePublicCallback go with no replacement.
        • Delete m_requireFunction, m_requireFactoryFunction and m_requireCache with their teardown (:64-69), RequireCacheKey and the require-function cache (:146-204), CreateRequireCallback, InstallCreateRequireBinding and RequireFileForImport (:206-297), the determineSpecificType port (:299-352), DispatchRequire, RequirePublicCallback and RequireCallbackImpl (:354-500), LoadImpl (:597-677), LoadModule (:679-825) and LoadData (:849-887); RuntimeCommonPlatform.cpp:275-290 (the Transitional.h up-calls). In ModuleInternal.h: InstallCreateRequireBinding and RequireFileForImport (:66-80), the require callbacks, loaders and GetRequireFunction (:103-151, keeping LoadScript while anything calls it) and the three members (:163-165).
        • The .so branch (ModuleInternal.cpp:714-777) and RequireNativeCallback (:502-507) move to platform::RequireNativeAddon for paths with the .so extension (its Node-API registration case included): dlopen, then NSMain with the array it reads by index (module, exports, require, __filename, __dirname) built from the module object (exports, require, filename, path).
        • InitLoaderConfig (RuntimeCommonPlatform.cpp:88-107) sets commonJsThisHasExtends = true.
        • Runtime::RunMainModule (Runtime.cpp:341-358) calls loader::RunMainEntry for every entry; the HoldBoot call (:352) goes. ModuleInternal::Load (:509-533, also @JavaScriptImplementation classes and inspector_modules after boot) and LoadWorker (:537-) call loader::RunCommonJsEntry for a CommonJS file; like today's require(path), a cached file does not run again. createJSInstance's runModule (Runtime.java:1080) can run before run() (:924-933); the main entry still takes require.main from it.
      • This replaces Built: 7's CommonJS adoption lines ("a CommonJS one runs today's require, then loader::HoldBoot", iOS and Android).
      • Pinned texts that move: Android testCreateRequire.js:63-68 (resolve and main are present now, cache stays absent). Android exceptionHandlingTests.js:308-321 as a whole: it reads e.fullMessage, which only NativeScriptException attaches (NativeScriptException.cpp:233-254), and the SyntaxError now arrives as V8 threw it. No spec in either tree pins "Cannot parse JSON file" or "Error calling module function". The non-string id text is unchanged on both. Android's Node-API failure text becomes iOS's.

    Built: 8.5 (core).

    • Module object: id (read-only, non-configurable), path (its directory), exports, filename, loaded (true once its code returned), paths (RequireLookupPaths of its directory, computed when first read) and require. filename is the canonical path, and so is id, except "." for the module loaded as require.main, as in Node (decided 2026-12-06). A module already in the require cache when it becomes require.main keeps its path as id.
    • require.resolve(request[, {paths}]): the path require() would load, or the builtin's name; the same errors as require(). Each of paths (absolute, or relative to the require's directory) is a directory to resolve from instead, in order; a non-array or a non-string entry throws "The property 'options.paths' is invalid. Received " (ERR_INVALID_ARG_VALUE). Only files resolve: a Node-API name throws what an unknown name throws.
    • require.resolve.paths(request): null for a builtin, [dir] for ., .., ./… and ../…, [appRoot] for ~/…, otherwise RequireLookupPaths(dir) (Node's _resolveLookupPaths).
    • require.main: the module object of the CommonJS main entry (RunMainEntry); before it runs, of the first RunCommonJsEntry. Undefined before one ran, for an ES module entry and after Quiesce. require.cache stays absent.
    • Detection (Q13): CompileFileForRequire compiles a .js file as CommonJS and reports "an ES module" when V8's error is an ES module syntax error, or a maybe-ES-module one and the file compiles as a module; the result is remembered in the 6.6 memo, so import and require detect a file once. An ES module found that way is RequireEsModule's, and a .js main entry with ES module syntax runs as an ES module entry. Other extensions are never detected.
    • Tests: RequireTest's module object, resolve, resolve.paths, require.main (through RunMainEntry and RunCommonJsEntry) and detection cases, the top-level-await text included.
    • Runtimes adopt: nothing beyond 8.4; neither runtime has require.resolve or require.main today.

    Built: 8.4–8.5 review round (2026-12-06).

    • Invalidation: InvalidateModules of a CommonJS file's key drops its require cache entry and every registry key recorded for that file (one per query), so no import keeps the old exports while require() runs the file again.
    • Module-run hook (§4.8): LoaderConfig::moduleRunScope, with the name as a const char* (Android's ModuleScope takes one). Android main opens tns::instrumentation::Frame("LoadModule <path>") and CrashBreadcrumbs::ModuleScope in ModuleInternal::LoadModule (ModuleInternal.cpp:813-818), once per CommonJS module; the adoption branch dropped them, and implements the hook with the two instead. ES modules had no scope; the core gives each evaluation root one. iOS leaves it null.
    • Require functions are held weakly: one stays the same function while anything holds it, and entries whose function was collected are pruned when the table doubles, so minting one per (directory, options) stays bounded by the live ones.
    • Costs of a cached require(): the Node-API up-call runs once per bare name: a name it declined is never asked again (an addon registering that name later is not found by it), and the order stays builtin, addon, file (I25), whatever require.resolve remembered. A .js detected as an ES module is remembered as one. A cached require() makes no Stat, read or up-call and allocates nothing (RequireTest pins the counts). A missing node_modules directory costs one Stat instead of eight.
    • Entries: RunCommonJsEntry runs a .mjs as an ES module, and a JSON or addon entry throws "Cannot run as an entry: it is not a JavaScript module" (so does RunMainEntry). A worker entry may be ~x; require('~') is the app root as a directory only.
    • Directories: a require function's directory is its canonical path; only ns:module's createRequire maps a virtual root (a file: URL's path) to the app root, so a real directory below a virtual root keeps its own siblings.
    • A main entry that throws stays require.main (id ".", loaded false) and leaves the require cache, so a later entry sees it as require.main and booting it again runs it again.
    • Watch: each nested require() costs about 2 KB of native stack (the review hit a RangeError at depth 487 on the test host's main thread). Nothing obvious to trim; a deep chain on a worker's smaller stack is the case to measure.
    • Behaviour changes for the release notes, verified against the runtimes' current code:
      • Android parsed package.json with org.json (comments, trailing commas, single quotes and unquoted keys accepted, a numeric main coerced); the core's parser is strict JSON.
      • iOS fell back to index.js silently when the app's package.json did not parse; it now fails with ERR_INVALID_PACKAGE_CONFIG ("Unable to locate main entry in /package.json").
      • iOS's Debug-only "***** JavaScript exception occurred *****" banner is gone; a failed main entry logs "Fatal: the main module failed to run".
      • Errors rethrown from require() carry no fullMessage on Android (only NativeScriptException::ReThrowToV8 attached it).
      • Worker onerror: a throwing entry's text is unchanged (minus fullMessage); iOS's missing entry was "Worker script does not exist: " and is now "Cannot find module '' (tried )"; Android's missing entry throws from the constructor; a bare name throws ERR_WORKER_PATH.
      • A package.json main starting with / is a device path; both runtimes resolved it inside the package.
      • Android's worker global require resolved from the calling module's directory; it is bound to the app root, as on iOS.
      • Unchanged, for the record: a script-style CommonJS main entry never waited for its timers, and still does not.
    • Android adoption: appRootAliases (Runtime.java:915) must keep pairing /data/user/0/<pkg> with /data/data/<pkg>: the require cache now keys through it, where getCanonicalPath folded the two.

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.