Skip to content

Commit a1fc68e

Browse files
committed
feat: soft reboot hooks and HMR participants for Vite
prepareHmrReboot() saves HMR participants from the current root injector, detaches the launch/exit handlers and disposes the modules and platform; whenHmrRebootSettled() waits for the re-bootstrap to settle and restores the participants in the new injector. @nativescript/vite calls them from the app entry's HMR dispose, so only the changed import chain re-runs. Participants are a multi-provider (NATIVESCRIPT_HMR_PARTICIPANTS: key, version, save, restore); none are registered yet. requestNativeScriptAppRestart(reason) asks the dev server for an app restart. Everything is a no-op without import.meta.hot.
1 parent 6a3e3c7 commit a1fc68e

5 files changed

Lines changed: 315 additions & 26 deletions

File tree

‎packages/angular/src/lib/application.ts‎

Lines changed: 168 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,14 @@ import { Observable, Subject } from 'rxjs';
2323
import { filter, map, take } from 'rxjs/operators';
2424
import { AppHostView } from './app-host-view';
2525
import { 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';
2734
import { NativeScriptDebug } from './trace';
2835

2936
export interface AppLaunchView extends LayoutBase {
@@ -228,14 +235,140 @@ export interface ApplicationConfig {
228235
}
229236

230237
interface 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

240373
export 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
}
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import { restoreHmrSnapshots, saveHmrSnapshots } from './hmr-snapshots';
2+
import type { NativeScriptHmrParticipant } from './tokens';
3+
4+
function participant(
5+
key: string,
6+
overrides: Partial<NativeScriptHmrParticipant> = {},
7+
): NativeScriptHmrParticipant & { restored: unknown[] } {
8+
const restored: unknown[] = [];
9+
return {
10+
key,
11+
save: () => `${key}-state`,
12+
restore: (state) => {
13+
restored.push(state);
14+
},
15+
restored,
16+
...overrides,
17+
};
18+
}
19+
20+
const passthrough = <R>(fn: () => R) => fn();
21+
22+
describe('HMR snapshots', () => {
23+
it('saves each participant by key, skipping one whose save throws', () => {
24+
const log = jest.fn();
25+
const snapshots = saveHmrSnapshots(
26+
[
27+
participant('a', { version: 2 }),
28+
participant('b', {
29+
save: () => {
30+
throw new Error('boom');
31+
},
32+
}),
33+
],
34+
log,
35+
);
36+
expect([...snapshots.entries()]).toEqual([['a', { version: 2, state: 'a-state' }]]);
37+
expect(log).toHaveBeenCalledTimes(1);
38+
});
39+
40+
it('restores only participants whose key and version match a snapshot', async () => {
41+
const log = jest.fn();
42+
const same = participant('same', { version: 1 });
43+
const bumped = participant('bumped', { version: 2 });
44+
const unknown = participant('unknown');
45+
const snapshots = saveHmrSnapshots(
46+
[participant('same', { version: 1 }), participant('bumped', { version: 1 })],
47+
log,
48+
);
49+
await restoreHmrSnapshots([same, bumped, unknown], snapshots, passthrough, log);
50+
expect(same.restored).toEqual(['same-state']);
51+
expect(bumped.restored).toEqual([]);
52+
expect(unknown.restored).toEqual([]);
53+
expect(log).toHaveBeenCalledTimes(1);
54+
});
55+
56+
it('logs a failing restore and still restores the rest', async () => {
57+
const log = jest.fn();
58+
const failing = participant('failing', {
59+
restore: () => Promise.reject(new Error('boom')),
60+
});
61+
const ok = participant('ok');
62+
const snapshots = saveHmrSnapshots([participant('failing'), participant('ok')], log);
63+
await restoreHmrSnapshots([failing, ok], snapshots, passthrough, log);
64+
expect(ok.restored).toEqual(['ok-state']);
65+
expect(log).toHaveBeenCalledTimes(1);
66+
});
67+
68+
it('runs each restore through the given runner', async () => {
69+
const run = jest.fn(passthrough);
70+
const snapshots = saveHmrSnapshots([participant('a')], jest.fn());
71+
await restoreHmrSnapshots([participant('a')], snapshots, run, jest.fn());
72+
expect(run).toHaveBeenCalledTimes(1);
73+
});
74+
});
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// Runtime-import free so it can be unit tested without Angular or NativeScript.
2+
import type { NativeScriptHmrParticipant } from './tokens';
3+
4+
export interface HmrSnapshot {
5+
version: number | undefined;
6+
state: unknown;
7+
}
8+
9+
export type HmrLog = (message: string, error?: unknown) => void;
10+
11+
export function saveHmrSnapshots(
12+
participants: readonly NativeScriptHmrParticipant[],
13+
log: HmrLog,
14+
): Map<string, HmrSnapshot> {
15+
const snapshots = new Map<string, HmrSnapshot>();
16+
for (const participant of participants) {
17+
try {
18+
snapshots.set(participant.key, { version: participant.version, state: participant.save() });
19+
} catch (error) {
20+
log(`HMR participant "${participant.key}" failed to save its state; skipping it.`, error);
21+
}
22+
}
23+
return snapshots;
24+
}
25+
26+
export async function restoreHmrSnapshots(
27+
participants: readonly NativeScriptHmrParticipant[],
28+
snapshots: ReadonlyMap<string, HmrSnapshot>,
29+
run: <R>(fn: () => R) => R,
30+
log: HmrLog,
31+
): Promise<void> {
32+
for (const participant of participants) {
33+
const snapshot = snapshots.get(participant.key);
34+
if (!snapshot) {
35+
continue;
36+
}
37+
if (snapshot.version !== participant.version) {
38+
log(
39+
`HMR participant "${participant.key}" snapshot version ${snapshot.version} does not match ${participant.version}; skipping restore.`,
40+
);
41+
continue;
42+
}
43+
try {
44+
await run(() => participant.restore(snapshot.state));
45+
} catch (error) {
46+
log(`HMR participant "${participant.key}" failed to restore its state; skipping it.`, error);
47+
}
48+
}
49+
}

‎packages/angular/src/lib/public_api.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,9 @@ export {
5555
preAngularDisposal$,
5656
runNativeScriptAngularApp,
5757
ApplicationConfig,
58+
prepareHmrReboot,
59+
whenHmrRebootSettled,
60+
requestNativeScriptAppRestart,
5861
} from './application';
5962
export * from './element-registry';
6063
export * from './nativescript-xhr-factory';

0 commit comments

Comments
 (0)