Skip to content

feat(runtime): base64 and the HTTP module loader from runtime-common - #625

Draft
edusperoni wants to merge 14 commits into
mainfrom
feat/runtime-common
Draft

edusperoni wants to merge 14 commits into
mainfrom
feat/runtime-common

Conversation

@edusperoni

@edusperoni edusperoni commented Dec 5, 2026 •

Copy link
Copy Markdown
Collaborator

First consumer of NativeScript/runtime-common, the shared iOS/Android loader core (design: docs/DESIGN.md there). Draft, so it can be tested with vite and other dev servers before review. The Android counterpart is linked below.

What moves to the core

  • Base64 (ns/Base64.h, ns/Base64Binding.h): the codec and the atob/btoa natives. Built by a new RuntimeCommon static-lib target from the NativeScript/runtime-common submodule.

  • HTTP module loader (ns/http/): the remote-module gate and allowlist, classification, canonicalization, timeouts, the single transport-error retry, deadline clamping, the synchronous fallback's wait bound, the cache switch with its inspector holders, and Clear-Site-Data. HttpLoader.mm keeps only the NSURLSession transport (partitions, NSURLCache generations, delegate queues) and the per-isolate canonicalization vocabulary. tns:: aliases keep the call sites unchanged.

  • Foundation and event loop (core ebb7b87): RuntimeCommonPlatform.mm implements the core's platform functions (Loader(), ApplyThreadPriority, RunJob, LoopFor, IsRuntimeAlive, MainContext). tns::EventLoop implements the core's Loop and gains PumpUntil. The three ad hoc pumps (top-level await, the pumped graph walk, the boot backstop) run through it. The termination flag moves onto the loop; Runtime forwards to it. Catch boundaries that JS or the loader reach also catch the core's JsError and Terminated.

User-visible changes

  • Module requests send User-Agent: NativeScript-HTTP-ESM, as Android already does.
  • In release builds with security.remoteModuleAllowlist, a module whose redirect ends outside the allowlist is refused. Before, the gate only checked the requested URL.
  • A failed module cache clear is reported: clearHttpCache() throws, and Network.clearBrowserCache answers -32000.
  • Graph-load fetch deadlines, the top-level-await deadline and the boot backstop deadline use steady_clock instead of the wall clock.
  • A module load whose event loop has stopped ends as a termination ("interrupted by isolate termination") instead of falling through to the synchronous fallback.
  • The boot backstop holds the Locker while it pumps, and runs Tasks::Drain() between pumps with nothing held.
  • The synchronous fallback fails a malformed URL immediately with "(malformed request URL)" instead of retrying it into "(network error)".

Tests

./run_tests.sh: 2515 passed, 0 failed, both normally and under ASan (-a). The core has host unit tests of its own, including the gate and the redirect check with isDebug=false, which the device suite (always Debug) never exercises.

Related

…core

The new NativeScript/runtime-common submodule pins the
NativeScript/runtime-common repository, the C++ shared with the Android
runtime. It builds as the RuntimeCommon static library target, linked into
NativeScript.framework, with the framework's prefix header for the V8
configuration, V8 as a system header path, and no header map, so core
sources only see their own headers and V8's.

The atob/btoa natives and the forgiving-base64 codec now come from there;
Base64.cpp keeps the builtin wiring.
The gate, classification, retry and deadline policy, the cache switch and
Clear-Site-Data come from the shared core (ns/http); HttpLoader keeps the
NSURLSession transport and the per-isolate canonicalization vocabulary.

User-visible changes:
- requests send User-Agent: NativeScript-HTTP-ESM;
- in release builds with a remote module allowlist, a redirect that ends
  outside it is refused;
- a failed cache clear throws from clearHttpCache() and answers -32000 to
  Network.clearBrowserCache;
- graph-load fetch deadlines are monotonic (steady_clock).
@coderabbitai

coderabbitai Bot commented Dec 5, 2026

Copy link
Copy Markdown

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

…ions

Pin NativeScript/runtime-common to ebb7b87 (foundation headers and the
Loop interface) and compile its new sources in the RuntimeCommon target.

Implement the new link-time platform functions: Loader() from
RuntimeConfig (refreshed whenever initializeWithConfig writes it, with
the V8 flag string the process actually applied), ApplyThreadPriority
via pthread QoS, RunJob inside an autorelease pool, IsRuntimeAlive,
MainContext, and the kRegistry trace category.

Teach every loader-reachable catch boundary the core's JsError and
Terminated ahead of its generic clauses: RequireCallback, RunModule,
RunMainScript, the event loop's RunGuarded, the worker entry, the
inspector modules entry, the graph walk's local compile, the resolver's
file compile, and both import() settle paths.
tns::EventLoop implements the core's Loop interface. PumpUntil checks
termination (the loop's flag, a terminating isolate, a stopped loop),
then the caller's predicate, then a steady-clock deadline before every
slice, and runs kNestableOnly, kV8Tasks or kPlatformWork slices with the
waits the runtime's pumps already used.

The termination flag moves onto the loop; Runtime forwards to it.

The TLA settle pump, the pumped graph walk and the boot backstop now go
through PumpUntil, so their deadlines are monotonic. The backstop runs
short pumps under its own scopes and drains Tasks outside them, since
the drain may enter UIApplicationMain and never return. A pumped walk
that ended on a stopped loop is reported as a termination.
… platform functions

Pins the core at 95d96cc (the app-file seam and the module code cache)
and adds its new sources, src/loader/CodeCache.cpp, CodeCacheQueue.cpp
and FileCompile.cpp, to the RuntimeCommon target.

- platform::StateBag: each Runtime owns an IsolateStateBag, reached
  through the RUNTIME slot. ~Runtime closes it as its last step under the
  Locker, after Caches::Remove and while the isolate is alive, so core
  state lives through all of teardown (F1).
- platform::Stat: stat(2); the freshness token is the source's mtime with
  nanoseconds (st_mtimespec).
- platform::ReadFile: the whole file or failure; a short read fails.
- LoaderConfig.codeCacheDir is <Caches>/NativeScript/CodeCache instead of
  the bare Caches directory.
…untime-common

Classic scripts and file ES modules compile through the core's
CompileFileClassicScript / CompileFileEsModule, with the same script
origin and source wrapper as before: the CommonJS wrapper for everything
but .mjs files and the app's bundle.js. The path is normalized first. A
compile error still logs in Debug and throws "Cannot compile script" for
a classic script, and leaves the exception pending for an ES module.

The off-thread file-module loader decides with platform::Stat,
CodeCacheEntryFor and HasFreshCodeCache at dispatch. On the pool it reads
with platform::ReadFile, always re-checks SourceUnchanged before
consuming a cache, and loads it with LoadCodeCache; finalize queues
creation with QueueCodeCache.

Caches use the core's format: hashed names under codeCacheDir, a header
keyed by the path relative to the app root, sub-second mtime freshness.
The iOS cache machinery (LoadScriptCache, QueueScriptCache,
FreshScriptCachePath, GetCacheFileName, its creation queue) and the
helpers only it used (ReadModule, ReadBinary, WriteBinary,
WrapModuleContent) are gone.

The UIApplicationDidEnterBackground observer is registered once by the
platform layer and calls loader::NotifyAppBackgrounded for every live
runtime, workers included, instead of only the main one.

A missing or unreadable file now throws the core's JsError ("Cannot find
module" / "Cannot read module"); an unreadable .mjs no longer aborts the
process.
Caches written before codeCacheDir are never read again. On the first
launch that finds no codeCacheDir, a utility-QoS task deletes them from
the top level of Caches and then creates codeCacheDir, so later launches
skip the sweep. Only regular files named like the old caches match:
<flattened path>.{js,mjs,cjs}.{cache,mcache}, plus the .XXXXXX
temporaries an interrupted write left behind. Caches is shared with the
app, so nothing is recursed into and nothing else is removed.
Takes the core fix for the code cache queue's quiet period, which was
computed in nanoseconds and posted as milliseconds, so an isolate whose
first creation task fired early never created another cache.
…s bundle id

A Mac Catalyst app outside the App Sandbox (the TestRunner Catalyst build
among them) gets the user's shared ~/Library/Caches. There codeCacheDir
is <Caches>/<bundle identifier>/NativeScript/CodeCache, the macOS
convention, and the one-time deletion of old caches is skipped: the top
level of the shared directory holds other apps' files. A sandboxed app's
container and iOS keep the per-app layout.
…nder its bundle id

AppCachesDirectory() resolves where the runtime keeps the app's cache
files: Caches, or Caches/<bundle identifier> on a Mac Catalyst app
outside the App Sandbox, whose Caches is the ~/Library/Caches every such
app shares. The code cache and ns-module-http-cache both go through it,
so two unsandboxed NativeScript apps no longer trim or clear each other's
HTTP module caches.
The pin brings the core's module identity unit (ns/loader/ModuleIdentity.h),
built into the RuntimeCommon target. platform::ParseUrl parses with the
runtime's own hidden-visibility ada, as the core's tests/AdaUrl.cpp does.
Adopts unit 6.1 of the shared loader core. Registry keys, script origins,
import.meta strings and the reading back of origins and file: URLs now come
from ns/loader/ModuleIdentity.h, configured in RefreshLoaderConfig with the
iOS legacy override: appRootOrigin file:///app (the app root below BaseDir),
legacyOrigins, the /app virtual file root, and /private/var aliased to /var.

- Paths are normalized lexically (CanonicalFilePath) instead of with
  stringByStandardizingPath, in both ModuleInternalCallbacks.mm and
  ModuleInternal.mm, so one file keeps one key. The app root is standardized
  once and spelled through the alias, and /private/var still keys as /var.
- file: URL keys are read through ada (FileUrlToPath) instead of NSURL.
- ModuleUrl loses ReportedModuleUrl, ModuleQuery, FileModulePath,
  HasUrlScheme and IsHttpRegistryKey; the Foundation NormalizePath and
  FileURLToPath copies are gone.
- import.meta is ImportMetaFor. Worker.mm and the inspector read origins
  back with OriginToPath instead of re-prefixing BaseDir; the inspector keeps
  a percent-decoded fallback for the URLs DevTools encodes, and still spells
  a rewritten source map URL the way the script's origin is spelled.

Origins, stack text, import.meta.url and import.meta.dirname of files under
the app root are unchanged. A classic script in the bundle but outside the
app root now has the origin file://<absolute path> (Q5); stack text, which
strips BaseDir, still reads as before. What JS can see:
- invalidateModules with an app file's file:///app/... URL (its
  import.meta.url) now invalidates that module (Q18).
- A file: URL with a host other than localhost, or with %2F, %5C or %00 in
  its path, names no module key (Q3).
- The core also maps app:/// URLs onto the app root, so invalidateModules
  with one now hits; this is not yet decided for iOS.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant