Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/common/bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,10 @@ injector.require(
"iOSSimulatorDiscovery",
"./mobile/mobile-core/ios-simulator-discovery",
);
injector.require(
"iOSMacDeviceDiscovery",
"./mobile/mobile-core/ios-mac-device-discovery",
);
injector.require(
"androidDeviceDiscovery",
"./mobile/mobile-core/android-device-discovery",
Expand Down
4 changes: 4 additions & 0 deletions lib/common/definitions/mobile.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1212,6 +1212,10 @@ declare global {
shouldReturnImmediateResult: boolean;
platform: string;
fullDiscovery?: boolean;
/**
* The device requested by index, identifier or name, if any.
*/
deviceId?: string;
/**
* Ends the wait for physical devices once the device requested on the
* command line has been found by any discovery.
Expand Down
291 changes: 291 additions & 0 deletions lib/common/mobile/ios/mac/ios-mac-application-manager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,291 @@
import * as crypto from "crypto";
import * as path from "path";
import { ApplicationManagerBase } from "../../application-manager-base";
import { hook, sleep } from "../../../helpers";
import { cache } from "../../../decorators";
import { IOS_LOG_PREDICATE } from "../../../constants";
import {
IChildProcess,
IDictionary,
IFileSystem,
IHooksService,
IPlistParser,
} from "../../../declarations";
import { IOptions } from "../../../../declarations";
import { ITempService } from "../../../../definitions/temp-service";

const LSREGISTER_PATH =
"/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister";

interface IIOSMacApplicationHost extends Mobile.IiOSDevice {
readonly wrapperPath: string;
readonly applicationBundlePath: string;
readonly executableName: string;
}

export class IOSMacApplicationManager extends ApplicationManagerBase {
constructor(
private device: IIOSMacApplicationHost,
private $childProcess: IChildProcess,
private $fs: IFileSystem,
private $options: IOptions,
private $plistParser: IPlistParser,
private $tempService: ITempService,
protected $deviceLogProvider: Mobile.IDeviceLogProvider,
$logger: ILogger,
$hooksService: IHooksService,
) {
super($logger, $hooksService, $deviceLogProvider);
}

public async getInstalledApplications(): Promise<string[]> {
const infoPlistPath = path.join(
this.device.applicationBundlePath,
"Info.plist",
);
if (!this.$fs.exists(infoPlistPath)) {
return [];
}

const infoPlist = await this.$plistParser.parseFile(infoPlistPath);
return infoPlist?.CFBundleIdentifier ? [infoPlist.CFBundleIdentifier] : [];
}

@hook("install")
public async installApplication(packageFilePath: string): Promise<void> {
const wrapperPath = this.device.wrapperPath;
this.$fs.deleteDirectory(wrapperPath);
this.$fs.ensureDirectoryExists(path.join(wrapperPath, "Wrapper"));
// ditto keeps the bundle's symlinks and extended attributes, which its
// code signature covers.
await this.$childProcess.spawnFromEvent(
"ditto",
[packageFilePath, this.device.applicationBundlePath],
"close",
);
this.$fs.symlink(
path.join("Wrapper", path.basename(this.device.applicationBundlePath)),
path.join(wrapperPath, "WrappedBundle"),
);
}

public async uninstallApplication(appIdentifier: string): Promise<void> {
await this.stopApplication({
appId: appIdentifier,
projectName: null,
projectDir: null,
});
this.$fs.deleteDirectory(this.device.wrapperPath);
}

public async startApplication(
appData: Mobile.IStartApplicationData,
): Promise<void> {
await this.setDeviceLogData(appData);
await this.restoreCodeSignature();
await this.registerWithLaunchServices();

const args = ["-n", this.device.wrapperPath];
if (appData.waitForDebugger) {
args.push("--args", "--nativescript-debug-brk");
}
await this.$childProcess.spawnFromEvent("open", args, "close");
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

const [pid] = await this.getRunningPids(appData.appId);
if (pid) {
this.$deviceLogProvider.setApplicationPidForDevice(
this.device.deviceInfo.identifier,
pid,
);
}
}

public async stopApplication(
appData: Mobile.IApplicationData,
): Promise<void> {
await this.device.destroyDebugSocket(appData.appId);

for (const signal of ["TERM", "KILL"]) {
const pids = await this.getRunningPids(appData.appId);
if (!pids.length) {
return;
}

await this.$childProcess
.spawnFromEvent("kill", [`-${signal}`, ...pids], "close")
.catch((err) => this.$logger.trace(err));

// `open -n` while the old instance is still exiting starts a second copy.
for (let attempt = 0; attempt < 40; attempt++) {
if (!(await this.getRunningPids(appData.appId)).length) {
return;
}
await sleep(50);
}
}
}

public async getDebuggableApps(): Promise<
Mobile.IDeviceApplicationInformation[]
> {
return [];
}

public async getDebuggableAppViews(
appIdentifiers: string[],
): Promise<IDictionary<Mobile.IDebugWebViewInfo[]>> {
return null;
}

/**
* Syncing writes into the signed bundle and breaks its seal, and macOS won't
* launch a bundle whose seal is broken. The signature embedded in the
* executable survives the sync, so its leaf certificate names the identity
* to re-sign with.
*/
private async restoreCodeSignature(): Promise<void> {
const bundlePath = this.device.applicationBundlePath;
const verify = await this.$childProcess.spawnFromEvent(
"codesign",
["--verify", "--strict", bundlePath],
"close",
{},
{ throwError: false },
);
if (verify.exitCode === 0) {
return;
}

try {
const certificatesPrefix = path.join(
await this.$tempService.mkdirSync("ios-mac-codesign"),
"certificate",
);
await this.$childProcess.spawnFromEvent(
"codesign",
["-d", `--extract-certificates=${certificatesPrefix}`, bundlePath],
"close",
);
const leafCertificatePath = `${certificatesPrefix}0`;
if (!this.$fs.exists(leafCertificatePath)) {
this.$logger.warn(
`${bundlePath} has no signing certificate to re-sign it with. Rebuild the app if macOS refuses to launch it.`,
);
return;
}

const identity = crypto
.createHash("sha1")
.update(this.$fs.readFile(leafCertificatePath))
.digest("hex");
await this.$childProcess.spawnFromEvent(
"codesign",
[
"--force",
"--sign",
identity,
"--preserve-metadata=identifier,entitlements,flags,runtime",
bundlePath,
],
"close",
);
} catch (err) {
this.$logger.warn(
`Unable to re-sign ${bundlePath}: ${err.message}. Rebuild the app if macOS refuses to launch it.`,
);
}
}

/**
* macOS only launches an iOS app whose code matches the CDHashes
* LaunchServices recorded for it. Once the bundle changes, the launch can
* race LaunchServices' own re-registration, use the stale record and fail
* with "Launch Constraint Violation", so register it before every launch.
*/
private async registerWithLaunchServices(): Promise<void> {
const result = await this.$childProcess.spawnFromEvent(
LSREGISTER_PATH,
["-f", this.device.wrapperPath],
"close",
{},
{ throwError: false },
);
if (result.exitCode !== 0) {
this.$logger.trace(
`Unable to register ${this.device.wrapperPath} with LaunchServices: ${result.stderr}`,
);
}
}

/**
* macOS runs the app from a copy of the wrapper under /private/var/folders,
* so match the bundle layout rather than the path the CLI installed to.
* Other iPad apps can share the executable name, so each match's
* Info.plist must also name this app.
*/
private async getRunningPids(appId: string): Promise<string[]> {
const name = this.device.executableName.replace(
/[.*+?^${}()|[\]\\]/g,
"\\$&",
);
const processPattern = `/Wrapper/${name}\\.app/${name}( |$)`;
const result = await this.$childProcess.spawnFromEvent(
"pgrep",
["-lf", processPattern],
"close",
{},
// pgrep exits with 1 when nothing matches.
{ throwError: false },
);

const bundlePattern = new RegExp(
`^(\\d+) (.*/Wrapper/${name}\\.app)/${name}(?: |$)`,
);
const pids: string[] = [];
for (const line of (result.stdout || "").split("\n")) {
const match = bundlePattern.exec(line);
if (match && (await this.isBundleOf(match[2], appId))) {
pids.push(match[1]);
}
}

return pids;
}

private async isBundleOf(
bundlePath: string,
appId: string,
): Promise<boolean> {
try {
const infoPlist = await this.$plistParser.parseFile(
path.join(bundlePath, "Info.plist"),
);
return infoPlist?.CFBundleIdentifier === appId;
} catch (err) {
this.$logger.trace(`Unable to read the Info.plist of ${bundlePath}`, err);
return false;
}
}

private async setDeviceLogData(
appData: Mobile.IApplicationData,
): Promise<void> {
this.$deviceLogProvider.setProjectNameForDevice(
this.device.deviceInfo.identifier,
appData.projectName,
);
this.$deviceLogProvider.setProjectDirForDevice(
this.device.deviceInfo.identifier,
appData.projectDir,
);

if (!this.$options.justlaunch) {
await this.startDeviceLog();
}
}

@cache()
private startDeviceLog(): Promise<void> {
return this.device.openDeviceLogStream({ predicate: IOS_LOG_PREDICATE });
}
}
42 changes: 42 additions & 0 deletions lib/common/mobile/ios/mac/ios-mac-constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import * as semver from "semver";

/**
* `--device mac` selects this Mac; it is also the device's imageIdentifier.
*/
export const IOS_MAC_DEVICE_ALIAS = "mac";

/**
* Mac builds get their own folder under DerivedData's Build/Products. They use
* the iphoneos SDK like phone builds, and .nsbuildinfo only records prepare
* time, so a shared <Config>-iphoneos folder would let switching between a
* phone and the Mac skip the build and install the other target's app.
*/
export const IOS_MAC_BUILD_DIR_NAME = "mac";

export function isIOSMacDevice(device: Mobile.IDevice): boolean {
return device?.deviceInfo?.imageIdentifier === IOS_MAC_DEVICE_ALIAS;
}

/**
* Whether this @nativescript/ios version loads UIKit from /System/iOSSupport
* on a Mac (NativeScript/ios#551). Older runtimes stop at launch with
* "UIApplicationDidFinishLaunchingNotification is not defined".
* Returns true for versions it can't parse, so only a known-bad one warns.
*/
export function iOSRuntimeCanRunOnMac(version: string): boolean {
const next = /^\d+\.\d+\.\d+-next\.(\d{4}-\d{2}-\d{2})-(\d+)$/.exec(
version ?? "",
);
if (next) {
const [, date, runId] = next;
const firstDate = "2026-11-11";
const firstRunId = 43080423883;
return date > firstDate || (date === firstDate && +runId >= firstRunId);
}

if (!semver.valid(version)) {
return true;
}

return semver.gte(version, "9.1.1");
}
Loading
Loading