From 7a381cf0f451d75612ffc9f8aac2b42a5910063a Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 21 Nov 2026 05:22:03 -0300 Subject: [PATCH 01/16] feat(ios): serve Vite dev over the USB CoreDevice tunnel A USB-connected iOS 17+ / visionOS device reaches the Mac over a CoreDevice tunnel (a utun with an fdXX::/64 ULA pair) without Wi-Fi and without the Local Network prompt. The tunnel only exists while a client holds it, and every new tunnel gets a new address. For a Vite HMR session whose only target of a platform is such a device, the run controller now opens the tunnel before prepare: it holds it with `devicectl device notification observe` for the session, reads the device's end from `devicectl list devices`, and takes the Mac's address in the same subnet from the local interfaces. The bundler passes that address to both Vite children as NS_HMR_HOST, so bundle.mjs and the dev server use the tunnel origin. The holder is killed when the device leaves the session or the CLI exits; if it dies on its own the CLI warns that the app lost the dev server. Only an @nativescript/vite that lists the platform under nativescriptCli.singleProcessDev gets the tunnel: older releases bind the dev server to NS_HMR_HOST and put an IPv6 literal into URLs unbracketed. A user-set NS_HMR_HOST, simulators, Wi-Fi or network-paired devices, iOS < 17, a missing devicectl, a tunnel that does not come up and sessions with more than one device of the platform also keep the LAN host from @nativescript/vite, with one trace line. --- lib/bootstrap.ts | 4 + lib/contracts/index.ts | 1 + lib/contracts/ios-device-tunnel-service.ts | 25 ++ lib/controllers/run-controller.ts | 71 ++++ .../bundler/bundler-compiler-service.ts | 33 +- lib/services/bundler/bundler.ts | 5 + lib/services/ios/ios-device-tunnel-service.ts | 312 ++++++++++++++++++ test/contracts.ts | 2 + test/controllers/run-controller.ts | 148 +++++++++ .../bundler/bundler-compiler-service.ts | 70 ++++ .../services/ios/ios-device-tunnel-service.ts | 282 ++++++++++++++++ 11 files changed, 950 insertions(+), 3 deletions(-) create mode 100644 lib/contracts/ios-device-tunnel-service.ts create mode 100644 lib/services/ios/ios-device-tunnel-service.ts create mode 100644 test/services/ios/ios-device-tunnel-service.ts diff --git a/lib/bootstrap.ts b/lib/bootstrap.ts index 4251bb5e95..469281df58 100644 --- a/lib/bootstrap.ts +++ b/lib/bootstrap.ts @@ -694,6 +694,10 @@ injector.require( "viteHmrPortService", "./services/bundler/vite-hmr-port-service", ); +injector.require( + "iOSDeviceTunnelService", + "./services/ios/ios-device-tunnel-service", +); injector.require( "applePortalSessionService", diff --git a/lib/contracts/index.ts b/lib/contracts/index.ts index 1c49a51d9c..37a8642d8f 100644 --- a/lib/contracts/index.ts +++ b/lib/contracts/index.ts @@ -50,6 +50,7 @@ export { Errors } from "./errors"; export { FileSystem } from "./file-system"; export { HostInfo } from "./host-info"; export { HttpClient } from "./http-client"; +export { IOSDeviceTunnelService } from "./ios-device-tunnel-service"; export { Logger } from "./logger"; export { PackageManager } from "./package-manager"; export { ProjectData } from "./project-data"; diff --git a/lib/contracts/ios-device-tunnel-service.ts b/lib/contracts/ios-device-tunnel-service.ts new file mode 100644 index 0000000000..099b14f5ed --- /dev/null +++ b/lib/contracts/ios-device-tunnel-service.ts @@ -0,0 +1,25 @@ +import { Contract } from "../common/di/contract"; + +/** + * Holds the CoreDevice tunnel of a USB-connected iOS 17+ / visionOS device + * so an app can reach the Vite dev server on the Mac over the cable, without + * Wi-Fi or the Local Network prompt. + */ +@Contract({ name: "iOSDeviceTunnelService" }) +export abstract class IOSDeviceTunnelService { + /** + * Opens the device's CoreDevice tunnel and keeps it up until `close` or + * the CLI exits. Resolves the Mac's address on the tunnel, or null when + * the device has no usable USB tunnel. A tunnel gets a new address every + * time it is re-established. + */ + abstract open(device: Mobile.IDevice): Promise; + + /** + * The Mac's tunnel address for the single device of `platform` that has + * an open tunnel, if any. + */ + abstract getHostAddress(platform: string): string | undefined; + + abstract close(deviceIdentifier: string): Promise; +} diff --git a/lib/controllers/run-controller.ts b/lib/controllers/run-controller.ts index 6d24fab353..f605e49bee 100644 --- a/lib/controllers/run-controller.ts +++ b/lib/controllers/run-controller.ts @@ -25,6 +25,7 @@ import { } from "../common/declarations"; import { IInjector } from "../common/definitions/yok"; import { ViteHmrPortService } from "../contracts/vite-hmr-port-service"; +import { IOSDeviceTunnelService } from "../contracts/ios-device-tunnel-service"; import { injector } from "../common/yok"; import { isIOSMacDevice } from "../common/mobile/ios/mac/ios-mac-constants"; @@ -67,6 +68,7 @@ export class RunController extends EventEmitter implements IRunController { protected $projectDataService: IProjectDataService, private $staticConfig: Config.IStaticConfig, private $viteHmrPortService: ViteHmrPortService, + private $iOSDeviceTunnelService: IOSDeviceTunnelService, ) { super(); } @@ -168,6 +170,10 @@ export class RunController extends EventEmitter implements IRunController { _.includes(deviceIdentifiersToRemove, descriptor.identifier), ).map((descriptor) => descriptor.identifier); + for (const deviceIdentifier of removedDeviceIdentifiers) { + 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++) { @@ -648,6 +654,13 @@ export class RunController extends EventEmitter implements IRunController { platform: string; isEmulator: boolean; }> = {}; + // Snapshot before any device action: a device whose sync fails leaves + // the session but must still count as a target of its platform. + const sessionDeviceDescriptors = [ + ...this.$liveSyncProcessDataService.getDeviceDescriptors( + projectData.projectDir, + ), + ]; const deviceAction = async (device: Mobile.IDevice) => { const deviceDescriptor = _.find( @@ -680,6 +693,12 @@ export class RunController extends EventEmitter implements IRunController { liveSyncInfo, "pre-build", ); + await this.openIOSViteHmrTunnel( + device, + projectData, + liveSyncInfo, + sessionDeviceDescriptors, + ); const prepareResultData = await this.$prepareController.prepare(prepareData); @@ -821,6 +840,58 @@ export class RunController extends EventEmitter implements IRunController { ); } + /** + * Serves Vite HMR to a USB-connected iOS / visionOS device over its + * CoreDevice tunnel. One dev server bakes one origin into `bundle.mjs` + * and a tunnel address is reachable only from its own device, so this + * applies only when the device is the session's only target of its + * platform. Must run before `prepare` spawns the Vite children. + */ + private async openIOSViteHmrTunnel( + device: Mobile.IDevice, + projectData: IProjectData, + liveSyncInfo: ILiveSyncInfo, + sessionDeviceDescriptors: ILiveSyncDeviceDescriptor[], + ): Promise { + const { platform, identifier } = device.deviceInfo; + if ( + !this.$mobileHelper.isApplePlatform(platform) || + projectData.bundler !== "vite" || + liveSyncInfo.skipWatcher || + !liveSyncInfo.useHotModuleReload || + liveSyncInfo.release || + process.env.NS_HMR_HOST + ) { + return; + } + if ( + !this.$bundlerCompilerService.acceptsIPv6DevHost(platform, projectData) + ) { + this.$logger.trace( + `Not using a USB tunnel for ${identifier}: the installed @nativescript/vite does not accept an IPv6 dev host.`, + ); + return; + } + + const platformTargets = sessionDeviceDescriptors.filter((descriptor) => { + const target = this.$devicesService.getDeviceByIdentifier( + descriptor.identifier, + ); + return ( + !target || + target.deviceInfo.platform.toLowerCase() === platform.toLowerCase() + ); + }); + if (platformTargets.length !== 1) { + this.$logger.trace( + `Not using a USB tunnel for ${identifier}: the session has ${platformTargets.length} ${platform} targets.`, + ); + return; + } + + await this.$iOSDeviceTunnelService.open(device); + } + /** * Set up `adb reverse tcp: tcp:` for an Android device * when the project bundles with Vite in HMR/watch mode, then export diff --git a/lib/services/bundler/bundler-compiler-service.ts b/lib/services/bundler/bundler-compiler-service.ts index 010ab95181..878954973b 100644 --- a/lib/services/bundler/bundler-compiler-service.ts +++ b/lib/services/bundler/bundler-compiler-service.ts @@ -35,6 +35,7 @@ import { } from "../../common/declarations"; import { ICleanupService } from "../../definitions/cleanup-service"; import { ViteHmrPortService } from "../../contracts/vite-hmr-port-service"; +import { IOSDeviceTunnelService } from "../../contracts/ios-device-tunnel-service"; import { injector } from "../../common/yok"; import { resolvePackagePath, @@ -122,6 +123,7 @@ export class BundlerCompilerService private $packageInstallationManager: IPackageInstallationManager, // private $sharedEventBus: ISharedEventBus private $projectConfigService: IProjectConfigService, private $viteHmrPortService: ViteHmrPortService, + private $iOSDeviceTunnelService: IOSDeviceTunnelService, ) { super(); } @@ -796,19 +798,38 @@ export class BundlerCompilerService if (process.env[VITE_SINGLE_PROCESS_ENV] === "0") { return false; } + return this.getViteSingleProcessPlatforms(projectData).includes(platform); + } + + /** + * Older `@nativescript/vite` releases bind the dev server to + * `NS_HMR_HOST` and put an IPv6 literal into URLs unbracketed. The fix + * shipped together with single-process dev, so its platform list is the + * capability marker. + */ + public acceptsIPv6DevHost( + platform: string, + projectData: IProjectData, + ): boolean { + return this.getViteSingleProcessPlatforms(projectData).includes( + platform.toLowerCase(), + ); + } + + private getViteSingleProcessPlatforms(projectData: IProjectData): string[] { try { const packageJSONPath = resolvePackageJSONPath( this.getBundlerPackageName(), { paths: [projectData.projectDir] }, ); if (!packageJSONPath) { - return false; + return []; } const platforms = this.$fs.readJson(packageJSONPath)?.nativescriptCli?.singleProcessDev; - return Array.isArray(platforms) && platforms.includes(platform); + return Array.isArray(platforms) ? platforms : []; } catch { - return false; + return []; } } @@ -832,6 +853,8 @@ export class BundlerCompilerService * sessions — the dev-server port. The port is resolved here, once, and * handed to `@nativescript/vite` as `NS_HMR_PORT`, so the URLs baked into * `bundle.mjs`, the server's bind and the `adb reverse` tunnel all match. + * When the platform's only device has a USB tunnel open, its Mac address + * becomes `NS_HMR_HOST`, unless the user set one. */ private async getViteChildEnv( platform: string, @@ -844,6 +867,10 @@ export class BundlerCompilerService env.NS_HMR_PORT = String( await this.$viteHmrPortService.getPort(platform), ); + const tunnelHost = this.$iOSDeviceTunnelService.getHostAddress(platform); + if (tunnelHost && !process.env.NS_HMR_HOST) { + env.NS_HMR_HOST = tunnelHost; + } } return env; } diff --git a/lib/services/bundler/bundler.ts b/lib/services/bundler/bundler.ts index 0b6d2997cd..b9ac76c92b 100644 --- a/lib/services/bundler/bundler.ts +++ b/lib/services/bundler/bundler.ts @@ -30,6 +30,11 @@ declare global { prepareData: IPrepareData, ): Promise; stopBundlerCompiler(platform: string): Promise; + /** + * Whether the installed `@nativescript/vite` accepts a bare IPv6 + * address as `NS_HMR_HOST` for `platform`. + */ + acceptsIPv6DevHost(platform: string, projectData: IProjectData): boolean; } /** diff --git a/lib/services/ios/ios-device-tunnel-service.ts b/lib/services/ios/ios-device-tunnel-service.ts new file mode 100644 index 0000000000..66b370f8f3 --- /dev/null +++ b/lib/services/ios/ios-device-tunnel-service.ts @@ -0,0 +1,312 @@ +import * as os from "os"; +import * as semver from "semver"; +import { + IChildProcess, + IDictionary, + IFileSystem, + IHostInfo, +} from "../../common/declarations"; +import { injector } from "../../common/yok"; +import { IOSDeviceTunnelService } from "../../contracts/ios-device-tunnel-service"; +import { ICleanupService } from "../../definitions/cleanup-service"; +import { ITempService } from "../../definitions/temp-service"; +import { DeviceConnectionType } from "../../constants"; +import type * as child_process from "child_process"; + +/** Long enough to outlive any dev session; devicectl's default is 300 s. */ +const HOLD_SECONDS = 365 * 24 * 60 * 60; + +interface ICoreDeviceConnection { + transportType?: string; + tunnelState?: string; + tunnelIPAddress?: string; +} + +interface ITunnel { + platform: string; + holder?: child_process.ChildProcess; + address: Promise; + closed: boolean; +} + +export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { + private tunnels: IDictionary = {}; + private hostAddresses: IDictionary = {}; + private tunnelReadyTimeoutMs = 10000; + private tunnelPollIntervalMs = 500; + + constructor( + private $childProcess: IChildProcess, + private $cleanupService: ICleanupService, + private $fs: IFileSystem, + private $hostInfo: IHostInfo, + private $logger: ILogger, + private $mobileHelper: Mobile.IMobileHelper, + private $tempService: ITempService, + ) {} + + public open(device: Mobile.IDevice): Promise { + const id = device.deviceInfo.identifier; + if (!this.tunnels[id]) { + const tunnel: ITunnel = { + platform: device.deviceInfo.platform.toLowerCase(), + address: null, + closed: false, + }; + this.tunnels[id] = tunnel; + tunnel.address = this.openCore(device, tunnel).catch((err): null => { + this.$logger.trace(`Unable to open the USB tunnel to ${id}: ${err}`); + this.stopHolder(tunnel); + return null; + }); + } + return this.tunnels[id].address; + } + + public getHostAddress(platform: string): string | undefined { + return this.hostAddresses[platform.toLowerCase()]; + } + + public async close(deviceIdentifier: string): Promise { + const tunnel = this.tunnels[deviceIdentifier]; + if (!tunnel) { + return; + } + delete this.tunnels[deviceIdentifier]; + tunnel.closed = true; + const address = await tunnel.address; + if (address && this.hostAddresses[tunnel.platform] === address) { + delete this.hostAddresses[tunnel.platform]; + } + this.stopHolder(tunnel); + } + + private async openCore( + device: Mobile.IDevice, + tunnel: ITunnel, + ): Promise { + const id = device.deviceInfo.identifier; + const ineligible = this.getIneligibilityReason(device); + if (ineligible) { + this.$logger.trace(`Not using a USB tunnel for ${id}: ${ineligible}.`); + return null; + } + + const jsonPath = await this.$tempService.path({ + prefix: "ns-devicectl-", + suffix: ".json", + }); + const connection = await this.getConnection(id, jsonPath); + if (connection?.transportType !== "wired") { + this.$logger.trace( + `Not using a USB tunnel for ${id}: devicectl reports ${connection ? `transport ${connection.transportType}` : "no such device"}.`, + ); + return null; + } + + tunnel.holder = this.startHolder(id, tunnel); + const deviceAddress = await this.waitForTunnel(id, jsonPath, tunnel); + const hostAddress = + deviceAddress && this.findLocalTunnelAddress(deviceAddress); + if (!hostAddress) { + this.$logger.trace( + `Not using a USB tunnel for ${id}: ${deviceAddress ? `no local address on the tunnel to ${deviceAddress}` : "the tunnel did not come up"}.`, + ); + this.stopHolder(tunnel); + return null; + } + if (tunnel.closed) { + return null; + } + + this.hostAddresses[tunnel.platform] = hostAddress; + this.$logger.info( + `Using the USB tunnel to ${device.deviceInfo.displayName} (Mac address ${hostAddress}) for the Vite dev server.`, + ); + return hostAddress; + } + + private getIneligibilityReason(device: Mobile.IDevice): string | null { + const { deviceInfo } = device; + if (!this.$hostInfo.isDarwin) { + return "not on macOS"; + } + if (device.isEmulator) { + return "it is a simulator"; + } + if (!deviceInfo.connectionTypes?.includes(DeviceConnectionType.USB)) { + return "it is not connected over USB"; + } + const version = semver.coerce(deviceInfo.version); + if ( + this.$mobileHelper.isiOSPlatform(deviceInfo.platform) && + (!version || semver.major(version) < 17) + ) { + return `iOS ${deviceInfo.version} has no CoreDevice tunnel`; + } + return null; + } + + private async getConnection( + deviceIdentifier: string, + jsonPath: string, + ): Promise { + const result = await this.$childProcess.trySpawnFromCloseEvent("xcrun", [ + "devicectl", + "list", + "devices", + "--quiet", + "--json-output", + jsonPath, + ]); + if (result.exitCode !== 0 || !this.$fs.exists(jsonPath)) { + return null; + } + const devices: any[] = this.$fs.readJson(jsonPath)?.result?.devices || []; + const match = devices.find( + (d) => d?.hardwareProperties?.udid === deviceIdentifier, + ); + return match ? match.connectionProperties || {} : null; + } + + private startHolder( + deviceIdentifier: string, + tunnel: ITunnel, + ): child_process.ChildProcess { + const holder = this.$childProcess.spawn( + "xcrun", + [ + "devicectl", + "device", + "notification", + "observe", + "--device", + deviceIdentifier, + "--name", + "org.nativescript.cli.usb-tunnel", + "--session-timeout", + String(HOLD_SECONDS), + "--timeout", + String(HOLD_SECONDS + 60), + "--quiet", + ], + { stdio: "ignore" }, + ); + holder.on("error", (err: Error) => + this.$logger.trace(`USB tunnel holder for ${deviceIdentifier}: ${err}`), + ); + holder.once("exit", () => { + if (holder.pid) { + this.$cleanupService.removeKillProcess(holder.pid.toString()); + } + if (tunnel.closed || tunnel.holder !== holder) { + return; + } + tunnel.holder = undefined; + tunnel.address.then((address) => { + if (address && !tunnel.closed) { + this.$logger.warn( + `The USB tunnel to ${deviceIdentifier} closed, so the app can no longer reach the Vite dev server at ${address}. Restart the run to reconnect.`, + ); + } + }); + }); + if (holder.pid) { + this.$cleanupService.addKillProcess(holder.pid.toString()); + } + return holder; + } + + private async waitForTunnel( + deviceIdentifier: string, + jsonPath: string, + tunnel: ITunnel, + ): Promise { + const deadline = Date.now() + this.tunnelReadyTimeoutMs; + while (tunnel.holder && !tunnel.closed && Date.now() < deadline) { + const connection = await this.getConnection(deviceIdentifier, jsonPath); + if ( + connection?.tunnelState === "connected" && + connection.tunnelIPAddress + ) { + return connection.tunnelIPAddress; + } + await new Promise((resolve) => + setTimeout(resolve, this.tunnelPollIntervalMs), + ); + } + return null; + } + + /** + * devicectl reports the device's end of the tunnel; the Mac's end is the + * local interface address in the same subnet. + */ + private findLocalTunnelAddress(deviceAddress: string): string | null { + const device = parseIPv6(deviceAddress); + if (!device) { + return null; + } + for (const entries of Object.values(this.getNetworkInterfaces())) { + for (const entry of entries || []) { + const local = parseIPv6(entry.address); + const mask = parseIPv6(entry.netmask); + if ( + !local || + !mask || + entry.address.includes("%") || + local.every((group, i) => group === device[i]) + ) { + continue; + } + if ( + local.every((group, i) => (group & mask[i]) === (device[i] & mask[i])) + ) { + return entry.address; + } + } + } + return null; + } + + protected getNetworkInterfaces(): NodeJS.Dict { + return os.networkInterfaces(); + } + + private stopHolder(tunnel: ITunnel): void { + const holder = tunnel.holder; + tunnel.holder = undefined; + if (holder && holder.exitCode === null && holder.signalCode === null) { + holder.kill(); + } + } +} + +/** The eight 16-bit groups of an IPv6 address, or null for anything else. */ +function parseIPv6(address: string): number[] | null { + if (!address || !address.includes(":") || address.includes(".")) { + return null; + } + const [head, tail, ...rest] = address.split("%")[0].split("::"); + if (rest.length) { + return null; + } + const toGroups = (part: string) => + part ? part.split(":").map((g) => parseInt(g, 16)) : []; + const left = toGroups(head); + const right = toGroups(tail); + const missing = 8 - left.length - right.length; + if (tail === undefined ? missing !== 0 : missing < 1) { + return null; + } + const groups = [ + ...left, + ...new Array(Math.max(missing, 0)).fill(0), + ...right, + ]; + return groups.every((g) => Number.isInteger(g) && g >= 0 && g <= 0xffff) + ? groups + : null; +} + +injector.register("iOSDeviceTunnelService", IOSDeviceTunnelServiceImpl); diff --git a/test/contracts.ts b/test/contracts.ts index ddd9cfbaf4..cd11151864 100644 --- a/test/contracts.ts +++ b/test/contracts.ts @@ -11,6 +11,7 @@ import { FileSystem, HostInfo, HttpClient, + IOSDeviceTunnelService, Logger, PackageManager, ProjectData, @@ -39,6 +40,7 @@ const tranche: [ProviderToken, string][] = [ [FileSystem, "fs"], [HostInfo, "hostInfo"], [HttpClient, "httpClient"], + [IOSDeviceTunnelService, "iOSDeviceTunnelService"], [Logger, "logger"], [PackageManager, "packageManager"], [ProjectData, "projectData"], diff --git a/test/controllers/run-controller.ts b/test/controllers/run-controller.ts index e8d419eb3b..0f048b05a4 100644 --- a/test/controllers/run-controller.ts +++ b/test/controllers/run-controller.ts @@ -142,6 +142,11 @@ function createTestInjector() { injector.register("viteHmrPortService", { getPort: async () => 5173, }); + injector.register("iOSDeviceTunnelService", { + open: async (): Promise => null, + getHostAddress: (): string => undefined, + close: async () => ({}), + }); const devicesService = injector.resolve("devicesService"); devicesService.getDevicesForPlatform = () => @@ -266,6 +271,149 @@ describe("RunController", () => { }); }); + describe("USB tunnel for Vite HMR", () => { + const secondIOSDevice = { + deviceInfo: { identifier: "mySecondiOSDevice", platform: "ios" }, + }; + const secondIOSDeviceDescriptor = { + identifier: "mySecondiOSDevice", + buildAction: async () => buildOutputPath, + buildData: {}, + }; + const hmrLiveSyncInfo = { ...liveSyncInfo, useHotModuleReload: true }; + let openedFor: string[] = null; + let closed: string[] = null; + let events: string[] = null; + let previousHost: string = undefined; + let acceptsIPv6DevHost: boolean; + + beforeEach(() => { + acceptsIPv6DevHost = true; + injector.resolve("bundlerCompilerService").acceptsIPv6DevHost = () => + acceptsIPv6DevHost; + openedFor = []; + closed = []; + events = []; + previousHost = process.env.NS_HMR_HOST; + delete process.env.NS_HMR_HOST; + map.mySecondiOSDevice = { + device: secondIOSDevice, + descriptor: secondIOSDeviceDescriptor, + }; + + const projectDataService = injector.resolve("projectDataService"); + const getProjectData = + projectDataService.getProjectData.bind(projectDataService); + projectDataService.getProjectData = (dir: string) => { + const projectData = getProjectData(dir); + projectData.bundler = "vite"; + return projectData; + }; + injector.resolve("devicesService").getDeviceByIdentifier = ( + identifier: string, + ) => map[identifier]?.device; + const tunnelService = injector.resolve("iOSDeviceTunnelService"); + tunnelService.open = async (device: Mobile.IDevice) => { + openedFor.push(device.deviceInfo.identifier); + events.push("tunnel"); + return "fd00::2"; + }; + tunnelService.close = async (identifier: string) => { + closed.push(identifier); + }; + const prepareController = injector.resolve("prepareController"); + prepareController.prepare = async (currentPrepareData: PrepareData) => { + events.push(`prepare ${currentPrepareData.platform}`); + return { + platform: currentPrepareData.platform, + hasNativeChanges: false, + }; + }; + }); + + afterEach(() => { + delete map.mySecondiOSDevice; + if (previousHost === undefined) { + delete process.env.NS_HMR_HOST; + } else { + process.env.NS_HMR_HOST = previousHost; + } + }); + + it("opens the tunnel of the session's only iOS device before preparing", async () => { + mockDevicesService(injector, [iOSDevice, androidDevice]); + + await runController.run({ + liveSyncInfo: hmrLiveSyncInfo, + deviceDescriptors: [iOSDeviceDescriptor, androidDeviceDescriptor], + }); + + assert.deepStrictEqual(openedFor, ["myiOSDevice"]); + assert.isBelow(events.indexOf("tunnel"), events.indexOf("prepare ios")); + }); + + it("does not open a tunnel when the session has two iOS devices", async () => { + mockDevicesService(injector, [iOSDevice, secondIOSDevice]); + + await runController.run({ + liveSyncInfo: hmrLiveSyncInfo, + deviceDescriptors: [iOSDeviceDescriptor, secondIOSDeviceDescriptor], + }); + + assert.deepStrictEqual(openedFor, []); + }); + + it("does not open a tunnel when the user set NS_HMR_HOST", async () => { + process.env.NS_HMR_HOST = "192.168.1.10"; + mockDevicesService(injector, [iOSDevice]); + + await runController.run({ + liveSyncInfo: hmrLiveSyncInfo, + deviceDescriptors: [iOSDeviceDescriptor], + }); + + assert.deepStrictEqual(openedFor, []); + }); + + it("does not open a tunnel for a @nativescript/vite without IPv6 dev hosts", async () => { + acceptsIPv6DevHost = false; + mockDevicesService(injector, [iOSDevice]); + + await runController.run({ + liveSyncInfo: hmrLiveSyncInfo, + deviceDescriptors: [iOSDeviceDescriptor], + }); + + assert.deepStrictEqual(openedFor, []); + }); + + it("does not open a tunnel without HMR", async () => { + mockDevicesService(injector, [iOSDevice]); + + await runController.run({ + liveSyncInfo, + deviceDescriptors: [iOSDeviceDescriptor], + }); + + assert.deepStrictEqual(openedFor, []); + }); + + it("closes the tunnel of a device that stops", async () => { + mockDevicesService(injector, [iOSDevice]); + await runController.run({ + liveSyncInfo: hmrLiveSyncInfo, + deviceDescriptors: [iOSDeviceDescriptor], + }); + + await runController.stop({ + projectDir, + deviceIdentifiers: ["myiOSDevice"], + }); + + assert.deepStrictEqual(closed, ["myiOSDevice"]); + }); + }); + describe("restartApplication", () => { let restartedApps: Array<{ device: string; isFullSync: boolean }> = null; let infoMessages: string[] = null; diff --git a/test/services/bundler/bundler-compiler-service.ts b/test/services/bundler/bundler-compiler-service.ts index dea9e43b01..e70fef2839 100644 --- a/test/services/bundler/bundler-compiler-service.ts +++ b/test/services/bundler/bundler-compiler-service.ts @@ -92,6 +92,9 @@ function createTestInjector( testInjector.register("viteHmrPortService", { getPort: async () => 5173, }); + testInjector.register("iOSDeviceTunnelService", { + getHostAddress: (): string => undefined, + }); return testInjector; } @@ -374,6 +377,56 @@ describe("BundlerCompilerService", () => { { NS_VITE_DIST_DIR: ".ns-vite-build/ios" }, ); }); + + describe("with a USB tunnel open", () => { + let previousHost: string; + beforeEach(() => { + previousHost = process.env.NS_HMR_HOST; + delete process.env.NS_HMR_HOST; + testInjector.resolve("iOSDeviceTunnelService").getHostAddress = ( + platform: string, + ) => (platform === "ios" ? "fd6f:72e:8d34::2" : undefined); + }); + afterEach(() => { + if (previousHost === undefined) { + delete process.env.NS_HMR_HOST; + } else { + process.env.NS_HMR_HOST = previousHost; + } + }); + + it("hands the tunnel's Mac address to that platform only", async () => { + assert.deepEqual( + await (bundlerCompilerService).getViteChildEnv("ios", { + watch: true, + hmr: true, + }), + { + NS_VITE_DIST_DIR: ".ns-vite-build/ios", + NS_HMR_PORT: "5173", + NS_HMR_HOST: "fd6f:72e:8d34::2", + }, + ); + assert.notProperty( + await (bundlerCompilerService).getViteChildEnv("android", { + watch: true, + hmr: true, + }), + "NS_HMR_HOST", + ); + }); + + it("leaves a user-set NS_HMR_HOST alone", async () => { + process.env.NS_HMR_HOST = "192.168.1.10"; + assert.notProperty( + await (bundlerCompilerService).getViteChildEnv("ios", { + watch: true, + hmr: true, + }), + "NS_HMR_HOST", + ); + }); + }); }); describe("startViteDevServer", () => { @@ -988,6 +1041,23 @@ describe("BundlerCompilerService", () => { process.env.NS_VITE_SINGLE_PROCESS = "0"; assert.isFalse(supports("ios")); }); + + it("marks the packages that accept an IPv6 dev host, opted out or not", () => { + const accepts = (platform: string) => + bundlerCompilerService.acceptsIPv6DevHost(platform, { + projectDir, + }); + writeVitePackage({ name: "@nativescript/vite" }); + assert.isFalse(accepts("iOS")); + + writeVitePackage({ + name: "@nativescript/vite", + nativescriptCli: { singleProcessDev: ["ios"] }, + }); + process.env.NS_VITE_SINGLE_PROCESS = "0"; + assert.isTrue(accepts("iOS")); + assert.isFalse(accepts("visionOS")); + }); }); describe("stopBundlerCompiler", () => { diff --git a/test/services/ios/ios-device-tunnel-service.ts b/test/services/ios/ios-device-tunnel-service.ts new file mode 100644 index 0000000000..b7c59b8945 --- /dev/null +++ b/test/services/ios/ios-device-tunnel-service.ts @@ -0,0 +1,282 @@ +import { assert } from "chai"; +import { EventEmitter } from "events"; +import { Yok } from "../../../lib/common/yok"; +import { IInjector } from "../../../lib/common/definitions/yok"; +import { MobileHelper } from "../../../lib/common/mobile/mobile-helper"; +import { DevicePlatformsConstants } from "../../../lib/common/mobile/device-platforms-constants"; +import { DeviceConnectionType } from "../../../lib/constants"; +import { IOSDeviceTunnelServiceImpl } from "../../../lib/services/ios/ios-device-tunnel-service"; +import { ErrorsStub, LoggerStub, TempServiceStub } from "../../stubs"; + +const UDID = "00008030-000408D42692802E"; + +class FakeHolder extends EventEmitter { + public pid = 4242; + public exitCode: number = null; + public signalCode: string = null; + public killed = false; + + public kill(): boolean { + this.killed = true; + this.signalCode = "SIGTERM"; + this.emit("exit", null, "SIGTERM"); + return true; + } +} + +function coreDevice(connectionProperties: object, udid = UDID) { + return { + identifier: "3E4C6519-03DF-5CEB-9EA3-E027A81E52FC", + hardwareProperties: { udid, platform: "iOS", reality: "physical" }, + connectionProperties, + }; +} + +const wiredDisconnected = { + transportType: "wired", + tunnelState: "disconnected", +}; +const wiredConnected = { + transportType: "wired", + tunnelState: "connected", + tunnelIPAddress: "fd6f:72e:8d34::1", +}; + +const macInterfaces = { + lo0: [ + { + address: "::1", + netmask: "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", + family: "IPv6", + }, + ], + en0: [ + { address: "192.168.1.10", netmask: "255.255.255.0", family: "IPv4" }, + { + address: "fe80::1c2b:3a4d:5e6f:7081", + netmask: "ffff:ffff:ffff:ffff::", + family: "IPv6", + }, + ], + utun4: [ + { + address: "fd58:5467:5f7b::2", + netmask: "ffff:ffff:ffff:ffff::", + family: "IPv6", + }, + ], + utun6: [ + { + address: "fe80::35c1:eb2f:dbab:733", + netmask: "ffff:ffff:ffff:ffff::", + family: "IPv6", + }, + { + address: "fd6f:72e:8d34::2", + netmask: "ffff:ffff:ffff:ffff::", + family: "IPv6", + }, + ], +}; + +function iPhone( + overrides: Partial = {}, + isEmulator = false, +) { + return ({ + isEmulator, + deviceInfo: { + identifier: UDID, + displayName: "iPhone", + platform: "iOS", + version: "26.0.1", + connectionTypes: [DeviceConnectionType.USB], + ...overrides, + }, + }); +} + +describe("IOSDeviceTunnelService", () => { + let devicectlListings: object[][]; + let listCalls: number; + let spawned: { args: string[]; holder: FakeHolder }[]; + let warnings: string[]; + let isDarwin: boolean; + let service: IOSDeviceTunnelServiceImpl; + + beforeEach(() => { + devicectlListings = []; + listCalls = 0; + spawned = []; + warnings = []; + isDarwin = true; + let lastListing: object[] = []; + + const injector: IInjector = new Yok(); + injector.register("childProcess", { + trySpawnFromCloseEvent: async () => { + listCalls++; + if (devicectlListings.length) { + lastListing = devicectlListings.shift(); + } + return { exitCode: lastListing ? 0 : 1 }; + }, + spawn: (command: string, args: string[]) => { + const holder = new FakeHolder(); + spawned.push({ args: [command, ...args], holder }); + return holder; + }, + }); + injector.register("cleanupService", { + addKillProcess: async () => ({}), + removeKillProcess: async () => ({}), + }); + injector.register("fs", { + exists: () => true, + readJson: () => ({ result: { devices: lastListing } }), + }); + injector.register("hostInfo", { + get isDarwin() { + return isDarwin; + }, + }); + const logger = new LoggerStub(); + logger.warn = (message: string) => { + warnings.push(message); + }; + injector.register("logger", logger); + injector.register("errors", ErrorsStub); + injector.register("devicePlatformsConstants", DevicePlatformsConstants); + injector.register("mobileHelper", MobileHelper); + injector.register("tempService", TempServiceStub); + injector.register("iOSDeviceTunnelService", IOSDeviceTunnelServiceImpl); + + service = injector.resolve("iOSDeviceTunnelService"); + (service).tunnelReadyTimeoutMs = 200; + (service).tunnelPollIntervalMs = 1; + (service).getNetworkInterfaces = () => macInterfaces; + }); + + it("holds the tunnel and resolves the Mac's address on it", async () => { + devicectlListings = [ + [coreDevice(wiredDisconnected)], + [coreDevice({ ...wiredConnected, tunnelState: "connecting" })], + [coreDevice(wiredConnected)], + ]; + + const address = await service.open(iPhone()); + + assert.equal(address, "fd6f:72e:8d34::2"); + assert.equal(service.getHostAddress("ios"), "fd6f:72e:8d34::2"); + assert.lengthOf(spawned, 1); + assert.includeMembers(spawned[0].args, [ + "xcrun", + "devicectl", + "notification", + "observe", + UDID, + ]); + assert.isFalse(spawned[0].holder.killed); + }); + + it("opens one tunnel per device however often it is asked", async () => { + devicectlListings = [[coreDevice(wiredConnected)]]; + + const [first, second] = await Promise.all([ + service.open(iPhone()), + service.open(iPhone()), + ]); + + assert.equal(first, "fd6f:72e:8d34::2"); + assert.equal(second, first); + assert.lengthOf(spawned, 1); + }); + + const ineligible: { + name: string; + device: Mobile.IDevice; + darwin?: boolean; + }[] = [ + { name: "a simulator", device: iPhone({}, true) }, + { + name: "a Wi-Fi-only device", + device: iPhone({ connectionTypes: [DeviceConnectionType.Wifi] }), + }, + { name: "a device on iOS 16", device: iPhone({ version: "16.7.10" }) }, + { name: "a device on a non-macOS host", device: iPhone(), darwin: false }, + ]; + for (const testCase of ineligible) { + it(`does not ask devicectl about ${testCase.name}`, async () => { + isDarwin = testCase.darwin ?? true; + + assert.isNull(await service.open(testCase.device)); + assert.equal(listCalls, 0); + assert.lengthOf(spawned, 0); + }); + } + + it("does not hold a tunnel for a network-paired device", async () => { + devicectlListings = [ + [coreDevice({ ...wiredConnected, transportType: "localNetwork" })], + ]; + + assert.isNull(await service.open(iPhone())); + assert.lengthOf(spawned, 0); + }); + + it("falls back when devicectl is unavailable", async () => { + devicectlListings = [null]; + + assert.isNull(await service.open(iPhone())); + assert.lengthOf(spawned, 0); + }); + + it("falls back when devicectl does not know the device", async () => { + devicectlListings = [ + [coreDevice(wiredConnected, "00008112-000128D1022A201E")], + ]; + + assert.isNull(await service.open(iPhone())); + assert.lengthOf(spawned, 0); + }); + + it("releases the holder when the tunnel never comes up", async () => { + devicectlListings = [[coreDevice(wiredDisconnected)]]; + + assert.isNull(await service.open(iPhone())); + assert.lengthOf(spawned, 1); + assert.isTrue(spawned[0].holder.killed); + assert.isUndefined(service.getHostAddress("ios")); + }); + + it("releases the holder when no Mac interface is on the tunnel", async () => { + devicectlListings = [ + [coreDevice({ ...wiredConnected, tunnelIPAddress: "fd11:2233:4455::1" })], + ]; + + assert.isNull(await service.open(iPhone())); + assert.isTrue(spawned[0].holder.killed); + }); + + it("releases the holder and the host on close", async () => { + devicectlListings = [[coreDevice(wiredConnected)]]; + await service.open(iPhone()); + + await service.close(UDID); + + assert.isTrue(spawned[0].holder.killed); + assert.isUndefined(service.getHostAddress("ios")); + assert.isEmpty(warnings); + }); + + it("warns when the tunnel closes on its own", async () => { + devicectlListings = [[coreDevice(wiredConnected)]]; + await service.open(iPhone()); + + spawned[0].holder.emit("exit", 1, null); + await new Promise((resolve) => setImmediate(resolve)); + + assert.lengthOf(warnings, 1); + assert.include(warnings[0], "fd6f:72e:8d34::2"); + }); +}); From 091f0fed8a2331424c33589677131f816322cb9c Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sun, 22 Nov 2026 19:34:45 -0300 Subject: [PATCH 02/16] fix(ios): count only the --device selection when deciding on the USB tunnel Session descriptors include every discovered device, so a booted simulator or a second iOS device on the network turned the tunnel off even when --device picked a single USB iPhone. --- lib/controllers/run-controller.ts | 9 +++++++++ test/controllers/run-controller.ts | 18 ++++++++++++++++++ test/stubs.ts | 1 + 3 files changed, 28 insertions(+) diff --git a/lib/controllers/run-controller.ts b/lib/controllers/run-controller.ts index f605e49bee..b8d2d6d308 100644 --- a/lib/controllers/run-controller.ts +++ b/lib/controllers/run-controller.ts @@ -873,7 +873,16 @@ export class RunController extends EventEmitter implements IRunController { return; } + // Descriptors cover every discovered device; `--device` narrows the + // session to one of them. + const selected = this.$devicesService.getDeviceByDeviceOption(); const platformTargets = sessionDeviceDescriptors.filter((descriptor) => { + if ( + selected && + descriptor.identifier !== selected.deviceInfo.identifier + ) { + return false; + } const target = this.$devicesService.getDeviceByIdentifier( descriptor.identifier, ); diff --git a/test/controllers/run-controller.ts b/test/controllers/run-controller.ts index 0f048b05a4..d57afc6fd2 100644 --- a/test/controllers/run-controller.ts +++ b/test/controllers/run-controller.ts @@ -363,6 +363,24 @@ describe("RunController", () => { assert.deepStrictEqual(openedFor, []); }); + it("opens the tunnel of the --device selection when another iOS device is attached", async () => { + const devicesService = injector.resolve("devicesService"); + devicesService.getDeviceByDeviceOption = () => iOSDevice; + mockDevicesService(injector, [iOSDevice]); + + try { + await runController.run({ + liveSyncInfo: hmrLiveSyncInfo, + deviceDescriptors: [iOSDeviceDescriptor, secondIOSDeviceDescriptor], + }); + } finally { + devicesService.getDeviceByDeviceOption = (): Mobile.IDevice => + undefined; + } + + assert.deepStrictEqual(openedFor, ["myiOSDevice"]); + }); + it("does not open a tunnel when the user set NS_HMR_HOST", async () => { process.env.NS_HMR_HOST = "192.168.1.10"; mockDevicesService(injector, [iOSDevice]); diff --git a/test/stubs.ts b/test/stubs.ts index c8b9bf3663..b797ea7fad 100644 --- a/test/stubs.ts +++ b/test/stubs.ts @@ -1557,6 +1557,7 @@ export class InjectorStub extends Yok implements IInjector { this.register("devicesService", { getDevice: (): Mobile.IDevice => undefined, getDeviceByIdentifier: (): Mobile.IDevice => undefined, + getDeviceByDeviceOption: (): Mobile.IDevice => undefined, }); this.register("terminalSpinnerService", TerminalSpinnerServiceStub); } From 8c5b27405f7278a36b80939a636d5c3b086141b8 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 24 Nov 2026 15:54:38 -0300 Subject: [PATCH 03/16] refactor(ios): build the USB tunnel service on the DI contract IOSDeviceTunnelServiceImpl extends the IOSDeviceTunnelService contract and injects its dependencies as fields instead of through $-constructor parameters. Bootstrap registers it with provideLazy() under the contract token, replacing injector.require() and the module's self-registration; the contract name keeps string lookups resolving. RunController and BundlerCompilerService inject the contract rather than taking it as a constructor parameter. --- lib/bootstrap.ts | 11 ++- lib/controllers/run-controller.ts | 7 +- .../bundler/bundler-compiler-service.ts | 5 +- lib/services/ios/ios-device-tunnel-service.ts | 69 +++++++++---------- .../services/ios/ios-device-tunnel-service.ts | 8 ++- 5 files changed, 53 insertions(+), 47 deletions(-) diff --git a/lib/bootstrap.ts b/lib/bootstrap.ts index 469281df58..26de9617b9 100644 --- a/lib/bootstrap.ts +++ b/lib/bootstrap.ts @@ -1,6 +1,7 @@ import { provideLazy } from "./common/di"; import { injector } from "./common/yok"; import { registerBuiltInCommand } from "./common/services/command-definition-adapter"; +import { IOSDeviceTunnelService } from "./contracts/ios-device-tunnel-service"; import type { fontsCommandDefinition } from "./commands/fonts"; import { AndroidPluginMirrorService } from "./contracts/internal/android-plugin-mirror-service"; import { NativeFileHashesMemo } from "./contracts/internal/native-file-hashes-memo"; @@ -694,9 +695,13 @@ injector.require( "viteHmrPortService", "./services/bundler/vite-hmr-port-service", ); -injector.require( - "iOSDeviceTunnelService", - "./services/ios/ios-device-tunnel-service", +injector.register( + provideLazy( + IOSDeviceTunnelService, + (): typeof import("./services/ios/ios-device-tunnel-service").IOSDeviceTunnelServiceImpl => + require("./services/ios/ios-device-tunnel-service") + .IOSDeviceTunnelServiceImpl, + ), ); injector.require( diff --git a/lib/controllers/run-controller.ts b/lib/controllers/run-controller.ts index b8d2d6d308..f80750cbf5 100644 --- a/lib/controllers/run-controller.ts +++ b/lib/controllers/run-controller.ts @@ -28,8 +28,10 @@ import { ViteHmrPortService } from "../contracts/vite-hmr-port-service"; import { IOSDeviceTunnelService } from "../contracts/ios-device-tunnel-service"; import { injector } from "../common/yok"; import { isIOSMacDevice } from "../common/mobile/ios/mac/ios-mac-constants"; +import { inject } from "../common/di/inject"; export class RunController extends EventEmitter implements IRunController { + private iOSDeviceTunnelService = inject(IOSDeviceTunnelService); private prepareReadyEventHandler: any = null; private appRestartRequestHandler: ( request: IBundlerAppRestartRequest, @@ -68,7 +70,6 @@ export class RunController extends EventEmitter implements IRunController { protected $projectDataService: IProjectDataService, private $staticConfig: Config.IStaticConfig, private $viteHmrPortService: ViteHmrPortService, - private $iOSDeviceTunnelService: IOSDeviceTunnelService, ) { super(); } @@ -171,7 +172,7 @@ export class RunController extends EventEmitter implements IRunController { ).map((descriptor) => descriptor.identifier); for (const deviceIdentifier of removedDeviceIdentifiers) { - await this.$iOSDeviceTunnelService.close(deviceIdentifier); + await this.iOSDeviceTunnelService.close(deviceIdentifier); } // Handle the case when no more devices left for any of the persisted platforms @@ -898,7 +899,7 @@ export class RunController extends EventEmitter implements IRunController { return; } - await this.$iOSDeviceTunnelService.open(device); + await this.iOSDeviceTunnelService.open(device); } /** diff --git a/lib/services/bundler/bundler-compiler-service.ts b/lib/services/bundler/bundler-compiler-service.ts index 878954973b..55046d6b13 100644 --- a/lib/services/bundler/bundler-compiler-service.ts +++ b/lib/services/bundler/bundler-compiler-service.ts @@ -37,6 +37,7 @@ import { ICleanupService } from "../../definitions/cleanup-service"; import { ViteHmrPortService } from "../../contracts/vite-hmr-port-service"; import { IOSDeviceTunnelService } from "../../contracts/ios-device-tunnel-service"; import { injector } from "../../common/yok"; +import { inject } from "../../common/di/inject"; import { resolvePackagePath, resolvePackageJSONPath, @@ -96,6 +97,7 @@ export class BundlerCompilerService extends EventEmitter implements IBundlerCompilerService { + private iOSDeviceTunnelService = inject(IOSDeviceTunnelService); private bundlerProcesses: IDictionary = {}; // Vite-only: the long-lived `vite serve` dev server the device fetches // modules and HMR updates from. Keyed by platform, managed by this CLI @@ -123,7 +125,6 @@ export class BundlerCompilerService private $packageInstallationManager: IPackageInstallationManager, // private $sharedEventBus: ISharedEventBus private $projectConfigService: IProjectConfigService, private $viteHmrPortService: ViteHmrPortService, - private $iOSDeviceTunnelService: IOSDeviceTunnelService, ) { super(); } @@ -867,7 +868,7 @@ export class BundlerCompilerService env.NS_HMR_PORT = String( await this.$viteHmrPortService.getPort(platform), ); - const tunnelHost = this.$iOSDeviceTunnelService.getHostAddress(platform); + const tunnelHost = this.iOSDeviceTunnelService.getHostAddress(platform); if (tunnelHost && !process.env.NS_HMR_HOST) { env.NS_HMR_HOST = tunnelHost; } diff --git a/lib/services/ios/ios-device-tunnel-service.ts b/lib/services/ios/ios-device-tunnel-service.ts index 66b370f8f3..31976028fa 100644 --- a/lib/services/ios/ios-device-tunnel-service.ts +++ b/lib/services/ios/ios-device-tunnel-service.ts @@ -1,15 +1,14 @@ import * as os from "os"; import * as semver from "semver"; -import { - IChildProcess, - IDictionary, - IFileSystem, - IHostInfo, -} from "../../common/declarations"; -import { injector } from "../../common/yok"; +import { IDictionary } from "../../common/declarations"; +import { inject } from "../../common/di/inject"; +import { ChildProcess } from "../../contracts/child-process"; +import { FileSystem } from "../../contracts/file-system"; +import { HostInfo } from "../../contracts/host-info"; import { IOSDeviceTunnelService } from "../../contracts/ios-device-tunnel-service"; +import { Logger } from "../../contracts/logger"; +import { TempService } from "../../contracts/temp-service"; import { ICleanupService } from "../../definitions/cleanup-service"; -import { ITempService } from "../../definitions/temp-service"; import { DeviceConnectionType } from "../../constants"; import type * as child_process from "child_process"; @@ -29,22 +28,20 @@ interface ITunnel { closed: boolean; } -export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { +export class IOSDeviceTunnelServiceImpl extends IOSDeviceTunnelService { + private childProcess = inject(ChildProcess); + private cleanupService = inject("cleanupService"); + private fs = inject(FileSystem); + private hostInfo = inject(HostInfo); + private logger = inject(Logger); + private mobileHelper = inject("mobileHelper"); + private tempService = inject(TempService); + private tunnels: IDictionary = {}; private hostAddresses: IDictionary = {}; private tunnelReadyTimeoutMs = 10000; private tunnelPollIntervalMs = 500; - constructor( - private $childProcess: IChildProcess, - private $cleanupService: ICleanupService, - private $fs: IFileSystem, - private $hostInfo: IHostInfo, - private $logger: ILogger, - private $mobileHelper: Mobile.IMobileHelper, - private $tempService: ITempService, - ) {} - public open(device: Mobile.IDevice): Promise { const id = device.deviceInfo.identifier; if (!this.tunnels[id]) { @@ -55,7 +52,7 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { }; this.tunnels[id] = tunnel; tunnel.address = this.openCore(device, tunnel).catch((err): null => { - this.$logger.trace(`Unable to open the USB tunnel to ${id}: ${err}`); + this.logger.trace(`Unable to open the USB tunnel to ${id}: ${err}`); this.stopHolder(tunnel); return null; }); @@ -88,17 +85,17 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { const id = device.deviceInfo.identifier; const ineligible = this.getIneligibilityReason(device); if (ineligible) { - this.$logger.trace(`Not using a USB tunnel for ${id}: ${ineligible}.`); + this.logger.trace(`Not using a USB tunnel for ${id}: ${ineligible}.`); return null; } - const jsonPath = await this.$tempService.path({ + const jsonPath = await this.tempService.path({ prefix: "ns-devicectl-", suffix: ".json", }); const connection = await this.getConnection(id, jsonPath); if (connection?.transportType !== "wired") { - this.$logger.trace( + this.logger.trace( `Not using a USB tunnel for ${id}: devicectl reports ${connection ? `transport ${connection.transportType}` : "no such device"}.`, ); return null; @@ -109,7 +106,7 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { const hostAddress = deviceAddress && this.findLocalTunnelAddress(deviceAddress); if (!hostAddress) { - this.$logger.trace( + this.logger.trace( `Not using a USB tunnel for ${id}: ${deviceAddress ? `no local address on the tunnel to ${deviceAddress}` : "the tunnel did not come up"}.`, ); this.stopHolder(tunnel); @@ -120,7 +117,7 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { } this.hostAddresses[tunnel.platform] = hostAddress; - this.$logger.info( + this.logger.info( `Using the USB tunnel to ${device.deviceInfo.displayName} (Mac address ${hostAddress}) for the Vite dev server.`, ); return hostAddress; @@ -128,7 +125,7 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { private getIneligibilityReason(device: Mobile.IDevice): string | null { const { deviceInfo } = device; - if (!this.$hostInfo.isDarwin) { + if (!this.hostInfo.isDarwin) { return "not on macOS"; } if (device.isEmulator) { @@ -139,7 +136,7 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { } const version = semver.coerce(deviceInfo.version); if ( - this.$mobileHelper.isiOSPlatform(deviceInfo.platform) && + this.mobileHelper.isiOSPlatform(deviceInfo.platform) && (!version || semver.major(version) < 17) ) { return `iOS ${deviceInfo.version} has no CoreDevice tunnel`; @@ -151,7 +148,7 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { deviceIdentifier: string, jsonPath: string, ): Promise { - const result = await this.$childProcess.trySpawnFromCloseEvent("xcrun", [ + const result = await this.childProcess.trySpawnFromCloseEvent("xcrun", [ "devicectl", "list", "devices", @@ -159,10 +156,10 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { "--json-output", jsonPath, ]); - if (result.exitCode !== 0 || !this.$fs.exists(jsonPath)) { + if (result.exitCode !== 0 || !this.fs.exists(jsonPath)) { return null; } - const devices: any[] = this.$fs.readJson(jsonPath)?.result?.devices || []; + const devices: any[] = this.fs.readJson(jsonPath)?.result?.devices || []; const match = devices.find( (d) => d?.hardwareProperties?.udid === deviceIdentifier, ); @@ -173,7 +170,7 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { deviceIdentifier: string, tunnel: ITunnel, ): child_process.ChildProcess { - const holder = this.$childProcess.spawn( + const holder = this.childProcess.spawn( "xcrun", [ "devicectl", @@ -193,11 +190,11 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { { stdio: "ignore" }, ); holder.on("error", (err: Error) => - this.$logger.trace(`USB tunnel holder for ${deviceIdentifier}: ${err}`), + this.logger.trace(`USB tunnel holder for ${deviceIdentifier}: ${err}`), ); holder.once("exit", () => { if (holder.pid) { - this.$cleanupService.removeKillProcess(holder.pid.toString()); + this.cleanupService.removeKillProcess(holder.pid.toString()); } if (tunnel.closed || tunnel.holder !== holder) { return; @@ -205,14 +202,14 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { tunnel.holder = undefined; tunnel.address.then((address) => { if (address && !tunnel.closed) { - this.$logger.warn( + this.logger.warn( `The USB tunnel to ${deviceIdentifier} closed, so the app can no longer reach the Vite dev server at ${address}. Restart the run to reconnect.`, ); } }); }); if (holder.pid) { - this.$cleanupService.addKillProcess(holder.pid.toString()); + this.cleanupService.addKillProcess(holder.pid.toString()); } return holder; } @@ -308,5 +305,3 @@ function parseIPv6(address: string): number[] | null { ? groups : null; } - -injector.register("iOSDeviceTunnelService", IOSDeviceTunnelServiceImpl); diff --git a/test/services/ios/ios-device-tunnel-service.ts b/test/services/ios/ios-device-tunnel-service.ts index b7c59b8945..d96818f9f7 100644 --- a/test/services/ios/ios-device-tunnel-service.ts +++ b/test/services/ios/ios-device-tunnel-service.ts @@ -2,9 +2,11 @@ import { assert } from "chai"; import { EventEmitter } from "events"; import { Yok } from "../../../lib/common/yok"; import { IInjector } from "../../../lib/common/definitions/yok"; +import { provide } from "../../../lib/common/di"; import { MobileHelper } from "../../../lib/common/mobile/mobile-helper"; import { DevicePlatformsConstants } from "../../../lib/common/mobile/device-platforms-constants"; import { DeviceConnectionType } from "../../../lib/constants"; +import { IOSDeviceTunnelService } from "../../../lib/contracts/ios-device-tunnel-service"; import { IOSDeviceTunnelServiceImpl } from "../../../lib/services/ios/ios-device-tunnel-service"; import { ErrorsStub, LoggerStub, TempServiceStub } from "../../stubs"; @@ -149,9 +151,11 @@ describe("IOSDeviceTunnelService", () => { injector.register("devicePlatformsConstants", DevicePlatformsConstants); injector.register("mobileHelper", MobileHelper); injector.register("tempService", TempServiceStub); - injector.register("iOSDeviceTunnelService", IOSDeviceTunnelServiceImpl); + injector.register( + provide(IOSDeviceTunnelService, IOSDeviceTunnelServiceImpl), + ); - service = injector.resolve("iOSDeviceTunnelService"); + service = injector.get(IOSDeviceTunnelService); (service).tunnelReadyTimeoutMs = 200; (service).tunnelPollIntervalMs = 1; (service).getNetworkInterfaces = () => macInterfaces; From 822423e38f84423e24bd3fa1d79c03dd351cf4f6 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 24 Nov 2026 15:57:27 -0300 Subject: [PATCH 04/16] test(ios): register the USB tunnel service and its stubs by contract token The tunnel spec provides the service and the contracted stubs it injects (ChildProcess, FileSystem, HostInfo, Logger, Errors, TempService) by token; the RunController and BundlerCompilerService specs provide and look up the tunnel stub through the IOSDeviceTunnelService contract. --- test/controllers/run-controller.ts | 14 ++-- .../bundler/bundler-compiler-service.ts | 8 ++- .../services/ios/ios-device-tunnel-service.ts | 67 ++++++++++++------- 3 files changed, 57 insertions(+), 32 deletions(-) diff --git a/test/controllers/run-controller.ts b/test/controllers/run-controller.ts index d57afc6fd2..25c3bcd93c 100644 --- a/test/controllers/run-controller.ts +++ b/test/controllers/run-controller.ts @@ -16,6 +16,7 @@ import { PrepareController } from "../../lib/controllers/prepare-controller"; import { LiveSyncProcessDataService } from "../../lib/services/livesync-process-data-service"; import { IDictionary } from "../../lib/common/declarations"; import { IInjector } from "../../lib/common/definitions/yok"; +import { IOSDeviceTunnelService } from "../../lib/contracts/ios-device-tunnel-service"; let isAttachToHmrStatusCalled = false; let prepareData: IPrepareData = null; @@ -142,10 +143,13 @@ function createTestInjector() { injector.register("viteHmrPortService", { getPort: async () => 5173, }); - injector.register("iOSDeviceTunnelService", { - open: async (): Promise => null, - getHostAddress: (): string => undefined, - close: async () => ({}), + injector.register({ + provide: IOSDeviceTunnelService, + useValue: { + open: async (): Promise => null, + getHostAddress: (): string => undefined, + close: async () => ({}), + }, }); const devicesService = injector.resolve("devicesService"); @@ -312,7 +316,7 @@ describe("RunController", () => { injector.resolve("devicesService").getDeviceByIdentifier = ( identifier: string, ) => map[identifier]?.device; - const tunnelService = injector.resolve("iOSDeviceTunnelService"); + const tunnelService = injector.get(IOSDeviceTunnelService); tunnelService.open = async (device: Mobile.IDevice) => { openedFor.push(device.deviceInfo.identifier); events.push("tunnel"); diff --git a/test/services/bundler/bundler-compiler-service.ts b/test/services/bundler/bundler-compiler-service.ts index e70fef2839..174b97c1ac 100644 --- a/test/services/bundler/bundler-compiler-service.ts +++ b/test/services/bundler/bundler-compiler-service.ts @@ -7,6 +7,7 @@ import * as os from "os"; import * as path from "path"; import { ErrorsStub } from "../../stubs"; import { IInjector } from "../../../lib/common/definitions/yok"; +import { IOSDeviceTunnelService } from "../../../lib/contracts/ios-device-tunnel-service"; import { BUNDLER_APP_RESTART_REQUESTED, BUNDLER_COMPILATION_COMPLETE, @@ -92,8 +93,9 @@ function createTestInjector( testInjector.register("viteHmrPortService", { getPort: async () => 5173, }); - testInjector.register("iOSDeviceTunnelService", { - getHostAddress: (): string => undefined, + testInjector.register({ + provide: IOSDeviceTunnelService, + useValue: { getHostAddress: (): string => undefined }, }); return testInjector; @@ -383,7 +385,7 @@ describe("BundlerCompilerService", () => { beforeEach(() => { previousHost = process.env.NS_HMR_HOST; delete process.env.NS_HMR_HOST; - testInjector.resolve("iOSDeviceTunnelService").getHostAddress = ( + testInjector.get(IOSDeviceTunnelService).getHostAddress = ( platform: string, ) => (platform === "ios" ? "fd6f:72e:8d34::2" : undefined); }); diff --git a/test/services/ios/ios-device-tunnel-service.ts b/test/services/ios/ios-device-tunnel-service.ts index d96818f9f7..bdbae10698 100644 --- a/test/services/ios/ios-device-tunnel-service.ts +++ b/test/services/ios/ios-device-tunnel-service.ts @@ -6,7 +6,15 @@ import { provide } from "../../../lib/common/di"; import { MobileHelper } from "../../../lib/common/mobile/mobile-helper"; import { DevicePlatformsConstants } from "../../../lib/common/mobile/device-platforms-constants"; import { DeviceConnectionType } from "../../../lib/constants"; -import { IOSDeviceTunnelService } from "../../../lib/contracts/ios-device-tunnel-service"; +import { + ChildProcess, + Errors, + FileSystem, + HostInfo, + IOSDeviceTunnelService, + Logger, + TempService, +} from "../../../lib/contracts"; import { IOSDeviceTunnelServiceImpl } from "../../../lib/services/ios/ios-device-tunnel-service"; import { ErrorsStub, LoggerStub, TempServiceStub } from "../../stubs"; @@ -115,45 +123,56 @@ describe("IOSDeviceTunnelService", () => { let lastListing: object[] = []; const injector: IInjector = new Yok(); - injector.register("childProcess", { - trySpawnFromCloseEvent: async () => { - listCalls++; - if (devicectlListings.length) { - lastListing = devicectlListings.shift(); - } - return { exitCode: lastListing ? 0 : 1 }; - }, - spawn: (command: string, args: string[]) => { - const holder = new FakeHolder(); - spawned.push({ args: [command, ...args], holder }); - return holder; + injector.register({ + provide: ChildProcess, + useValue: { + trySpawnFromCloseEvent: async () => { + listCalls++; + if (devicectlListings.length) { + lastListing = devicectlListings.shift(); + } + return { exitCode: lastListing ? 0 : 1 }; + }, + spawn: (command: string, args: string[]) => { + const holder = new FakeHolder(); + spawned.push({ args: [command, ...args], holder }); + return holder; + }, }, }); injector.register("cleanupService", { addKillProcess: async () => ({}), removeKillProcess: async () => ({}), }); - injector.register("fs", { - exists: () => true, - readJson: () => ({ result: { devices: lastListing } }), + injector.register({ + provide: FileSystem, + useValue: { + exists: () => true, + readJson: () => ({ result: { devices: lastListing } }), + }, }); - injector.register("hostInfo", { - get isDarwin() { - return isDarwin; + injector.register({ + provide: HostInfo, + useValue: { + get isDarwin() { + return isDarwin; + }, }, }); const logger = new LoggerStub(); logger.warn = (message: string) => { warnings.push(message); }; - injector.register("logger", logger); - injector.register("errors", ErrorsStub); + injector.register([ + { provide: Logger, useValue: logger }, + { provide: Errors, useClass: ErrorsStub }, + ]); injector.register("devicePlatformsConstants", DevicePlatformsConstants); injector.register("mobileHelper", MobileHelper); - injector.register("tempService", TempServiceStub); - injector.register( + injector.register([ + { provide: TempService, useClass: TempServiceStub }, provide(IOSDeviceTunnelService, IOSDeviceTunnelServiceImpl), - ); + ]); service = injector.get(IOSDeviceTunnelService); (service).tunnelReadyTimeoutMs = 200; From 3411519f08346fb8f4fbb1d2e142b2e9f52227bf Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Tue, 1 Dec 2026 19:14:39 -0300 Subject: [PATCH 05/16] refactor(ios): make the USB tunnel service an internal contract The service is the CLI's own plumbing and never shipped under a string name, so its contract moves to lib/contracts/internal as a plain @Contract() and is not exported from nativescript/contracts. --- lib/bootstrap.ts | 2 +- lib/contracts/index.ts | 1 - lib/contracts/{ => internal}/ios-device-tunnel-service.ts | 4 ++-- lib/controllers/run-controller.ts | 2 +- lib/services/bundler/bundler-compiler-service.ts | 2 +- lib/services/ios/ios-device-tunnel-service.ts | 2 +- test/contracts.ts | 2 -- test/controllers/run-controller.ts | 2 +- test/services/bundler/bundler-compiler-service.ts | 2 +- test/services/ios/ios-device-tunnel-service.ts | 2 +- 10 files changed, 9 insertions(+), 12 deletions(-) rename lib/contracts/{ => internal}/ios-device-tunnel-service.ts (89%) diff --git a/lib/bootstrap.ts b/lib/bootstrap.ts index 26de9617b9..3e947cc737 100644 --- a/lib/bootstrap.ts +++ b/lib/bootstrap.ts @@ -1,7 +1,7 @@ import { provideLazy } from "./common/di"; import { injector } from "./common/yok"; import { registerBuiltInCommand } from "./common/services/command-definition-adapter"; -import { IOSDeviceTunnelService } from "./contracts/ios-device-tunnel-service"; +import { IOSDeviceTunnelService } from "./contracts/internal/ios-device-tunnel-service"; import type { fontsCommandDefinition } from "./commands/fonts"; import { AndroidPluginMirrorService } from "./contracts/internal/android-plugin-mirror-service"; import { NativeFileHashesMemo } from "./contracts/internal/native-file-hashes-memo"; diff --git a/lib/contracts/index.ts b/lib/contracts/index.ts index 37a8642d8f..1c49a51d9c 100644 --- a/lib/contracts/index.ts +++ b/lib/contracts/index.ts @@ -50,7 +50,6 @@ export { Errors } from "./errors"; export { FileSystem } from "./file-system"; export { HostInfo } from "./host-info"; export { HttpClient } from "./http-client"; -export { IOSDeviceTunnelService } from "./ios-device-tunnel-service"; export { Logger } from "./logger"; export { PackageManager } from "./package-manager"; export { ProjectData } from "./project-data"; diff --git a/lib/contracts/ios-device-tunnel-service.ts b/lib/contracts/internal/ios-device-tunnel-service.ts similarity index 89% rename from lib/contracts/ios-device-tunnel-service.ts rename to lib/contracts/internal/ios-device-tunnel-service.ts index 099b14f5ed..b80412287d 100644 --- a/lib/contracts/ios-device-tunnel-service.ts +++ b/lib/contracts/internal/ios-device-tunnel-service.ts @@ -1,11 +1,11 @@ -import { Contract } from "../common/di/contract"; +import { Contract } from "../../common/di/contract"; /** * Holds the CoreDevice tunnel of a USB-connected iOS 17+ / visionOS device * so an app can reach the Vite dev server on the Mac over the cable, without * Wi-Fi or the Local Network prompt. */ -@Contract({ name: "iOSDeviceTunnelService" }) +@Contract() export abstract class IOSDeviceTunnelService { /** * Opens the device's CoreDevice tunnel and keeps it up until `close` or diff --git a/lib/controllers/run-controller.ts b/lib/controllers/run-controller.ts index f80750cbf5..185f5c3dd4 100644 --- a/lib/controllers/run-controller.ts +++ b/lib/controllers/run-controller.ts @@ -25,7 +25,7 @@ import { } from "../common/declarations"; import { IInjector } from "../common/definitions/yok"; import { ViteHmrPortService } from "../contracts/vite-hmr-port-service"; -import { IOSDeviceTunnelService } from "../contracts/ios-device-tunnel-service"; +import { IOSDeviceTunnelService } from "../contracts/internal/ios-device-tunnel-service"; import { injector } from "../common/yok"; import { isIOSMacDevice } from "../common/mobile/ios/mac/ios-mac-constants"; import { inject } from "../common/di/inject"; diff --git a/lib/services/bundler/bundler-compiler-service.ts b/lib/services/bundler/bundler-compiler-service.ts index 55046d6b13..003d77a34f 100644 --- a/lib/services/bundler/bundler-compiler-service.ts +++ b/lib/services/bundler/bundler-compiler-service.ts @@ -35,7 +35,7 @@ import { } from "../../common/declarations"; import { ICleanupService } from "../../definitions/cleanup-service"; import { ViteHmrPortService } from "../../contracts/vite-hmr-port-service"; -import { IOSDeviceTunnelService } from "../../contracts/ios-device-tunnel-service"; +import { IOSDeviceTunnelService } from "../../contracts/internal/ios-device-tunnel-service"; import { injector } from "../../common/yok"; import { inject } from "../../common/di/inject"; import { diff --git a/lib/services/ios/ios-device-tunnel-service.ts b/lib/services/ios/ios-device-tunnel-service.ts index 31976028fa..a00c7c7ef4 100644 --- a/lib/services/ios/ios-device-tunnel-service.ts +++ b/lib/services/ios/ios-device-tunnel-service.ts @@ -5,7 +5,7 @@ import { inject } from "../../common/di/inject"; import { ChildProcess } from "../../contracts/child-process"; import { FileSystem } from "../../contracts/file-system"; import { HostInfo } from "../../contracts/host-info"; -import { IOSDeviceTunnelService } from "../../contracts/ios-device-tunnel-service"; +import { IOSDeviceTunnelService } from "../../contracts/internal/ios-device-tunnel-service"; import { Logger } from "../../contracts/logger"; import { TempService } from "../../contracts/temp-service"; import { ICleanupService } from "../../definitions/cleanup-service"; diff --git a/test/contracts.ts b/test/contracts.ts index cd11151864..ddd9cfbaf4 100644 --- a/test/contracts.ts +++ b/test/contracts.ts @@ -11,7 +11,6 @@ import { FileSystem, HostInfo, HttpClient, - IOSDeviceTunnelService, Logger, PackageManager, ProjectData, @@ -40,7 +39,6 @@ const tranche: [ProviderToken, string][] = [ [FileSystem, "fs"], [HostInfo, "hostInfo"], [HttpClient, "httpClient"], - [IOSDeviceTunnelService, "iOSDeviceTunnelService"], [Logger, "logger"], [PackageManager, "packageManager"], [ProjectData, "projectData"], diff --git a/test/controllers/run-controller.ts b/test/controllers/run-controller.ts index 25c3bcd93c..b91b780ab5 100644 --- a/test/controllers/run-controller.ts +++ b/test/controllers/run-controller.ts @@ -16,7 +16,7 @@ import { PrepareController } from "../../lib/controllers/prepare-controller"; import { LiveSyncProcessDataService } from "../../lib/services/livesync-process-data-service"; import { IDictionary } from "../../lib/common/declarations"; import { IInjector } from "../../lib/common/definitions/yok"; -import { IOSDeviceTunnelService } from "../../lib/contracts/ios-device-tunnel-service"; +import { IOSDeviceTunnelService } from "../../lib/contracts/internal/ios-device-tunnel-service"; let isAttachToHmrStatusCalled = false; let prepareData: IPrepareData = null; diff --git a/test/services/bundler/bundler-compiler-service.ts b/test/services/bundler/bundler-compiler-service.ts index 174b97c1ac..c45526d75a 100644 --- a/test/services/bundler/bundler-compiler-service.ts +++ b/test/services/bundler/bundler-compiler-service.ts @@ -7,7 +7,7 @@ import * as os from "os"; import * as path from "path"; import { ErrorsStub } from "../../stubs"; import { IInjector } from "../../../lib/common/definitions/yok"; -import { IOSDeviceTunnelService } from "../../../lib/contracts/ios-device-tunnel-service"; +import { IOSDeviceTunnelService } from "../../../lib/contracts/internal/ios-device-tunnel-service"; import { BUNDLER_APP_RESTART_REQUESTED, BUNDLER_COMPILATION_COMPLETE, diff --git a/test/services/ios/ios-device-tunnel-service.ts b/test/services/ios/ios-device-tunnel-service.ts index bdbae10698..9c8b52d30a 100644 --- a/test/services/ios/ios-device-tunnel-service.ts +++ b/test/services/ios/ios-device-tunnel-service.ts @@ -11,10 +11,10 @@ import { Errors, FileSystem, HostInfo, - IOSDeviceTunnelService, Logger, TempService, } from "../../../lib/contracts"; +import { IOSDeviceTunnelService } from "../../../lib/contracts/internal/ios-device-tunnel-service"; import { IOSDeviceTunnelServiceImpl } from "../../../lib/services/ios/ios-device-tunnel-service"; import { ErrorsStub, LoggerStub, TempServiceStub } from "../../stubs"; From cd4358418a4d86f39dd48dfb47214af54ea2872e Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 3 Dec 2026 04:00:05 -0300 Subject: [PATCH 06/16] style(ios): match the DI conventions used elsewhere inject() comes from the common/di barrel, and the provideLazy loader has no explicit return type, as in the other registrations. --- lib/bootstrap.ts | 2 +- lib/controllers/run-controller.ts | 2 +- lib/services/bundler/bundler-compiler-service.ts | 2 +- lib/services/ios/ios-device-tunnel-service.ts | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/bootstrap.ts b/lib/bootstrap.ts index 3e947cc737..31dfabd607 100644 --- a/lib/bootstrap.ts +++ b/lib/bootstrap.ts @@ -698,7 +698,7 @@ injector.require( injector.register( provideLazy( IOSDeviceTunnelService, - (): typeof import("./services/ios/ios-device-tunnel-service").IOSDeviceTunnelServiceImpl => + () => require("./services/ios/ios-device-tunnel-service") .IOSDeviceTunnelServiceImpl, ), diff --git a/lib/controllers/run-controller.ts b/lib/controllers/run-controller.ts index 185f5c3dd4..dd8d4eb73f 100644 --- a/lib/controllers/run-controller.ts +++ b/lib/controllers/run-controller.ts @@ -28,7 +28,7 @@ import { ViteHmrPortService } from "../contracts/vite-hmr-port-service"; import { IOSDeviceTunnelService } from "../contracts/internal/ios-device-tunnel-service"; import { injector } from "../common/yok"; import { isIOSMacDevice } from "../common/mobile/ios/mac/ios-mac-constants"; -import { inject } from "../common/di/inject"; +import { inject } from "../common/di"; export class RunController extends EventEmitter implements IRunController { private iOSDeviceTunnelService = inject(IOSDeviceTunnelService); diff --git a/lib/services/bundler/bundler-compiler-service.ts b/lib/services/bundler/bundler-compiler-service.ts index 003d77a34f..f51708755f 100644 --- a/lib/services/bundler/bundler-compiler-service.ts +++ b/lib/services/bundler/bundler-compiler-service.ts @@ -37,7 +37,7 @@ import { ICleanupService } from "../../definitions/cleanup-service"; import { ViteHmrPortService } from "../../contracts/vite-hmr-port-service"; import { IOSDeviceTunnelService } from "../../contracts/internal/ios-device-tunnel-service"; import { injector } from "../../common/yok"; -import { inject } from "../../common/di/inject"; +import { inject } from "../../common/di"; import { resolvePackagePath, resolvePackageJSONPath, diff --git a/lib/services/ios/ios-device-tunnel-service.ts b/lib/services/ios/ios-device-tunnel-service.ts index a00c7c7ef4..e0828b3032 100644 --- a/lib/services/ios/ios-device-tunnel-service.ts +++ b/lib/services/ios/ios-device-tunnel-service.ts @@ -1,7 +1,7 @@ import * as os from "os"; import * as semver from "semver"; import { IDictionary } from "../../common/declarations"; -import { inject } from "../../common/di/inject"; +import { inject } from "../../common/di"; import { ChildProcess } from "../../contracts/child-process"; import { FileSystem } from "../../contracts/file-system"; import { HostInfo } from "../../contracts/host-info"; From 61e0ae74e2a05b540a01f253814efe3db9576eaa Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 3 Dec 2026 23:06:26 -0300 Subject: [PATCH 07/16] refactor(ios): implement the USB tunnel service's contract rather than extend it The contract holds only abstract members, so the implementation implements it, as the DI skill now asks. --- lib/services/ios/ios-device-tunnel-service.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/services/ios/ios-device-tunnel-service.ts b/lib/services/ios/ios-device-tunnel-service.ts index e0828b3032..fcce592dc1 100644 --- a/lib/services/ios/ios-device-tunnel-service.ts +++ b/lib/services/ios/ios-device-tunnel-service.ts @@ -28,7 +28,7 @@ interface ITunnel { closed: boolean; } -export class IOSDeviceTunnelServiceImpl extends IOSDeviceTunnelService { +export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { private childProcess = inject(ChildProcess); private cleanupService = inject("cleanupService"); private fs = inject(FileSystem); From cfd83c627b5c4d0fa552c8bedf4c327b638a3c7a Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 4 Dec 2026 01:34:29 -0300 Subject: [PATCH 08/16] fix(ios): bound each devicectl listing for the USB tunnel `devicectl list devices` had no timeout, so a listing that never exits blocked opening the tunnel, and with it the device's prepare; the polling deadline only applies between listings. Each listing now stops after 10 seconds and counts as a failed one, which falls back to the dev server's usual address. --- lib/services/ios/ios-device-tunnel-service.ts | 16 ++++++------ .../services/ios/ios-device-tunnel-service.ts | 25 ++++++++++++++++++- 2 files changed, 32 insertions(+), 9 deletions(-) diff --git a/lib/services/ios/ios-device-tunnel-service.ts b/lib/services/ios/ios-device-tunnel-service.ts index fcce592dc1..d7cc3b14c2 100644 --- a/lib/services/ios/ios-device-tunnel-service.ts +++ b/lib/services/ios/ios-device-tunnel-service.ts @@ -41,6 +41,7 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { private hostAddresses: IDictionary = {}; private tunnelReadyTimeoutMs = 10000; private tunnelPollIntervalMs = 500; + private listTimeoutMs = 10000; public open(device: Mobile.IDevice): Promise { const id = device.deviceInfo.identifier; @@ -148,14 +149,13 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { deviceIdentifier: string, jsonPath: string, ): Promise { - const result = await this.childProcess.trySpawnFromCloseEvent("xcrun", [ - "devicectl", - "list", - "devices", - "--quiet", - "--json-output", - jsonPath, - ]); + // A wedged CoreDevice service can leave devicectl running indefinitely. + const result = await this.childProcess.trySpawnFromCloseEvent( + "xcrun", + ["devicectl", "list", "devices", "--quiet", "--json-output", jsonPath], + {}, + { throwError: false, timeout: this.listTimeoutMs }, + ); if (result.exitCode !== 0 || !this.fs.exists(jsonPath)) { return null; } diff --git a/test/services/ios/ios-device-tunnel-service.ts b/test/services/ios/ios-device-tunnel-service.ts index 9c8b52d30a..74a6e95b9d 100644 --- a/test/services/ios/ios-device-tunnel-service.ts +++ b/test/services/ios/ios-device-tunnel-service.ts @@ -109,6 +109,7 @@ function iPhone( describe("IOSDeviceTunnelService", () => { let devicectlListings: object[][]; let listCalls: number; + let listTimeouts: number[]; let spawned: { args: string[]; holder: FakeHolder }[]; let warnings: string[]; let isDarwin: boolean; @@ -117,6 +118,7 @@ describe("IOSDeviceTunnelService", () => { beforeEach(() => { devicectlListings = []; listCalls = 0; + listTimeouts = []; spawned = []; warnings = []; isDarwin = true; @@ -126,8 +128,14 @@ describe("IOSDeviceTunnelService", () => { injector.register({ provide: ChildProcess, useValue: { - trySpawnFromCloseEvent: async () => { + trySpawnFromCloseEvent: async ( + _command: string, + _args: string[], + _options: object, + spawnFromEventOptions?: { timeout?: number }, + ) => { listCalls++; + listTimeouts.push(spawnFromEventOptions?.timeout); if (devicectlListings.length) { lastListing = devicectlListings.shift(); } @@ -202,6 +210,21 @@ describe("IOSDeviceTunnelService", () => { assert.isFalse(spawned[0].holder.killed); }); + it("bounds every devicectl listing", async () => { + devicectlListings = [ + [coreDevice(wiredDisconnected)], + [coreDevice({ ...wiredConnected, tunnelState: "connecting" })], + [coreDevice(wiredConnected)], + ]; + + await service.open(iPhone()); + + assert.equal(listCalls, 3); + for (const timeout of listTimeouts) { + assert.isAbove(timeout, 0); + } + }); + it("opens one tunnel per device however often it is asked", async () => { devicectlListings = [[coreDevice(wiredConnected)]]; From 1097c08d81176a81e494cdd0d5de628a59568d8f Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 4 Dec 2026 02:21:51 -0300 Subject: [PATCH 09/16] feat(android): send a file from memory over the livesync socket A Vite HMR session needs to put a small per-device file into the app directory on Android: the content differs between devices, so it can't live in the shared platforms app folder that `sendFile` reads from, and the hash-based diff must never skip it. `sendFileFromBuffer` writes the same CREATE_FILE operation as `sendFile`, taking the app-relative path and the bytes directly. The header is now built from a relative path and a length so both share the wire format. --- lib/definitions/livesync.d.ts | 8 +++ .../livesync/android-livesync-tool.ts | 38 +++++++++++--- .../livesync/android-livesync-tool.ts | 52 +++++++++++++++++++ 3 files changed, 90 insertions(+), 8 deletions(-) diff --git a/lib/definitions/livesync.d.ts b/lib/definitions/livesync.d.ts index 5def3b3910..8502442bca 100644 --- a/lib/definitions/livesync.d.ts +++ b/lib/definitions/livesync.d.ts @@ -413,6 +413,14 @@ declare global { * @returns {Promise} */ sendFile(filePath: string): Promise; + /** + * Sends `content` as the file at `relativeFilePath` in the app directory + * on the device. The runtime writes it before it handles the next operation. + */ + sendFileFromBuffer( + relativeFilePath: string, + content: Buffer, + ): Promise; /** * Sends files through the socket. * @param filePaths - Array of files that will be send by the socket. diff --git a/lib/services/livesync/android-livesync-tool.ts b/lib/services/livesync/android-livesync-tool.ts index 9057a64c79..cce307d954 100644 --- a/lib/services/livesync/android-livesync-tool.ts +++ b/lib/services/livesync/android-livesync-tool.ts @@ -103,10 +103,25 @@ export class AndroidLivesyncTool implements IAndroidLivesyncTool { } public async sendFile(filePath: string): Promise { - await this.sendFileHeader(filePath); + this.verifyActiveConnection(); + const stats = this.$fs.getFsStats(filePath); + await this.sendFileHeader(this.resolveRelativePath(filePath), stats.size); await this.sendFileContent(filePath); } + public async sendFileFromBuffer( + relativeFilePath: string, + content: Buffer, + ): Promise { + this.verifyActiveConnection(); + await this.sendFileHeader( + this.$mobileHelper.buildDevicePath(relativeFilePath), + content.length, + ); + await this.writeToSocket(content); + await this.writeToSocket(crypto.createHash("md5").update(content).digest()); + } + public async sendFiles(filePaths: string[]) { for (const filePath of filePaths) { if (this.$fs.getLsStats(filePath).isFile()) { @@ -245,11 +260,12 @@ export class AndroidLivesyncTool implements IAndroidLivesyncTool { return !!this.socketConnection; } - private async sendFileHeader(filePath: string): Promise { + private async sendFileHeader( + relativeFilePath: string, + fileContentLengthBytes: number, + ): Promise { this.verifyActiveConnection(); - const filePathData = this.getFilePathData(filePath); - const stats = this.$fs.getFsStats(filePathData.filePath); - const fileContentLengthBytes = stats.size; + const filePathData = this.getRelativePathData(relativeFilePath); const fileContentLengthString = fileContentLengthBytes.toString(); const fileContentLengthSize = Buffer.byteLength(fileContentLengthString); const headerBuffer = Buffer.alloc( @@ -572,9 +588,16 @@ export class AndroidLivesyncTool implements IAndroidLivesyncTool { filePathLengthBytes: number; filePathLengthString: string; filePathLengthSize: number; - filePath: string; } { - const relativeFilePath = this.resolveRelativePath(filePath); + return this.getRelativePathData(this.resolveRelativePath(filePath)); + } + + private getRelativePathData(relativeFilePath: string): { + relativeFilePath: string; + filePathLengthBytes: number; + filePathLengthString: string; + filePathLengthSize: number; + } { const filePathLengthBytes = Buffer.byteLength(relativeFilePath); const filePathLengthString = filePathLengthBytes.toString(); const filePathLengthSize = Buffer.byteLength(filePathLengthString); @@ -584,7 +607,6 @@ export class AndroidLivesyncTool implements IAndroidLivesyncTool { filePathLengthBytes, filePathLengthString, filePathLengthSize, - filePath, }; } diff --git a/test/services/livesync/android-livesync-tool.ts b/test/services/livesync/android-livesync-tool.ts index 712cecd59f..3f3f142d5d 100644 --- a/test/services/livesync/android-livesync-tool.ts +++ b/test/services/livesync/android-livesync-tool.ts @@ -504,6 +504,58 @@ describe("AndroidLivesyncTool", () => { }); }); + describe("sendFileFromBuffer", () => { + it("sends the content under the given app-relative path", async () => { + const content = '{"origin":"http://127.0.0.1:5173","token":"t"}'; + + await livesyncTool.sendFileFromBuffer( + "dev-server.json", + Buffer.from(content), + ); + + const sendFileData = getSendFileData( + (testSocket as TestSocket).accomulatedData, + ); + assert.equal(sendFileData.fileName, "dev-server.json"); + assert.equal(sendFileData.fileContent, content); + assert(sendFileData.headerHashMatch); + assert(sendFileData.fileHashMatch); + assert.equal( + sendFileData.operation, + AndroidLivesyncTool.CREATE_FILE_OPERATION, + ); + }); + + it("writes the same bytes as sendFile for the same file", async () => { + const filePath = path.join(testAppPlatformPath, nestedJsFilePath); + await livesyncTool.sendFile(filePath); + const fromFile = Buffer.concat( + (testSocket as TestSocket).accomulatedData.splice(0), + ); + + await livesyncTool.sendFileFromBuffer( + nestedJsFilePath, + Buffer.from(fileContents[nestedJsFilePath]), + ); + const fromBuffer = Buffer.concat( + (testSocket as TestSocket).accomulatedData, + ); + + assert.isTrue(fromBuffer.equals(fromFile)); + }); + + it("rejects if no connection", () => { + livesyncTool.end(); + + return assert.isRejected( + livesyncTool.sendFileFromBuffer( + "dev-server.json", + Buffer.from("{}"), + ), + ); + }); + }); + describe("remove file", () => { it("sends correct information", async () => { //arrange From 9249d25cceaa21c340034ad32a6499633cde4beb Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 4 Dec 2026 02:22:25 -0300 Subject: [PATCH 10/16] feat(vite): choose each device's dev server origin in the CLI One Vite dev server serves every device of a platform, but devices reach it differently: the loopback through `adb reverse` or on a simulator, 10.0.2.2 from an Android emulator, the Mac's end of a USB tunnel from a physical iOS device, or the LAN. Baking one origin into `bundle.mjs` made the dev server guess, and limited the USB tunnel to a session with a single iOS target. When the installed `@nativescript/vite` lists the platform under `nativescriptCli.devServerFile`, the CLI now decides per device: `DevServerOriginService` picks the origin right before the device's full sync (a user-set `NS_HMR_HOST` first, then adb reverse, the emulator host, the simulator loopback, the device's own USB tunnel, then the LAN address) and holds the platform's dev server token, which `vite serve` gets as `NS_HMR_TOKEN`. The dev server no longer receives origin hints: no `NS_HMR_HOST` from the tunnel and no `NS_ADB_*` variables. adb reverse still runs per device, now just before the full sync that launches the app. Each physical iOS device opens its own tunnel, and a tunnel that drops is forgotten so the device is no longer pointed at it. The tunnel is only used on this path, which makes `acceptsIPv6DevHost` redundant. An older `@nativescript/vite` keeps the bundle-baked origin and the `NS_ADB_*` hand-off as before. --- lib/bootstrap.ts | 9 + .../internal/dev-server-origin-service.ts | 42 +++ .../internal/ios-device-tunnel-service.ts | 5 +- lib/controllers/run-controller.ts | 167 +++++----- .../bundler/bundler-compiler-service.ts | 48 +-- lib/services/bundler/bundler.ts | 7 +- .../bundler/dev-server-origin-service.ts | 199 ++++++++++++ lib/services/ios/ios-device-tunnel-service.ts | 28 +- test/controllers/run-controller.ts | 300 ++++++++++++----- .../bundler/bundler-compiler-service.ts | 115 ++++--- .../bundler/dev-server-origin-service.ts | 301 ++++++++++++++++++ .../services/ios/ios-device-tunnel-service.ts | 42 ++- 12 files changed, 1027 insertions(+), 236 deletions(-) create mode 100644 lib/contracts/internal/dev-server-origin-service.ts create mode 100644 lib/services/bundler/dev-server-origin-service.ts create mode 100644 test/services/bundler/dev-server-origin-service.ts diff --git a/lib/bootstrap.ts b/lib/bootstrap.ts index 31dfabd607..f347efbba7 100644 --- a/lib/bootstrap.ts +++ b/lib/bootstrap.ts @@ -1,6 +1,7 @@ import { provideLazy } from "./common/di"; import { injector } from "./common/yok"; import { registerBuiltInCommand } from "./common/services/command-definition-adapter"; +import { DevServerOriginService } from "./contracts/internal/dev-server-origin-service"; import { IOSDeviceTunnelService } from "./contracts/internal/ios-device-tunnel-service"; import type { fontsCommandDefinition } from "./commands/fonts"; import { AndroidPluginMirrorService } from "./contracts/internal/android-plugin-mirror-service"; @@ -703,6 +704,14 @@ injector.register( .IOSDeviceTunnelServiceImpl, ), ); +injector.register( + provideLazy( + DevServerOriginService, + () => + require("./services/bundler/dev-server-origin-service") + .DevServerOriginServiceImpl, + ), +); injector.require( "applePortalSessionService", diff --git a/lib/contracts/internal/dev-server-origin-service.ts b/lib/contracts/internal/dev-server-origin-service.ts new file mode 100644 index 0000000000..494b2a7b12 --- /dev/null +++ b/lib/contracts/internal/dev-server-origin-service.ts @@ -0,0 +1,42 @@ +import { Contract } from "../../common/di/contract"; + +export interface IDevServerOriginOptions { + /** Android: `adb reverse tcp: tcp:` is confirmed for the device. */ + adbReverse?: boolean; +} + +/** + * Decides, per device, the origin an app uses to reach the platform's Vite + * dev server, and the content of the `dev-server.json` file that hands the + * origin and the dev server's token to the app. + */ +@Contract() +export abstract class DevServerOriginService { + /** + * The token of the platform's dev server. Generated on first use and kept + * for the life of the process, so a restarted dev server still accepts the + * files already on the devices. + */ + abstract getToken(platform: string): string; + + /** + * Chooses the device's origin from what the CLI knows about how it reaches + * this machine, records it and resolves it. A physical iOS / visionOS + * device uses its USB tunnel only while one is open. + */ + abstract chooseOrigin( + device: Mobile.IDevice, + options?: IDevServerOriginOptions, + ): Promise; + + /** The device's last chosen origin, if any. */ + abstract getOrigin(deviceIdentifier: string): string | undefined; + + /** + * The `dev-server.json` content for the device, or null when no origin was + * chosen for it, in which case nothing is delivered. + */ + abstract getDevServerFile(deviceIdentifier: string): string | null; + + abstract forget(deviceIdentifier: string): void; +} diff --git a/lib/contracts/internal/ios-device-tunnel-service.ts b/lib/contracts/internal/ios-device-tunnel-service.ts index b80412287d..aecabc5cbf 100644 --- a/lib/contracts/internal/ios-device-tunnel-service.ts +++ b/lib/contracts/internal/ios-device-tunnel-service.ts @@ -16,10 +16,9 @@ export abstract class IOSDeviceTunnelService { abstract open(device: Mobile.IDevice): Promise; /** - * The Mac's tunnel address for the single device of `platform` that has - * an open tunnel, if any. + * The Mac's address on the device's tunnel while the tunnel is up. */ - abstract getHostAddress(platform: string): string | undefined; + abstract getHostAddress(deviceIdentifier: string): string | undefined; abstract close(deviceIdentifier: string): Promise; } diff --git a/lib/controllers/run-controller.ts b/lib/controllers/run-controller.ts index dd8d4eb73f..57ee928ed5 100644 --- a/lib/controllers/run-controller.ts +++ b/lib/controllers/run-controller.ts @@ -26,11 +26,13 @@ import { 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: ( @@ -172,6 +174,7 @@ export class RunController extends EventEmitter implements IRunController { ).map((descriptor) => descriptor.identifier); for (const deviceIdentifier of removedDeviceIdentifiers) { + this.devServerOriginService.forget(deviceIdentifier); await this.iOSDeviceTunnelService.close(deviceIdentifier); } @@ -655,14 +658,6 @@ export class RunController extends EventEmitter implements IRunController { platform: string; isEmulator: boolean; }> = {}; - // Snapshot before any device action: a device whose sync fails leaves - // the session but must still count as a target of its platform. - const sessionDeviceDescriptors = [ - ...this.$liveSyncProcessDataService.getDeviceDescriptors( - projectData.projectDir, - ), - ]; - const deviceAction = async (device: Mobile.IDevice) => { const deviceDescriptor = _.find( deviceDescriptors, @@ -681,25 +676,26 @@ export class RunController extends EventEmitter implements IRunController { }, ); - // 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( + const usesDevServerFile = this.usesDevServerFile( device, projectData, liveSyncInfo, - "pre-build", - ); - await this.openIOSViteHmrTunnel( - device, - projectData, - liveSyncInfo, - sessionDeviceDescriptors, ); + 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); @@ -766,6 +762,10 @@ export class RunController extends EventEmitter implements IRunController { this.$liveSyncServiceResolver.resolveLiveSyncService( platformData.platformNameLowerCase, ); + if (usesDevServerFile) { + await this.chooseDevServerOrigin(device); + } + const { force, useHotModuleReload, skipWatcher } = liveSyncInfo; const liveSyncResultInfo = await platformLiveSyncService.fullSync({ force, @@ -776,16 +776,18 @@ export class RunController extends EventEmitter implements IRunController { liveSyncDeviceData: deviceDescriptor, }); - // 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", - ); + 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, @@ -842,64 +844,69 @@ export class RunController extends EventEmitter implements IRunController { } /** - * Serves Vite HMR to a USB-connected iOS / visionOS device over its - * CoreDevice tunnel. One dev server bakes one origin into `bundle.mjs` - * and a tunnel address is reachable only from its own device, so this - * applies only when the device is the session's only target of its - * platform. Must run before `prepare` spawns the Vite children. + * Whether the device reads its dev server origin from a `dev-server.json` + * the CLI delivers, rather than from the bundle. */ - private async openIOSViteHmrTunnel( + private usesDevServerFile( device: Mobile.IDevice, projectData: IProjectData, liveSyncInfo: ILiveSyncInfo, - sessionDeviceDescriptors: ILiveSyncDeviceDescriptor[], - ): Promise { - const { platform, identifier } = device.deviceInfo; - if ( - !this.$mobileHelper.isApplePlatform(platform) || - projectData.bundler !== "vite" || - liveSyncInfo.skipWatcher || - !liveSyncInfo.useHotModuleReload || - liveSyncInfo.release || - process.env.NS_HMR_HOST - ) { - return; - } - if ( - !this.$bundlerCompilerService.acceptsIPv6DevHost(platform, projectData) - ) { - this.$logger.trace( - `Not using a USB tunnel for ${identifier}: the installed @nativescript/vite does not accept an IPv6 dev host.`, - ); - return; - } + ): boolean { + return ( + projectData.bundler === "vite" && + !liveSyncInfo.skipWatcher && + !!liveSyncInfo.useHotModuleReload && + !liveSyncInfo.release && + this.$bundlerCompilerService.usesDevServerFile( + device.deviceInfo.platform, + projectData, + ) + ); + } - // Descriptors cover every discovered device; `--device` narrows the - // session to one of them. - const selected = this.$devicesService.getDeviceByDeviceOption(); - const platformTargets = sessionDeviceDescriptors.filter((descriptor) => { + /** + * 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; + let adbReverse = false; + let port: number; + if (this.$mobileHelper.isAndroidPlatform(platform)) { if ( - selected && - descriptor.identifier !== selected.deviceInfo.identifier + !isTruthyEnvFlag(process.env.NS_HMR_NO_ADB_REVERSE) && + !isTruthyEnvFlag(process.env.NS_HMR_PREFER_LAN_HOST) ) { - return false; + 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}`, + ); + } } - const target = this.$devicesService.getDeviceByIdentifier( - descriptor.identifier, - ); - return ( - !target || - target.deviceInfo.platform.toLowerCase() === platform.toLowerCase() - ); + } else if (!device.isEmulator && !process.env.NS_HMR_HOST?.trim()) { + await this.iOSDeviceTunnelService.open(device); + } + + const origin = await this.devServerOriginService.chooseOrigin(device, { + adbReverse, }); - if (platformTargets.length !== 1) { - this.$logger.trace( - `Not using a USB tunnel for ${identifier}: the session has ${platformTargets.length} ${platform} targets.`, + 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}.`, ); - return; } - - await this.iOSDeviceTunnelService.open(device); } /** diff --git a/lib/services/bundler/bundler-compiler-service.ts b/lib/services/bundler/bundler-compiler-service.ts index f51708755f..693dfa3012 100644 --- a/lib/services/bundler/bundler-compiler-service.ts +++ b/lib/services/bundler/bundler-compiler-service.ts @@ -35,7 +35,7 @@ import { } from "../../common/declarations"; import { ICleanupService } from "../../definitions/cleanup-service"; 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 { inject } from "../../common/di"; import { @@ -97,7 +97,7 @@ export class BundlerCompilerService extends EventEmitter implements IBundlerCompilerService { - private iOSDeviceTunnelService = inject(IOSDeviceTunnelService); + private devServerOriginService = inject(DevServerOriginService); private bundlerProcesses: IDictionary = {}; // Vite-only: the long-lived `vite serve` dev server the device fetches // modules and HMR updates from. Keyed by platform, managed by this CLI @@ -743,6 +743,7 @@ export class BundlerCompilerService ? await this.getViteChildEnv( platformData.platformNameLowerCase, prepareData, + projectData, ) : {}), }; @@ -799,25 +800,32 @@ export class BundlerCompilerService if (process.env[VITE_SINGLE_PROCESS_ENV] === "0") { return false; } - return this.getViteSingleProcessPlatforms(projectData).includes(platform); + return this.getViteCliCapabilityPlatforms( + "singleProcessDev", + projectData, + ).includes(platform); } - /** - * Older `@nativescript/vite` releases bind the dev server to - * `NS_HMR_HOST` and put an IPv6 literal into URLs unbracketed. The fix - * shipped together with single-process dev, so its platform list is the - * capability marker. - */ - public acceptsIPv6DevHost( + public usesDevServerFile( platform: string, projectData: IProjectData, ): boolean { - return this.getViteSingleProcessPlatforms(projectData).includes( - platform.toLowerCase(), + return ( + this.getBundler() === "vite" && + this.getViteCliCapabilityPlatforms("devServerFile", projectData).includes( + platform.toLowerCase(), + ) ); } - private getViteSingleProcessPlatforms(projectData: IProjectData): string[] { + /** + * The platforms the installed `@nativescript/vite` lists under + * `nativescriptCli.` in its package.json. + */ + private getViteCliCapabilityPlatforms( + capability: "singleProcessDev" | "devServerFile", + projectData: IProjectData, + ): string[] { try { const packageJSONPath = resolvePackageJSONPath( this.getBundlerPackageName(), @@ -827,7 +835,7 @@ export class BundlerCompilerService return []; } const platforms = - this.$fs.readJson(packageJSONPath)?.nativescriptCli?.singleProcessDev; + this.$fs.readJson(packageJSONPath)?.nativescriptCli?.[capability]; return Array.isArray(platforms) ? platforms : []; } catch { return []; @@ -854,12 +862,13 @@ export class BundlerCompilerService * sessions — the dev-server port. The port is resolved here, once, and * handed to `@nativescript/vite` as `NS_HMR_PORT`, so the URLs baked into * `bundle.mjs`, the server's bind and the `adb reverse` tunnel all match. - * When the platform's only device has a USB tunnel open, its Mac address - * becomes `NS_HMR_HOST`, unless the user set one. + * When the devices read their origin from `dev-server.json`, the server + * also gets the token the CLI writes into that file. */ private async getViteChildEnv( platform: string, prepareData: IPrepareData, + projectData: IProjectData, ): Promise { const env: IStringDictionary = { NS_VITE_DIST_DIR: this.getViteDistRelativeDir(platform), @@ -868,9 +877,8 @@ export class BundlerCompilerService env.NS_HMR_PORT = String( await this.$viteHmrPortService.getPort(platform), ); - const tunnelHost = this.iOSDeviceTunnelService.getHostAddress(platform); - if (tunnelHost && !process.env.NS_HMR_HOST) { - env.NS_HMR_HOST = tunnelHost; + if (this.usesDevServerFile(platform, projectData)) { + env.NS_HMR_TOKEN = this.devServerOriginService.getToken(platform); } } return env; @@ -946,7 +954,7 @@ export class BundlerCompilerService hooks: ViteDevServerHooks = {}, ): Promise<{ childProcess: child_process.ChildProcess; port: number }> { const key = platformData.platformNameLowerCase; - const viteEnv = await this.getViteChildEnv(key, prepareData); + const viteEnv = await this.getViteChildEnv(key, prepareData, projectData); const port = Number(viteEnv.NS_HMR_PORT); const envData = this.buildEnvData( diff --git a/lib/services/bundler/bundler.ts b/lib/services/bundler/bundler.ts index b9ac76c92b..485e08e500 100644 --- a/lib/services/bundler/bundler.ts +++ b/lib/services/bundler/bundler.ts @@ -31,10 +31,11 @@ declare global { ): Promise; stopBundlerCompiler(platform: string): Promise; /** - * Whether the installed `@nativescript/vite` accepts a bare IPv6 - * address as `NS_HMR_HOST` for `platform`. + * Whether the installed `@nativescript/vite` reads each device's dev + * server origin from a `dev-server.json` the CLI delivers for + * `platform`, instead of baking one origin into the bundle. */ - acceptsIPv6DevHost(platform: string, projectData: IProjectData): boolean; + usesDevServerFile(platform: string, projectData: IProjectData): boolean; } /** diff --git a/lib/services/bundler/dev-server-origin-service.ts b/lib/services/bundler/dev-server-origin-service.ts new file mode 100644 index 0000000000..fc62eb4090 --- /dev/null +++ b/lib/services/bundler/dev-server-origin-service.ts @@ -0,0 +1,199 @@ +import * as crypto from "crypto"; +import * as net from "net"; +import * as os from "os"; +import { IDictionary } from "../../common/declarations"; +import { inject } from "../../common/di"; +import { + DevServerOriginService, + IDevServerOriginOptions, +} from "../../contracts/internal/dev-server-origin-service"; +import { IOSDeviceTunnelService } from "../../contracts/internal/ios-device-tunnel-service"; +import { Logger } from "../../contracts/logger"; +import { ViteHmrPortService } from "../../contracts/vite-hmr-port-service"; + +const LOOPBACK = "127.0.0.1"; +const ANDROID_EMULATOR_HOST = "10.0.2.2"; + +export interface IDevServerOriginInputs { + port: number; + /** `NS_HMR_HOST` as the user set it. */ + envHost?: string; + isAndroid: boolean; + isEmulator: boolean; + adbReverse?: boolean; + /** The Mac's address on the device's USB tunnel. */ + tunnelAddress?: string; + lanAddress?: string; +} + +/** + * The origin a device uses for the dev server. The app uses the string + * verbatim as module identity, so it is assembled here rather than + * serialized through a URL parser. + */ +export function chooseDevServerOrigin(inputs: IDevServerOriginInputs): string { + const envHost = inputs.envHost?.trim(); + if (envHost) { + return formatDevServerOrigin(envHost, inputs.port); + } + return formatDevServerOrigin(chooseDevServerHost(inputs), inputs.port); +} + +function chooseDevServerHost(inputs: IDevServerOriginInputs): string { + if (inputs.isAndroid) { + if (inputs.adbReverse) { + return LOOPBACK; + } + if (inputs.isEmulator) { + return ANDROID_EMULATOR_HOST; + } + } else { + if (inputs.isEmulator) { + return LOOPBACK; + } + if (inputs.tunnelAddress) { + return inputs.tunnelAddress; + } + } + return inputs.lanAddress || LOOPBACK; +} + +/** + * `http://:`, with an IPv6 host bracketed. `host` may carry its + * own port (`host:port`, `[v6]:port`), which then wins over `port`. + */ +export function formatDevServerOrigin(host: string, port: number): string { + if (host.startsWith("[")) { + const closing = host.indexOf("]"); + if (closing !== -1) { + const bracketed = host.slice(0, closing + 1); + const explicitPort = parsePort(host.slice(closing + 1)); + return `http://${bracketed}:${explicitPort ?? port}`; + } + } + if (net.isIPv6(host)) { + return `http://[${host}]:${port}`; + } + const colon = host.indexOf(":"); + if (colon !== -1 && colon === host.lastIndexOf(":")) { + const explicitPort = parsePort(host.slice(colon)); + if (explicitPort !== undefined) { + return `http://${host.slice(0, colon)}:${explicitPort}`; + } + } + return `http://${host}:${port}`; +} + +function parsePort(suffix: string): number | undefined { + if (!/^:\d+$/.test(suffix)) { + return undefined; + } + const port = Number(suffix.slice(1)); + return port > 0 && port <= 65535 ? port : undefined; +} + +/** + * The first external IPv4 address, skipping link-local ones: macOS lists + * 169.254.x.x on AWDL and idle USB interfaces, which other devices can't + * reliably reach. + */ +export function guessLanAddress( + interfaces: NodeJS.Dict, +): string | undefined { + for (const entries of Object.values(interfaces)) { + for (const entry of entries || []) { + const family = entry?.family as string | number; + if ( + !entry || + entry.internal || + (family !== "IPv4" && family !== 4) || + !entry.address || + entry.address.startsWith("169.254.") + ) { + continue; + } + return entry.address; + } + } + return undefined; +} + +export class DevServerOriginServiceImpl implements DevServerOriginService { + private iOSDeviceTunnelService = inject(IOSDeviceTunnelService); + private logger = inject(Logger); + private mobileHelper = inject("mobileHelper"); + private viteHmrPortService = inject(ViteHmrPortService); + + private tokens: IDictionary = {}; + private devices: IDictionary<{ platform: string; origin: string }> = {}; + + public getToken(platform: string): string { + const key = platform.toLowerCase(); + if (!this.tokens[key]) { + this.tokens[key] = crypto.randomBytes(24).toString("base64url"); + } + return this.tokens[key]; + } + + public async chooseOrigin( + device: Mobile.IDevice, + options: IDevServerOriginOptions = {}, + ): Promise { + const { identifier } = device.deviceInfo; + const platform = device.deviceInfo.platform.toLowerCase(); + const isAndroid = this.mobileHelper.isAndroidPlatform(platform); + const inputs: IDevServerOriginInputs = { + port: await this.viteHmrPortService.getPort(platform), + envHost: process.env.NS_HMR_HOST, + isAndroid, + isEmulator: device.isEmulator, + adbReverse: options.adbReverse, + tunnelAddress: isAndroid + ? undefined + : this.iOSDeviceTunnelService.getHostAddress(identifier), + lanAddress: guessLanAddress(this.getNetworkInterfaces()), + }; + const origin = chooseDevServerOrigin(inputs); + this.devices[identifier] = { platform, origin }; + this.logger.trace( + `Vite dev server origin for ${identifier}: ${origin}`, + inputs, + ); + const reachesLoopback = + device.isEmulator || (isAndroid && options.adbReverse); + if ( + !reachesLoopback && + !inputs.envHost?.trim() && + !inputs.tunnelAddress && + !inputs.lanAddress + ) { + this.logger.warn( + `Found no LAN address on this machine, so ${device.deviceInfo.displayName || identifier} may not reach the Vite dev server at ${origin}. Set NS_HMR_HOST to an address the device can reach.`, + ); + } + return origin; + } + + public getOrigin(deviceIdentifier: string): string | undefined { + return this.devices[deviceIdentifier]?.origin; + } + + public getDevServerFile(deviceIdentifier: string): string | null { + const device = this.devices[deviceIdentifier]; + if (!device) { + return null; + } + return JSON.stringify({ + origin: device.origin, + token: this.getToken(device.platform), + }); + } + + public forget(deviceIdentifier: string): void { + delete this.devices[deviceIdentifier]; + } + + protected getNetworkInterfaces(): NodeJS.Dict { + return os.networkInterfaces(); + } +} diff --git a/lib/services/ios/ios-device-tunnel-service.ts b/lib/services/ios/ios-device-tunnel-service.ts index d7cc3b14c2..6b1980527c 100644 --- a/lib/services/ios/ios-device-tunnel-service.ts +++ b/lib/services/ios/ios-device-tunnel-service.ts @@ -22,7 +22,6 @@ interface ICoreDeviceConnection { } interface ITunnel { - platform: string; holder?: child_process.ChildProcess; address: Promise; closed: boolean; @@ -47,7 +46,6 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { const id = device.deviceInfo.identifier; if (!this.tunnels[id]) { const tunnel: ITunnel = { - platform: device.deviceInfo.platform.toLowerCase(), address: null, closed: false, }; @@ -61,8 +59,8 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { return this.tunnels[id].address; } - public getHostAddress(platform: string): string | undefined { - return this.hostAddresses[platform.toLowerCase()]; + public getHostAddress(deviceIdentifier: string): string | undefined { + return this.hostAddresses[deviceIdentifier]; } public async close(deviceIdentifier: string): Promise { @@ -71,12 +69,10 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { return; } delete this.tunnels[deviceIdentifier]; + delete this.hostAddresses[deviceIdentifier]; tunnel.closed = true; - const address = await tunnel.address; - if (address && this.hostAddresses[tunnel.platform] === address) { - delete this.hostAddresses[tunnel.platform]; - } this.stopHolder(tunnel); + await tunnel.address; } private async openCore( @@ -117,7 +113,7 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { return null; } - this.hostAddresses[tunnel.platform] = hostAddress; + this.hostAddresses[id] = hostAddress; this.logger.info( `Using the USB tunnel to ${device.deviceInfo.displayName} (Mac address ${hostAddress}) for the Vite dev server.`, ); @@ -201,11 +197,17 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { } tunnel.holder = undefined; tunnel.address.then((address) => { - if (address && !tunnel.closed) { - this.logger.warn( - `The USB tunnel to ${deviceIdentifier} closed, so the app can no longer reach the Vite dev server at ${address}. Restart the run to reconnect.`, - ); + if (!address || tunnel.closed) { + return; + } + tunnel.closed = true; + if (this.tunnels[deviceIdentifier] === tunnel) { + delete this.tunnels[deviceIdentifier]; + delete this.hostAddresses[deviceIdentifier]; } + this.logger.warn( + `The USB tunnel to ${deviceIdentifier} closed, so the app can no longer reach the Vite dev server at ${address}. Restart the run to reconnect.`, + ); }); }); if (holder.pid) { diff --git a/test/controllers/run-controller.ts b/test/controllers/run-controller.ts index b91b780ab5..4313a1a1f9 100644 --- a/test/controllers/run-controller.ts +++ b/test/controllers/run-controller.ts @@ -17,6 +17,8 @@ import { LiveSyncProcessDataService } from "../../lib/services/livesync-process- import { IDictionary } from "../../lib/common/declarations"; import { IInjector } from "../../lib/common/definitions/yok"; import { IOSDeviceTunnelService } from "../../lib/contracts/internal/ios-device-tunnel-service"; +import { DevServerOriginService } from "../../lib/contracts/internal/dev-server-origin-service"; +import { DevServerOriginServiceImpl } from "../../lib/services/bundler/dev-server-origin-service"; let isAttachToHmrStatusCalled = false; let prepareData: IPrepareData = null; @@ -151,6 +153,10 @@ function createTestInjector() { close: async () => ({}), }, }); + injector.register({ + provide: DevServerOriginService, + useClass: DevServerOriginServiceImpl, + }); const devicesService = injector.resolve("devicesService"); devicesService.getDevicesForPlatform = () => @@ -275,7 +281,7 @@ describe("RunController", () => { }); }); - describe("USB tunnel for Vite HMR", () => { + describe("Vite dev server origin", () => { const secondIOSDevice = { deviceInfo: { identifier: "mySecondiOSDevice", platform: "ios" }, }; @@ -284,26 +290,95 @@ describe("RunController", () => { buildAction: async () => buildOutputPath, buildData: {}, }; + const iOSSimulator = { + deviceInfo: { identifier: "myiOSSimulator", platform: "ios" }, + isEmulator: true, + }; + const iOSSimulatorDescriptor = { + identifier: "myiOSSimulator", + buildAction: async () => buildOutputPath, + buildData: {}, + }; + const adbCalls: string[][] = []; + const androidEmulator = { + deviceInfo: { identifier: "emulator-5554", platform: "android" }, + isEmulator: true, + adb: { + executeCommand: async (args: string[]) => { + adbCalls.push(args); + events.push(`adb ${args.join(" ")}`); + return args.join(" ") === "reverse --list" && reverseWorks + ? "emulator-5554 tcp:5173 tcp:5173" + : ""; + }, + }, + }; + const androidEmulatorDescriptor = { + identifier: "emulator-5554", + buildAction: async () => buildOutputPath, + buildData: {}, + }; const hmrLiveSyncInfo = { ...liveSyncInfo, useHotModuleReload: true }; + const envNames = [ + "NS_HMR_HOST", + "NS_HMR_NO_ADB_REVERSE", + "NS_HMR_PREFER_LAN_HOST", + "NS_ADB_REVERSE_READY", + "NS_DEVICE_SERIAL", + "NS_ADB_PATH", + ]; + let previousEnv: IDictionary = null; + let tunnelAddresses: IDictionary = null; let openedFor: string[] = null; let closed: string[] = null; let events: string[] = null; - let previousHost: string = undefined; - let acceptsIPv6DevHost: boolean; + let filesAtFullSync: IDictionary = null; + let devServerFilePlatforms: string[]; + let reverseWorks: boolean; + + let syncFailures: string[]; + + const run = async (devices: any[], info: any = hmrLiveSyncInfo) => { + mockDevicesService(injector, devices); + await runController.run({ + liveSyncInfo: info, + deviceDescriptors: devices.map((device) => ({ + ...map[device.deviceInfo.identifier].descriptor, + buildData: { nativePrepare: {} }, + })), + }); + assert.deepStrictEqual(syncFailures, []); + }; beforeEach(() => { - acceptsIPv6DevHost = true; - injector.resolve("bundlerCompilerService").acceptsIPv6DevHost = () => - acceptsIPv6DevHost; + devServerFilePlatforms = ["ios", "android"]; + reverseWorks = true; + injector.resolve("bundlerCompilerService").usesDevServerFile = ( + platform: string, + ) => devServerFilePlatforms.includes(platform.toLowerCase()); + tunnelAddresses = {}; openedFor = []; closed = []; events = []; - previousHost = process.env.NS_HMR_HOST; - delete process.env.NS_HMR_HOST; + adbCalls.length = 0; + filesAtFullSync = {}; + previousEnv = {}; + for (const name of envNames) { + previousEnv[name] = process.env[name]; + delete process.env[name]; + } map.mySecondiOSDevice = { device: secondIOSDevice, descriptor: secondIOSDeviceDescriptor, }; + map.myiOSSimulator = { + device: iOSSimulator, + descriptor: iOSSimulatorDescriptor, + }; + map["emulator-5554"] = { + device: androidEmulator, + descriptor: androidEmulatorDescriptor, + }; const projectDataService = injector.resolve("projectDataService"); const getProjectData = @@ -313,15 +388,15 @@ describe("RunController", () => { projectData.bundler = "vite"; return projectData; }; - injector.resolve("devicesService").getDeviceByIdentifier = ( - identifier: string, - ) => map[identifier]?.device; const tunnelService = injector.get(IOSDeviceTunnelService); tunnelService.open = async (device: Mobile.IDevice) => { - openedFor.push(device.deviceInfo.identifier); - events.push("tunnel"); - return "fd00::2"; + const id = device.deviceInfo.identifier; + openedFor.push(id); + events.push(`tunnel ${id}`); + tunnelAddresses[id] = `fd00::${openedFor.length}`; + return tunnelAddresses[id]; }; + tunnelService.getHostAddress = (id: string) => tunnelAddresses[id]; tunnelService.close = async (identifier: string) => { closed.push(identifier); }; @@ -333,99 +408,173 @@ describe("RunController", () => { hasNativeChanges: false, }; }; + syncFailures = []; + injector.resolve("logger").warn = (message: string) => { + if (/^Unable to /.test(message)) { + syncFailures.push(message); + } + }; + injector.resolve("buildController").shouldBuild = async () => false; + injector.resolve("platformsDataService").getPlatformData = ( + platform: string, + ) => ({ platformNameLowerCase: platform.toLowerCase() }); + injector.resolve("analyticsService").trackEventActionInGoogleAnalytics = + async (): Promise => undefined; + const devServerOriginService = injector.get(DevServerOriginService); + for (const name of ["iOSLiveSyncService", "androidLiveSyncService"]) { + const liveSyncService = injector.resolve(name); + liveSyncService.fullSync = async (syncInfo: IFullSyncInfo) => { + const id = syncInfo.device.deviceInfo.identifier; + events.push(`fullSync ${id}`); + filesAtFullSync[id] = devServerOriginService.getDevServerFile(id); + return { + ...getFullSyncResult(), + deviceAppData: { + appIdentifier, + device: syncInfo.device, + platform: syncInfo.device.deviceInfo.platform, + }, + }; + }; + liveSyncService.shouldRestart = async () => true; + liveSyncService.restartApplication = async (): Promise => + undefined; + } }); afterEach(() => { delete map.mySecondiOSDevice; - if (previousHost === undefined) { - delete process.env.NS_HMR_HOST; - } else { - process.env.NS_HMR_HOST = previousHost; + delete map.myiOSSimulator; + delete map["emulator-5554"]; + for (const name of envNames) { + if (previousEnv[name] === undefined) { + delete process.env[name]; + } else { + process.env[name] = previousEnv[name]; + } } }); - it("opens the tunnel of the session's only iOS device before preparing", async () => { - mockDevicesService(injector, [iOSDevice, androidDevice]); + it("gives each physical iOS device its own tunnel origin", async () => { + await run([iOSDevice, secondIOSDevice]); - await runController.run({ - liveSyncInfo: hmrLiveSyncInfo, - deviceDescriptors: [iOSDeviceDescriptor, androidDeviceDescriptor], - }); - - assert.deepStrictEqual(openedFor, ["myiOSDevice"]); - assert.isBelow(events.indexOf("tunnel"), events.indexOf("prepare ios")); + assert.deepStrictEqual(openedFor, ["myiOSDevice", "mySecondiOSDevice"]); + const token = injector.get(DevServerOriginService).getToken("ios"); + assert.deepStrictEqual( + _.mapValues(filesAtFullSync, (file) => JSON.parse(file)), + { + myiOSDevice: { origin: "http://[fd00::1]:5173", token }, + mySecondiOSDevice: { origin: "http://[fd00::2]:5173", token }, + }, + ); }); - it("does not open a tunnel when the session has two iOS devices", async () => { - mockDevicesService(injector, [iOSDevice, secondIOSDevice]); + it("opens a device's tunnel before its full sync, after preparing", async () => { + await run([iOSDevice]); - await runController.run({ - liveSyncInfo: hmrLiveSyncInfo, - deviceDescriptors: [iOSDeviceDescriptor, secondIOSDeviceDescriptor], - }); + assert.deepStrictEqual(events, [ + "prepare ios", + "tunnel myiOSDevice", + "fullSync myiOSDevice", + ]); + }); + + it("points a simulator at the loopback without a tunnel", async () => { + await run([iOSSimulator]); assert.deepStrictEqual(openedFor, []); + assert.equal( + JSON.parse(filesAtFullSync.myiOSSimulator).origin, + "http://127.0.0.1:5173", + ); }); - it("opens the tunnel of the --device selection when another iOS device is attached", async () => { - const devicesService = injector.resolve("devicesService"); - devicesService.getDeviceByDeviceOption = () => iOSDevice; - mockDevicesService(injector, [iOSDevice]); + it("uses a user-set NS_HMR_HOST for every device and opens no tunnel", async () => { + process.env.NS_HMR_HOST = "dev.example.test:8443"; - try { - await runController.run({ - liveSyncInfo: hmrLiveSyncInfo, - deviceDescriptors: [iOSDeviceDescriptor, secondIOSDeviceDescriptor], - }); - } finally { - devicesService.getDeviceByDeviceOption = (): Mobile.IDevice => - undefined; - } + await run([iOSDevice, iOSSimulator]); - assert.deepStrictEqual(openedFor, ["myiOSDevice"]); + assert.deepStrictEqual(openedFor, []); + assert.deepStrictEqual( + _.mapValues(filesAtFullSync, (file) => JSON.parse(file).origin), + { + myiOSDevice: "http://dev.example.test:8443", + myiOSSimulator: "http://dev.example.test:8443", + }, + ); }); - it("does not open a tunnel when the user set NS_HMR_HOST", async () => { - process.env.NS_HMR_HOST = "192.168.1.10"; - mockDevicesService(injector, [iOSDevice]); + it("sets up adb reverse before the Android full sync and uses the loopback", async () => { + await run([androidEmulator]); - await runController.run({ - liveSyncInfo: hmrLiveSyncInfo, - deviceDescriptors: [iOSDeviceDescriptor], - }); + assert.equal( + JSON.parse(filesAtFullSync["emulator-5554"]).origin, + "http://127.0.0.1:5173", + ); + assert.isBelow( + events.indexOf("adb reverse tcp:5173 tcp:5173"), + events.indexOf("fullSync emulator-5554"), + ); + assert.isBelow( + events.indexOf("prepare android"), + events.indexOf("adb reverse tcp:5173 tcp:5173"), + ); + assert.isUndefined(process.env.NS_ADB_REVERSE_READY); + assert.isUndefined(process.env.NS_DEVICE_SERIAL); + assert.isUndefined(process.env.NS_ADB_PATH); + }); - assert.deepStrictEqual(openedFor, []); + it("falls back to 10.0.2.2 on an emulator whose reverse fails", async () => { + reverseWorks = false; + + await run([androidEmulator]); + + assert.equal( + JSON.parse(filesAtFullSync["emulator-5554"]).origin, + "http://10.0.2.2:5173", + ); }); - it("does not open a tunnel for a @nativescript/vite without IPv6 dev hosts", async () => { - acceptsIPv6DevHost = false; - mockDevicesService(injector, [iOSDevice]); + it("skips adb reverse when the user opts out", async () => { + process.env.NS_HMR_NO_ADB_REVERSE = "1"; - await runController.run({ - liveSyncInfo: hmrLiveSyncInfo, - deviceDescriptors: [iOSDeviceDescriptor], - }); + await run([androidEmulator]); - assert.deepStrictEqual(openedFor, []); + assert.deepStrictEqual(adbCalls, []); + assert.equal( + JSON.parse(filesAtFullSync["emulator-5554"]).origin, + "http://10.0.2.2:5173", + ); }); - it("does not open a tunnel without HMR", async () => { - mockDevicesService(injector, [iOSDevice]); + it("keeps the bundle's origin and the bundler env for a @nativescript/vite without dev-server.json", async () => { + devServerFilePlatforms = []; - await runController.run({ - liveSyncInfo, - deviceDescriptors: [iOSDeviceDescriptor], + await run([iOSDevice, androidEmulator]); + + assert.deepStrictEqual(openedFor, []); + assert.deepStrictEqual(filesAtFullSync, { + myiOSDevice: null, + "emulator-5554": null, }); + assert.equal(process.env.NS_ADB_REVERSE_READY, "1"); + assert.equal(process.env.NS_DEVICE_SERIAL, "emulator-5554"); + assert.equal(process.env.NS_ADB_PATH, "adb"); + assert.isBelow( + events.indexOf("adb reverse tcp:5173 tcp:5173"), + events.indexOf("prepare android"), + ); + }); + + it("chooses no origin without HMR", async () => { + await run([iOSDevice], liveSyncInfo); assert.deepStrictEqual(openedFor, []); + assert.deepStrictEqual(filesAtFullSync, { myiOSDevice: null }); }); - it("closes the tunnel of a device that stops", async () => { - mockDevicesService(injector, [iOSDevice]); - await runController.run({ - liveSyncInfo: hmrLiveSyncInfo, - deviceDescriptors: [iOSDeviceDescriptor], - }); + it("forgets the origin and closes the tunnel of a device that stops", async () => { + await run([iOSDevice]); await runController.stop({ projectDir, @@ -433,6 +582,9 @@ describe("RunController", () => { }); assert.deepStrictEqual(closed, ["myiOSDevice"]); + assert.isNull( + injector.get(DevServerOriginService).getDevServerFile("myiOSDevice"), + ); }); }); diff --git a/test/services/bundler/bundler-compiler-service.ts b/test/services/bundler/bundler-compiler-service.ts index c45526d75a..42040c2538 100644 --- a/test/services/bundler/bundler-compiler-service.ts +++ b/test/services/bundler/bundler-compiler-service.ts @@ -7,7 +7,7 @@ import * as os from "os"; import * as path from "path"; import { ErrorsStub } from "../../stubs"; import { IInjector } from "../../../lib/common/definitions/yok"; -import { IOSDeviceTunnelService } from "../../../lib/contracts/internal/ios-device-tunnel-service"; +import { DevServerOriginService } from "../../../lib/contracts/internal/dev-server-origin-service"; import { BUNDLER_APP_RESTART_REQUESTED, BUNDLER_COMPILATION_COMPLETE, @@ -94,8 +94,8 @@ function createTestInjector( getPort: async () => 5173, }); testInjector.register({ - provide: IOSDeviceTunnelService, - useValue: { getHostAddress: (): string => undefined }, + provide: DevServerOriginService, + useValue: { getToken: (): string => "token" }, }); return testInjector; @@ -380,52 +380,68 @@ describe("BundlerCompilerService", () => { ); }); - describe("with a USB tunnel open", () => { - let previousHost: string; + describe("when the devices read dev-server.json", () => { + let projectDir: string; beforeEach(() => { - previousHost = process.env.NS_HMR_HOST; - delete process.env.NS_HMR_HOST; - testInjector.get(IOSDeviceTunnelService).getHostAddress = ( + projectDir = fs.mkdtempSync(path.join(os.tmpdir(), "ns-vite-dsf-")); + const dir = path.join( + projectDir, + "node_modules", + "@nativescript", + "vite", + ); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync( + path.join(dir, "package.json"), + JSON.stringify({ + name: "@nativescript/vite", + nativescriptCli: { devServerFile: ["ios"] }, + }), + ); + testInjector.resolve("fs").readJson = (file: string) => + JSON.parse(fs.readFileSync(file, "utf8")); + testInjector.get(DevServerOriginService).getToken = ( platform: string, - ) => (platform === "ios" ? "fd6f:72e:8d34::2" : undefined); + ) => `token-${platform}`; }); afterEach(() => { - if (previousHost === undefined) { - delete process.env.NS_HMR_HOST; - } else { - process.env.NS_HMR_HOST = previousHost; - } + fs.rmSync(projectDir, { recursive: true, force: true }); }); - it("hands the tunnel's Mac address to that platform only", async () => { + it("hands the dev server the platform's token", async () => { assert.deepEqual( - await (bundlerCompilerService).getViteChildEnv("ios", { - watch: true, - hmr: true, - }), + await (bundlerCompilerService).getViteChildEnv( + "ios", + { watch: true, hmr: true }, + { projectDir }, + ), { NS_VITE_DIST_DIR: ".ns-vite-build/ios", NS_HMR_PORT: "5173", - NS_HMR_HOST: "fd6f:72e:8d34::2", + NS_HMR_TOKEN: "token-ios", }, ); + }); + + it("passes no token for a platform the package does not list", async () => { assert.notProperty( - await (bundlerCompilerService).getViteChildEnv("android", { - watch: true, - hmr: true, - }), - "NS_HMR_HOST", + await (bundlerCompilerService).getViteChildEnv( + "android", + { watch: true, hmr: true }, + { projectDir }, + ), + "NS_HMR_TOKEN", ); }); - it("leaves a user-set NS_HMR_HOST alone", async () => { - process.env.NS_HMR_HOST = "192.168.1.10"; + it("passes no token to a build that runs no dev server", async () => { assert.notProperty( - await (bundlerCompilerService).getViteChildEnv("ios", { - watch: true, - hmr: true, - }), - "NS_HMR_HOST", + await (bundlerCompilerService).getViteChildEnv( + "ios", + { watch: true, hmr: true, release: true }, + { projectDir }, + ), + "NS_HMR_TOKEN", ); }); }); @@ -1044,21 +1060,40 @@ describe("BundlerCompilerService", () => { assert.isFalse(supports("ios")); }); - it("marks the packages that accept an IPv6 dev host, opted out or not", () => { - const accepts = (platform: string) => - bundlerCompilerService.acceptsIPv6DevHost(platform, { + it("reads the platforms whose devices use dev-server.json, opted out of single-process or not", () => { + const uses = (platform: string) => + bundlerCompilerService.usesDevServerFile(platform, { projectDir, }); - writeVitePackage({ name: "@nativescript/vite" }); - assert.isFalse(accepts("iOS")); - writeVitePackage({ name: "@nativescript/vite", nativescriptCli: { singleProcessDev: ["ios"] }, }); + assert.isFalse(uses("iOS")); + + writeVitePackage({ + name: "@nativescript/vite", + nativescriptCli: { + singleProcessDev: ["ios"], + devServerFile: ["ios", "android"], + }, + }); process.env.NS_VITE_SINGLE_PROCESS = "0"; - assert.isTrue(accepts("iOS")); - assert.isFalse(accepts("visionOS")); + assert.isTrue(uses("iOS")); + assert.isTrue(uses("android")); + assert.isFalse(uses("visionOS")); + }); + + it("never applies to webpack", () => { + writeVitePackage({ + name: "@nativescript/vite", + nativescriptCli: { devServerFile: ["ios"] }, + }); + (bundlerCompilerService).getBundler = () => "webpack"; + + assert.isFalse( + bundlerCompilerService.usesDevServerFile("ios", { projectDir }), + ); }); }); diff --git a/test/services/bundler/dev-server-origin-service.ts b/test/services/bundler/dev-server-origin-service.ts new file mode 100644 index 0000000000..32892af777 --- /dev/null +++ b/test/services/bundler/dev-server-origin-service.ts @@ -0,0 +1,301 @@ +import { assert } from "chai"; +import { Yok } from "../../../lib/common/yok"; +import { IInjector } from "../../../lib/common/definitions/yok"; +import { provide } from "../../../lib/common/di"; +import { Errors, Logger } from "../../../lib/contracts"; +import { DevServerOriginService } from "../../../lib/contracts/internal/dev-server-origin-service"; +import { IOSDeviceTunnelService } from "../../../lib/contracts/internal/ios-device-tunnel-service"; +import { + chooseDevServerOrigin, + DevServerOriginServiceImpl, + formatDevServerOrigin, + guessLanAddress, + IDevServerOriginInputs, +} from "../../../lib/services/bundler/dev-server-origin-service"; +import { ErrorsStub, LoggerStub } from "../../stubs"; + +const lan = "192.168.1.10"; + +function origin(inputs: Partial): string { + return chooseDevServerOrigin({ + port: 5173, + isAndroid: false, + isEmulator: false, + lanAddress: lan, + ...inputs, + }); +} + +describe("chooseDevServerOrigin", () => { + describe("with NS_HMR_HOST", () => { + const cases: [string, string][] = [ + ["dev.example.test", "http://dev.example.test:5173"], + ["dev.example.test:8443", "http://dev.example.test:8443"], + ["10.0.0.5", "http://10.0.0.5:5173"], + ["fd6f:72e:8d34::2", "http://[fd6f:72e:8d34::2]:5173"], + ["[fd6f:72e:8d34::2]", "http://[fd6f:72e:8d34::2]:5173"], + ["[fd6f:72e:8d34::2]:8080", "http://[fd6f:72e:8d34::2]:8080"], + [" dev.example.test ", "http://dev.example.test:5173"], + ]; + for (const [envHost, expected] of cases) { + it(`uses "${envHost}" for every kind of device`, () => { + for (const isAndroid of [true, false]) { + for (const isEmulator of [true, false]) { + assert.equal( + origin({ + envHost, + isAndroid, + isEmulator, + adbReverse: true, + tunnelAddress: "fd00::2", + }), + expected, + ); + } + } + }); + } + + it("ignores an empty or blank value", () => { + assert.equal( + origin({ envHost: "", isAndroid: true, adbReverse: true }), + "http://127.0.0.1:5173", + ); + assert.equal( + origin({ envHost: " ", isAndroid: true, adbReverse: true }), + "http://127.0.0.1:5173", + ); + }); + }); + + it("uses the loopback on Android when adb reverse works", () => { + assert.equal( + origin({ isAndroid: true, isEmulator: false, adbReverse: true }), + "http://127.0.0.1:5173", + ); + assert.equal( + origin({ isAndroid: true, isEmulator: true, adbReverse: true }), + "http://127.0.0.1:5173", + ); + }); + + it("uses 10.0.2.2 on an Android emulator without adb reverse", () => { + assert.equal( + origin({ isAndroid: true, isEmulator: true }), + "http://10.0.2.2:5173", + ); + }); + + it("uses the loopback on an iOS simulator", () => { + assert.equal( + origin({ isEmulator: true, tunnelAddress: "fd00::2" }), + "http://127.0.0.1:5173", + ); + }); + + it("uses the Mac's tunnel address, bracketed, on a physical iOS device", () => { + assert.equal( + origin({ tunnelAddress: "fd6f:72e:8d34::2" }), + "http://[fd6f:72e:8d34::2]:5173", + ); + }); + + it("uses the LAN address on a physical device with no other route", () => { + assert.equal(origin({}), `http://${lan}:5173`); + assert.equal(origin({ isAndroid: true }), `http://${lan}:5173`); + }); + + it("falls back to the loopback without a LAN address", () => { + assert.equal(origin({ lanAddress: undefined }), "http://127.0.0.1:5173"); + }); + + it("uses the platform's port", () => { + assert.equal( + origin({ port: 5174, isEmulator: true }), + "http://127.0.0.1:5174", + ); + }); +}); + +describe("formatDevServerOrigin", () => { + it("uses the platform's port when a bracketed host's suffix is not a port", () => { + assert.equal( + formatDevServerOrigin("[::1]:notaport", 5173), + "http://[::1]:5173", + ); + }); + + it("brackets a bare IPv6 address with an embedded IPv4 part", () => { + assert.equal( + formatDevServerOrigin("::ffff:192.168.1.10", 5173), + "http://[::ffff:192.168.1.10]:5173", + ); + }); +}); + +describe("guessLanAddress", () => { + it("returns the first external, non-link-local IPv4 address", () => { + assert.equal( + guessLanAddress({ + lo0: [{ address: "127.0.0.1", family: "IPv4", internal: true }], + awdl0: [{ address: "169.254.10.2", family: "IPv4", internal: false }], + utun4: [{ address: "fd00::2", family: "IPv6", internal: false }], + en0: [{ address: "192.168.1.10", family: 4, internal: false }], + en1: [{ address: "10.0.0.7", family: "IPv4", internal: false }], + }), + "192.168.1.10", + ); + }); + + it("returns nothing when no interface qualifies", () => { + assert.isUndefined( + guessLanAddress({ + lo0: [{ address: "127.0.0.1", family: "IPv4", internal: true }], + utun4: [{ address: "fd00::2", family: "IPv6", internal: false }], + }), + ); + }); +}); + +describe("DevServerOriginService", () => { + const previousHost = process.env.NS_HMR_HOST; + let service: DevServerOriginServiceImpl; + let tunnelAddresses: Record; + let interfaces: object; + let warnings: string[]; + + const device = ( + identifier: string, + platform: string, + isEmulator = false, + ): Mobile.IDevice => + { + deviceInfo: { identifier, platform, displayName: identifier }, + isEmulator, + }; + + beforeEach(() => { + delete process.env.NS_HMR_HOST; + tunnelAddresses = {}; + warnings = []; + interfaces = { + en0: [{ address: lan, family: "IPv4", internal: false }], + }; + + const injector: IInjector = new Yok(); + const logger = new LoggerStub(); + logger.warn = (message: string) => { + warnings.push(message); + }; + injector.register([ + { provide: Logger, useValue: logger }, + { provide: Errors, useClass: ErrorsStub }, + ]); + injector.register("mobileHelper", { + isAndroidPlatform: (platform: string) => + platform.toLowerCase() === "android", + }); + injector.register("viteHmrPortService", { + getPort: async (platform: string) => + platform === "android" ? 5174 : 5173, + }); + injector.register({ + provide: IOSDeviceTunnelService, + useValue: { + getHostAddress: (id: string) => tunnelAddresses[id], + }, + }); + injector.register( + provide(DevServerOriginService, DevServerOriginServiceImpl), + ); + service = injector.get(DevServerOriginService); + (service).getNetworkInterfaces = () => interfaces; + }); + + afterEach(() => { + if (previousHost === undefined) { + delete process.env.NS_HMR_HOST; + } else { + process.env.NS_HMR_HOST = previousHost; + } + }); + + it("keeps one URL-safe token per platform", () => { + const ios = service.getToken("ios"); + + assert.match(ios, /^[A-Za-z0-9_-]{32}$/); + assert.equal(service.getToken("iOS"), ios); + assert.notEqual(service.getToken("android"), ios); + }); + + it("writes the chosen origin and the platform's token into the device's file", async () => { + tunnelAddresses.phone = "fd6f:72e:8d34::2"; + + const chosen = await service.chooseOrigin(device("phone", "iOS")); + + assert.equal(chosen, "http://[fd6f:72e:8d34::2]:5173"); + assert.equal(service.getOrigin("phone"), chosen); + assert.deepEqual(JSON.parse(service.getDevServerFile("phone")), { + origin: "http://[fd6f:72e:8d34::2]:5173", + token: service.getToken("ios"), + }); + }); + + it("keeps each device's origin apart", async () => { + tunnelAddresses.first = "fd00::1"; + tunnelAddresses.second = "fd00::2"; + + await service.chooseOrigin(device("first", "iOS")); + await service.chooseOrigin(device("second", "iOS")); + await service.chooseOrigin(device("emulator-5554", "Android", true), { + adbReverse: true, + }); + + assert.equal(service.getOrigin("first"), "http://[fd00::1]:5173"); + assert.equal(service.getOrigin("second"), "http://[fd00::2]:5173"); + assert.equal(service.getOrigin("emulator-5554"), "http://127.0.0.1:5174"); + }); + + it("follows the tunnel's current state when chosen again", async () => { + tunnelAddresses.phone = "fd00::1"; + await service.chooseOrigin(device("phone", "iOS")); + + delete tunnelAddresses.phone; + + assert.equal( + await service.chooseOrigin(device("phone", "iOS")), + `http://${lan}:5173`, + ); + }); + + it("uses NS_HMR_HOST from the environment", async () => { + process.env.NS_HMR_HOST = "dev.example.test"; + tunnelAddresses.phone = "fd00::1"; + + assert.equal( + await service.chooseOrigin(device("phone", "iOS")), + "http://dev.example.test:5173", + ); + }); + + it("has no file for a device it chose nothing for, or forgot", async () => { + assert.isNull(service.getDevServerFile("phone")); + + await service.chooseOrigin(device("sim", "iOS", true)); + service.forget("sim"); + + assert.isNull(service.getDevServerFile("sim")); + assert.isUndefined(service.getOrigin("sim")); + }); + + it("warns when a physical device has no route but a missing LAN address", async () => { + interfaces = {}; + + await service.chooseOrigin(device("sim", "iOS", true)); + assert.isEmpty(warnings); + + await service.chooseOrigin(device("phone", "iOS")); + assert.lengthOf(warnings, 1); + assert.include(warnings[0], "NS_HMR_HOST"); + }); +}); diff --git a/test/services/ios/ios-device-tunnel-service.ts b/test/services/ios/ios-device-tunnel-service.ts index 74a6e95b9d..bb0bb3b0dd 100644 --- a/test/services/ios/ios-device-tunnel-service.ts +++ b/test/services/ios/ios-device-tunnel-service.ts @@ -198,7 +198,7 @@ describe("IOSDeviceTunnelService", () => { const address = await service.open(iPhone()); assert.equal(address, "fd6f:72e:8d34::2"); - assert.equal(service.getHostAddress("ios"), "fd6f:72e:8d34::2"); + assert.equal(service.getHostAddress(UDID), "fd6f:72e:8d34::2"); assert.lengthOf(spawned, 1); assert.includeMembers(spawned[0].args, [ "xcrun", @@ -292,7 +292,7 @@ describe("IOSDeviceTunnelService", () => { assert.isNull(await service.open(iPhone())); assert.lengthOf(spawned, 1); assert.isTrue(spawned[0].holder.killed); - assert.isUndefined(service.getHostAddress("ios")); + assert.isUndefined(service.getHostAddress(UDID)); }); it("releases the holder when no Mac interface is on the tunnel", async () => { @@ -311,7 +311,7 @@ describe("IOSDeviceTunnelService", () => { await service.close(UDID); assert.isTrue(spawned[0].holder.killed); - assert.isUndefined(service.getHostAddress("ios")); + assert.isUndefined(service.getHostAddress(UDID)); assert.isEmpty(warnings); }); @@ -325,4 +325,40 @@ describe("IOSDeviceTunnelService", () => { assert.lengthOf(warnings, 1); assert.include(warnings[0], "fd6f:72e:8d34::2"); }); + + it("forgets a tunnel that closed on its own, so the next open holds a new one", async () => { + devicectlListings = [[coreDevice(wiredConnected)]]; + await service.open(iPhone()); + + spawned[0].holder.emit("exit", 1, null); + await new Promise((resolve) => setImmediate(resolve)); + + assert.isUndefined(service.getHostAddress(UDID)); + assert.equal(await service.open(iPhone()), "fd6f:72e:8d34::2"); + assert.lengthOf(spawned, 2); + }); + + it("keeps each device's tunnel address apart", async () => { + const secondUDID = "00008112-000128D1022A201E"; + devicectlListings = [ + [ + coreDevice(wiredConnected), + coreDevice( + { ...wiredConnected, tunnelIPAddress: "fd58:5467:5f7b::1" }, + secondUDID, + ), + ], + ]; + + await service.open(iPhone()); + await service.open(iPhone({ identifier: secondUDID })); + + assert.equal(service.getHostAddress(UDID), "fd6f:72e:8d34::2"); + assert.equal(service.getHostAddress(secondUDID), "fd58:5467:5f7b::2"); + + await service.close(UDID); + + assert.isUndefined(service.getHostAddress(UDID)); + assert.equal(service.getHostAddress(secondUDID), "fd58:5467:5f7b::2"); + }); }); From 3a5b9bc32d6047ee8893eb3467eefc1035f07d67 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 4 Dec 2026 02:26:11 -0300 Subject: [PATCH 11/16] feat(vite): deliver dev-server.json to each device on every full sync The origin chosen for a device only helps once the app can read it. It goes into `dev-server.json` next to `bundle.mjs`, per device, and never into the shared platforms app folder, which every device and the installed package share. - iOS simulator: written into the installed `.app/app` after the sync, and again after a native rebuild reinstalls the app. - Physical iOS device: added as `app/dev-server.json` to that device's `sync.zip`, which the runtime extracts at boot. - Android: sent from memory over the livesync socket on every full sync, outside the hash diff, followed by DO_SYNC even when no other file changed, since only DO_SYNC confirms the runtime wrote what preceded it. A reinstalled APK replaces the app directory on its first launch, so a native rebuild now runs a full sync after the install. --- lib/constants.ts | 6 + ...android-device-livesync-sockets-service.ts | 20 +- .../livesync/android-livesync-service.ts | 53 +++-- lib/services/livesync/ios-livesync-service.ts | 76 ++++++- ...android-device-livesync-sockets-service.ts | 115 +++++++++- .../livesync/android-livesync-service.ts | 62 ++++++ .../services/livesync/ios-livesync-service.ts | 196 ++++++++++++++++++ 7 files changed, 507 insertions(+), 21 deletions(-) create mode 100644 test/services/livesync/android-livesync-service.ts create mode 100644 test/services/livesync/ios-livesync-service.ts diff --git a/lib/constants.ts b/lib/constants.ts index aa6fb3f8c7..8e6dfc796c 100644 --- a/lib/constants.ts +++ b/lib/constants.ts @@ -23,6 +23,12 @@ export const RSPACK_PLUGIN_NAME = "@nativescript/rspack"; // and tells `@nativescript/vite` where via `NS_VITE_DIST_DIR`; the package's // own fallback (`.ns-vite-build`) only applies to standalone `vite` runs. export const VITE_DIST_FOLDER_NAME = ".ns-vite-build"; +/** + * Per-device file next to `bundle.mjs` that tells a Vite HMR app the dev + * server's origin and token. Never part of the shared platforms app folder: + * the origin differs between devices. + */ +export const DEV_SERVER_FILE_NAME = "dev-server.json"; export const TNS_CORE_MODULES_WIDGETS_NAME = "tns-core-modules-widgets"; export const UI_MOBILE_BASE_NAME = "@nativescript/ui-mobile-base"; export const TNS_ANDROID_RUNTIME_NAME = "tns-android"; diff --git a/lib/services/livesync/android-device-livesync-sockets-service.ts b/lib/services/livesync/android-device-livesync-sockets-service.ts index 6fc9d31e69..8b64c67857 100644 --- a/lib/services/livesync/android-device-livesync-sockets-service.ts +++ b/lib/services/livesync/android-device-livesync-sockets-service.ts @@ -13,6 +13,9 @@ import { IInjector } from "../../common/definitions/yok"; import { ICleanupService } from "../../definitions/cleanup-service"; import { ISpawnCommandInfo } from "../../detached-processes/cleanup-process-definitions"; import { ITempService } from "../../definitions/temp-service"; +import { inject } from "../../common/di"; +import { DevServerOriginService } from "../../contracts/internal/dev-server-origin-service"; +import { DEV_SERVER_FILE_NAME } from "../../constants"; /** * Whether a file sync asks the app to refresh itself in place. Never under @@ -36,6 +39,7 @@ export class AndroidDeviceSocketsLiveSyncService IAndroidNativeScriptDeviceLiveSyncService, INativeScriptDeviceLiveSyncService { + private devServerOriginService = inject(DevServerOriginService); private livesyncTool: IAndroidLivesyncTool; private static STATUS_UPDATE_INTERVAL = 10000; private static MINIMAL_VERSION_LONG_LIVING_CONNECTION = "0.2.0"; @@ -141,7 +145,21 @@ export class AndroidDeviceSocketsLiveSyncService let result = { operationId, didRefresh: true }; - if (liveSyncInfo.modifiedFilesData.length) { + const devServerFile = liveSyncInfo.isFullSync + ? this.devServerOriginService.getDevServerFile( + this.device.deviceInfo.identifier, + ) + : null; + if (devServerFile) { + await this.livesyncTool.sendFileFromBuffer( + DEV_SERVER_FILE_NAME, + Buffer.from(devServerFile), + ); + } + + // The runtime acknowledges only DO_SYNC, after it has written every + // file sent before it. + if (liveSyncInfo.modifiedFilesData.length || devServerFile) { const canExecuteFastSync = refreshesInPlaceOnSync(liveSyncInfo, projectData) && this.canExecuteFastSyncForPaths( diff --git a/lib/services/livesync/android-livesync-service.ts b/lib/services/livesync/android-livesync-service.ts index 8ff185ca0d..54cfd2c3d6 100644 --- a/lib/services/livesync/android-livesync-service.ts +++ b/lib/services/livesync/android-livesync-service.ts @@ -14,12 +14,15 @@ import { import { IInjector } from "../../common/definitions/yok"; import { injector } from "../../common/yok"; import { IOptions } from "../../declarations"; +import { inject } from "../../common/di"; +import { DevServerOriginService } from "../../contracts/internal/dev-server-origin-service"; export class AndroidLiveSyncService extends PlatformLiveSyncServiceBase implements IPlatformLiveSyncService { private static MIN_SOCKETS_LIVESYNC_RUNTIME_VERSION = "4.2.0-2018-07-20-02"; + private devServerOriginService = inject(DevServerOriginService); constructor( protected $platformsDataService: IPlatformsDataService, protected $projectFilesManager: IProjectFilesManager, @@ -27,7 +30,7 @@ export class AndroidLiveSyncService $devicePathProvider: IDevicePathProvider, $fs: IFileSystem, $logger: ILogger, - $options: IOptions + $options: IOptions, ) { super( $fs, @@ -35,46 +38,46 @@ export class AndroidLiveSyncService $platformsDataService, $projectFilesManager, $devicePathProvider, - $options + $options, ); } protected _getDeviceLiveSyncService( device: Mobile.IDevice, data: IProjectDir, - frameworkVersion: string + frameworkVersion: string, ): INativeScriptDeviceLiveSyncService { if ( semver.gt( frameworkVersion, - AndroidLiveSyncService.MIN_SOCKETS_LIVESYNC_RUNTIME_VERSION + AndroidLiveSyncService.MIN_SOCKETS_LIVESYNC_RUNTIME_VERSION, ) ) { return this.$injector.resolve( AndroidDeviceSocketsLiveSyncService, - { device, data } + { device, data }, ); } return this.$injector.resolve( AndroidDeviceLiveSyncService, - { device, data } + { device, data }, ); } @performanceLog() public async liveSyncWatchAction( device: Mobile.IDevice, - liveSyncInfo: ILiveSyncWatchInfo + liveSyncInfo: ILiveSyncWatchInfo, ): Promise { const liveSyncResult = await super.liveSyncWatchAction( device, - liveSyncInfo + liveSyncInfo, ); const result = await this.finalizeSync( device, liveSyncInfo.projectData, - liveSyncResult + liveSyncResult, ); return result; @@ -82,28 +85,52 @@ export class AndroidLiveSyncService @performanceLog() public async fullSync( - syncInfo: IFullSyncInfo + syncInfo: IFullSyncInfo, ): Promise { const liveSyncResult = await super.fullSync(syncInfo); const result = await this.finalizeSync( syncInfo.device, syncInfo.projectData, - liveSyncResult + liveSyncResult, ); return result; } + /** + * The first launch of a new APK replaces the app directory with the + * APK's, which drops `dev-server.json`, so it is synced again. + */ + public async syncAfterInstall( + device: Mobile.IDevice, + liveSyncInfo: ILiveSyncWatchInfo, + ): Promise { + if ( + !this.devServerOriginService.getDevServerFile( + device.deviceInfo.identifier, + ) + ) { + return; + } + await this.fullSync({ + projectData: liveSyncInfo.projectData, + device, + liveSyncDeviceData: liveSyncInfo.liveSyncDeviceData, + watch: true, + useHotModuleReload: liveSyncInfo.useHotModuleReload, + }); + } + private async finalizeSync( device: Mobile.IDevice, projectData: IProjectData, - liveSyncResult: ILiveSyncResultInfo + liveSyncResult: ILiveSyncResultInfo, ): Promise { const liveSyncService = ( this.getDeviceLiveSyncService(device, projectData) ); const finalizeResult = await liveSyncService.finalizeSync( liveSyncResult, - projectData + projectData, ); const result = _.extend(liveSyncResult, finalizeResult); return result; diff --git a/lib/services/livesync/ios-livesync-service.ts b/lib/services/livesync/ios-livesync-service.ts index cedcf2b5c2..9660068d5b 100644 --- a/lib/services/livesync/ios-livesync-service.ts +++ b/lib/services/livesync/ios-livesync-service.ts @@ -2,7 +2,7 @@ import * as path from "path"; import { IOSDeviceLiveSyncService } from "./ios-device-livesync-service"; import { PlatformLiveSyncServiceBase } from "./platform-livesync-service-base"; -import { APP_FOLDER_NAME } from "../../constants"; +import { APP_FOLDER_NAME, DEV_SERVER_FILE_NAME } from "../../constants"; import { LiveSyncPaths } from "../../common/constants"; import { performanceLog } from "../../common/decorators"; import { IPlatformsDataService } from "../../definitions/platform"; @@ -15,11 +15,15 @@ import { IInjector } from "../../common/definitions/yok"; import { injector } from "../../common/yok"; import { ITempService } from "../../definitions/temp-service"; import { IOptions } from "../../declarations"; +import { inject } from "../../common/di"; +import { DevServerOriginService } from "../../contracts/internal/dev-server-origin-service"; export class IOSLiveSyncService extends PlatformLiveSyncServiceBase implements IPlatformLiveSyncService { + private devServerOriginService = inject(DevServerOriginService); + constructor( protected $fs: IFileSystem, protected $platformsDataService: IPlatformsDataService, @@ -45,7 +49,9 @@ export class IOSLiveSyncService const device = syncInfo.device; if (device.isEmulator) { - return super.fullSync(syncInfo); + const result = await super.fullSync(syncInfo); + await this.writeDevServerFile(result.deviceAppData); + return result; } const projectData = syncInfo.projectData; const platformData = this.$platformsDataService.getPlatformData( @@ -66,10 +72,18 @@ export class IOSLiveSyncService const filesToTransfer = this.$fs.enumerateFilesInDirectorySync(projectFilesPath); + const devServerFile = await this.createDevServerFile( + device.deviceInfo.identifier, + ); - await this.$fs.zipFiles(tempZip, filesToTransfer, (res) => { - return path.join(APP_FOLDER_NAME, path.relative(projectFilesPath, res)); - }); + await this.$fs.zipFiles( + tempZip, + devServerFile ? [...filesToTransfer, devServerFile] : filesToTransfer, + (res) => + res === devServerFile + ? path.join(APP_FOLDER_NAME, DEV_SERVER_FILE_NAME) + : path.join(APP_FOLDER_NAME, path.relative(projectFilesPath, res)), + ); const deviceProjectRootPath = await deviceAppData.getDeviceProjectRootPath(); @@ -234,7 +248,17 @@ export class IOSLiveSyncService device: Mobile.IDevice, liveSyncInfo: ILiveSyncWatchInfo, ): Promise { - if (!device.isEmulator) { + if (device.isEmulator) { + await this.writeDevServerFile( + await this.getAppData({ + projectData: liveSyncInfo.projectData, + device, + liveSyncDeviceData: liveSyncInfo.liveSyncDeviceData, + watch: true, + useHotModuleReload: liveSyncInfo.useHotModuleReload, + }), + ); + } else { // In this case we should execute fullsync because iOS Runtime requires the full content of app dir to be extracted in the root of sync dir. await this.fullSync({ projectData: liveSyncInfo.projectData, @@ -246,6 +270,46 @@ export class IOSLiveSyncService } } + /** + * Writes the device's `dev-server.json` next to `bundle.mjs` in the + * installed app (a simulator) or the synced one (a device). + */ + private async writeDevServerFile( + deviceAppData: Mobile.IDeviceAppData, + ): Promise { + const localPath = await this.createDevServerFile( + deviceAppData.device.deviceInfo.identifier, + ); + if (!localPath) { + return; + } + const devicePath = path.join( + await deviceAppData.getDeviceProjectRootPath(), + DEV_SERVER_FILE_NAME, + ); + await deviceAppData.device.fileSystem.putFile( + localPath, + devicePath, + deviceAppData.appIdentifier, + ); + } + + private async createDevServerFile( + deviceIdentifier: string, + ): Promise { + const content = + this.devServerOriginService.getDevServerFile(deviceIdentifier); + if (!content) { + return null; + } + const localPath = await this.$tempService.path({ + prefix: "dev-server", + suffix: ".json", + }); + this.$fs.writeFile(localPath, content); + return localPath; + } + protected _getDeviceLiveSyncService( device: Mobile.IDevice, data: IProjectDir, diff --git a/test/services/livesync/android-device-livesync-sockets-service.ts b/test/services/livesync/android-device-livesync-sockets-service.ts index 4077b3a020..c6cbac5bfc 100644 --- a/test/services/livesync/android-device-livesync-sockets-service.ts +++ b/test/services/livesync/android-device-livesync-sockets-service.ts @@ -1,5 +1,12 @@ import { assert } from "chai"; -import { refreshesInPlaceOnSync } from "../../../lib/services/livesync/android-device-livesync-sockets-service"; +import { Yok } from "../../../lib/common/yok"; +import { IInjector } from "../../../lib/common/definitions/yok"; +import { DevServerOriginService } from "../../../lib/contracts/internal/dev-server-origin-service"; +import { + AndroidDeviceSocketsLiveSyncService, + refreshesInPlaceOnSync, +} from "../../../lib/services/livesync/android-device-livesync-sockets-service"; +import { LoggerStub } from "../../stubs"; describe("refreshesInPlaceOnSync", () => { it("refreshes an incremental sync", () => { @@ -32,3 +39,109 @@ describe("refreshesInPlaceOnSync", () => { ); }); }); + +describe("AndroidDeviceSocketsLiveSyncService dev-server.json delivery", () => { + const appIdentifier = "org.nativescript.devserver"; + const devServerFile = '{"origin":"http://127.0.0.1:5173","token":"t"}'; + let devServerFiles: Record; + let operations: string[]; + let sentBuffers: { relativePath: string; content: string }[]; + let doSyncOptions: IDoSyncOperationOptions[]; + let service: AndroidDeviceSocketsLiveSyncService; + + const device = { + deviceInfo: { identifier: "emulator-5554", platform: "Android" }, + fileSystem: { + deleteFile: async (): Promise => undefined, + }, + }; + + beforeEach(() => { + devServerFiles = {}; + operations = []; + sentBuffers = []; + doSyncOptions = []; + + const injector: IInjector = new Yok(); + injector.register("injector", injector); + injector.register("logger", LoggerStub); + injector.register("errors", {}); + injector.register("fs", {}); + injector.register("mobileHelper", {}); + injector.register("androidProcessService", {}); + injector.register("platformsDataService", {}); + injector.register("staticConfig", { + getAdbFilePath: async () => "adb", + }); + injector.register("options", {}); + injector.register("cleanupService", { + addCleanupCommand: async (): Promise => undefined, + removeCleanupCommand: async (): Promise => undefined, + }); + injector.register("devicePlatformsConstants", {}); + injector.register("tempService", {}); + injector.register("filesHashService", {}); + injector.register({ + provide: DevServerOriginService, + useValue: { + getDevServerFile: (id: string) => devServerFiles[id] ?? null, + }, + }); + service = injector.resolve(AndroidDeviceSocketsLiveSyncService, { + device, + data: {}, + }); + (service).livesyncTool = { + protocolVersion: "0.2.0", + generateOperationIdentifier: () => "operation", + isOperationInProgress: () => false, + sendFileFromBuffer: async (relativePath: string, content: Buffer) => { + operations.push("file"); + sentBuffers.push({ relativePath, content: content.toString() }); + }, + sendDoSyncOperation: async (options: IDoSyncOperationOptions) => { + operations.push("doSync"); + doSyncOptions.push(options); + return { operationId: options.operationId, didRefresh: false }; + }, + end: (): void => undefined, + }; + }); + + const finalize = (isFullSync: boolean, modifiedFilesData: any[] = []) => + service.finalizeSync( + { + isFullSync, + modifiedFilesData, + useHotModuleReload: true, + deviceAppData: { appIdentifier, device }, + }, + { bundler: "vite" }, + ); + + it("sends the file before DO_SYNC on a full sync, even when no file changed", async () => { + devServerFiles["emulator-5554"] = devServerFile; + + await finalize(true); + + assert.deepEqual(operations, ["file", "doSync"]); + assert.deepEqual(sentBuffers, [ + { relativePath: "dev-server.json", content: devServerFile }, + ]); + assert.isFalse(doSyncOptions[0].doRefresh); + }); + + it("does not send it on an incremental sync", async () => { + devServerFiles["emulator-5554"] = devServerFile; + + await finalize(false); + + assert.deepEqual(operations, []); + }); + + it("leaves a full sync without an origin as it was", async () => { + await finalize(true); + + assert.deepEqual(operations, []); + }); +}); diff --git a/test/services/livesync/android-livesync-service.ts b/test/services/livesync/android-livesync-service.ts new file mode 100644 index 0000000000..46b9e2d1c2 --- /dev/null +++ b/test/services/livesync/android-livesync-service.ts @@ -0,0 +1,62 @@ +import { assert } from "chai"; +import { Yok } from "../../../lib/common/yok"; +import { IInjector } from "../../../lib/common/definitions/yok"; +import { DevServerOriginService } from "../../../lib/contracts/internal/dev-server-origin-service"; +import { AndroidLiveSyncService } from "../../../lib/services/livesync/android-livesync-service"; +import { LoggerStub } from "../../stubs"; + +describe("AndroidLiveSyncService", () => { + describe("syncAfterInstall", () => { + let devServerFiles: Record; + let fullSyncs: IFullSyncInfo[]; + let service: AndroidLiveSyncService; + const device = { + deviceInfo: { identifier: "emulator-5554", platform: "Android" }, + }; + const watchInfo = { + projectData: { projectDir: "/project" }, + liveSyncDeviceData: { identifier: "emulator-5554" }, + useHotModuleReload: true, + }; + + beforeEach(() => { + devServerFiles = {}; + fullSyncs = []; + const injector: IInjector = new Yok(); + injector.register("injector", injector); + injector.register("platformsDataService", {}); + injector.register("projectFilesManager", {}); + injector.register("devicePathProvider", {}); + injector.register("fs", {}); + injector.register("logger", LoggerStub); + injector.register("options", {}); + injector.register({ + provide: DevServerOriginService, + useValue: { + getDevServerFile: (id: string) => devServerFiles[id] ?? null, + }, + }); + service = injector.resolve(AndroidLiveSyncService); + service.fullSync = async (syncInfo: IFullSyncInfo) => { + fullSyncs.push(syncInfo); + return {}; + }; + }); + + it("syncs fully again so the new APK's first launch gets dev-server.json back", async () => { + devServerFiles["emulator-5554"] = "{}"; + + await service.syncAfterInstall(device, watchInfo); + + assert.lengthOf(fullSyncs, 1); + assert.strictEqual(fullSyncs[0].device, device); + assert.isTrue(fullSyncs[0].useHotModuleReload); + }); + + it("does nothing for a device without an origin", async () => { + await service.syncAfterInstall(device, watchInfo); + + assert.deepEqual(fullSyncs, []); + }); + }); +}); diff --git a/test/services/livesync/ios-livesync-service.ts b/test/services/livesync/ios-livesync-service.ts new file mode 100644 index 0000000000..2fba977ab4 --- /dev/null +++ b/test/services/livesync/ios-livesync-service.ts @@ -0,0 +1,196 @@ +import { assert } from "chai"; +import * as path from "path"; +import * as sinon from "sinon"; +import { Yok } from "../../../lib/common/yok"; +import { IInjector } from "../../../lib/common/definitions/yok"; +import { DevServerOriginService } from "../../../lib/contracts/internal/dev-server-origin-service"; +import { IOSLiveSyncService } from "../../../lib/services/livesync/ios-livesync-service"; +import { PlatformLiveSyncServiceBase } from "../../../lib/services/livesync/platform-livesync-service-base"; +import { LoggerStub } from "../../stubs"; + +const appIdentifier = "org.nativescript.devserver"; +const appDestination = "/project/platforms/ios/App/app-dest"; +const appFolder = path.join(appDestination, "app"); +const bundlePath = path.join(appFolder, "bundle.mjs"); +const simulatorAppRoot = "/Simulator/Containers/App.app/app"; +const deviceAppRoot = "Library/Application Support/LiveSync/app"; +const devServerFile = '{"origin":"http://127.0.0.1:5173","token":"t"}'; + +describe("IOSLiveSyncService dev-server.json delivery", () => { + let sandbox: sinon.SinonSandbox; + let service: IOSLiveSyncService; + let devServerFiles: Record; + let written: Record; + let zipped: { files: string[]; entries: string[] }; + let transferredAppFiles: string[]; + let putFiles: { localPath: string; devicePath: string; appId: string }[]; + + const projectData = { + projectDir: "/project", + projectIdentifiers: { ios: appIdentifier }, + }; + + const device = (identifier: string, isEmulator: boolean): Mobile.IDevice => + { + isEmulator, + deviceInfo: { identifier, platform: "iOS" }, + fileSystem: { + putFile: async ( + localPath: string, + devicePath: string, + appId: string, + ) => { + putFiles.push({ localPath, devicePath, appId }); + }, + transferFiles: async (): Promise => undefined, + }, + applicationManager: { + setTransferredAppFiles: async (files: string[]) => { + transferredAppFiles = files; + }, + }, + }; + + beforeEach(() => { + sandbox = sinon.createSandbox(); + devServerFiles = {}; + written = {}; + zipped = null; + transferredAppFiles = null; + putFiles = []; + let tempFiles = 0; + + const injector: IInjector = new Yok(); + injector.register("injector", injector); + injector.register("fs", { + enumerateFilesInDirectorySync: () => [bundlePath], + writeFile: (filePath: string, content: string) => { + written[filePath] = content; + }, + zipFiles: async ( + _zip: string, + files: string[], + mapper: (file: string) => string, + ) => { + zipped = { files, entries: files.map(mapper) }; + }, + }); + injector.register("platformsDataService", { + getPlatformData: () => ({ + appDestinationDirectoryPath: appDestination, + platformProjectService: { getFrameworkVersion: () => "8.9.0" }, + }), + }); + injector.register("projectFilesManager", {}); + injector.register("tempService", { + path: async (options: { prefix: string; suffix: string }) => + `/tmp/${options.prefix}-${++tempFiles}${options.suffix}`, + }); + injector.register("devicePathProvider", { + getDeviceProjectRootPath: async (target: Mobile.IDevice) => + target.isEmulator ? simulatorAppRoot : deviceAppRoot, + getDeviceSyncZipPath: (target: Mobile.IDevice) => + target.isEmulator + ? undefined + : "Library/Application Support/LiveSync/sync.zip", + }); + injector.register("logger", LoggerStub); + injector.register("options", { hostProjectModuleName: "app" }); + injector.register({ + provide: DevServerOriginService, + useValue: { + getDevServerFile: (id: string) => devServerFiles[id] ?? null, + }, + }); + service = injector.resolve(IOSLiveSyncService); + + sandbox + .stub(PlatformLiveSyncServiceBase.prototype, "fullSync") + .callsFake(async function ( + this: PlatformLiveSyncServiceBase, + syncInfo: IFullSyncInfo, + ) { + return { + deviceAppData: await this.getAppData(syncInfo), + isFullSync: true, + modifiedFilesData: [], + useHotModuleReload: true, + }; + }); + }); + + afterEach(() => { + sandbox.restore(); + }); + + const fullSync = (target: Mobile.IDevice) => + service.fullSync({ + projectData, + device: target, + watch: true, + useHotModuleReload: true, + liveSyncDeviceData: {}, + }); + + describe("on a simulator", () => { + it("writes the file next to bundle.mjs in the installed app after the sync", async () => { + devServerFiles.sim = devServerFile; + + await fullSync(device("sim", true)); + + assert.lengthOf(putFiles, 1); + assert.equal( + putFiles[0].devicePath, + path.join(simulatorAppRoot, "dev-server.json"), + ); + assert.equal(putFiles[0].appId, appIdentifier); + assert.equal(written[putFiles[0].localPath], devServerFile); + }); + + it("writes nothing for a device without an origin", async () => { + await fullSync(device("sim", true)); + + assert.deepEqual(putFiles, []); + }); + + it("writes the file again into a reinstalled app", async () => { + devServerFiles.sim = devServerFile; + + await service.syncAfterInstall(device("sim", true), { + projectData, + liveSyncDeviceData: {}, + useHotModuleReload: true, + }); + + assert.lengthOf(putFiles, 1); + assert.equal( + putFiles[0].devicePath, + path.join(simulatorAppRoot, "dev-server.json"), + ); + }); + }); + + describe("on a physical device", () => { + it("adds the file to that device's sync.zip next to bundle.mjs", async () => { + devServerFiles.phone = devServerFile; + + await fullSync(device("phone", false)); + + assert.deepEqual(zipped.entries, [ + "app/bundle.mjs", + "app/dev-server.json", + ]); + assert.equal(written[zipped.files[1]], devServerFile); + assert.deepEqual(transferredAppFiles, [bundlePath]); + assert.deepEqual(putFiles, []); + }); + + it("zips only the app for a device without an origin", async () => { + devServerFiles.other = devServerFile; + + await fullSync(device("phone", false)); + + assert.deepEqual(zipped.entries, ["app/bundle.mjs"]); + }); + }); +}); From b515300e1cfe7668a827a73db6a63563df0d692a Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 4 Dec 2026 02:26:26 -0300 Subject: [PATCH 12/16] feat(vite): write an https origin when the dev server serves https `@nativescript/vite` serves https when `NS_HTTPS` is "1" or "true", and the app takes the origin in `dev-server.json` verbatim, so the scheme has to match. The CLI reads `NS_HTTPS` the same way. --- .../bundler/dev-server-origin-service.ts | 35 ++++++++++++----- .../bundler/bundler-compiler-service.ts | 23 +++++++++++ .../bundler/dev-server-origin-service.ts | 38 +++++++++++++++++++ 3 files changed, 87 insertions(+), 9 deletions(-) diff --git a/lib/services/bundler/dev-server-origin-service.ts b/lib/services/bundler/dev-server-origin-service.ts index fc62eb4090..94a43db7ad 100644 --- a/lib/services/bundler/dev-server-origin-service.ts +++ b/lib/services/bundler/dev-server-origin-service.ts @@ -16,6 +16,8 @@ const ANDROID_EMULATOR_HOST = "10.0.2.2"; export interface IDevServerOriginInputs { port: number; + /** The dev server serves https. */ + https?: boolean; /** `NS_HMR_HOST` as the user set it. */ envHost?: string; isAndroid: boolean; @@ -32,11 +34,21 @@ export interface IDevServerOriginInputs { * serialized through a URL parser. */ export function chooseDevServerOrigin(inputs: IDevServerOriginInputs): string { + const scheme = inputs.https ? "https" : "http"; const envHost = inputs.envHost?.trim(); if (envHost) { - return formatDevServerOrigin(envHost, inputs.port); + return formatDevServerOrigin(envHost, inputs.port, scheme); } - return formatDevServerOrigin(chooseDevServerHost(inputs), inputs.port); + return formatDevServerOrigin( + chooseDevServerHost(inputs), + inputs.port, + scheme, + ); +} + +/** Mirrors how `@nativescript/vite` decides to serve https. */ +export function isDevServerHttps(env: NodeJS.ProcessEnv): boolean { + return env.NS_HTTPS === "1" || env.NS_HTTPS === "true"; } function chooseDevServerHost(inputs: IDevServerOriginInputs): string { @@ -59,29 +71,33 @@ function chooseDevServerHost(inputs: IDevServerOriginInputs): string { } /** - * `http://:`, with an IPv6 host bracketed. `host` may carry its - * own port (`host:port`, `[v6]:port`), which then wins over `port`. + * `://:`, with an IPv6 host bracketed. `host` may carry + * its own port (`host:port`, `[v6]:port`), which then wins over `port`. */ -export function formatDevServerOrigin(host: string, port: number): string { +export function formatDevServerOrigin( + host: string, + port: number, + scheme: "http" | "https" = "http", +): string { if (host.startsWith("[")) { const closing = host.indexOf("]"); if (closing !== -1) { const bracketed = host.slice(0, closing + 1); const explicitPort = parsePort(host.slice(closing + 1)); - return `http://${bracketed}:${explicitPort ?? port}`; + return `${scheme}://${bracketed}:${explicitPort ?? port}`; } } if (net.isIPv6(host)) { - return `http://[${host}]:${port}`; + return `${scheme}://[${host}]:${port}`; } const colon = host.indexOf(":"); if (colon !== -1 && colon === host.lastIndexOf(":")) { const explicitPort = parsePort(host.slice(colon)); if (explicitPort !== undefined) { - return `http://${host.slice(0, colon)}:${explicitPort}`; + return `${scheme}://${host.slice(0, colon)}:${explicitPort}`; } } - return `http://${host}:${port}`; + return `${scheme}://${host}:${port}`; } function parsePort(suffix: string): number | undefined { @@ -144,6 +160,7 @@ export class DevServerOriginServiceImpl implements DevServerOriginService { const isAndroid = this.mobileHelper.isAndroidPlatform(platform); const inputs: IDevServerOriginInputs = { port: await this.viteHmrPortService.getPort(platform), + https: isDevServerHttps(process.env), envHost: process.env.NS_HMR_HOST, isAndroid, isEmulator: device.isEmulator, diff --git a/test/services/bundler/bundler-compiler-service.ts b/test/services/bundler/bundler-compiler-service.ts index 42040c2538..671c9390c8 100644 --- a/test/services/bundler/bundler-compiler-service.ts +++ b/test/services/bundler/bundler-compiler-service.ts @@ -423,6 +423,29 @@ describe("BundlerCompilerService", () => { ); }); + it("hands over the token in two-process mode too", async () => { + const previous = process.env.NS_VITE_SINGLE_PROCESS; + process.env.NS_VITE_SINGLE_PROCESS = "0"; + try { + assert.equal( + ( + await (bundlerCompilerService).getViteChildEnv( + "ios", + { watch: true, hmr: true }, + { projectDir }, + ) + ).NS_HMR_TOKEN, + "token-ios", + ); + } finally { + if (previous === undefined) { + delete process.env.NS_VITE_SINGLE_PROCESS; + } else { + process.env.NS_VITE_SINGLE_PROCESS = previous; + } + } + }); + it("passes no token for a platform the package does not list", async () => { assert.notProperty( await (bundlerCompilerService).getViteChildEnv( diff --git a/test/services/bundler/dev-server-origin-service.ts b/test/services/bundler/dev-server-origin-service.ts index 32892af777..a743d0c3df 100644 --- a/test/services/bundler/dev-server-origin-service.ts +++ b/test/services/bundler/dev-server-origin-service.ts @@ -10,6 +10,7 @@ import { DevServerOriginServiceImpl, formatDevServerOrigin, guessLanAddress, + isDevServerHttps, IDevServerOriginInputs, } from "../../../lib/services/bundler/dev-server-origin-service"; import { ErrorsStub, LoggerStub } from "../../stubs"; @@ -109,6 +110,17 @@ describe("chooseDevServerOrigin", () => { assert.equal(origin({ lanAddress: undefined }), "http://127.0.0.1:5173"); }); + it("uses https when the dev server serves it", () => { + assert.equal( + origin({ https: true, tunnelAddress: "fd00::2" }), + "https://[fd00::2]:5173", + ); + assert.equal( + origin({ https: true, envHost: "dev.example.test:8443" }), + "https://dev.example.test:8443", + ); + }); + it("uses the platform's port", () => { assert.equal( origin({ port: 5174, isEmulator: true }), @@ -133,6 +145,16 @@ describe("formatDevServerOrigin", () => { }); }); +describe("isDevServerHttps", () => { + it("follows NS_HTTPS the way @nativescript/vite reads it", () => { + assert.isTrue(isDevServerHttps({ NS_HTTPS: "1" })); + assert.isTrue(isDevServerHttps({ NS_HTTPS: "true" })); + assert.isFalse(isDevServerHttps({ NS_HTTPS: "yes" })); + assert.isFalse(isDevServerHttps({ NS_HTTPS: "0" })); + assert.isFalse(isDevServerHttps({})); + }); +}); + describe("guessLanAddress", () => { it("returns the first external, non-link-local IPv4 address", () => { assert.equal( @@ -159,6 +181,7 @@ describe("guessLanAddress", () => { describe("DevServerOriginService", () => { const previousHost = process.env.NS_HMR_HOST; + const previousHttps = process.env.NS_HTTPS; let service: DevServerOriginServiceImpl; let tunnelAddresses: Record; let interfaces: object; @@ -176,6 +199,7 @@ describe("DevServerOriginService", () => { beforeEach(() => { delete process.env.NS_HMR_HOST; + delete process.env.NS_HTTPS; tunnelAddresses = {}; warnings = []; interfaces = { @@ -218,6 +242,20 @@ describe("DevServerOriginService", () => { } else { process.env.NS_HMR_HOST = previousHost; } + if (previousHttps === undefined) { + delete process.env.NS_HTTPS; + } else { + process.env.NS_HTTPS = previousHttps; + } + }); + + it("writes an https origin when NS_HTTPS is set", async () => { + process.env.NS_HTTPS = "1"; + + assert.equal( + await service.chooseOrigin(device("sim", "iOS", true)), + "https://127.0.0.1:5173", + ); }); it("keeps one URL-safe token per platform", () => { From 12cb19d5c52e4ecf57b4d6a373f5ba5523b90ed9 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 4 Dec 2026 02:28:06 -0300 Subject: [PATCH 13/16] feat(ios): move a device to another origin when its USB tunnel drops A tunnel address only exists while its tunnel is up: once the cable is pulled or the CoreDevice tunnel resets, the app can no longer reach the dev server, and the session used to need a restart. The tunnel service now reports a tunnel that goes down on its own. The run controller then chooses that device's origin again (typically the Mac's LAN address, for a device that is also on the network), uploads its `dev-server.json` to `LiveSync/app/` and restarts only that device's app. The rewrite waits its turn on the session's action chain; a device that is gone by then is reported rather than failing the session. --- .../internal/ios-device-tunnel-service.ts | 6 ++ lib/controllers/run-controller.ts | 68 ++++++++++++++++ lib/definitions/livesync.d.ts | 9 +++ lib/services/ios/ios-device-tunnel-service.ts | 10 ++- lib/services/livesync/ios-livesync-service.ts | 17 ++++ test/controllers/run-controller.ts | 78 ++++++++++++++++++- .../services/ios/ios-device-tunnel-service.ts | 14 ++++ 7 files changed, 199 insertions(+), 3 deletions(-) diff --git a/lib/contracts/internal/ios-device-tunnel-service.ts b/lib/contracts/internal/ios-device-tunnel-service.ts index aecabc5cbf..f3ebe96b92 100644 --- a/lib/contracts/internal/ios-device-tunnel-service.ts +++ b/lib/contracts/internal/ios-device-tunnel-service.ts @@ -21,4 +21,10 @@ export abstract class IOSDeviceTunnelService { abstract getHostAddress(deviceIdentifier: string): string | undefined; abstract close(deviceIdentifier: string): Promise; + + /** + * Calls `listener` with the device's identifier when an open tunnel goes + * down without `close`, after `getHostAddress` stopped returning it. + */ + abstract onTunnelLost(listener: (deviceIdentifier: string) => void): void; } diff --git a/lib/controllers/run-controller.ts b/lib/controllers/run-controller.ts index 57ee928ed5..bf92f73684 100644 --- a/lib/controllers/run-controller.ts +++ b/lib/controllers/run-controller.ts @@ -150,6 +150,7 @@ export class RunController extends EventEmitter implements IRunController { ); this.attachDeviceLostHandler(); + this.attachTunnelLostHandler(); } public async stop(data: IStopRunData): Promise { @@ -648,6 +649,73 @@ export class RunController extends EventEmitter implements IRunController { ); } + @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, diff --git a/lib/definitions/livesync.d.ts b/lib/definitions/livesync.d.ts index 8502442bca..def8886a2b 100644 --- a/lib/definitions/livesync.d.ts +++ b/lib/definitions/livesync.d.ts @@ -311,6 +311,15 @@ declare global { device: Mobile.IDevice, liveSyncInfo: ILiveSyncWatchInfo, ): Promise; + /** + * Writes the device's current `dev-server.json` into the app already on + * it, outside a full sync. The app reads it when it next starts. + */ + syncDevServerFile?( + device: Mobile.IDevice, + projectData: IProjectData, + liveSyncDeviceData: ILiveSyncDeviceDescriptor, + ): Promise; } interface IRestartApplicationInfo { diff --git a/lib/services/ios/ios-device-tunnel-service.ts b/lib/services/ios/ios-device-tunnel-service.ts index 6b1980527c..7b1ff23b8e 100644 --- a/lib/services/ios/ios-device-tunnel-service.ts +++ b/lib/services/ios/ios-device-tunnel-service.ts @@ -38,6 +38,7 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { private tunnels: IDictionary = {}; private hostAddresses: IDictionary = {}; + private tunnelLostListeners: ((deviceIdentifier: string) => void)[] = []; private tunnelReadyTimeoutMs = 10000; private tunnelPollIntervalMs = 500; private listTimeoutMs = 10000; @@ -63,6 +64,10 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { return this.hostAddresses[deviceIdentifier]; } + public onTunnelLost(listener: (deviceIdentifier: string) => void): void { + this.tunnelLostListeners.push(listener); + } + public async close(deviceIdentifier: string): Promise { const tunnel = this.tunnels[deviceIdentifier]; if (!tunnel) { @@ -206,8 +211,11 @@ export class IOSDeviceTunnelServiceImpl implements IOSDeviceTunnelService { delete this.hostAddresses[deviceIdentifier]; } this.logger.warn( - `The USB tunnel to ${deviceIdentifier} closed, so the app can no longer reach the Vite dev server at ${address}. Restart the run to reconnect.`, + `The USB tunnel to ${deviceIdentifier} closed, so the app can no longer reach the Vite dev server at ${address}.`, ); + for (const listener of this.tunnelLostListeners) { + listener(deviceIdentifier); + } }); }); if (holder.pid) { diff --git a/lib/services/livesync/ios-livesync-service.ts b/lib/services/livesync/ios-livesync-service.ts index 9660068d5b..f64cb2fc12 100644 --- a/lib/services/livesync/ios-livesync-service.ts +++ b/lib/services/livesync/ios-livesync-service.ts @@ -6,6 +6,7 @@ import { APP_FOLDER_NAME, DEV_SERVER_FILE_NAME } from "../../constants"; import { LiveSyncPaths } from "../../common/constants"; import { performanceLog } from "../../common/decorators"; import { IPlatformsDataService } from "../../definitions/platform"; +import { IProjectData } from "../../definitions/project"; import { IFileSystem, IProjectFilesManager, @@ -270,6 +271,22 @@ export class IOSLiveSyncService } } + public async syncDevServerFile( + device: Mobile.IDevice, + projectData: IProjectData, + liveSyncDeviceData: ILiveSyncDeviceDescriptor, + ): Promise { + await this.writeDevServerFile( + await this.getAppData({ + projectData, + device, + liveSyncDeviceData, + watch: true, + useHotModuleReload: true, + }), + ); + } + /** * Writes the device's `dev-server.json` next to `bundle.mjs` in the * installed app (a simulator) or the synced one (a device). diff --git a/test/controllers/run-controller.ts b/test/controllers/run-controller.ts index 4313a1a1f9..f77c7b9f40 100644 --- a/test/controllers/run-controller.ts +++ b/test/controllers/run-controller.ts @@ -151,6 +151,7 @@ function createTestInjector() { open: async (): Promise => null, getHostAddress: (): string => undefined, close: async () => ({}), + onTunnelLost: (): void => undefined, }, }); injector.register({ @@ -335,6 +336,9 @@ describe("RunController", () => { let filesAtFullSync: IDictionary = null; let devServerFilePlatforms: string[]; let reverseWorks: boolean; + let tunnelLost: (deviceIdentifier: string) => Promise; + let rewritten: { device: string; file: string }[]; + let restarted: string[]; let syncFailures: string[]; @@ -397,6 +401,15 @@ describe("RunController", () => { return tunnelAddresses[id]; }; tunnelService.getHostAddress = (id: string) => tunnelAddresses[id]; + tunnelLost = null; + tunnelService.onTunnelLost = (listener: any) => { + tunnelLost = listener; + }; + rewritten = []; + restarted = []; + injector.resolve("devicesService").getDeviceByIdentifier = ( + identifier: string, + ) => map[identifier]?.device; tunnelService.close = async (identifier: string) => { closed.push(identifier); }; @@ -437,9 +450,28 @@ describe("RunController", () => { }; }; liveSyncService.shouldRestart = async () => true; - liveSyncService.restartApplication = async (): Promise => - undefined; + liveSyncService.restartApplication = async ( + _projectData: any, + result: ILiveSyncResultInfo, + ) => { + restarted.push(result.deviceAppData.device.deviceInfo.identifier); + }; + liveSyncService.getAppData = async (syncInfo: IFullSyncInfo) => ({ + appIdentifier, + device: syncInfo.device, + platform: syncInfo.device.deviceInfo.platform, + }); } + injector.resolve("iOSLiveSyncService").syncDevServerFile = async ( + device: Mobile.IDevice, + ) => { + rewritten.push({ + device: device.deviceInfo.identifier, + file: devServerOriginService.getDevServerFile( + device.deviceInfo.identifier, + ), + }); + }; }); afterEach(() => { @@ -573,6 +605,48 @@ describe("RunController", () => { assert.deepStrictEqual(filesAtFullSync, { myiOSDevice: null }); }); + it("rewrites the file of a device whose tunnel drops and restarts only its app", async () => { + await run([iOSDevice, secondIOSDevice]); + restarted = []; + const before = injector + .get(DevServerOriginService) + .getOrigin("mySecondiOSDevice"); + + delete tunnelAddresses.myiOSDevice; + await tunnelLost("myiOSDevice"); + + assert.lengthOf(rewritten, 1); + assert.equal(rewritten[0].device, "myiOSDevice"); + assert.notInclude(JSON.parse(rewritten[0].file).origin, "fd00::1"); + assert.deepStrictEqual(restarted, ["myiOSDevice"]); + assert.equal( + injector.get(DevServerOriginService).getOrigin("mySecondiOSDevice"), + before, + ); + }); + + it("leaves a device alone when its origin does not change", async () => { + process.env.NS_HMR_HOST = "dev.example.test"; + await run([iOSDevice]); + restarted = []; + + await tunnelLost("myiOSDevice"); + + assert.deepStrictEqual(rewritten, []); + assert.deepStrictEqual(restarted, []); + }); + + it("ignores a tunnel loss for a device on the bundle-baked origin", async () => { + devServerFilePlatforms = []; + await run([iOSDevice]); + restarted = []; + + await tunnelLost("myiOSDevice"); + + assert.deepStrictEqual(rewritten, []); + assert.deepStrictEqual(restarted, []); + }); + it("forgets the origin and closes the tunnel of a device that stops", async () => { await run([iOSDevice]); diff --git a/test/services/ios/ios-device-tunnel-service.ts b/test/services/ios/ios-device-tunnel-service.ts index bb0bb3b0dd..10cc853d7d 100644 --- a/test/services/ios/ios-device-tunnel-service.ts +++ b/test/services/ios/ios-device-tunnel-service.ts @@ -326,6 +326,20 @@ describe("IOSDeviceTunnelService", () => { assert.include(warnings[0], "fd6f:72e:8d34::2"); }); + it("tells listeners about a tunnel that closed on its own, not about a closed one", async () => { + const lost: string[] = []; + service.onTunnelLost((id) => lost.push(id)); + devicectlListings = [[coreDevice(wiredConnected)]]; + await service.open(iPhone()); + await service.close(UDID); + await service.open(iPhone()); + + spawned[1].holder.emit("exit", 1, null); + await new Promise((resolve) => setImmediate(resolve)); + + assert.deepEqual(lost, [UDID]); + }); + it("forgets a tunnel that closed on its own, so the next open holds a new one", async () => { devicectlListings = [[coreDevice(wiredConnected)]]; await service.open(iPhone()); From f0d33492ed40702dbcf52c4cf107d8d878680a45 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 4 Dec 2026 02:34:38 -0300 Subject: [PATCH 14/16] docs(vite): say which origin hand-off each @nativescript/vite gets The comments on the dev server spawn, the shared child environment, the port service and the Android pre-build reverse described the `NS_ADB_*` hand-off and the bundle-baked origin as the only way. They apply only to a package without `nativescriptCli.devServerFile`. --- lib/contracts/vite-hmr-port-service.ts | 5 ++--- lib/controllers/run-controller.ts | 3 +++ .../bundler/bundler-compiler-service.ts | 19 ++++++++++--------- 3 files changed, 15 insertions(+), 12 deletions(-) diff --git a/lib/contracts/vite-hmr-port-service.ts b/lib/contracts/vite-hmr-port-service.ts index 8cab600139..ccf1a6c0a3 100644 --- a/lib/contracts/vite-hmr-port-service.ts +++ b/lib/contracts/vite-hmr-port-service.ts @@ -9,9 +9,8 @@ export abstract class ViteHmrPortService { * Resolves the port the Vite dev server for `platform` listens on: the * first free port at or above `NS_HMR_PORT` (default 5173) that no other * platform in this process holds. Resolved once per platform and stable - * for the life of the process, so the build watcher (which bakes the port - * into `bundle.mjs`), the dev server and the Android `adb reverse` tunnel - * all agree on it. + * for the life of the process, so the dev server, the origin each device + * is given and the Android `adb reverse` tunnel all agree on it. * * With `NS_HMR_STRICT_PORT` set, a busy preferred port fails instead of * moving to the next one. diff --git a/lib/controllers/run-controller.ts b/lib/controllers/run-controller.ts index bf92f73684..eccea1a9f1 100644 --- a/lib/controllers/run-controller.ts +++ b/lib/controllers/run-controller.ts @@ -981,6 +981,9 @@ export class RunController extends EventEmitter implements IRunController { * 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 diff --git a/lib/services/bundler/bundler-compiler-service.ts b/lib/services/bundler/bundler-compiler-service.ts index 693dfa3012..1c9b79440e 100644 --- a/lib/services/bundler/bundler-compiler-service.ts +++ b/lib/services/bundler/bundler-compiler-service.ts @@ -860,10 +860,11 @@ export class BundlerCompilerService * Environment both Vite children (the build watcher and the dev server) * must share for a platform: the staging directory, and — for HMR * sessions — the dev-server port. The port is resolved here, once, and - * handed to `@nativescript/vite` as `NS_HMR_PORT`, so the URLs baked into - * `bundle.mjs`, the server's bind and the `adb reverse` tunnel all match. - * When the devices read their origin from `dev-server.json`, the server - * also gets the token the CLI writes into that file. + * handed to `@nativescript/vite` as `NS_HMR_PORT`, so the server's bind, + * the device origins and the `adb reverse` tunnel all match. When the + * devices read their origin from `dev-server.json`, the server also gets + * the token the CLI writes into that file; otherwise the package bakes + * the origin into `bundle.mjs`. */ private async getViteChildEnv( platform: string, @@ -894,11 +895,11 @@ export class BundlerCompilerService * baked into the app. Historically users wired this up themselves with * `concurrently`/`wait-on`, which left two uncoordinated processes both * touching adb during cold start (the source of the Android - * "Searching for devices…" freeze). By spawning it here as a child of - * the CLI, the dev server inherits the CLI's environment — crucially - * `NS_ADB_REVERSE_READY`/`NS_DEVICE_SERIAL`/`NS_ADB_PATH` set by the - * run-controller — so the CLI is the single adb owner and the dev - * server never spawns adb itself. + * "Searching for devices…" freeze). The CLI is the single adb owner. A + * `@nativescript/vite` that reads `dev-server.json` knows no device + * origin and never runs adb; an older one inherits the + * `NS_ADB_REVERSE_READY`/`NS_DEVICE_SERIAL`/`NS_ADB_PATH` the + * run-controller sets, so it doesn't spawn adb either. * * No-op unless bundler is vite, HMR is on, watch mode, and not release. * Best-effort: failures are logged, never thrown — a dev-server hiccup From 97d003c4ea3d8a5ae8740654d0cc4c838ed5d5bb Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 4 Dec 2026 02:34:52 -0300 Subject: [PATCH 15/16] feat(vite): give every device the LAN origin when NS_HMR_PREFER_LAN_HOST is set In `@nativescript/vite`, `NS_HMR_PREFER_LAN_HOST` meant "use this Mac's LAN address", ahead of adb reverse and the platform defaults. With the origin chosen per device by the CLI, it keeps that meaning: no adb reverse and no USB tunnel are set up, and every device gets the LAN address unless `NS_HMR_HOST` is set. Without a LAN address the usual routes apply. `NS_HMR_NO_ADB_REVERSE` on its own only skips the reverse, so an emulator still gets 10.0.2.2 and a physical device the LAN address. --- lib/controllers/run-controller.ts | 12 +++-- .../bundler/dev-server-origin-service.ts | 7 +++ test/controllers/run-controller.ts | 43 +++++++++++++++ .../bundler/dev-server-origin-service.ts | 53 +++++++++++++++++++ 4 files changed, 110 insertions(+), 5 deletions(-) diff --git a/lib/controllers/run-controller.ts b/lib/controllers/run-controller.ts index eccea1a9f1..21abbf3a48 100644 --- a/lib/controllers/run-controller.ts +++ b/lib/controllers/run-controller.ts @@ -939,13 +939,11 @@ export class RunController extends EventEmitter implements IRunController { */ 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) && - !isTruthyEnvFlag(process.env.NS_HMR_PREFER_LAN_HOST) - ) { + if (!isTruthyEnvFlag(process.env.NS_HMR_NO_ADB_REVERSE) && !preferLan) { port = await this.$viteHmrPortService.getPort(platform); try { adbReverse = await this.ensureAndroidReverse( @@ -959,7 +957,11 @@ export class RunController extends EventEmitter implements IRunController { ); } } - } else if (!device.isEmulator && !process.env.NS_HMR_HOST?.trim()) { + } else if ( + !device.isEmulator && + !preferLan && + !process.env.NS_HMR_HOST?.trim() + ) { await this.iOSDeviceTunnelService.open(device); } diff --git a/lib/services/bundler/dev-server-origin-service.ts b/lib/services/bundler/dev-server-origin-service.ts index 94a43db7ad..2d7e1939bf 100644 --- a/lib/services/bundler/dev-server-origin-service.ts +++ b/lib/services/bundler/dev-server-origin-service.ts @@ -2,6 +2,7 @@ import * as crypto from "crypto"; import * as net from "net"; import * as os from "os"; import { IDictionary } from "../../common/declarations"; +import { isTruthyEnvFlag } from "../../common/helpers"; import { inject } from "../../common/di"; import { DevServerOriginService, @@ -20,6 +21,8 @@ export interface IDevServerOriginInputs { https?: boolean; /** `NS_HMR_HOST` as the user set it. */ envHost?: string; + /** `NS_HMR_PREFER_LAN_HOST`: the LAN address wins over every route but `NS_HMR_HOST`. */ + preferLan?: boolean; isAndroid: boolean; isEmulator: boolean; adbReverse?: boolean; @@ -52,6 +55,9 @@ export function isDevServerHttps(env: NodeJS.ProcessEnv): boolean { } function chooseDevServerHost(inputs: IDevServerOriginInputs): string { + if (inputs.preferLan && inputs.lanAddress) { + return inputs.lanAddress; + } if (inputs.isAndroid) { if (inputs.adbReverse) { return LOOPBACK; @@ -162,6 +168,7 @@ export class DevServerOriginServiceImpl implements DevServerOriginService { port: await this.viteHmrPortService.getPort(platform), https: isDevServerHttps(process.env), envHost: process.env.NS_HMR_HOST, + preferLan: isTruthyEnvFlag(process.env.NS_HMR_PREFER_LAN_HOST), isAndroid, isEmulator: device.isEmulator, adbReverse: options.adbReverse, diff --git a/test/controllers/run-controller.ts b/test/controllers/run-controller.ts index f77c7b9f40..f3899a1e60 100644 --- a/test/controllers/run-controller.ts +++ b/test/controllers/run-controller.ts @@ -319,6 +319,12 @@ describe("RunController", () => { buildAction: async () => buildOutputPath, buildData: {}, }; + const androidPhone = { + deviceInfo: { identifier: "R5CT21", platform: "android" }, + isEmulator: false, + adb: androidEmulator.adb, + }; + const lanAddress = "192.168.1.20"; const hmrLiveSyncInfo = { ...liveSyncInfo, useHotModuleReload: true }; const envNames = [ "NS_HMR_HOST", @@ -383,6 +389,10 @@ describe("RunController", () => { device: androidEmulator, descriptor: androidEmulatorDescriptor, }; + map.R5CT21 = { + device: androidPhone, + descriptor: { ...androidEmulatorDescriptor, identifier: "R5CT21" }, + }; const projectDataService = injector.resolve("projectDataService"); const getProjectData = @@ -434,6 +444,9 @@ describe("RunController", () => { injector.resolve("analyticsService").trackEventActionInGoogleAnalytics = async (): Promise => undefined; const devServerOriginService = injector.get(DevServerOriginService); + (devServerOriginService).getNetworkInterfaces = () => ({ + en0: [{ address: lanAddress, family: "IPv4", internal: false }], + }); for (const name of ["iOSLiveSyncService", "androidLiveSyncService"]) { const liveSyncService = injector.resolve(name); liveSyncService.fullSync = async (syncInfo: IFullSyncInfo) => { @@ -478,6 +491,7 @@ describe("RunController", () => { delete map.mySecondiOSDevice; delete map.myiOSSimulator; delete map["emulator-5554"]; + delete map.R5CT21; for (const name of envNames) { if (previousEnv[name] === undefined) { delete process.env[name]; @@ -567,6 +581,35 @@ describe("RunController", () => { ); }); + it("gives a physical Android device without adb reverse the LAN origin", async () => { + process.env.NS_HMR_NO_ADB_REVERSE = "1"; + + await run([androidPhone]); + + assert.deepStrictEqual(adbCalls, []); + assert.equal( + JSON.parse(filesAtFullSync.R5CT21).origin, + `http://${lanAddress}:5173`, + ); + }); + + it("gives every device the LAN origin when the user prefers it", async () => { + process.env.NS_HMR_PREFER_LAN_HOST = "1"; + + await run([androidEmulator, iOSDevice, iOSSimulator]); + + assert.deepStrictEqual(adbCalls, []); + assert.deepStrictEqual(openedFor, []); + assert.deepStrictEqual( + _.mapValues(filesAtFullSync, (file) => JSON.parse(file).origin), + { + "emulator-5554": `http://${lanAddress}:5173`, + myiOSDevice: `http://${lanAddress}:5173`, + myiOSSimulator: `http://${lanAddress}:5173`, + }, + ); + }); + it("skips adb reverse when the user opts out", async () => { process.env.NS_HMR_NO_ADB_REVERSE = "1"; diff --git a/test/services/bundler/dev-server-origin-service.ts b/test/services/bundler/dev-server-origin-service.ts index a743d0c3df..14dff934e1 100644 --- a/test/services/bundler/dev-server-origin-service.ts +++ b/test/services/bundler/dev-server-origin-service.ts @@ -110,6 +110,41 @@ describe("chooseDevServerOrigin", () => { assert.equal(origin({ lanAddress: undefined }), "http://127.0.0.1:5173"); }); + describe("when the user prefers the LAN address", () => { + it("gives it to every device, whatever route it has", () => { + for (const inputs of [ + { isAndroid: true, isEmulator: true, adbReverse: true }, + { isAndroid: true, isEmulator: true }, + { isEmulator: true }, + { tunnelAddress: "fd00::2" }, + ]) { + assert.equal( + origin({ ...inputs, preferLan: true }), + `http://${lan}:5173`, + ); + } + }); + + it("still yields to NS_HMR_HOST", () => { + assert.equal( + origin({ preferLan: true, envHost: "dev.example.test" }), + "http://dev.example.test:5173", + ); + }); + + it("falls back to the usual route without a LAN address", () => { + assert.equal( + origin({ + preferLan: true, + lanAddress: undefined, + isAndroid: true, + isEmulator: true, + }), + "http://10.0.2.2:5173", + ); + }); + }); + it("uses https when the dev server serves it", () => { assert.equal( origin({ https: true, tunnelAddress: "fd00::2" }), @@ -182,6 +217,7 @@ describe("guessLanAddress", () => { describe("DevServerOriginService", () => { const previousHost = process.env.NS_HMR_HOST; const previousHttps = process.env.NS_HTTPS; + const previousPreferLan = process.env.NS_HMR_PREFER_LAN_HOST; let service: DevServerOriginServiceImpl; let tunnelAddresses: Record; let interfaces: object; @@ -200,6 +236,7 @@ describe("DevServerOriginService", () => { beforeEach(() => { delete process.env.NS_HMR_HOST; delete process.env.NS_HTTPS; + delete process.env.NS_HMR_PREFER_LAN_HOST; tunnelAddresses = {}; warnings = []; interfaces = { @@ -247,6 +284,22 @@ describe("DevServerOriginService", () => { } else { process.env.NS_HTTPS = previousHttps; } + if (previousPreferLan === undefined) { + delete process.env.NS_HMR_PREFER_LAN_HOST; + } else { + process.env.NS_HMR_PREFER_LAN_HOST = previousPreferLan; + } + }); + + it("reads NS_HMR_PREFER_LAN_HOST from the environment", async () => { + process.env.NS_HMR_PREFER_LAN_HOST = "1"; + + assert.equal( + await service.chooseOrigin(device("emulator-5554", "Android", true), { + adbReverse: true, + }), + `http://${lan}:5174`, + ); }); it("writes an https origin when NS_HTTPS is set", async () => { From 202b04a9d73507d879ba1e57d570832b9212febb Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 4 Dec 2026 02:34:52 -0300 Subject: [PATCH 16/16] fix(vite): deliver dev-server.json again after a recovery reinstall When an HMR fast sync fails, the run controller reinstalls the app if it needs to and syncs again. A reinstall drops `dev-server.json` (the simulator gets a new `.app`, and an APK's first launch replaces the Android app directory), so the app could no longer find the dev server. `installOnDeviceIfNeeded` now resolves whether it installed, and on a reinstall a device whose `@nativescript/vite` reads `dev-server.json` gets the platform's after-install sync, which writes the file again. --- lib/controllers/run-controller.ts | 15 +++- lib/definitions/run.d.ts | 3 +- .../device/device-install-app-service.ts | 3 +- test/controllers/run-controller.ts | 84 +++++++++++++++++++ 4 files changed, 99 insertions(+), 6 deletions(-) diff --git a/lib/controllers/run-controller.ts b/lib/controllers/run-controller.ts index 21abbf3a48..afafcbe0c1 100644 --- a/lib/controllers/run-controller.ts +++ b/lib/controllers/run-controller.ts @@ -1337,10 +1337,17 @@ export class RunController extends EventEmitter implements IRunController { } } - await this.$deviceInstallAppService.installOnDeviceIfNeeded( - device, - deviceDescriptor.buildData, - ); + 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(); } diff --git a/lib/definitions/run.d.ts b/lib/definitions/run.d.ts index 7a5af896a2..2c54798dd1 100644 --- a/lib/definitions/run.d.ts +++ b/lib/definitions/run.d.ts @@ -41,11 +41,12 @@ declare global { buildData: IBuildData, packageFile?: string, ): Promise; + /** Resolves whether it installed the app. */ installOnDeviceIfNeeded( device: Mobile.IDevice, buildData: IBuildData, packageFile?: string, - ): Promise; + ): Promise; shouldInstall( device: Mobile.IDevice, buildData: IBuildData, diff --git a/lib/services/device/device-install-app-service.ts b/lib/services/device/device-install-app-service.ts index c071d562c0..d21232ca3a 100644 --- a/lib/services/device/device-install-app-service.ts +++ b/lib/services/device/device-install-app-service.ts @@ -97,11 +97,12 @@ export class DeviceInstallAppService implements IDeviceInstallAppService { device: Mobile.IDevice, buildData: IBuildData, packageFile?: string, - ): Promise { + ): Promise { const shouldInstall = await this.shouldInstall(device, buildData); if (shouldInstall) { await this.installOnDevice(device, buildData, packageFile); } + return shouldInstall; } public async shouldInstall( diff --git a/test/controllers/run-controller.ts b/test/controllers/run-controller.ts index f3899a1e60..d5ff0675fc 100644 --- a/test/controllers/run-controller.ts +++ b/test/controllers/run-controller.ts @@ -610,6 +610,90 @@ describe("RunController", () => { ); }); + describe("when a failed fast sync reinstalls the app", () => { + let watchActions: number; + let afterInstall: string[]; + let reinstalls: boolean; + + const syncChange = async (device: any) => { + const projectData = injector + .resolve("projectDataService") + .getProjectData(projectDir); + await (runController).syncChangedDataOnDevices( + { + files: ["/project/platforms/app/bundle.mjs"], + staleFiles: [], + hasOnlyHotUpdateFiles: false, + hasNativeChanges: false, + hmrData: null, + platform: device.deviceInfo.platform, + }, + projectData, + hmrLiveSyncInfo, + ); + }; + + beforeEach(() => { + watchActions = 0; + afterInstall = []; + reinstalls = true; + injector.resolve("deviceInstallAppService").installOnDeviceIfNeeded = + async () => reinstalls; + for (const name of ["iOSLiveSyncService", "androidLiveSyncService"]) { + const liveSyncService = injector.resolve(name); + liveSyncService.liveSyncWatchAction = async ( + device: Mobile.IDevice, + ) => { + if (++watchActions === 1) { + throw new Error("app not running"); + } + return { + modifiedFilesData: [], + isFullSync: false, + useHotModuleReload: true, + deviceAppData: { + appIdentifier, + device, + platform: device.deviceInfo.platform, + }, + }; + }; + liveSyncService.syncAfterInstall = async (device: Mobile.IDevice) => { + afterInstall.push(device.deviceInfo.identifier); + }; + } + }); + + for (const target of [androidEmulator, iOSSimulator, iOSDevice]) { + it(`delivers dev-server.json again to ${target.deviceInfo.identifier}`, async () => { + await run([target]); + + await syncChange(target); + + assert.deepStrictEqual(afterInstall, [target.deviceInfo.identifier]); + assert.equal(watchActions, 2); + }); + } + + it("delivers nothing when nothing was reinstalled", async () => { + reinstalls = false; + await run([iOSSimulator]); + + await syncChange(iOSSimulator); + + assert.deepStrictEqual(afterInstall, []); + }); + + it("delivers nothing for a @nativescript/vite without dev-server.json", async () => { + devServerFilePlatforms = []; + await run([iOSSimulator]); + + await syncChange(iOSSimulator); + + assert.deepStrictEqual(afterInstall, []); + }); + }); + it("skips adb reverse when the user opts out", async () => { process.env.NS_HMR_NO_ADB_REVERSE = "1";