@@ -23,7 +23,14 @@ import { Observable, Subject } from 'rxjs';
2323import { filter , map , take } from 'rxjs/operators' ;
2424import { AppHostView } from './app-host-view' ;
2525import { NativeScriptLoadingService } from './loading.service' ;
26- import { APP_ROOT_VIEW , DISABLE_ROOT_VIEW_HANDLING , NATIVESCRIPT_ROOT_MODULE_ID } from './tokens' ;
26+ import { HmrSnapshot , restoreHmrSnapshots , saveHmrSnapshots } from './hmr-snapshots' ;
27+ import {
28+ APP_ROOT_VIEW ,
29+ DISABLE_ROOT_VIEW_HANDLING ,
30+ NATIVESCRIPT_HMR_PARTICIPANTS ,
31+ NATIVESCRIPT_ROOT_MODULE_ID ,
32+ NativeScriptHmrParticipant ,
33+ } from './tokens' ;
2734import { NativeScriptDebug } from './trace' ;
2835
2936export interface AppLaunchView extends LayoutBase {
@@ -228,14 +235,140 @@ export interface ApplicationConfig {
228235}
229236
230237interface ViteHotContext {
231- on ( event : string , cb : ( payload : any ) => void ) : void ;
238+ send ( event : string , payload ?: unknown ) : void ;
239+ }
240+
241+ type MainRef = NgModuleRef < unknown > | ApplicationRef ;
242+
243+ interface HmrRun {
244+ mainRef ( ) : MainRef | null ;
245+ dispose ( ) : void ;
246+ }
247+
248+ interface PendingHmrReboot {
249+ bootstrapStarted : boolean ;
250+ bootstrapped : Promise < MainRef | null > ;
251+ resolveBootstrapped ( ref : MainRef | null ) : void ;
252+ settled ?: Promise < void > ;
253+ }
254+
255+ // A zone that never settles (e.g. an app-level setInterval) must not stall the dev client's update queue.
256+ const HMR_STABLE_TIMEOUT_MS = 5000 ;
257+
258+ // This module is never re-evaluated in a dev session, but the app entry that
259+ // calls runNativeScriptAngularApp is, so this state outlives each app run.
260+ let currentHmrRun : HmrRun | null = null ;
261+ let pendingHmrReboot : PendingHmrReboot | null = null ;
262+ let hmrSnapshots = new Map < string , HmrSnapshot > ( ) ;
263+
264+ function logHmr ( message : string , error ?: unknown ) {
265+ if ( error === undefined ) {
266+ console . warn ( `[@nativescript/angular] ${ message } ` ) ;
267+ } else {
268+ console . error ( `[@nativescript/angular] ${ message } ` , error ) ;
269+ }
270+ }
271+
272+ function readHmrParticipants ( ref : MainRef ) : readonly NativeScriptHmrParticipant [ ] {
273+ try {
274+ return ref . injector . get ( NATIVESCRIPT_HMR_PARTICIPANTS , null ) ?? [ ] ;
275+ } catch ( error ) {
276+ logHmr ( 'Could not read the HMR participants.' , error ) ;
277+ return [ ] ;
278+ }
232279}
233280
234- // This module is never re-evaluated on a dev full reload, but the app entry
235- // calling runNativeScriptAngularApp is: register the listener once and have it
236- // dispose whichever app run is current.
237- let disposeCurrentAppForFullReload : ( ( ) => void ) | null = null ;
238- let fullReloadListenerRegistered = false ;
281+ /**
282+ * Dev only, called by the dev server's HMR client before it re-imports the app
283+ * entry: saves the HMR participants' state and tears the running app down so
284+ * the re-imported entry can bootstrap a new one. A no-op when nothing is running.
285+ */
286+ export async function prepareHmrReboot ( ) : Promise < void > {
287+ const run = currentHmrRun ;
288+ if ( ! run ) {
289+ return ;
290+ }
291+ currentHmrRun = null ;
292+ // Snapshots not yet restored (the previous reboot is unsettled or failed) are newer than anything this run holds.
293+ const ref = run . mainRef ( ) ;
294+ if ( ref && ! pendingHmrReboot ) {
295+ hmrSnapshots = saveHmrSnapshots ( readHmrParticipants ( ref ) , logHmr ) ;
296+ }
297+ pendingHmrReboot ?. resolveBootstrapped ( null ) ;
298+ let resolveBootstrapped : ( ref : MainRef | null ) => void ;
299+ const bootstrapped = new Promise < MainRef | null > ( ( resolve ) => ( resolveBootstrapped = resolve ) ) ;
300+ pendingHmrReboot = { bootstrapStarted : false , bootstrapped, resolveBootstrapped } ;
301+ run . dispose ( ) ;
302+ }
303+
304+ /**
305+ * Dev only: resolves once the app bootstrapped after {@link prepareHmrReboot}
306+ * is stable and its HMR participants are restored. Resolves immediately when no
307+ * reboot is pending, and also when the bootstrap fails (the error is logged and
308+ * shown in the app).
309+ */
310+ export function whenHmrRebootSettled ( ) : Promise < void > {
311+ const reboot = pendingHmrReboot ;
312+ if ( ! reboot ) {
313+ return Promise . resolve ( ) ;
314+ }
315+ return ( reboot . settled ??= settleHmrReboot ( reboot ) ) ;
316+ }
317+
318+ async function settleHmrReboot ( reboot : PendingHmrReboot ) : Promise < void > {
319+ try {
320+ await restoreAfterHmrReboot ( reboot ) ;
321+ } catch ( error ) {
322+ logHmr ( 'Could not restore HMR state after a reboot.' , error ) ;
323+ }
324+ // Unrestored snapshots are kept on purpose: the next reboot will likely carry the fix.
325+ if ( pendingHmrReboot === reboot ) {
326+ pendingHmrReboot = null ;
327+ }
328+ }
329+
330+ async function restoreAfterHmrReboot ( reboot : PendingHmrReboot ) : Promise < void > {
331+ if ( ! reboot . bootstrapStarted ) {
332+ logHmr ( 'The app entry did not bootstrap Angular after an HMR reboot; HMR state was not restored.' ) ;
333+ return ;
334+ }
335+ const ref = await reboot . bootstrapped ;
336+ if ( ! ref || pendingHmrReboot !== reboot ) {
337+ return ;
338+ }
339+ const appRef = ref instanceof ApplicationRef ? ref : ref . injector . get ( ApplicationRef ) ;
340+ const zone = ref . injector . get ( NgZone ) ;
341+ let timer : ReturnType < typeof setTimeout > ;
342+ const stable = await Promise . race ( [
343+ appRef . whenStable ( ) . then ( ( ) => true ) ,
344+ // Outside Angular: a pending timer in the Angular zone would itself keep the app unstable.
345+ new Promise < boolean > ( ( resolve ) =>
346+ zone . runOutsideAngular ( ( ) => ( timer = setTimeout ( ( ) => resolve ( false ) , HMR_STABLE_TIMEOUT_MS ) ) ) ,
347+ ) ,
348+ ] ) ;
349+ clearTimeout ( timer ) ;
350+ if ( ! stable ) {
351+ logHmr ( `The app was not stable ${ HMR_STABLE_TIMEOUT_MS } ms after an HMR reboot; restoring HMR state anyway.` ) ;
352+ }
353+ if ( pendingHmrReboot !== reboot || appRef . destroyed ) {
354+ return ;
355+ }
356+ if ( hmrSnapshots . size ) {
357+ await restoreHmrSnapshots ( readHmrParticipants ( ref ) , hmrSnapshots , ( fn ) => zone . run ( fn ) , logHmr ) ;
358+ }
359+ if ( pendingHmrReboot === reboot ) {
360+ hmrSnapshots = new Map ( ) ;
361+ }
362+ }
363+
364+ /**
365+ * Dev only: asks the dev server to restart the app, for state an HMR
366+ * participant cannot carry across a reboot. A no-op outside a Vite dev session.
367+ */
368+ export function requestNativeScriptAppRestart ( reason : string ) : void {
369+ // Must stay the literal `import.meta.hot`: Vite only injects the hot context for that form.
370+ ( import . meta as ImportMeta & { hot ?: ViteHotContext } ) . hot ?. send ( 'ns:restart' , { reason } ) ;
371+ }
239372
240373export function runNativeScriptAngularApp < T , K > ( options : AppRunOptions < T , K > ) {
241374 let mainModuleRef : NgModuleRef < T > | ApplicationRef = null ;
@@ -304,6 +437,12 @@ export function runNativeScriptAngularApp<T, K>(options: AppRunOptions<T, K>) {
304437 setRootView ( errorTextBox ) ;
305438 } ;
306439 const bootstrapRoot = ( reason : NgModuleReason ) => {
440+ const hmrReboot = pendingHmrReboot ;
441+ if ( hmrReboot && ! hmrReboot . bootstrapStarted ) {
442+ hmrReboot . bootstrapStarted = true ;
443+ // Started here rather than on demand so the restore runs even if the dev client never awaits it.
444+ hmrReboot . settled ??= settleHmrReboot ( hmrReboot ) ;
445+ }
307446 try {
308447 bootstrapId = Date . now ( ) ;
309448 const currentBootstrapId = bootstrapId ;
@@ -322,6 +461,7 @@ export function runNativeScriptAngularApp<T, K>(options: AppRunOptions<T, K>) {
322461 return ;
323462 }
324463 mainModuleRef = ref ;
464+ hmrReboot ?. resolveBootstrapped ( ref ) ;
325465
326466 ( ref instanceof ApplicationRef ? ref . components [ 0 ] : ref ) . onDestroy (
327467 ( ) => ( mainModuleRef = mainModuleRef === ref ? null : mainModuleRef ) ,
@@ -340,6 +480,10 @@ export function runNativeScriptAngularApp<T, K>(options: AppRunOptions<T, K>) {
340480 bootstrapped = true ;
341481 NativeScriptDebug . bootstrapLogError ( `Error bootstrapping app module:\n${ err . message } \n\n${ err . stack } ` ) ;
342482 showErrorUI ( err ) ;
483+ if ( hmrReboot && currentBootstrapId === bootstrapId ) {
484+ logHmr ( 'The app failed to bootstrap after an HMR reboot.' , err ) ;
485+ hmrReboot . resolveBootstrapped ( null ) ;
486+ }
343487 throw err ;
344488 } ,
345489 ) ,
@@ -438,6 +582,10 @@ export function runNativeScriptAngularApp<T, K>(options: AppRunOptions<T, K>) {
438582 ) ;
439583 } catch ( err ) {
440584 NativeScriptDebug . bootstrapLogError ( `Error in Bootstrap Function:\n${ err . message } \n\n${ err . stack } ` ) ;
585+ if ( hmrReboot ) {
586+ logHmr ( 'The app failed to bootstrap after an HMR reboot.' , err ) ;
587+ hmrReboot . resolveBootstrapped ( null ) ;
588+ }
441589 }
442590 } ;
443591 const disposePlatform = ( reason : NgModuleReason ) => {
@@ -476,25 +624,19 @@ export function runNativeScriptAngularApp<T, K>(options: AppRunOptions<T, K>) {
476624 global . NativeScriptGlobals . events . addEventListener = oldAddEventListener ;
477625 }
478626 // Must stay the literal `import.meta.hot`: Vite only injects the hot context for that form.
479- const hot = ( import . meta as ImportMeta & { hot ?: ViteHotContext } ) . hot ;
480- if ( hot ) {
481- disposeCurrentAppForFullReload = ( ) => {
482- Application . off ( Application . launchEvent , launchCallback ) ;
483- Application . off ( Application . exitEvent , exitCallback ) ;
484- disposeLastModules ( 'hotreload' ) ;
485- disposePlatform ( 'hotreload' ) ;
486- // The re-evaluated entry redefines every app component; without this,
487- // dev mode warns NG0912 because the cached component IDs map to the old classes.
488- ɵresetCompiledComponents ( ) ;
627+ if ( ( import . meta as ImportMeta & { hot ?: ViteHotContext } ) . hot ) {
628+ currentHmrRun = {
629+ mainRef : ( ) => mainModuleRef ,
630+ dispose : ( ) => {
631+ Application . off ( Application . launchEvent , launchCallback ) ;
632+ Application . off ( Application . exitEvent , exitCallback ) ;
633+ disposeLastModules ( 'hotreload' ) ;
634+ disposePlatform ( 'hotreload' ) ;
635+ // The next bootstrap may define edited copies of app components; without
636+ // this, dev mode warns NG0912 because cached component IDs map to the old classes.
637+ ɵresetCompiledComponents ( ) ;
638+ } ,
489639 } ;
490- if ( ! fullReloadListenerRegistered ) {
491- fullReloadListenerRegistered = true ;
492- hot . on ( 'vite:beforeFullReload' , ( ) => {
493- const dispose = disposeCurrentAppForFullReload ;
494- disposeCurrentAppForFullReload = null ;
495- dispose ?.( ) ;
496- } ) ;
497- }
498640 }
499641 if ( import . meta[ 'webpackHot' ] ) {
500642 // handle HMR Application.run
@@ -532,7 +674,7 @@ export function runNativeScriptAngularApp<T, K>(options: AppRunOptions<T, K>) {
532674 // A host that already launched the app (e.g. a dev server's boot UI) will not
533675 // fire launchEvent again, so bootstrap now instead of waiting for it.
534676 if ( options . embedded || Application . hasLaunched ( ) ) {
535- bootstrapRoot ( 'applaunch' ) ;
677+ bootstrapRoot ( pendingHmrReboot ? 'hotreload' : 'applaunch' ) ;
536678 } else {
537679 Application . run ( ) ;
538680 }
0 commit comments