Title: ESM loader: remaining cross-platform decisions and deferred follow-ups from #1965 · Issue #2020 · NativeScript/android · GitHub
Open Graph Title: ESM loader: remaining cross-platform decisions and deferred follow-ups from #1965 · Issue #2020 · NativeScript/android
X Title: ESM loader: remaining cross-platform decisions and deferred follow-ups from #1965 · Issue #2020 · NativeScript/android
Description: #1965 landed the full loader-overhaul parity with ios#383 plus several hardening rounds. Everything that could be fixed unilaterally was; this issue tracks what deliberately remains: contract questions that need one answer on both platfo...
Open Graph Description: #1965 landed the full loader-overhaul parity with ios#383 plus several hardening rounds. Everything that could be fixed unilaterally was; this issue tracks what deliberately remains: contract quest...
X Description: #1965 landed the full loader-overhaul parity with ios#383 plus several hardening rounds. Everything that could be fixed unilaterally was; this issue tracks what deliberately remains: contract quest...
Opengraph URL: https://github.com/NativeScript/android/issues/2020
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"ESM loader: remaining cross-platform decisions and deferred follow-ups from #1965","articleBody":"#1965 landed the full loader-overhaul parity with ios#383 plus several hardening rounds. Everything that could be fixed unilaterally was; this issue tracks what deliberately remains: contract questions that need one answer on both platforms, and Android-side follow-ups that were out of the PR's scope. The iOS-side defects the same reviews surfaced are tracked in NativeScript/ios#443 (fixes landed as NativeScript/ios#444).\n\n## Cross-platform decisions (one answer, both runtimes)\n\n- [ ] **require(esm) facade evaluates under sync-strict** (shared bug): `createPumpingRequire()` of an already-settled TLA module with a default export throws the async-graph refusal naming `ns:require-facade:\u003cpath>` — `IsGraphAsync()` is transitive and the facade requests the TLA target. Violates the contract twice (pumping lifts the TLA refusal; exports-cascade step 3) and the error recommends the API that just failed. Fix shape to agree on: direct `Evaluate()` + assert-fulfilled for the facade, or a synthetic-module bypass on the evaluation options.\n- [ ] **Import-map keys carrying queries**: Android strips query/fragment before the map consult (query-bearing keys can never match); iOS matches them for static imports. The HTML import-maps spec matches the specifier as written. Pick a side and align.\n- [ ] **`import.meta.url` shape**: Android exposes the full device path; iOS base-strips to `file:///app/...`. Portable code matching `file:///app/` breaks on Android today. Couples with `file://` specifier candidate handling and iOS's `dirname` inconsistency.\n- [ ] **Transport identity**: Android sends `User-Agent: NativeScript-HTTP-ESM` and inherits the process `CookieHandler`; iOS sends no UA and disables cookies. Cookies especially need a joint call.\n- [ ] **Transport timeouts**: Android 15s connect/15s read vs iOS 5s/10s. The docs now state the per-attempt/per-read semantics honestly, but the values should converge (a stalled edge can outlive the graph deadline).\n- [ ] **`HasPendingAsyncModuleGraphWork` is process-wide on both platforms**: a worker's graph load holds the *main* boot backstop open. Make it per-isolate.\n- [ ] **Instantiate-failure registry semantics**: iOS evicts the root, Android leaves-and-self-heals; HTML/Node module-map semantics say keep-and-rethrow. Neither does that — pick one.\n- [ ] **Import attributes are silently ignored** (`import x from './d.json' with { type: 'json' }` loads as JS on both); Node throws. Document or implement, jointly.\n- [ ] **Import-map validation error-text shape**: parse-detail suffix conditionality and multi-offense selection differ slightly between the platforms' JSON parsers. Normalize or document.\n- [ ] **`createRequire`'s hand-rolled `file:` parser disagrees with `node:url`** (`%2F` honored, `file:/`/`FILE:` rejected vs Node); shared. Rebase it on the `URL` primordial (the comment claiming that's unavailable is wrong on both sides).\n- [ ] **JSON modules are built textually** (`\"export default \" + jsonText`), so a `\"__proto__\"` key becomes a prototype setter instead of an own property. Shared deviation from JSON-module semantics.\n- [ ] **`require-factory` hooks**: `__requireOverride` is Android-only with no producers in-tree; `__pauseOnNextRequire` is iOS-only (inspector-produced). Converge or delete.\n- [ ] **The 1s local-entry yield**: normative in both docs, but its original purpose was iOS's pre-`main()` runway. Decide whether to shrink/remove (doc change on both).\n- [ ] **Waiter-invariant race fixture**: the \"already-evaluating with no continuation attached\" dynamic-import window is documented but unenforced on both platforms — needs a spec that pins it.\n- [ ] **Pump mechanism shape on iOS** (surfaced by porting android#1965's timer specs to iOS): a pumping require started from inside iOS's shared JS-timer `CFRunLoopTimer` callback can never observe another timer fire — CFRunLoopTimer does not re-enter. Android's pump drains the ordered lane directly and is immune; whether iOS should adopt the same drain shape instead of spinning the runloop is a joint pump-contract call.\n- [ ] **Frozen-at-mint pumping options**: neither suite pins that the options object is validated once and immune to later mutation. Add the spec on both.\n\n## Android follow-ups\n\n> **Reclassified 2026-08-20:** the five checked items immediately below turned out to be features present in the merged ios#383 code that the port had missed — implemented in #2021.\n\n- [x] **ESM code cache** — landed in #2021: `CompileFileEsModule` consumes/produces cache blobs (`.mcache` keying avoids colliding with the classic `.cache` for the same file).\n- [x] **Fetch concurrency cap** — landed in #2021: 16 concurrent fetches process-wide (iOS: `HTTPMaximumConnectionsPerHost = 16`), queued jobs drained by finishing threads, spawn failures delivered as transport errors.\n- [x] **Canonical-key transport signatures** — landed in #2021: the transport takes keys from callers (iOS's shape); also fixed collapsed-scheme cache-bust marks never matching.\n- [x] **HTTP worker entries** — landed in #2021: `new Worker(\"http://…\")` works end-to-end (security gate, vocabulary copy, settle gate, inspector URL), spec included.\n- [x] **`ns:module` binding beside the loader state** — landed in #2021 (ios `5ca0c43c`), including the `ParseImportMap`/`InstallParsedImportMap` split that removes the double parse.\n\n- [x] **Lock the process-global interop caches** — done in 7c9c3db3, though not as scoped here. The three caches this item names were already covered by #2013: `Console` timers and `ArgConverter`'s type-long cache became per-runtime `RuntimeState::For\u003cT>(isolate)` (the `Isolate*`-keyed process-global maps are gone entirely), `MetadataNode`'s name/tree-node caches got `s_nodeCacheMutex`, `MetadataReader` got its own `StateMutex`, and `JEnv::s_classCache`/`s_missingClasses` plus `MethodCache::s_mthod_ctor_signature_cache` each got a `shared_mutex` — all on the lock-the-find-and-the-emplace-but-never-across-the-build discipline this item asks for. Auditing the runtime for what genuinely remained in that class turned up four more, all fixed in 7c9c3db3:\n - `File::Buffer` — one process-wide 1MB scratch buffer that `File::ReadText` filled and returned a pointer *into*. Main and worker runtimes read modules concurrently from their own threads, so one thread's `fread` overwrote bytes another was still copying out: **silent module-source corruption rather than a crash**, which is why this one never appeared in a tombstone. It also never saved the allocation it appears to save — every caller goes through the `std::string` overload, which copied out of it on the next line — so reads now go straight into the returned string and the borrowing overload (no callers) is deleted.\n - `JType::EnsureInstance` — published `*instance` *before* `Init` had filled `clazz`/`ctor`/`valueMethodId`, so a second thread could find the pointer non-null and call through uninitialised JNI ids, on the hot boxing path. Now `std::call_once` per `Type`.\n - `CallbackHandlers::Init` — runs once per runtime from `PrepareV8Runtime`, so every worker start rewrote the process-global class and method-id statics (and re-ran `MethodCache::Init`) while the isolates already running were reading them. Process-global half now under `call_once`; `MetadataNode::Init(isolate)` stays per-isolate.\n - `MetadataNode::IsJavascriptKeyword` — filled a function-local `static set\u003cstring>` behind an `empty()` check, racing reads from every runtime's thread.\n\n Audited and deliberately left alone: `JsV8InspectorClient::Domains` is unguarded but main-isolate only (workers use `WorkerInspectorClient`, which never registers domain dispatchers); `SimpleProfiler::s_frames` is racy *and* stores a pointer into a reallocating vector, but `SimpleProfiler::Init` has no callers (dead code); `PageResource::s_cachedPageResources` is write-only, nothing reads it.\n- [ ] **`Runtime::ReadFileText`'s `m_fileWriteMutex` is broken three ways** (surfaced while removing `File::Buffer`, which this mutex superficially looked like it guarded — it never did). Its real purpose is LiveSync: `NativeScriptSyncServiceSocketImpl.createOrOverrideFile()` takes `runtime.lock()` so the runtime does not compile a half-written hot-synced module. But (1) `m_fileWriteMutex` is a non-static *member* (`Runtime.h`), so LiveSync locking one runtime excludes nothing on a worker's thread — precisely the case that matters; (2) the lock is taken *after* `prepareFile()` deletes the file and `new FileOutputStream` truncates it, so it covers only `fos.write` and not the window a reader actually hits; (3) the `finally` calls `runtime.unlock()` even when `lock()` was never reached (a throw from `mkdirs()`/`new FileOutputStream`), which is UB and on bionic can release a lock the JS thread holds inside `ReadFileText`. Fix direction: make the *write* atomic — temp file plus same-directory `ATOMIC_MOVE` — instead of locking readers. `rename(2)` within a directory is atomic, so a reader gets the whole old or the whole new file; that also closes the delete/truncate window no reader-side lock can reach, and drops a mutex from every debug module read. `m_fileWriteMutex` and `Runtime::Lock`/`Unlock` then delete cleanly, keeping `com.tns.Runtime.lock()/unlock()` as deprecated no-ops since they are `public` and external tooling may call them. Implemented in #2022 — **unmerged**: LiveSync has no automated coverage in the runtime test app, so it needs a manual hot-sync check (`ns run android`, edit a file, confirm reload; also a newly-created file and a deleted one, since `prepareFile()` is gone) before merging.\n\n- [ ] **`NS_DEBUG` is unreachable on a real device** (env var); the docs call it \"the only way to trace boot\". A `debug.nativescript.*` system property (pattern already used in `Runtime::GetAndroidVersion`) would make it real.\n- [ ] **Remaining K14 leftovers**: three resolver/import empty-return-without-exception windows in teardown/OOM paths; `catch (std::exception e)` by value in `ModuleInternal.cpp`; `IsolateData::RUNTIME` is never cleared (the `TryGetRuntime` guards are defense-in-depth only and one teardown comment overstates the invariant).\n- [ ] **`NS_TIMERS_NESTING_CLAMP`** is documented opt-in and defined by no build file — confirm that's intended (the HTML 4ms nesting clamp is currently off everywhere, including the test suite).\n- [ ] **Verify `@nativescript/core`'s `setTimeout` rides `__ns__setTimeout`**: the pumping-require timer story assumes it (the test app's own polyfill is a Java `Handler` post that no pump can dispatch, by construction). Confirm against core before advertising the behavior.\n- [ ] **Dev-server smoke test against `@nativescript/vite`** (the same gate as iOS): validates the canonicalization change, the vocabulary purge, the MIME gate, and the ESM-entry routing — and, if the sync-fetch anomaly guard stays cold, authorizes deleting it.\n- [ ] **Accepted-and-documented, revisit if it bites**: the boot backstop blocks the launching thread (up to 120s, dev-time HTTP entries only) by explicit decision — `runtime.run()` returning entry-settled is load-bearing for `NativeScriptActivity`; `require.resolve`/`require.cache`/`require.main` remain absent (feature-detectable).\n\n\n","author":{"url":"https://github.com/edusperoni","@type":"Person","name":"edusperoni"},"datePublished":"2026-08-20T02:49:26Z","url":"https://github.com/NativeScript/android/issues/2020"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:85b7691d-38c0-8dae-6de3-90ba84fd2c40 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | BB54:29AEE8:1465F16:1B2EDE1:6B012E0F |
| html-safe-nonce | b17b13530409115f651b1598d3bda5ba1f9d9197c451b921569c628c288478db |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJCQjU0OjI5QUVFODoxNDY1RjE2OjFCMkVERTE6NkIwMTJFMEYiLCJ2aXNpdG9yX2lkIjoiNDkwOTEyMDExNjE1MjY3NTg1NiIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | a8048d0459940353e24b99822d63146f55748094e91d07c816444f0476d7f74c |
| hovercard-subject-tag | issue:5199136296 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/NativeScript/android/2020/issue_layout |
| twitter:image | https://opengraph.githubassets.com/067d94624a15d81a3e9b7f9c2df685bdcf68d04b61e207b3fce82532e2130f8a/NativeScript/android/issues/2020 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/067d94624a15d81a3e9b7f9c2df685bdcf68d04b61e207b3fce82532e2130f8a/NativeScript/android/issues/2020 |
| og:image:alt | #1965 landed the full loader-overhaul parity with ios#383 plus several hardening rounds. Everything that could be fixed unilaterally was; this issue tracks what deliberately remains: contract quest... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | edusperoni |
| hostname | github.com |
| expected-hostname | github.com |
| None | cc5dfdd32f62ebd3223cab3af3aa2b268d3605218237326a48a99d1efd89495c |
| turbo-cache-control | no-preview |
| go-import | github.com/NativeScript/android git https://github.com/NativeScript/android.git |
| octolytics-dimension-user_id | 7392261 |
| octolytics-dimension-user_login | NativeScript |
| octolytics-dimension-repository_id | 29137950 |
| octolytics-dimension-repository_nwo | NativeScript/android |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 29137950 |
| octolytics-dimension-repository_network_root_nwo | NativeScript/android |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 8c77c9e8439031ad54c75a250694842892f693e1 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width