Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 95 additions & 4 deletions docs/ns-builtin-modules.md
Original file line number Diff line number Diff line change
Expand Up @@ -426,8 +426,8 @@ apply, worker teardown) belongs to whatever tooling drives it.

| export | description |
|---|---|
| `configureLoader(config)` | Installs loader policy for the calling isolate. Sections: `importMap` (`imports` + `scopes`), `volatilePatterns` (URL substrings always re-fetched), `canonicalization` (registry-keying vocabulary). Each **present** section replaces its state wholesale, an empty array included. Throws `TypeError` on any malformed input, having validated the whole config first, so a rejected call installs nothing. |
| `invalidateModules(urls)` | Evicts the given URLs (canonicalized) from the module registry and marks them bust-next-fetch, so the next network fetch bypasses every HTTP cache layer. Takes an array of strings; throws `TypeError` otherwise. |
| `configureLoader(config)` | Installs loader policy for the calling isolate. Sections: `importMap` (`imports` + `scopes`), `volatilePatterns` (URL substrings re-requested on every import instead of reused from the registry; see [HTTP caching](#http-caching)), `canonicalization` (registry-keying vocabulary). Each **present** section replaces its state wholesale, an empty array included. Throws `TypeError` on any malformed input, having validated the whole config first, so a rejected call installs nothing. |
| `invalidateModules(urls)` | Evicts the given URLs (canonicalized) from the module registry, so the next import of each requests it again. That request is an ordinary one: the server's caching headers decide whether a cache may answer it; see [HTTP caching](#http-caching). Takes an array of strings; throws `TypeError` otherwise. |
| `getLoadedModuleUrls()` | The URL-like keys currently in the module registry, as an array of strings (used to compute full-reload eviction sets). |
| `createRequire(filenameOrURL)` | A `require` resolving against `filenameOrURL`'s directory (a trailing slash names the directory itself). Accepts an absolute path string, a `file:` URL string, or a URL object; anything else throws `TypeError`, and an `http(s)` base is refused outright because `require()` of a dev-served module is not supported — import those. ES module graphs load under Node's `require(esm)` rule: a graph containing top-level await is refused before it evaluates. |
| `createPumpingRequire(filenameOrURL, options?)` | Same argument contract and same resolution, but an ES module graph with top-level await is evaluated by driving the loop until it settles, instead of being refused. **Callable only from a task context.** See [Pumping requires](#pumping-requires). |
Expand Down Expand Up @@ -515,8 +515,16 @@ otherwise, and `streamedCompileStats()`, which returns process-wide counts of
how HTTP module bodies large enough for a background compile were compiled
(`finalized`, `discarded` after another walk registered the same key first,
`fellBack` to the JS thread), the background compiles `running` now, and the
isolate teardowns that waited one out (`teardownWaits`); release builds omit
all three. Missing members are simply absent — never
isolate teardowns that waited one out (`teardownWaits`), and
`httpFetchDiagnostics(url)`, which returns how the loader would fetch `url`:
the active `transport` (`"okhttp"` or `"platform"`, see
[HTTP caching](#http-caching)), its `hostClass` (`"loopback"` or `"remote"`,
see [Fetch concurrency](#fetch-concurrency)) and that class's `concurrency`, and
throws `httpFetchDiagnostics expects a URL string` otherwise, and
`forcePlatformHttpTransport(force)`, which makes every isolate's later module
fetches use the platform transport even when the app ships OkHttp (`false`
undoes it) and throws `forcePlatformHttpTransport expects a boolean`
otherwise; release builds omit all five. Missing members are simply absent — never
present-but-throwing — so feature checks work. The module is registered in
every build: the security boundary for remote module loading sits at the
network layer (`security.allowRemoteModules` in nativescript.config, enforced
Expand Down Expand Up @@ -980,6 +988,89 @@ treats it as a network error for a module script rather than as an empty
module. The `<essence>` in the foreign-MIME message is the normalized essence,
not the raw header.

### HTTP caching

The loader fetches modules the way a browser fetches module scripts: the
request carries no cache directives of its own (no `Cache-Control`, no
`Pragma`), the URL is requested exactly as resolved, and connections are
persistent. Whether a stored response may answer a request is decided by the
**response** headers, so a dev server must send:

- `Cache-Control: no-cache` (ideally with an `ETag` or `Last-Modified`
validator, so an unchanged module costs a `304`) or `Cache-Control: no-store`
for source modules. Either guarantees that a module re-requested after
`invalidateModules` reflects what the server serves now.
- A long `max-age` with `immutable` only for content-addressed URLs (a hash in
the path or query).

A response with neither `Cache-Control` nor `Expires` but with a
`Last-Modified` header is heuristically cacheable under HTTP and **can** be
served stale wherever a cache is in play: send explicit cache headers instead.

`invalidateModules` and `volatilePatterns` act on the module registry only.
The request they cause is an ordinary one.

On Android, which of the two transports fetches modules depends on whether the
app ships OkHttp (`com.squareup.okhttp3:okhttp`, 3.x to 5.x):

| | OkHttp in the app | no OkHttp |
|---|---|---|
| client | a dedicated `OkHttpClient`, never one the app configured | `HttpURLConnection` |
| HTTP cache | its own, on disk: `ns-module-http-cache` in the app's cache directory, 256 MB | none: a `ResponseCache` the app installs is neither read nor written, and every request reaches the origin |

Both send the same request headers, follow redirects within the same
protocol, apply the same timeouts and fetch deadline, pass the same security
gate and classify responses the same way. Besides caching, these differences
remain:

- Process-wide `java.net` defaults reach only `HttpURLConnection`: a default
`CookieHandler`, `Authenticator`, and
`HttpsURLConnection.setDefaultSSLSocketFactory` /
`setDefaultHostnameVerifier`. The loader's OkHttp client uses none of them,
so an https dev server trusted only through those defaults loads modules
over `HttpURLConnection` but not over OkHttp.
- The platform connection pool keeps only a few idle connections, so after a
burst of fetches fewer of them are reused than with OkHttp.
- OkHttp negotiates HTTP/2 with https servers that offer it, and then runs
concurrent fetches as streams on one connection.
The OkHttp cache can answer a fresh response without a request, even after an
app restart, and revalidates a stored response with its validator. The
synchronous fallback fetch uses the same transport as the graph walk.

### Fetch concurrency

The module-graph walk fetches modules concurrently, up to a cap shared by
every isolate in the process. The cap depends on the module URL's host:

| host class | hosts | default |
|---|---|---|
| `loopback` | `127.0.0.1`, `[::1]`, `localhost`, and the emulator host aliases `10.0.2.2` (Android Emulator) and `10.0.3.2` (Genymotion) | 6 |
| `remote` | any other | 32 |

A loopback host on a device or emulator is almost always an `adb reverse`
tunnel (the Vite plugin sets one up for both), and adbd's listener overflows
when too many connections open at once; each overflow costs the client about
a second of SYN retry. The emulator host aliases go through the emulator's
NAT, which loads large graphs faster with few connections. A remote host is bound by its round trip instead, so
more fetches in flight load a graph faster. Fetches over the cap wait in a
queue for their class, and that wait counts against the graph walk's fetch
deadline.

An app can override either value in its app config:

```json
{
"android": {
"moduleFetchConcurrency": { "loopback": 6, "remote": 32 }
}
}
```

Both keys are optional. Each must be a positive integer; a larger value than
64 is clamped to 64. Anything else (a non-object `moduleFetchConcurrency`, a
non-integer, zero or a negative number) logs a warning and keeps the default.
The values are read once, at the first module fetch.

### App entries and bootstraps

An app's entry can be either CommonJS or an ES module, and the choice decides
Expand Down
3 changes: 2 additions & 1 deletion test-app/app/src/main/assets/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
"suppressCallJSMethodExceptions": false,
"enableLineBreakpoints": false,
"enableMultithreadedJavascript": true,
"interfaceProxies": false
"interfaceProxies": false,
"moduleFetchConcurrency": { "remote": 24 }
},
"discardUncaughtJsExceptions": false,
"security": {
Expand Down
Loading
Loading