Repository navigation
feat(ios): run iOS apps on an Apple silicon Mac with --device mac
#6205
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
NathanWalker
wants to merge
2
commits into
main
Choose a base branch
from
feat/ios-designed-for-ipad
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
291 changes: 291 additions & 0 deletions
291
lib/common/mobile/ios/mac/ios-mac-application-manager.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"); | ||
|
|
||
| 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 }); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.