Repository navigation
feat(vite)!: thin dev mode, the device as a standard Vite client - #11650
Open
edusperoni wants to merge 54 commits into
Open
edusperoni wants to merge 54 commits into
edusperoni wants to merge 54 commits into
Conversation
Thin mode (NS_VITE_THIN=1) serves device modules straight from Vite's client environment under /ns/v, with a /@vite/client shim, instead of the /ns/m rewrite pipeline. Bare imports resolve through the client plugin container (resolver ids verbatim, never realpath'd), so each file has one URL and one module instance; core self-registers into __NS_CORE_MODULES__ through a footer. One URL per file in the /ns/m pipeline too: - drop the raw explicit-.js fastpath, which served node_modules files under a second URL (duplicate rxjs instances) - route /@fs URLs outside both roots through /ns/m Relay Vite's css-update payloads to /ns-hmr clients. Once a component loads an external runtime style, Analog answers later stylesheet edits with a stock Vite update instead of angular:component-update; the device client fires vite:beforeUpdate/vite:afterUpdate for it like Vite's client, and the hot registry gets on/off for app-lifetime listeners (e.g. a framework renderer that owns the stylesheets). The session bootstrap exposes the dev origin as __NS_DEV_ORIGIN__.
Tooling behind the thin-mode experiment: URL crawl/duplicate detectors, an HMR message probe, a CDP console/eval recorder for ns debug, a fixture repack script, the Angular 22 fixture app and FINDINGS.md (rounds 1-9). Not meant to merge as-is.
3 of 5 tasks
|
View your CI Pipeline Execution ↗ for commit 5dc6baa
💡 With Ultracache enabled, Nx Cloud learns each task's file inputs in CI and uses them on later runs. Turn on Ultracache in workspace settings ↗ · Read docs ↗ ☁️ Nx Cloud last updated this comment at |
commit: |
The server builds the eviction set and the entry to re-import in the device's URL space (/ns/v<vite-url> in thin mode) and sends entryUrl in ns:angular-update; the device no longer derives /ns/m URLs for it. Full-reload eviction recognises /ns/v app modules, and the leaf fallback re-imports evicted URLs untagged.
legacy-vite.sh exports and builds a ref's packages/vite (default origin/main) into an untracked folder; refresh-fixture-packages.sh vite-legacy installs it into the fixture.
Device modules are always Vite's client-environment output under /ns/v; NS_VITE_THIN is gone. Delete everything only the /ns/m pipeline reached: - /ns/m routes, import rewriting, device transforms and AST helpers - /ns/core (bridge + core bundle), /ns/rt, /ns/entry and startEntry, /ns/node, /ns/txn, the vendor unifier and the shared transform cache - the Vue /ns/sfc and /ns/asm routes - the Angular register-only entry rewrite, /@ng/component boot gate and component-update ledger The framework strategy interface loses the members only /ns/m called, and importMapEntries(origin) becomes importMapSpecifiers(). BREAKING CHANGE: the legacy dev pipeline and the removed framework strategy members are gone. Vue, Solid, React and TypeScript device updates and worker HMR still rely on /ns/m URLs and are degraded until the Vite-client update path lands.
The device joins Vite's own HMR WebSocket (vite-hmr subprotocol, token from the dev session) and runs a port of Vite's browser client: a serialized queue with awaited listeners, js-update/css-update, full-reload, prune, error and hot.invalidate -> vite:invalidate. Hot contexts are keyed by the exact Vite URL, and Vite's ?t= stamps are part of module identity under /ns/v, so an updated module is a fresh instance as in a browser. A full reload disposes and evicts the app's modules and re-imports the entry in-process; import.meta.hot.data survives it. Frameworks' own Vite plugins decide updates. The NS update protocol is gone: /ns-hmr and its relay, ns:hmr-delta/full-graph, ns:angular-update and the Angular reboot, the Vue SFC registry, the module graph and every framework server strategy's update path. Only app CSS stays NS-specific, as the ns:css-updates custom event. Angular follows Angular CLI's rules: template and style edits update in place; a .ts save that changes more than template/styles, a root component update and angular:invalidate become a full-reload. The /@ng/component gate answers boot-time metadata fetches with a no-op so a reload never replays a stale update (which tore down the root page-router-outlet). Device code shares state through ESM modules instead of __NS_* globals (the hot registry, dev origin and client strategy globals are gone). BREAKING CHANGE: the framework strategy API shrinks to flavor, importMapSpecifiers, volatilePatterns and preserveQueryPaths; runHotUpdatePrologue, NsHotUpdateContext, __NS_HMR_ON_UPDATE__ and the ./hmr/client/framework and hot-context exports are removed.
Some changes can't be applied in-process, so the dev server asks the CLI
to restart the app instead: an edit to code the device never re-evaluates
(node_modules, linked core, the dev client), a Vite server restart, a
module that called import.meta.hot.decline(), or a full reload whose
teardown threw. requestAppRestart(reason) sends
{ type: 'nativescript:restart', reason } over the vite serve IPC channel;
without one it logs the reason and the device shows a persistent
"Restart required" overlay instead of soft-reloading. The device asks via
the ns:restart custom event. Under HMR the watch build now notifies the
CLI only when bundle.mjs actually changed, which restarts the app through
the existing livesync path.
The device's socket URL stays valid across Vite server restarts: the
WebSocket token is pinned for the process. A disconnect only reconnects.
App CSS updates carry the stylesheet text, so the dev client makes no
HTTP requests through the app's (zone-patched) globals.
Merged
4 of 5 tasks
The app entry becomes self-accepting (injected per flavor; Angular for now), so any edit below it propagates to a js-update on the entry and only the changed import chain re-runs, under fresh ?t= URLs; unchanged modules keep their instances. The framework's entry dispose tears the app down and its settle hook reports the re-bootstrap. A Vite full-reload now means an app restart; the in-process evict-everything reload is gone and import.meta.hot.data follows Vite's semantics again. Angular class-body and root-component edits propagate to the entry instead of becoming full-reloads (Analog's self-accept marking is undone for those saves); template and style edits still update in place. Before an update the server sends ns:rerun with the exact set of modules that will re-evaluate. The device dispatches, in order: nativescript:beforeReboot to all listeners, nativescript:beforeRerun only to modules being re-evaluated (before any dispose), the entry dispose, the entry import, nativescript:afterReboot once the framework settled, and nativescript:beforeRestart before a restart request. Payloads expose isRerun/isChanged/modules lookups that accept import.meta.url, Vite URLs or file paths. @nativescript/vite/client types these events. BREAKING CHANGE: Vite full-reload restarts the app instead of re-evaluating it in place.
Before an update reaches the device, the server transforms every module it will re-evaluate (and, for an accepted template, the components that import it). If one fails, the update is withheld and Vite's error payload is sent instead, so the running app is untouched; the next successful update covers everything changed since the last one that applied. Angular templates are checked through the app's own compiler, since a broken template doesn't make Analog's transform throw, and component updates are held behind the same gate. When new code throws while loading or bootstrapping, the app stays alive on the error overlay and the next update retries: failed modules in the update's chain are evicted so the retry re-evaluates them, and a retry that fails again outside the chain restarts the app. A rejecting or throwing teardown still restarts. The error overlay (iOS, Android, in-tree) shows the root-relative location, message and code frame, and has a "Restart app" action. The server records when it served each module; when a device connects and something it was served has since changed, it sends one catch-up soft reboot.
config.define is the only source of defines: bundled code gets them by
substitution and served modules through Vite's own /@vite/env, which the
boot bundle imports first. The separate defines-seed module, its seed
values and the rule that kept two copies in agreement are gone, as are the
__NS_TARGET_FLAVOR__/__NS_APP_ROOT_* defines nothing reads.
State shared between the separately built boot bundle and served modules
lives on one typed object, globalThis[Symbol.for('nativescript.dev')]
(bootComplete, appCss/appCssAst, knownApplications, overlay, httpOrigin,
coreModules, cjsShape). Globals used on only one side of that boundary
became module state, and dead or write-only globals are deleted. Building
the HMR boot bundle now fails if no device-reachable origin resolves
instead of silently dropping the env import.
The device now loads modules exactly like a browser: <origin><vite-url>,
served by Vite's own middleware. The /ns/v prefix, the thin route and
its specifier rewriting are gone, and every NativeScript endpoint lives
under /__ns_dev__ (session, client, import map, deps bundle). No /ns/*
route remains.
- /@vite/client resolves to the device client through a pre resolveId
on Vite's aliased client id.
- One middleware ahead of Vite's own strips the runtime's
__ns_dev_nonce, records served modules for the boot catch-up, and
makes literal dynamic import('/...') absolute in responses: current
NativeScript runtimes resolve a root-relative dynamic import on the
filesystem. It runs at response time so Vite's soft invalidation can
keep ?t= current.
- server.fs.allow covers @nativescript/core and @nativescript/vite;
import-map targets are registered as safe module paths and must be
files; NS_HMR_HOST hostnames are allowed hosts.
- The @nativescript/core registration footer is a serve-only transform.
- Deps-bundle core subpath imports get exact import-map keys.
- Angular template and style saves are linked to their component before
Analog handles them, so an edit to a component that isn't transformed
yet (after a restart, or an unvisited lazy route) still recompiles it.
- A served module only counts as missed by a device when something
compiled into it was edited after it was served.
Removed: the /ns/core bridge and module-specifier code, the unwired boot
recorder, the empty-body guard and the spike tools that drove /ns/*.
BREAKING CHANGE: only Vite base '/' is supported on device for now.
The esbuild deps bundle (vendor.mjs), vendor-bootstrap, the vendor
manifest/registry and their globals are gone. Dependencies are served as
transformed node_modules files through Vite like any other module, so
every file has exactly one instance: the deps bundle inlined
@valor/nativescript-websockets and zone.js (and imagepicker on the
toolbox) while the same files were also served.
Vite's optimizer is off by default under HMR. Discovery mode reorders the
graph mid-session (Angular re-optimized on first boot, a full-reload)
and its ?v= stamps gave core a second URL in apps with core installed in
node_modules. CommonJS packages go through Vite's standard
optimizeDeps.include, kept to the app's and flavor's own includes, and
?v= is stripped for @nativescript/core and @nativescript/vite.
The import map shrinks to what runtime bare resolution can still need
(@nativescript/core, the app's dependencies, framework specifiers, node:
builtins): Vite rewrites every bare import in served code. Consumers of
the vendor registry reach core through the bundle's require shim or ESM
imports. The Android SBG never read the vendor stub, so it is removed.
BREAKING CHANGE: a runtime require('pkg') of an npm package from served
code no longer resolves unless the package is pre-bundled through
optimizeDeps.include; the flavor `vendor` option and the vendor-bootstrap
export are removed.
… HMR TypeScript and JavaScript apps get an entry boundary: the dispose closes modals and turns the re-run entry's Application.run into resetRootView, and the settle hook resolves once the new root view loads. In dev the bundler context (page XML, code-behind, registered modules) is a served virtual module imported by the entry instead of being baked into the boot bundle, so XML, code-behind and util edits reach the entry and soft-reboot instead of restarting the app. Re-running the context unregisters its names first so edited XML replaces the old registration. The global app.css is a normal CSS import of the entry in every flavor: Vite serves it as CSS-as-JS, edits are self-accepting js-updates applied in place (and covered by the compile check), and updateStyle restyles the root view and modals. The virtual app-css module, ns:css-updates, connect-sync and the app-css state/refresh/handler code are gone; release builds keep their bundled stylesheet. Workers keep Vite's ?worker_file URL on the dev origin, so the worker realm gets /@vite/env before core. Workers are owned by the module that created them and terminated when it re-runs or is pruned; edits to worker code restart the app. Also: @nativescript/vite/client keeps its vite/client reference in the emitted types (preserve="true") so import.meta.hot is typed, and the dev client logs with console.log since NativeScript's console has no debug.
…v type check
Vue component HMR is plugin-vue's own (template rerender keeps state,
script reload, scoped styles in place); edits that reach the app entry
without passing through an SFC soft-reboot through a new Vue entry
boundary, which reuses the core teardown and unmounts the replaced app
once the new root is up. The dead named-imports interop plugin and the
Babel packages only it used are removed.
Under HMR the boot bundle's require shim no longer turns a failed
require() into {}: a miss throws with the runtime's error as cause and
says how to fix it (optimizeDeps.include, or import it as ESM). Node
builtins and require.context keep their stubs; release behaviour is
unchanged.
With HMR active the dev type check only warns, so a type error no longer
stops the watch build from emitting bundle.mjs. NS_VITE_TYPECHECK, the
typeCheck option and --env.typecheck still override it.
Solid and React are unchanged; their findings are recorded in DESIGN.md.
Under HMR the boot bundle only imports Vite's /@vite/env and a served virtual boot module that holds the old boot imports as bare specifiers, and the client bootstrap is a served virtual module too. Vite's own import analysis therefore writes every @nativescript/core and @nativescript/vite URL the device loads, ?v= included once an optimizer exists, so core keeps one identity without NativeScript re-deriving URLs. bundle.mjs drops from ~1 MB to under 1 KB. Removed: the boot bundle's global require shim (release too; Rollup already converts CommonJS at build time), the core registration footer and its coreModules/cjsShape globals, and the ?v= strip for core. Runtime-builtin imports (ns:*) are kept as bare specifiers in served responses, ns:module is loaded through a dynamic import, the dev overlay imports core as ESM, and the dominative two-phase boot falls back to resetRootView as release does. BREAKING CHANGE: the boot bundle no longer installs a global require shim; a require() of an unknown module now throws the runtime's error.
…obal require Dev mode turns Vite's dependency optimizer back on. Discovery scans the app's real sources plus the core and runtime files the boot module imports, so core's own third-party deps (tslib, css-tree, ...) are pre-bundled once for every importer. Core, @nativescript/vite, linked packages and platform-main packages stay excluded and are served as source; a Rolldown plugin turns require() of an excluded package inside a pre-bundle into an ESM import. The boot module's bare imports and the import map's package keys are included up front, so the Angular compiler's late imports no longer trigger a re-optimize. Angular packages are linked inside the optimizer and the serve-time linker skips pre-bundles. nsOptimizeDepsPolicyPlugin is removed. Served modules no longer reach a global require. A serve-only transform gives a module with a free require / __non_webpack_require__ its own require: literal specifiers are hoisted to imports that Vite resolves, builtins and files on disk go to the runtime's createRequire, and anything else throws naming the module. NS_VITE_STRICT_REQUIRE=1 makes the dev boot replace the runtime's global require with one that throws when called. Editing a file inside a pre-bundled installed dependency restarts the dev server with forced re-optimization, then restarts the app. Release output is byte-identical. Cold device requests drop from 707 to 332 (Angular), 481 to 327 (Vue) and 566 to 430 (toolbox). BREAKING CHANGE: in dev, require() of a module that is not a literal, resolvable specifier, a runtime builtin or a file on disk now throws. Import it, or use createRequire from ns:module.
…chNodeModules Like webpack, dev mode no longer watches node_modules by default. With --env.watchNodeModules, an edit to a pre-bundled dependency's source still restarts the dev server with forced re-optimization and then the app.
The flag only adds server.watch.ignored negations for the app's direct dependencies (plus the node_modules and scope directories, which chokidar must enter outside macOS FSEvents), so the same behaviour is available to anyone writing those globs in their own Vite config. The plugins react to whatever Vite's watcher reports. An edit to a package served from node_modules propagates like app code, unless its update would re-evaluate a pre-bundle or @nativescript/core / @nativescript/vite, which restarts the app. An edit to a source file of a current pre-bundle restarts the dev server with forced re-optimization and then the app; the separate fs.watch layer is removed. create events for files the watcher never walked are handled like updates.
The dev bundle.mjs is a small bundled loader with no static HTTP import: it imports /@vite/env (with a reachability timeout) and awaits the served boot module, and the app's own Application.run launches the app, as in release. The placeholder root, the patched first-boot run(), the launch bridge, the boot heartbeat and progress UI, the JSON session and import map routes, setDevBootComplete and the placeholder globals are removed, including core's placeholder branch in iOSApplication.run(). When the dev server is unreachable or the boot fails before the app launched, the loader launches a minimal UIKit screen of its own: an alert that restarts the app once the server answers again, or a card with the boot error and the server's transform error that restarts the app on the next saved edit. Its window attaches to every window scene, so a scene session restored with core's delegate shows it too. The session and import map load as modules, in parallel. The boot graph is pre-transformed at server start, and the HMR build's first CLI notification waits until it is idle. Error payloads are not buffered while no device is connected. The verbose flag resolves from the CLI flags when first read without them. NS_VITE_PREBUNDLE_CORE=1 pre-bundles an installed (not linked) core: about 80 boot requests instead of about 320, one core instance. BREAKING CHANGE: dev mode no longer shows a placeholder root while the app loads; the launch screen stays until the app's run().
…utes, core pre-bundled by default When the dev server comes back while the fallback screen polls for it, the server answers 409 instead of restarting the app if the CLI spawned it, it is the process's first server start, and the polling process is older than the server: the CLI's own launch after its first build replaces that process, so the app boots once. Every other case still restarts. The flag that owes the next connection an app restart after a server restart is cleared by any restart request that reaches the CLI. /__ns_dev__/restart and /__ns_dev__/boot-failed require the dev server's WebSocket token. The token is created once per project in node_modules/.ns-vite/dev-ws-token, pinned as Vite's webSocketToken and baked into bundle.mjs, since the HMR build and vite serve run as separate processes. An installed @nativescript/core is pre-bundled by Vite's optimizer by default (NS_VITE_PREBUNDLE_CORE=0 opts out); a linked core is still served as source. On an iPhone 11 Pro over Wi-Fi this takes boot from about 320 to about 80 requests and saves 0.5-0.75 s.
The dev server keeps Vite's own WebSocket token for each `vite serve` process (an in-process restart keeps it) and publishes it, mode 0600, under the OS temp dir keyed by project root and port, outside the project and fs.allow, so the dev server can no longer serve it. Under the CLI the HMR build waits for the dev server to listen before reading it, so bundle.mjs carries the current session's token; a fallback process from an older session gets 403 until the CLI's launch replaces it. The spike fixtures pin Vite 8.3.8 so ns run and the crawls use one copy.
A served module whose dynamic imports were rewritten to absolute URLs carries the origin in its body, while Vite's ETag and `immutable` describe the origin-independent original. The device caches responses across launches and the origin can change (LAN address, USB tunnel), so such a response gets an ETag suffixed with an origin tag and loses `immutable` (no-cache). If-None-Match validators issued for the current origin are mapped back to Vite's ETags, so 304s keep working; those from another origin never match. The /__ns_dev__/* routes answer no-store: the session carries the per-session WebSocket token.
Vite marks every `?v=` URL `max-age=31536000,immutable`, but only a dependency pre-bundle's bytes are tied to that hash. A file of a package excluded from pre-bundling (served as source) can change on disk under the same `?v=`: a hand edit, patch-package, a freshly built linked package. With the device's HTTP cache persisting across launches, it would keep running the old body. Such JavaScript responses are sent with `no-cache` (ETag kept, so unchanged files still revalidate as 304); pre-bundles stay immutable.
An update the compile gate withheld while a file was broken was never sent, so an edit made during the broken window could miss the device once the error was fixed. The first update that passes after a withheld one now goes out as a single entry soft reboot covering every edit since the last update that went out (an app restart for flavors without an entry boundary); the modules those edits touched are re-stamped first. A bare import nothing resolves no longer aborts the optimizer's dependency scan for the whole session: the scan treats it as external and warns once. The entry boundary returns a source map, so lines in the app entry stay aligned. configuration/base.ts and helpers/main-entry.ts resolve project paths on first use, so the package can be imported outside an app directory (`nx run vite:test` from the workspace root).
…spike files Removed the unused @babel/plugin-transform-typescript, @babel/plugin-transform-unicode-property-regex, @jridgewell/sourcemap-codec and @rollup/plugin-commonjs dependencies, the ./solid-bootstrap export with its unused source, and the ./hmr/shared/runtime/dev-overlay export. The __NS_DEV_TELEMETRY__ / __NS_TELEMETRY__ counters and __NS_HMR_IMPORT__ are gone; the overlay position lives on the namespaced dev object (setHmrDevOverlayPosition). The toolbox's phase-spike files are removed; the client type coverage they gave lives in client-types.spec.ts. BREAKING CHANGE: the ./solid-bootstrap and ./hmr/shared/runtime/dev-overlay subpath exports are removed, and globalThis.__NS_HMR_OVERLAY_POSITION__ is no longer read.
After withheld saves, the passing update goes out unchanged when every withheld save edited only stylesheets that the update re-sends whole (a self-accepting stylesheet update, a css-update, or a partial imported only into re-sent sheets). Anything else, a Vue <style> block, an Angular template or a script, still turns into the entry soft reboot; a save older than the gate's record fails closed.
…ENV at load `vite build` sets NODE_ENV to production before it loads the config, so a module-level NODE_ENV check put the HMR watch build on the no-HMR path (no code splitting), which fails as soon as a second input such as an Android app component exists. HMR is now derived from the config's mode and --env.hmr.
…k screen Under HMR on Android the dev boot module statically imports the served app components and core's NativeScriptActivity ahead of the app entry. The runtime holds Application.onCreate until bundle.mjs settles, and a named proxy is generated at runtime under its exact name and injected into the app's PathClassLoader, so the launcher activity exists before Android instantiates it, with no static-binding-generator file on disk. Only a custom Application class, created before any JavaScript runs, is still built to disk. The raw core URLs those built components used to import (a second core instance) are gone with nsCoreExternalUrlsPlugin. When the boot fails or the dev server is unreachable, the Android dev loader shows a minimal fallback activity instead of crashing, reports boot-failed and polls restart through the runtime's module loader (the routes answer as a module with ?module=1), and probes the server port before fetching so an unreachable host doesn't hold app startup into an ANR.
4 of 5 tasks
Android joins iOS and visionOS in single-process dev. The one artifact Android still needs on disk, a custom Application app component (created before any JavaScript runs, so the static binding generator must see it), is built by the dev server itself: a one-off Vite build of the app's own config with the Application as the only input, kept in memory and written through the dev output writer. It is rebuilt when one of its modules changes, and the sync restarts the app; a failed rebuild keeps the last good chunk. The first sync waits for it, since the CLI's native build runs on that message. In single-process mode the serve process drops the build-only CLI notification plugin, the static copy and the type-check plugins, which would otherwise send a second initial message or block the server.
The custom Application chunk runs from disk before any served code, so its modules are once-per-process on Android, like core. An edit to any of them (including a util the served app also imports) sends no hot update or soft reboot: the chunk is rebuilt, synced, and the CLI restarts the app so the new process evaluates the new chunk. Its sources come from the build's module graph, so a re-export barrel or an import that renders no code still triggers the rebuild. When a rebuild changes nothing on disk but a served module of an edited file exists, the server requests the app restart itself.
The dev server bound `0.0.0.0`, which on macOS refuses IPv6, so an iPhone over the USB CoreDevice tunnel (host side `fdXX::2`) could not connect. It now uses `server.host: true`: Node listens on dual-stack `::` and falls back to `0.0.0.0` where IPv6 can't bind. `NS_HMR_HOST` no longer sets the listen address, so pointing devices at the tunnel address keeps Wi-Fi devices, simulators and emulators working in the same session. An explicit `server.host` still wins over the default. A bare IPv6 device host (`NS_HMR_HOST=fd00::2` or `server.host: 'fd00::2'`) is emitted bracketed: `http://[fd00::2]:5173`.
4 of 5 tasks
2.0.4 brackets an IPv6 host in the iOS WebSocket handshake, so the HMR socket connects when the dev host is an IPv6 address (the CoreDevice USB tunnel).
3.0.1 applies a template edit in place after a non-component .ts save (analogjs/analog#2817) and a component stylesheet edit in place (analogjs/analog#2857). Analog 2.x and 3.0.0 each lack at least one of them. The experimental.useAngularCompilationAPI and externalRuntimeStyles options are gone: neither exists in Analog 3, whose default compiler is the one already used. BREAKING CHANGE: Angular apps need @analogjs/vite-plugin-angular ^3.0.1.
The runtimes resolve relative and root-relative specifiers of a module loaded over HTTP against that module's URL, static and dynamic, with the query kept (NativeScript/ios#586; Android 9.1.x). The dev server no longer writes its origin into served modules, so their bodies, ETags and cache headers no longer depend on it, and non-literal relative imports work. Runtime builtins are still restored in responses. The HMR client's own update import stays absolute: Vite's import analysis wraps it in injectQuery, which would add `import` to a root-relative URL and change the module's identity. BREAKING CHANGE: on iOS and visionOS, lazy imports under Vite HMR need a runtime with NativeScript/ios#586.
NativeScript/ios#585 removes `__ns_dev_nonce` from module requests. A runtime that still adds it does so only when it re-fetches a module evicted after a failed soft reboot; later edits of that file then restart the app instead of updating in place, until the dev server restarts.
Vite serves pre-bundles (`?v=<hash>`) as `immutable`, but derives the persisted hash from the lockfile, the config and the dependency ids, not from the bundled code. With the runtimes' HTTP cache (NativeScript/ios#585, the Android OkHttp transport), a warm start after a rebuild from scratch reused the old hash, and the device kept running its cached copy of a hand-edited or watched dependency without any request. A generation id kept in Vite's cacheDir is part of a plugin name, and so of Vite's config hash. It changes on each rebuild from scratch (`--force`, the pre-bundle watcher's restart, a deleted deps cache) and is reused otherwise, so normal starts keep their URLs and their cache.
An app's iOS and Android dev servers run at the same time (one `ns run` per platform, or one for several devices), and both used Vite's default `node_modules/.vite`. Their pre-bundles resolve platform files, so each server's start deleted and rebuilt the other's, and a server could serve the other platform's code for a dependency it had not loaded yet, under its own immutable `?v=` URL. `baseConfig` now sets `cacheDir` to `node_modules/.vite/<platform>`; an app's own `cacheDir` still wins.
edusperoni
marked this pull request as ready for review
December 4, 2026 02:01
Release builds split node_modules into a `vendor.mjs` chunk through `manualChunks`. Drop it and let Rolldown's default chunking produce `bundle.mjs` plus the lazy chunks: - Rolldown 1.2 deprecates `manualChunks` and maps it to a codeSplitting group with `includeDependenciesRecursively: true`, so the rule that kept @nativescript/core in the main bundle did not hold: in a Vue app 229 of 230 core modules landed in vendor.mjs, pulled in through nativescript-vue. - vendor.mjs is an ES chunk that bundle.mjs imports, so it evaluated before bundle.mjs's own body. Vue's runtime ran before the XHR polyfill and bundle-entry-points; in Angular apps rxjs, css-tree and core-aliases-early ran before the polyfill and the core globals. - It moved dependencies only lazy routes use into the boot chunk. - The Angular-linker reason no longer applies: Analog links partial declarations at transform time, and the unlinked-partials guard checks before chunking. Total output size is unchanged. The CLI build message no longer lists a vendor file among the chunk files, and the Angular non-HMR development override has no `manualChunks` left to delete.
`process.env.NODE_ENV` was replaced three times: the global `define` (from the mode), `@rollup/plugin-replace` and the dev optimizer's `define` (both from the mode or the DEBUG env). Drop the replace plugin and derive the optimizer's value from the mode as well. Only Vue reads NODE_ENV (in @vue/shared, reactivity and runtime-core), and a device has no global `process`, so any read left behind throws. Vite 8 already replaces it in served modules and release builds, and release output is byte-identical without the replace plugin. The global `define` stays: Vite derives NODE_ENV from the host environment, so without it `vite build --mode development` (the CLI's debug builds) would ship Vue's production build. The optimizer's entry stays for the same reason: pre-bundles ignore the config's `define`, and a host NODE_ENV would otherwise leak into them. Behaviour change: a release build with DEBUG set no longer ships Vue's development build; NODE_ENV follows the mode, as webpack's `optimization.nodeEnv` does. Removes the @rollup/plugin-replace dependency.
…platform nativescript-theme-core 1.x ships `core.light.ios.css` and `core.light.android.css` but no `core.light.css`. The aliases that map the generic name to the platform file came after the package's catch-all alias, so they never applied. Imports only worked because a build-start plugin wrote symlinks into node_modules: a `nativescript-theme-core` link into every app's node_modules, even apps without the dependency, and generic `.css` links in the shared hoisted package pointing at whichever platform built first. An Android release build could ship the iOS theme. Put the platform aliases ahead of the catch-all and delete the symlink plugin, the CSS load fallback (it never ran once the files existed) and the theme branch of the postcss-import resolver.
Vite 8.3 adds the top-level `tsconfig` option, which picks the file `resolve.tsconfigPaths` reads for every module. Without it Vite reads the nearest `tsconfig.json`, so `paths` that live only in `tsconfig.app.json` or `jsconfig.json` do not resolve. Raise the dependency, the workspace's devDependency and its override to `^8.3.0`; the workspace now installs Vite 8.4.1 with Rolldown 1.3.4.
Replace our tsconfig `paths` resolver with `resolve.tsconfigPaths` and the top-level `tsconfig` option, set to the first of tsconfig.app.json, tsconfig.json and jsconfig.json, the file the paths were read from before. Worker bundles use Vite's resolver too, so their own copy of the plugin goes as well. Vite resolves platform-suffixed targets (`x.ios.ts`), directories with an `index.ios.ts` and aliases outside the app the same way, and follows TypeScript where ours did not: - `extends` of a package config (`@org/tsconfig/base.json`) was ignored, so its paths never applied; - `paths` were merged across `extends`, while TypeScript replaces them; - only the first target of each alias was tried. Vite resolves `paths` inside `vite:resolve`, after every `pre` plugin, where ours ran ahead of the two package resolvers. Both now leave alone any specifier a `paths` pattern matches (they only skipped exact keys, and nativescript-package-resolver nothing), so an alias named after an installed package with a platform `main` still reaches the alias target. A catch-all `"*"` pattern is not treated as a match. `getTsConfigAliasRoots`, which nothing called, goes with the resolver.
Older NativeScript templates map `"*": ["./node_modules/*"]` in compilerOptions.paths. Vite's tsconfig resolver applies it to every bare import, so a package with an `exports` map resolves to its `require` entry instead of its `import` one, with no error. Warn once when the project's tsconfig has such an entry and tell the user to remove it.
…names The dev server guessed one origin for every device of a platform (LAN address, 10.0.2.2, adb reverse or NS_HMR_HOST) and baked it, with the WebSocket token, into bundle.mjs and into every URL it served. Devices that reach the Mac differently (a simulator on loopback, a phone over its USB tunnel, an emulator through adb reverse) could not share one dev server, and a wrong guess left the app on the "unreachable" screen. The NativeScript CLI now decides the origin per device and writes it, with the token, into a dev-server.json next to bundle.mjs. This package declares that it reads the file (`nativescriptCli.devServerFile` in package.json), so the CLI only takes that path for versions that do: - bundle.mjs carries neither origin nor token. It imports ./dev-server.json, boots from the origin it names, verbatim, and shows a "waiting for ns run" screen when the file is missing. - The served dev boot module exports bootDevSession(), which bundle.mjs calls with the file's origin and token. - The session descriptor and the import map are origin-free: the device builds absolute URLs, the HMR WebSocket URL and the import map's values and scope keys from its own origin before configureLoader. A file importer such as bundle.mjs would resolve a root-relative map value on disk. - The dev client bootstrap exports startDevClient(), which the session bootstrap calls with the origin, so the HMR client keeps absolute update URLs. - The dev server pins its WebSocket token to NS_HMR_TOKEN, which the CLI generates per platform dev server. - The HMR `vite build` path that only older CLIs run writes the same origin-free bundle.mjs, without resolving an origin or reading a token file.
Each device now boots from the origin the NativeScript CLI writes into its dev-server.json, and nothing in this package computes a device origin or hands the WebSocket token over a file anymore. Removed with their specs: - helpers/dev-host.ts: the origin resolution (resolveDeviceReachableOrigin and resolveDeviceReachableHost), the LAN address guess, the 10.0.2.2 fallback and Vite's own `adb reverse`. This package no longer reads NS_HMR_PREFER_LAN_HOST, NS_ADB_REVERSE_READY, NS_DEVICE_SERIAL, NS_ADB_PATH or NS_HMR_NO_ADB_REVERSE. NS_HMR_HOST stays for the host check (allowDeviceHost). - hmr/server/server-origin.ts (getServerOrigin). - helpers/dev-ws-token.ts, the token file the dev server published for the HMR build, and waitForDevServerListening, which only that build's token read used. The README describes the per-device dev-server.json instead of the removed variables.
2.0.3 sends an IPv6 host unbracketed in the iOS WebSocket handshake, so Vite rejects the HMR upgrade from a device on the USB tunnel origin (http://[fdXX::2]:5173): the app loads its modules but gets no hot updates.
9.1.0-alpha.6 has no ns:module builtin, which @nativescript/vite's dev boot imports, so the toolbox failed to boot under Vite with "Module 'ns:module' is not available".
Contributor
|
@edusperoni I pushed two dependency bumps here. I hit both while running the toolbox on Vite on a physical iPhone and a Pixel 9 for the CLI side (nativescript-cli #6209 and #6210, both merged). If you'd rather pin differently, say so and I'll change them.
Device runs with these two changes, toolbox on Vite, this branch's
|
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
PR Checklist
What is the current behavior?
Dev mode re-implements a lot of Vite on top of Vite, and has its own protocol for the device:
/ns/mrewrite pipeline and/ns/*routes, with their own resolution, URL canonicalization and hot-context injection. The same file can be served under several URLs, which gives duplicate module instances:@nativescript/corethrough the/ns/corebridge plus two/ns/mspellings, and rxjs with and without its extension.css-update) never reach the device.requireshim that turned unknown modules into{}.Application.run, and scattered__NS_*/global.__xglobals.What is the new behavior?
packages/vite: 436 files changed, +16.1k / −66.8k lines across 52 commits. The phase log is below.Device side:
?t=is part of module identity./__ns_dev__.Reload model:
nativescript:beforeReboot/beforeRerun/afterReboot/beforeRestartevents for libraries.@nativescript/vite, Android's customApplication), restarts the app through CLI IPC.Dependencies:
requireand never the global one. A strict shadow of the globalrequireis on by default (NS_VITE_STRICT_REQUIRE=0turns it off).--env.watchNodeModulesonly adds standardserver.watch.ignorednegations.Boot:
bundle.mjsis a small loader, and the app's ownrun()launches.adb reverseor on a simulator,10.0.2.2from an emulator, the Mac's end of an iPhone's USB tunnel, the LAN, orNS_HMR_HOST) and writes it with the session token intodev-server.jsonnext tobundle.mjson that device.bundle.mjsreads the file and boots from that origin verbatim; without it, the app shows a "waiting forns run" screen.bundle.mjs, the session descriptor and the import map carry no origin: the device builds absolute URLs, the HMR WebSocket URL and the import map from its own origin. So one dev server serves devices that reach it differently, and the dev server makes no origin guesses (its LAN guess,10.0.2.2fallback, ownadb reverseand token file are removed). The package declares this undernativescriptCli.devServerFile./__ns_dev__action routes need the per-session token, which the CLI generates and passes asNS_HMR_TOKEN.server.host: true). A host name inNS_HMR_HOSTis allowed through Vite's host check.Single-process dev (iOS, visionOS, Android), with NativeScript/nativescript-cli#6209:
vite servealone writesbundle.mjs,package.json, the assets and, on Android, a customApplicationchunk built with the app's own config.nativescriptCli.singleProcessDev. A new CLI keeps a working path for older packages; this package needs a CLI with feat(vite): choose each device's dev server origin, with the iOS USB tunnel nativescript-cli#6210.Android:
NativeScriptActivityare served and imported by the boot module ahead of the entry. Their named classes are generated at runtime while the runtime holdsApplication.onCreate, so only a customApplicationstill needs a file on disk.Angular:
--no-hmrworks (the compilation API is off).@analogjs/vite-plugin-angular^3.0.1 is required (in-place template and component stylesheet updates: fix(vite-plugin-angular): keep template HMR in place after non-component file changes analogjs/analog#2817, fix(vite-plugin-angular): keep component stylesheet edits in place for direct stylesheet requests analogjs/analog#2857).Vue and TS/XML:
app.cssis a Vite CSS module.Verified:
packages/vitevitest passes 862 tests, also throughnx run vite:testfrom the workspace root.http://127.0.0.1:5173; the app booted and applied a template edit through HMR, and the device'sbundle.mjsheld no address and no token.dev-server.jsonwritten by hand as the LAN address and then ashttp://[::1]:5173: it booted, and each edit reached both simulators in place.127.0.0.1throughadb reverse, and10.0.2.2withNS_HMR_NO_ADB_REVERSE; both booted and applied edits through HMR.vite buildpath.--no-hmr, release build) and nativescript-vue 3.1 fixtures, plus the toolbox through crawls. Earlier Angular runs on physical devices used Analog 2.9.7.Runtime dependencies
NativeScript/ios:
nextbuilds) is required: the dev server no longer rewrites dynamic imports to absolute URLs, so on an older runtime lazy imports fail under HMR.nextbuilds. Checked with this branch on the iOSnextof 2026-12-03 (simulator): a relaunch requests no pre-bundle and revalidates the other modules with304. The minimum runtime is set once a release has them. The dev server no longer strips the__ns_dev_noncethat File Transfer module to download or upload arbitrary files #585 removes: a runtime that still sends it (on a re-fetch after a failed soft reboot) gets app restarts for later edits of that file.NativeScript/android:
nextbuilds. Checked on the Androidnextof 2026-12-03 with OkHttp 4.12.0 in the app (emulator): same relaunch numbers as iOS.Known gaps
dev-server.json(delivered insync.zip, origin on the USB tunnel) is not yet run on an iPhone.Application's new overridden methods or interfaces still needns runagain, as with webpack today: Application changes don't trigger a native rebuild. Body edits apply (rebuild → sync → restart).inspector_modulesby bare name.Phase log
ed72bef83/ns/mpipeline is deleted (≈17.8k lines)6e6fe1e96?t=is part of module identity; the NS update protocol is deleted28a8f5149b2eb5959enativescript:beforeReboot/beforeRerun/afterReboot/beforeRestartevents083d0ace4bcc327d77config.defineis the single source of defines; one namespacedSymbol.for('nativescript.dev')global883c6451b/__ns_dev__; no/ns/*routes left757e11380541e11cb9app.cssas a Vite CSS module for every flavor; workers owned by the module that created them690b27ecbrequiremiss throws a clear error; the dev type check never blocks the watch buildd1509a553bundle.mjsunder 1 KB, no globalrequireshim0a43ce9d1requireinstead of the global one. Cold requests: Angular 707 → 332, Vue 481 → 3274937c3879,77e2e3d21--env.watchNodeModules= per-dependencyserver.watch.ignorednegations; not watched by default54524c046701162c3a71fa3dc44,2acc6410d,656f7d7ac/__ns_dev__no-store, origin-tagged ETags, noimmutableon non-pre-bundle?v=files)5e03cf963nxtestsc74cfb274__NS_*globals and toolbox spike files removed192b0dcff,2a1c7d3d2,ed6eb56c8,50edfe7f7requireon by default; spike harness untracked8a9e6e07414fcb7ddf)c5b62ddf3--no-hmrfixed; release guard; Analog peer^2.7.1c96b9c688,9f8b6300b14fcb7ddf,e41163ad1Applicationchunk with the app's own config);Applicationedits are an HMR rejection: rebuild → sync → restart79c30e03cNS_HMR_HOSTno longer sets the bind; bare IPv6 device hosts are bracketeda4ee47d81initadds@valor/nativescript-websockets^2.0.4 (IPv6 host bracketed in the iOS handshake, needed for HMR over the USB tunnel)c844252a5^3.0.1; options Analog 3 no longer has are removed2da0e3674nextruntime of 2026-12-01 (simulator, and iPhone 11 Pro over the IPv6 USB tunnel) and Android 9.1.3 (emulator)a98f6f719a1f0c0137?v=URLs (a generation id in a plugin name, so in Vite's config hash), so a device's HTTP cache can't keep a staleimmutablecopy; checked on the iOS simulator and Android emulator with a hand-edited dependency373e4b63cnode_modules/.vite/<platform>: an app's iOS and Android dev servers run at once and overwrote each other's platform-resolved pre-bundles; checked with both running on a simulator and an emulator69748090dmanualChunksremoved: its vendor chunk evaluated beforebundle.mjs(Vue's runtime before the XHR polyfill andbundle-entry-points), pulled core and lazy-only dependencies into it, and used Rolldown's deprecated API; release bundles are nowbundle.mjsplus lazy chunks86326b756process.env.NODE_ENVfrom the mode only:@rollup/plugin-replaceremoved (a release build withDEBUGset no longer ships Vue's dev build)3a3d2bab2nativescript-theme-core1.x: platform stylesheet aliases ahead of the package catch-all, so each platform gets its own theme; the plugins that wrote symlinks intonode_modulesare removed2363c143dvite ^8.3.0, for the top-leveltsconfigoptionff8d9aec5pathsresolved by Vite (resolve.tsconfigPaths+tsconfig: tsconfig.app.json, tsconfig.json or jsconfig.json) instead of our resolver, so packageextends,pathsreplacement acrossextendsand multiple targets follow TypeScript. Apps with a catch-all"*": ["./node_modules/*"](older templates) now have it honoured;631a2e8e0warns once at startup and asks them to remove itf05340601dev-server.json, written by the CLI;bundle.mjs, the session and the import map are origin-free; the token comes fromNS_HMR_TOKEN;nativescriptCli.devServerFilebff55413710.0.2.2fallback, its ownadb reverse, the token file (≈2.4k lines)