import { HmrConstants, DeviceDiscoveryEventNames } from "../common/constants"; import { BUNDLER_APP_RESTART_REQUESTED, PREPARE_READY_EVENT_NAME, TrackActionNames, DEBUGGER_DETACHED_EVENT_NAME, RunOnDeviceEvents, USER_INTERACTION_NEEDED_EVENT_NAME, } from "../constants"; import { cache, performanceLog } from "../common/decorators"; import { isTruthyEnvFlag } from "../common/helpers"; import { EventEmitter } from "events"; import * as util from "util"; import * as _ from "lodash"; import { IProjectDataService, IProjectData } from "../definitions/project"; import { IBuildController } from "../definitions/build"; import { IPlatformsDataService } from "../definitions/platform"; import { IDebugController } from "../definitions/debug"; import { IPluginsService } from "../definitions/plugins"; import { IAnalyticsService, IErrors, IHooksService, IDictionary, } from "../common/declarations"; import { IInjector } from "../common/definitions/yok"; import { ViteHmrPortService } from "../contracts/vite-hmr-port-service"; import { IOSDeviceTunnelService } from "../contracts/internal/ios-device-tunnel-service"; import { DevServerOriginService } from "../contracts/internal/dev-server-origin-service"; import { injector } from "../common/yok"; import { isIOSMacDevice } from "../common/mobile/ios/mac/ios-mac-constants"; import { inject } from "../common/di"; export class RunController extends EventEmitter implements IRunController { private devServerOriginService = inject(DevServerOriginService); private iOSDeviceTunnelService = inject(IOSDeviceTunnelService); private prepareReadyEventHandler: any = null; private appRestartRequestHandler: ( request: IBundlerAppRestartRequest, ) => void = null; private _syncInProgress = false; private _pendingSyncs: Map< string, { data: IFilesChangeEventData; projectData: IProjectData; liveSyncInfo: ILiveSyncInfo; } > = new Map(); constructor( protected $analyticsService: IAnalyticsService, private $buildController: IBuildController, private $bundlerCompilerService: IBundlerCompilerService, private $debugController: IDebugController, private $deviceInstallAppService: IDeviceInstallAppService, protected $devicesService: Mobile.IDevicesService, protected $errors: IErrors, protected $injector: IInjector, private $hmrStatusService: IHmrStatusService, public $hooksService: IHooksService, private $liveSyncServiceResolver: ILiveSyncServiceResolver, private $liveSyncProcessDataService: ILiveSyncProcessDataService, protected $logger: ILogger, protected $mobileHelper: Mobile.IMobileHelper, private $platformsDataService: IPlatformsDataService, private $pluginsService: IPluginsService, private $prepareController: IPrepareController, private $prepareDataService: IPrepareDataService, private $prepareNativePlatformService: IPrepareNativePlatformService, private $projectChangesService: IProjectChangesService, protected $projectDataService: IProjectDataService, private $staticConfig: Config.IStaticConfig, private $viteHmrPortService: ViteHmrPortService, ) { super(); } public async run(runData: IRunData): Promise { const { liveSyncInfo, deviceDescriptors } = runData; const { projectDir } = liveSyncInfo; const projectData = this.$projectDataService.getProjectData(projectDir); await this.initializeSetup(projectData); const deviceDescriptorsForInitialSync = this.getDeviceDescriptorsForInitialSync(projectDir, deviceDescriptors); const newPlatforms = this.$devicesService.getPlatformsFromDeviceDescriptors(deviceDescriptors); const oldPlatforms = this.$liveSyncProcessDataService.getPlatforms(projectDir); const platforms = _.uniq(_.concat(newPlatforms, oldPlatforms)); this.$liveSyncProcessDataService.persistData( projectDir, deviceDescriptors, platforms, liveSyncInfo, ); const shouldStartWatcher = !liveSyncInfo.skipWatcher && this.$liveSyncProcessDataService.hasDeviceDescriptors(projectDir); if (shouldStartWatcher && liveSyncInfo.useHotModuleReload) { this.$hmrStatusService.attachToHmrStatusEvent(); } if (!this.prepareReadyEventHandler) { const handler = async (data: IFilesChangeEventData) => { if (data.hasNativeChanges) { const platformData = this.$platformsDataService.getPlatformData( data.platform, projectData, ); const prepareData = this.$prepareDataService.getPrepareData( liveSyncInfo.projectDir, data.platform, { ...liveSyncInfo, watch: !liveSyncInfo.skipWatcher }, ); const changesInfo = await this.$projectChangesService.checkForChanges( platformData, projectData, prepareData, ); if (!changesInfo.hasChanges) { return; } } this.scheduleSyncOnDevices(data, projectData, liveSyncInfo); }; this.prepareReadyEventHandler = handler.bind(this); this.$prepareController.on( PREPARE_READY_EVENT_NAME, this.prepareReadyEventHandler, ); } if (!this.appRestartRequestHandler) { this.appRestartRequestHandler = (request) => this.restartApplicationOnPlatform(request); this.$bundlerCompilerService.on( BUNDLER_APP_RESTART_REQUESTED, this.appRestartRequestHandler, ); } await this.syncInitialDataOnDevices( projectData, liveSyncInfo, deviceDescriptorsForInitialSync, ); this.attachDeviceLostHandler(); this.attachTunnelLostHandler(); } public async stop(data: IStopRunData): Promise { const { projectDir, deviceIdentifiers, stopOptions } = data; const liveSyncProcessInfo = this.$liveSyncProcessDataService.getPersistedData(projectDir); if (liveSyncProcessInfo && !liveSyncProcessInfo.isStopped) { // In case we are coming from error during livesync, the current action is the one that erred (but we are still executing it), // so we cannot await it as this will cause infinite loop. const shouldAwaitPendingOperation = !stopOptions || stopOptions.shouldAwaitAllActions; const deviceIdentifiersToRemove = deviceIdentifiers && deviceIdentifiers.length ? deviceIdentifiers : _.map(liveSyncProcessInfo.deviceDescriptors, (d) => d.identifier); const removedDeviceIdentifiers = _.remove( liveSyncProcessInfo.deviceDescriptors, (descriptor) => _.includes(deviceIdentifiersToRemove, descriptor.identifier), ).map((descriptor) => descriptor.identifier); for (const deviceIdentifier of removedDeviceIdentifiers) { this.devServerOriginService.forget(deviceIdentifier); await this.iOSDeviceTunnelService.close(deviceIdentifier); } // Handle the case when no more devices left for any of the persisted platforms for (let i = 0; i < liveSyncProcessInfo.platforms.length; i++) { const platform = liveSyncProcessInfo.platforms[i]; const devices = this.$devicesService.getDevicesForPlatform(platform); if (!devices || !devices.length) { await this.$prepareController.stopWatchers(projectDir, platform); } } // In case deviceIdentifiers are not passed, we should stop the whole LiveSync. if ( !deviceIdentifiers || !deviceIdentifiers.length || !liveSyncProcessInfo.deviceDescriptors || !liveSyncProcessInfo.deviceDescriptors.length ) { if (liveSyncProcessInfo.timer) { clearTimeout(liveSyncProcessInfo.timer as unknown as number); } for (let k = 0; k < liveSyncProcessInfo.platforms.length; k++) { await this.$prepareController.stopWatchers( projectDir, liveSyncProcessInfo.platforms[k], ); } liveSyncProcessInfo.isStopped = true; if (liveSyncProcessInfo.actionsChain && shouldAwaitPendingOperation) { await liveSyncProcessInfo.actionsChain; } liveSyncProcessInfo.deviceDescriptors = []; if (this.prepareReadyEventHandler) { this.$prepareController.removeListener( PREPARE_READY_EVENT_NAME, this.prepareReadyEventHandler, ); this.prepareReadyEventHandler = null; } if (this.appRestartRequestHandler) { this.$bundlerCompilerService.removeListener( BUNDLER_APP_RESTART_REQUESTED, this.appRestartRequestHandler, ); this.appRestartRequestHandler = null; } const projectData = this.$projectDataService.getProjectData(projectDir); await this.$hooksService.executeAfterHooks("watch", { hookArgs: { projectData, }, }); } else if ( liveSyncProcessInfo.currentSyncAction && shouldAwaitPendingOperation ) { await liveSyncProcessInfo.currentSyncAction; } // Emit RunOnDevice stopped when we've really stopped. _.each(removedDeviceIdentifiers, (deviceIdentifier) => { this.emitCore(RunOnDeviceEvents.runOnDeviceStopped, { projectDir, deviceIdentifier, keepProcessAlive: stopOptions?.keepProcessAlive, }); }); if (stopOptions?.keepProcessAlive) { this.removeAllListeners(RunOnDeviceEvents.runOnDeviceStopped); } } } public getDeviceDescriptors(data: { projectDir: string; }): ILiveSyncDeviceDescriptor[] { return this.$liveSyncProcessDataService.getDeviceDescriptors( data.projectDir, ); } /** * Restarts the application of a running session without preparing, * building or syncing anything. Queued on the session's action chain so it * cannot overtake a sync that is already under way, and routed through * `refreshApplication` so a debug session gets its debugger back. */ public async restartApplication( data: IRestartApplicationData, ): Promise { const { projectDir, deviceIdentifiers } = data; const liveSyncProcessInfo = this.$liveSyncProcessDataService.getPersistedData(projectDir); if (!liveSyncProcessInfo || liveSyncProcessInfo.isStopped) { this.$logger.info( "There is no running application to restart. Start a run or debug session first.", ); return; } const deviceDescriptors = ( liveSyncProcessInfo.deviceDescriptors || [] ).filter( (descriptor) => !deviceIdentifiers || !deviceIdentifiers.length || _.includes(deviceIdentifiers, descriptor.identifier), ); if (!deviceDescriptors.length) { this.$logger.info("There is no device to restart the application on."); return; } const projectData = this.$projectDataService.getProjectData(projectDir); const useHotModuleReload = !!liveSyncProcessInfo.liveSyncInfo?.useHotModuleReload; // A device stopped while this action waited in the chain must not be restarted. const findCurrentDescriptor = (device: Mobile.IDevice) => _.find( this.$liveSyncProcessDataService.getDeviceDescriptors(projectDir), (dd) => dd.identifier === device.deviceInfo.identifier && _.some(deviceDescriptors, (d) => d.identifier === dd.identifier), ); const deviceAction = async (device: Mobile.IDevice) => { const deviceDescriptor = findCurrentDescriptor(device); if (!deviceDescriptor) { return; } try { const platformLiveSyncService = this.$liveSyncServiceResolver.resolveLiveSyncService( device.deviceInfo.platform, ); const deviceAppData = await platformLiveSyncService.getAppData({ device, watch: true, projectData, liveSyncDeviceData: deviceDescriptor, useHotModuleReload, }); await this.refreshApplication( projectData, { deviceAppData, modifiedFilesData: [], isFullSync: false, useHotModuleReload, }, // Neither a hot update nor a native change, which is what // `refreshApplicationWithoutDebug` reads as "restart". { files: [], staleFiles: [], hasOnlyHotUpdateFiles: false, hasNativeChanges: false, hmrData: null, platform: device.deviceInfo.platform.toLowerCase(), }, deviceDescriptor, ); } catch (err) { this.$logger.warn( `Unable to restart the application on device: ${device.deviceInfo.identifier}. Error is: ${err.message || err}.`, ); this.$logger.trace(err); this.emitCore(RunOnDeviceEvents.runOnDeviceError, { projectDir: projectData.projectDir, deviceIdentifier: device.deviceInfo.identifier, applicationIdentifier: projectData.projectIdentifiers[ device.deviceInfo.platform.toLowerCase() ], error: err, }); } }; await this.addActionToChain(projectDir, () => this.$devicesService.execute( deviceAction, (device: Mobile.IDevice) => !!findCurrentDescriptor(device), ), ); } private async restartApplicationOnPlatform( request: IBundlerAppRestartRequest, ): Promise { const { projectDir, platform, reason } = request; const onPlatform = this.$devicesService .getDevicesForPlatform(platform) .map((device) => device.deviceInfo.identifier); const deviceIdentifiers = this.$liveSyncProcessDataService .getDeviceDescriptors(projectDir) .map((descriptor) => descriptor.identifier) .filter((identifier) => onPlatform.includes(identifier)); // An empty list would mean "every device" to `restartApplication`. if (!deviceIdentifiers.length) { this.$logger.trace( `Ignoring the ${platform} app restart request (${reason}): no ${platform} device in the session.`, ); return; } this.$logger.info(`Restarting the app on ${platform}: ${reason}`); try { await this.restartApplication({ projectDir, deviceIdentifiers }); } catch (err) { this.$logger.warn( `Unable to restart the app on ${platform}: ${err.message || err}`, ); } } protected async refreshApplication( projectData: IProjectData, liveSyncResultInfo: ILiveSyncResultInfo, filesChangeEventData: IFilesChangeEventData, deviceDescriptor: ILiveSyncDeviceDescriptor, fullSyncAction?: () => Promise, ): Promise { const result = deviceDescriptor.debuggingEnabled ? await this.refreshApplicationWithDebug( projectData, liveSyncResultInfo, filesChangeEventData, deviceDescriptor, ) : await this.refreshApplicationWithoutDebug( projectData, liveSyncResultInfo, filesChangeEventData, deviceDescriptor, undefined, fullSyncAction, ); const device = liveSyncResultInfo.deviceAppData.device; this.emitCore(RunOnDeviceEvents.runOnDeviceExecuted, { projectDir: projectData.projectDir, deviceIdentifier: device.deviceInfo.identifier, applicationIdentifier: projectData.projectIdentifiers[ device.deviceInfo.platform.toLowerCase() ], syncedFiles: liveSyncResultInfo.modifiedFilesData.map((m) => m.getLocalPath(), ), isFullSync: liveSyncResultInfo.isFullSync, }); return result; } protected async refreshApplicationWithDebug( projectData: IProjectData, liveSyncResultInfo: ILiveSyncResultInfo, filesChangeEventData: IFilesChangeEventData, deviceDescriptor: ILiveSyncDeviceDescriptor, ): Promise { const debugOptions = deviceDescriptor.debugOptions || {}; liveSyncResultInfo.waitForDebugger = !!debugOptions.debugBrk; liveSyncResultInfo.forceRefreshWithSocket = true; const refreshInfo = await this.refreshApplicationWithoutDebug( projectData, liveSyncResultInfo, filesChangeEventData, deviceDescriptor, { shouldSkipEmitLiveSyncNotification: true, shouldCheckDeveloperDiscImage: true, }, ); // we do not stop the application when debugBrk is false, so we need to attach, instead of launch // if we try to send the launch request, the debugger port will not be printed and the command will timeout debugOptions.start = !debugOptions.debugBrk; debugOptions.forceDebuggerAttachedEvent = refreshInfo.didRestart; await this.$debugController.enableDebuggingCoreWithoutWaitingCurrentAction( projectData.projectDir, deviceDescriptor.identifier, debugOptions, ); return refreshInfo; } @performanceLog() protected async refreshApplicationWithoutDebug( projectData: IProjectData, liveSyncResultInfo: ILiveSyncResultInfo, filesChangeEventData: IFilesChangeEventData, deviceDescriptor: ILiveSyncDeviceDescriptor, settings?: IRefreshApplicationSettings, fullSyncAction?: () => Promise, ): Promise { const result = { didRestart: false }; const platform = liveSyncResultInfo.deviceAppData.platform; const applicationIdentifier = projectData.projectIdentifiers[platform.toLowerCase()]; const platformLiveSyncService = this.$liveSyncServiceResolver.resolveLiveSyncService(platform); try { const isFullSync = filesChangeEventData && (filesChangeEventData.hasNativeChanges || !filesChangeEventData.hasOnlyHotUpdateFiles); let shouldRestart = isFullSync; if (!shouldRestart) { shouldRestart = await platformLiveSyncService.shouldRestart( projectData, liveSyncResultInfo, ); } if (!shouldRestart) { shouldRestart = !(await platformLiveSyncService.tryRefreshApplication( projectData, liveSyncResultInfo, )); } if (!isFullSync && shouldRestart && fullSyncAction) { this.$logger.trace( `Syncing all files as the current app state does not support hot updates.`, ); liveSyncResultInfo.didRecover = true; await fullSyncAction(); } if (shouldRestart) { this.emit(DEBUGGER_DETACHED_EVENT_NAME, { deviceIdentifier: liveSyncResultInfo.deviceAppData.device.deviceInfo.identifier, }); await platformLiveSyncService.restartApplication( projectData, liveSyncResultInfo, ); result.didRestart = true; } } catch (err) { this.$logger.info( `Error while trying to start application ${applicationIdentifier} on device ${ liveSyncResultInfo.deviceAppData.device.deviceInfo.identifier }. Error is: ${err.message || err}`, ); const msg = `Unable to start application ${applicationIdentifier} on device ${liveSyncResultInfo.deviceAppData.device.deviceInfo.identifier}. Try starting it manually.`; this.$logger.warn(msg); const device = liveSyncResultInfo.deviceAppData.device; const deviceIdentifier = device.deviceInfo.identifier; if (!settings || !settings.shouldSkipEmitLiveSyncNotification) { this.emitCore(RunOnDeviceEvents.runOnDeviceNotification, { projectDir: projectData.projectDir, deviceIdentifier: device.deviceInfo.identifier, applicationIdentifier: projectData.projectIdentifiers[ device.deviceInfo.platform.toLowerCase() ], notification: msg, }); } if ( settings && settings.shouldCheckDeveloperDiscImage && (err.message || err) === "Could not find developer disk image" ) { const attachDebuggerOptions: IAttachDebuggerData = { platform: device.deviceInfo.platform, isEmulator: device.isEmulator, projectDir: projectData.projectDir, deviceIdentifier, debugOptions: deviceDescriptor.debugOptions, outputPath: deviceDescriptor.buildData.outputPath, }; this.emit(USER_INTERACTION_NEEDED_EVENT_NAME, attachDebuggerOptions); } } return result; } private getDeviceDescriptorsForInitialSync( projectDir: string, deviceDescriptors: ILiveSyncDeviceDescriptor[], ) { const currentRunData = this.$liveSyncProcessDataService.getPersistedData(projectDir); const isAlreadyLiveSyncing = currentRunData && !currentRunData.isStopped; // Prevent cases where liveSync is called consecutive times with the same device, for example [ A, B, C ] and then [ A, B, D ] - we want to execute initialSync only for D. const deviceDescriptorsForInitialSync = isAlreadyLiveSyncing ? _.differenceBy( deviceDescriptors, currentRunData.deviceDescriptors, "identifier", ) : deviceDescriptors; return deviceDescriptorsForInitialSync; } private async initializeSetup(projectData: IProjectData): Promise { try { await this.$pluginsService.ensureAllDependenciesAreInstalled(projectData); } catch (err) { this.$logger.trace(err); this.$errors.fail( `Unable to install dependencies. Make sure your package.json is valid and all dependencies are correct. Error is: ${err.message}`, ); } } @cache() private attachDeviceLostHandler(): void { this.$devicesService.on( DeviceDiscoveryEventNames.DEVICE_LOST, async (device: Mobile.IDevice) => { this.$logger.trace( `Received ${DeviceDiscoveryEventNames.DEVICE_LOST} event in LiveSync service for ${device.deviceInfo.identifier}. Will stop LiveSync operation for this device.`, ); for (const projectDir in this.$liveSyncProcessDataService.getAllPersistedData()) { try { const deviceDescriptors = this.getDeviceDescriptors({ projectDir }); if ( _.find( deviceDescriptors, (d) => d.identifier === device.deviceInfo.identifier, ) ) { await this.stop({ projectDir, deviceIdentifiers: [device.deviceInfo.identifier], }); } } catch (err) { this.$logger.warn( `Unable to stop LiveSync operation for ${device.deviceInfo.identifier}.`, err, ); } } }, ); } @cache() private attachTunnelLostHandler(): void { this.iOSDeviceTunnelService.onTunnelLost((deviceIdentifier) => this.switchDevServerOrigin(deviceIdentifier), ); } /** * Points the device's `dev-server.json` at the origin it can use now and * restarts only its app, so it reconnects there. */ private async switchDevServerOrigin(deviceIdentifier: string): Promise { const previous = this.devServerOriginService.getOrigin(deviceIdentifier); if (!previous) { return; } for (const projectDir in this.$liveSyncProcessDataService.getAllPersistedData()) { const descriptor = _.find( this.$liveSyncProcessDataService.getDeviceDescriptors(projectDir), (d) => d.identifier === deviceIdentifier, ); if (!descriptor) { continue; } const switched = await this.addActionToChain(projectDir, async () => { try { if (!this.devServerOriginService.getOrigin(deviceIdentifier)) { return false; } const device = this.$devicesService.getDeviceByIdentifier(deviceIdentifier); const origin = await this.devServerOriginService.chooseOrigin(device); if (origin === previous) { return false; } const platformLiveSyncService = this.$liveSyncServiceResolver.resolveLiveSyncService( device.deviceInfo.platform, ); if (!platformLiveSyncService.syncDevServerFile) { return false; } this.$logger.info( `Switching ${device.deviceInfo.displayName || deviceIdentifier} to the Vite dev server at ${origin} and restarting the app.`, ); await platformLiveSyncService.syncDevServerFile( device, this.$projectDataService.getProjectData(projectDir), descriptor, ); return true; } catch (err) { this.$logger.warn( `Unable to point ${deviceIdentifier} at another Vite dev server origin: ${err.message || err}. Restart the run to reconnect.`, ); return false; } }); if (switched) { await this.restartApplication({ projectDir, deviceIdentifiers: [deviceIdentifier], }); } } } private async syncInitialDataOnDevices( projectData: IProjectData, liveSyncInfo: ILiveSyncInfo, deviceDescriptors: ILiveSyncDeviceDescriptor[], ): Promise { const rebuiltInformation: IDictionary<{ packageFilePath: string; platform: string; isEmulator: boolean; }> = {}; const deviceAction = async (device: Mobile.IDevice) => { const deviceDescriptor = _.find( deviceDescriptors, (dd) => dd.identifier === device.deviceInfo.identifier, ); const prepareData = this.$prepareDataService.getPrepareData( liveSyncInfo.projectDir, device.deviceInfo.platform, { ...liveSyncInfo, ...deviceDescriptor.buildData, nativePrepare: { skipNativePrepare: !!deviceDescriptor.skipNativePrepare, }, watch: !liveSyncInfo.skipWatcher, }, ); const usesDevServerFile = this.usesDevServerFile( device, projectData, liveSyncInfo, ); if (!usesDevServerFile) { // For Android + Vite HMR, own the `adb reverse` ourselves — // with our SDK-resolved adb, scoped to this exact serial, and // only after the device is up — then hand the bundler the // result via env vars. This MUST run before `prepare` (which // spawns the Vite bundler that inherits `process.env`) so the // bundler trusts the tunnel instead of racing us to spawn its // own adb during config-load. See packages/vite hardening. await this.setupAndroidViteHmrReverse( device, projectData, liveSyncInfo, "pre-build", ); } const prepareResultData = await this.$prepareController.prepare(prepareData); const buildData = { ...deviceDescriptor.buildData, buildForDevice: !device.isEmulator, buildForMac: isIOSMacDevice(device), }; const platformData = this.$platformsDataService.getPlatformData( device.deviceInfo.platform, projectData, ); try { let packageFilePath: string = null; // Case where we have three devices attached, a change that requires build is found, // we'll rebuild the app only for the first device, but we should install new package on all three devices. if ( rebuiltInformation[platformData.platformNameLowerCase] && (this.$mobileHelper.isAndroidPlatform( platformData.platformNameLowerCase, ) || rebuiltInformation[platformData.platformNameLowerCase] .isEmulator === device.isEmulator) ) { packageFilePath = rebuiltInformation[platformData.platformNameLowerCase] .packageFilePath; await this.$deviceInstallAppService.installOnDevice( device, buildData, packageFilePath, ); } else { const shouldBuild = prepareResultData.hasNativeChanges || buildData.nativePrepare.forceRebuildNativeApp || (await this.$buildController.shouldBuild(buildData)); if (shouldBuild) { packageFilePath = await deviceDescriptor.buildAction(); rebuiltInformation[platformData.platformNameLowerCase] = { isEmulator: device.isEmulator, platform: platformData.platformNameLowerCase, packageFilePath, }; } else { await this.$analyticsService.trackEventActionInGoogleAnalytics({ action: TrackActionNames.LiveSync, device, projectDir: projectData.projectDir, }); } await this.$deviceInstallAppService.installOnDeviceIfNeeded( device, buildData, packageFilePath, ); } const platformLiveSyncService = this.$liveSyncServiceResolver.resolveLiveSyncService( platformData.platformNameLowerCase, ); if (usesDevServerFile) { await this.chooseDevServerOrigin(device); } const { force, useHotModuleReload, skipWatcher } = liveSyncInfo; const liveSyncResultInfo = await platformLiveSyncService.fullSync({ force, useHotModuleReload, projectData, device, watch: !skipWatcher, liveSyncDeviceData: deviceDescriptor, }); if (!usesDevServerFile) { // Re-establish the adb reverse on the CURRENT transport right // before launch — the transport can change during build/install // and drop the mapping set in `pre-build`, which would leave the // app unable to reach the Vite dev server at 127.0.0.1. await this.setupAndroidViteHmrReverse( device, projectData, liveSyncInfo, "pre-launch", ); } await this.refreshApplication( projectData, liveSyncResultInfo, null, deviceDescriptor, ); this.$logger.info( `Successfully synced application ${liveSyncResultInfo.deviceAppData.appIdentifier} on device ${liveSyncResultInfo.deviceAppData.device.deviceInfo.identifier}.`, ); this.emitCore(RunOnDeviceEvents.runOnDeviceStarted, { projectDir: projectData.projectDir, deviceIdentifier: device.deviceInfo.identifier, applicationIdentifier: projectData.projectIdentifiers[ device.deviceInfo.platform.toLowerCase() ], }); } catch (err) { this.$logger.warn( `Unable to apply changes on device: ${device.deviceInfo.identifier}. Error is: ${err.message}.`, ); this.$logger.trace(err); this.emitCore(RunOnDeviceEvents.runOnDeviceError, { projectDir: projectData.projectDir, deviceIdentifier: device.deviceInfo.identifier, applicationIdentifier: projectData.projectIdentifiers[ device.deviceInfo.platform.toLowerCase() ], error: err, }); await this.stop({ projectDir: projectData.projectDir, deviceIdentifiers: [device.deviceInfo.identifier], stopOptions: { shouldAwaitAllActions: false }, }); } }; await this.addActionToChain(projectData.projectDir, () => this.$devicesService.execute(deviceAction, (device: Mobile.IDevice) => _.some( deviceDescriptors, (deviceDescriptor) => deviceDescriptor.identifier === device.deviceInfo.identifier, ), ), ); } /** * Whether the device reads its dev server origin from a `dev-server.json` * the CLI delivers, rather than from the bundle. */ private usesDevServerFile( device: Mobile.IDevice, projectData: IProjectData, liveSyncInfo: ILiveSyncInfo, ): boolean { return ( projectData.bundler === "vite" && !liveSyncInfo.skipWatcher && !!liveSyncInfo.useHotModuleReload && !liveSyncInfo.release && this.$bundlerCompilerService.usesDevServerFile( device.deviceInfo.platform, projectData, ) ); } /** * Sets up the device's route to the dev server and records the origin its * `dev-server.json` carries. Must run before the full sync: that sync * delivers the file, and on Android it launches the app. */ private async chooseDevServerOrigin(device: Mobile.IDevice): Promise { const { platform, identifier } = device.deviceInfo; const preferLan = isTruthyEnvFlag(process.env.NS_HMR_PREFER_LAN_HOST); let adbReverse = false; let port: number; if (this.$mobileHelper.isAndroidPlatform(platform)) { if (!isTruthyEnvFlag(process.env.NS_HMR_NO_ADB_REVERSE) && !preferLan) { port = await this.$viteHmrPortService.getPort(platform); try { adbReverse = await this.ensureAndroidReverse( device, identifier, port, ); } catch (err) { this.$logger.trace( `Setting up adb reverse tcp:${port} on ${identifier} failed: ${err}`, ); } } } else if ( !device.isEmulator && !preferLan && !process.env.NS_HMR_HOST?.trim() ) { await this.iOSDeviceTunnelService.open(device); } const origin = await this.devServerOriginService.chooseOrigin(device, { adbReverse, }); if (port && !adbReverse) { this.$logger.warn( `Could not confirm 'adb reverse tcp:${port}' on ${identifier}, so the app uses the Vite dev server at ${origin}. If this persists, cold-boot or wipe the emulator, or set NS_HMR_NO_ADB_REVERSE=1.`, ); } else { this.$logger.info( `${device.deviceInfo.displayName || identifier} uses the Vite dev server at ${origin}.`, ); } } /** * Set up `adb reverse tcp: tcp:` for an Android device * when the project bundles with Vite in HMR/watch mode, then export * the result to the bundler subprocess via environment variables. * Only for a `@nativescript/vite` that bakes the origin into * `bundle.mjs`; see `chooseDevServerOrigin` for one that reads * `dev-server.json`. * * The Vite dev-host helper prefers an ADB tunnel (device-side * `127.0.0.1:` → host) over the emulator's flaky slirp NAT * (`10.0.2.2`). Historically the bundler tried to wire that tunnel * itself at config-load time, racing this CLI's device discovery * over the single global adb daemon and intermittently freezing the * run at "Searching for devices…". The CLI is the right owner: it * knows the exact target serial and when the device is ready, and it * already drives a single, version-matched adb. We do the reverse * here and signal the bundler with `NS_ADB_REVERSE_READY=1` so it * never spawns adb on its own. * * Best-effort: any failure is logged at trace level and swallowed. * The bundler then falls back to its own (now hardened) adb path, or * ultimately to `10.0.2.2`, so a reverse hiccup never fails the run. */ private async setupAndroidViteHmrReverse( device: Mobile.IDevice, projectData: IProjectData, liveSyncInfo: ILiveSyncInfo, phase: "pre-build" | "pre-launch", ): Promise { try { if (!this.$mobileHelper.isAndroidPlatform(device.deviceInfo.platform)) { return; } if (projectData.bundler !== "vite") { return; } // HMR over the tunnel only matters for a live watch session. if (liveSyncInfo.skipWatcher || !liveSyncInfo.useHotModuleReload) { return; } // Respect the user's explicit opt-out — they want the // `10.0.2.2` / LAN path, so don't create a tunnel or claim one // exists. if (isTruthyEnvFlag(process.env.NS_HMR_NO_ADB_REVERSE)) { return; } // `NS_HMR_PREFER_LAN_HOST` means the dev wants LAN routing // (physical device over Wi-Fi); the dev-host resolver suppresses // the adb-reverse path for it, so don't bother wiring one. if (isTruthyEnvFlag(process.env.NS_HMR_PREFER_LAN_HOST)) { return; } const serial = device.deviceInfo.identifier; const port = await this.$viteHmrPortService.getPort( device.deviceInfo.platform, ); if (phase === "pre-build") { // Decide the origin baked into bundle.mjs. Hand the bundler our // exact adb (so any self-managed fallback can't version-mismatch // the daemon) and, if the tunnel comes up, tell it to emit // `127.0.0.1` and skip adb entirely. process.env.NS_ADB_PATH = await this.$staticConfig.getAdbFilePath(); process.env.NS_DEVICE_SERIAL = serial; const ok = await this.ensureAndroidReverse(device, serial, port); if (ok) { process.env.NS_ADB_REVERSE_READY = "1"; this.$logger.info( `Set up adb reverse tcp:${port} tcp:${port} for ${serial} (Vite HMR routes device-side 127.0.0.1:${port} through ADB).`, ); } else { this.$logger.warn( `Could not confirm 'adb reverse tcp:${port}' on ${serial} (device adbd slow/unresponsive). Vite HMR will fall back to 10.0.2.2. If this persists, cold-boot/wipe the emulator, or set NS_HMR_NO_ADB_REVERSE=1.`, ); } return; } // phase === "pre-launch": re-establish the mapping right before the // app boots. `adb reverse` mappings are bound to the device's adb // transport, and that transport can change during the (long) build // + install (fresh emulators reconnect as they settle), silently // dropping the early mapping. We only bother when we actually told // the bundle to use `127.0.0.1` (READY set during pre-build). if (!isTruthyEnvFlag(process.env.NS_ADB_REVERSE_READY)) { return; } const ok = await this.ensureAndroidReverse(device, serial, port); if (!ok) { this.$logger.warn( `adb reverse tcp:${port} was not active before launch on ${serial}; the app may fail to reach the Vite dev server at 127.0.0.1:${port}.`, ); } } catch (err) { this.$logger.trace( `Setting up adb reverse for Vite HMR (${phase}) failed; leaving it to the bundler fallback. Error: ${err}`, ); } } /** * Apply `adb reverse tcp: tcp:` to the device and confirm * via `adb reverse --list` that it actually landed, retrying a few * times. Every device-side call is bounded with a Node `spawn` timeout * + `SIGKILL` so a wedged/slow adbd (observed blocking 90s+ on some * fresh-boot / API-36 arm64 emulators) can never hang the run — the * hung adb child is reaped, not orphaned. Returns whether the mapping * is confirmed present. */ private async ensureAndroidReverse( device: Mobile.IDevice, serial: string, port: number, ): Promise { const adb = (device as Mobile.IAndroidDevice).adb; const ADB_WAIT_MS = 15000; const ADB_REVERSE_MS = 20000; const bounded = (timeout: number) => ({ deviceIdentifier: serial, treatErrorsAsWarnings: true, childProcessOptions: { timeout, killSignal: "SIGKILL" }, }); // `wait-for-device` only blocks until the transport is up; bounded so a // never-ready device can't stall us. await adb.executeCommand(["wait-for-device"], bounded(ADB_WAIT_MS)); for (let attempt = 1; attempt <= 3; attempt++) { await adb.executeCommand( ["reverse", `tcp:${port}`, `tcp:${port}`], bounded(ADB_REVERSE_MS), ); // Verify it landed (a SIGKILL'd-on-timeout reverse resolves rather // than throws, so success of the call isn't proof). const list = ( await adb.executeCommand(["reverse", "--list"], bounded(ADB_WAIT_MS)) )?.toString?.() ?? ""; if (list.includes(`tcp:${port}`)) { return true; } } return false; } private async syncChangedDataOnDevices( data: IFilesChangeEventData, projectData: IProjectData, liveSyncInfo: ILiveSyncInfo, ): Promise { const successfullySyncedMessageFormat = `Successfully synced application %s on device %s.`; const rebuiltInformation: IDictionary<{ packageFilePath: string; platform: string; isEmulator: boolean; }> = {}; const deviceAction = async (device: Mobile.IDevice) => { const deviceDescriptors = this.$liveSyncProcessDataService.getDeviceDescriptors( projectData.projectDir, ); const deviceDescriptor = _.find( deviceDescriptors, (dd) => dd.identifier === device.deviceInfo.identifier, ); const platformData = this.$platformsDataService.getPlatformData( data.platform, projectData, ); const prepareData = this.$prepareDataService.getPrepareData( liveSyncInfo.projectDir, device.deviceInfo.platform, { ...liveSyncInfo, ...deviceDescriptor.buildData, nativePrepare: { skipNativePrepare: !!deviceDescriptor.skipNativePrepare, }, watch: !liveSyncInfo.skipWatcher, }, ); try { const platformLiveSyncService = this.$liveSyncServiceResolver.resolveLiveSyncService( device.deviceInfo.platform, ); const allAppFiles = data.hmrData?.fallbackFiles?.length ? data.hmrData.fallbackFiles : data.files; const filesToSync = data.hasOnlyHotUpdateFiles ? data.files : allAppFiles; const watchInfo = { liveSyncDeviceData: deviceDescriptor, projectData, // todo: remove stale files once everything is stable // currently, watcher fires multiple times & may clean up unsynced files // filesToRemove: data.staleFiles ?? [], filesToRemove: [] as string[], filesToSync, hmrData: data.hmrData, useHotModuleReload: liveSyncInfo.useHotModuleReload, force: liveSyncInfo.force, connectTimeout: 1000, }; const deviceAppData = await platformLiveSyncService.getAppData( _.merge({ device, watch: true }, watchInfo), ); if (data.hasNativeChanges) { const rebuiltInfo = rebuiltInformation[platformData.platformNameLowerCase] && (this.$mobileHelper.isAndroidPlatform( platformData.platformNameLowerCase, ) || rebuiltInformation[platformData.platformNameLowerCase] .isEmulator === device.isEmulator); if (!rebuiltInfo) { await this.$prepareNativePlatformService.prepareNativePlatform( platformData, projectData, prepareData, ); await deviceDescriptor.buildAction(); rebuiltInformation[platformData.platformNameLowerCase] = { isEmulator: device.isEmulator, platform: platformData.platformNameLowerCase, packageFilePath: null, }; } await this.$deviceInstallAppService.installOnDevice( device, deviceDescriptor.buildData, rebuiltInformation[platformData.platformNameLowerCase] .packageFilePath, ); await platformLiveSyncService.syncAfterInstall(device, watchInfo); await this.refreshApplication( projectData, { deviceAppData, modifiedFilesData: [], isFullSync: false, useHotModuleReload: liveSyncInfo.useHotModuleReload, }, data, deviceDescriptor, ); this.$logger.info( util.format( successfullySyncedMessageFormat, deviceAppData.appIdentifier, device.deviceInfo.identifier, ), ); } else { const isInHMRMode = liveSyncInfo.useHotModuleReload && data.hmrData && data.hmrData.hash; if (isInHMRMode) { this.$hmrStatusService.watchHmrStatus( device.deviceInfo.identifier, data.hmrData.hash, ); } const watchAction = async (): Promise => { const liveSyncResultInfo = await platformLiveSyncService.liveSyncWatchAction( device, watchInfo, ); const fullSyncAction = async () => { watchInfo.filesToSync = allAppFiles; const fullLiveSyncResultInfo = await platformLiveSyncService.liveSyncWatchAction( device, watchInfo, ); // IMPORTANT: keep the same instance as we rely on side effects _.assign(liveSyncResultInfo, fullLiveSyncResultInfo); }; await this.$hooksService.executeBeforeHooks("watchAction", { hookArgs: { liveSyncResultInfo, filesToSync, allAppFiles, isInHMRMode, filesChangedEvent: data, }, }); await this.refreshApplication( projectData, liveSyncResultInfo, data, deviceDescriptor, fullSyncAction, ); if (!liveSyncResultInfo.didRecover && isInHMRMode) { const status = await this.$hmrStatusService.getHmrStatus( device.deviceInfo.identifier, data.hmrData.hash, ); // the timeout is assumed OK as the app could be blocked on a breakpoint if (status === HmrConstants.HMR_ERROR_STATUS) { await fullSyncAction(); liveSyncResultInfo.isFullSync = true; await this.refreshApplication( projectData, liveSyncResultInfo, data, deviceDescriptor, ); } } await this.$hooksService.executeAfterHooks("watchAction", { liveSyncResultInfo, filesToSync, allAppFiles, filesChangedEvent: data, isInHMRMode, }); this.$logger.info( util.format( successfullySyncedMessageFormat, deviceAppData.appIdentifier, device.deviceInfo.identifier, ), ); }; if (liveSyncInfo.useHotModuleReload) { try { this.$logger.trace( "Try executing watch action without any preparation of files.", ); await watchAction(); this.$logger.trace( "Successfully executed watch action without any preparation of files.", ); return; } catch (err) { this.$logger.trace( `Error while trying to execute fast sync. Now we'll check the state of the app and we'll try to resurrect from the error. The error is: ${err}`, ); } } const reinstalled = await this.$deviceInstallAppService.installOnDeviceIfNeeded( device, deviceDescriptor.buildData, ); if ( reinstalled && this.usesDevServerFile(device, projectData, liveSyncInfo) ) { await platformLiveSyncService.syncAfterInstall(device, watchInfo); } watchInfo.connectTimeout = null; await watchAction(); } } catch (err: any) { this.$logger.warn( `Unable to apply changes for device: ${ device.deviceInfo.identifier }. Error is: ${err && err.message}. Will retry on next change.`, ); this.emitCore(RunOnDeviceEvents.runOnDeviceError, { projectDir: projectData.projectDir, deviceIdentifier: device.deviceInfo.identifier, applicationIdentifier: projectData.projectIdentifiers[ device.deviceInfo.platform.toLowerCase() ], error: err, }); } }; await this.addActionToChain(projectData.projectDir, () => this.$devicesService.execute(deviceAction, (device: Mobile.IDevice) => { const liveSyncProcessInfo = this.$liveSyncProcessDataService.getPersistedData( projectData.projectDir, ); return ( data.platform.toLowerCase() === device.deviceInfo.platform.toLowerCase() && liveSyncProcessInfo && _.some( liveSyncProcessInfo.deviceDescriptors, (deviceDescriptor) => deviceDescriptor.identifier === device.deviceInfo.identifier, ) ); }), ); } private scheduleSyncOnDevices( data: IFilesChangeEventData, projectData: IProjectData, liveSyncInfo: ILiveSyncInfo, ): void { if (this._syncInProgress) { const platform = data.platform; const existing = this._pendingSyncs.get(platform); if (existing) { existing.data = this.mergeFilesChangeEvents(existing.data, data); } else { this._pendingSyncs.set(platform, { data, projectData, liveSyncInfo }); } return; } this.executeSyncOnDevices(data, projectData, liveSyncInfo); } private async executeSyncOnDevices( data: IFilesChangeEventData, projectData: IProjectData, liveSyncInfo: ILiveSyncInfo, ): Promise { this._syncInProgress = true; try { await this.syncChangedDataOnDevices(data, projectData, liveSyncInfo); } catch (err: any) { this.$logger.trace(`Error during sync on devices: ${err.message || err}`); } finally { const nextEntry = this._pendingSyncs.entries().next(); if (!nextEntry.done) { const [platform, pending] = nextEntry.value; this._pendingSyncs.delete(platform); this.executeSyncOnDevices( pending.data, pending.projectData, pending.liveSyncInfo, ); } else { this._syncInProgress = false; } } } private mergeFilesChangeEvents( a: IFilesChangeEventData, b: IFilesChangeEventData, ): IFilesChangeEventData { return { files: [...new Set([...a.files, ...b.files])], staleFiles: [ ...new Set([...(a.staleFiles || []), ...(b.staleFiles || [])]), ], hasOnlyHotUpdateFiles: a.hasOnlyHotUpdateFiles && b.hasOnlyHotUpdateFiles, hasNativeChanges: a.hasNativeChanges || b.hasNativeChanges, hmrData: b.hmrData, platform: b.platform, }; } private async addActionToChain( projectDir: string, action: () => Promise, ): Promise { const liveSyncInfo = this.$liveSyncProcessDataService.getPersistedData(projectDir); if (liveSyncInfo) { liveSyncInfo.actionsChain = liveSyncInfo.actionsChain .then(async () => { if (!liveSyncInfo.isStopped) { liveSyncInfo.currentSyncAction = action(); const res = await liveSyncInfo.currentSyncAction; return res; } }) .catch((err: any) => { this.$logger.warn(`Error in action chain: ${err.message || err}`); }); const result = await liveSyncInfo.actionsChain; return result; } } private emitCore(event: string, data: ILiveSyncEventData): void { this.$logger.trace(`Will emit event ${event} with data`, data); this.emit(event, data); } } injector.register("runController", RunController);