import Foundation import XUtils import Subprocess public struct Packer: Sendable { public let buildSettings: BuildSettings public let plan: Plan public init(buildSettings: BuildSettings, plan: Plan) { self.plan = plan self.buildSettings = buildSettings } private func build() async throws { let xtoolDir = URL(fileURLWithPath: "xtool") let packageDir = xtoolDir.appendingPathComponent(".xtool-tmp") try? FileManager.default.removeItem(at: packageDir) try FileManager.default.createDirectory(at: packageDir, withIntermediateDirectories: true) if URL(fileURLWithPath: "Packages").dirExists { try FileManager.default.createSymbolicLink( atPath: packageDir.appendingPathComponent("Packages").path, withDestinationPath: "../../Packages" ) } let packageSwift = packageDir.appendingPathComponent("Package.swift") let contents = """ // swift-tools-version: 6.0 import PackageDescription let package = Package( name: "\(plan.app.product)-Builder", platforms: [ .iOS("\(plan.app.deploymentTarget)"), ], dependencies: [ .package(name: "RootPackage", path: "../.."), ], targets: [ \( plan.allProducts.map { """ .executableTarget( name: "\($0.targetName)", dependencies: [ .product(name: "\($0.product)", package: "RootPackage"), ], linkerSettings: \($0.linkerSettings) ) """ } .joined(separator: ",\n") ) ] )\n """ try Data(contents.utf8).write(to: packageSwift) for product in plan.allProducts { let sources: URL = packageDir.appendingPathComponent("Sources/\(product.targetName)", isDirectory: true) try FileManager.default.createDirectory(at: sources, withIntermediateDirectories: true) try Data().write(to: sources.appendingPathComponent("stub.c", isDirectory: false)) } let buildConfig = try await buildSettings .withPackagePath(packageDir.path) .swiftPMInvocation( forTool: "build", arguments: [ "--scratch-path", ".build", // resolving can cause SwiftPM to overwrite the root package deps // with just the deps needed for the builder package (which is to // say, any "dev dependencies" of the root package may be removed.) // fortunately we've already resolved the root package by this point // in order to dump the plan, so we can skip resolution here to skirt // the issue. "--disable-automatic-resolution", ], ) try await Subprocess.run( buildConfig, output: .currentStandardOutput, error: .currentStandardError, ) .checkSuccess() } public func pack() async throws -> URL { try await build() let output = try TemporaryDirectory(name: "\(plan.app.product).app") let outputURL = output.url let binPath: String switch buildSettings.buildSystem { case .swiftPM: binPath = "\(buildSettings.triple)/\(buildSettings.configuration.rawValue)" case .swiftBuild: let platformName = buildSettings.triple.contains("simulator") ? "iphonesimulator" : "iphoneos" binPath = "out/Products/\(buildSettings.configuration.swiftBuildValue)-\(platformName)" } let binDir = URL( fileURLWithPath: ".build/\(binPath)", isDirectory: true ) try await withThrowingTaskGroup(of: Void.self) { group in for product in plan.allProducts { try pack( product: product, binDir: binDir, outputURL: product.directory(inApp: outputURL), &group ) } while !group.isEmpty { do { try await group.next() } catch is CancellationError { // continue } catch { group.cancelAll() throw error } } } let dest = URL(fileURLWithPath: "xtool").appendingPathComponent(outputURL.lastPathComponent) try? FileManager.default.removeItem(at: dest) try output.persist(at: dest) return dest } @Sendable private func pack( product: Plan.Product, binDir: URL, outputURL: URL, _ group: inout ThrowingTaskGroup ) throws { @Sendable func packFileToRoot(srcName: String) async throws { let srcURL = URL(fileURLWithPath: srcName) let destURL = outputURL.appendingPathComponent(srcURL.lastPathComponent) try FileManager.default.copyItem(at: srcURL, to: destURL) try Task.checkCancellation() } @Sendable func packFile(srcName: String, dstName: String? = nil, sign: Bool = false) async throws { let srcURL = URL(fileURLWithPath: srcName, relativeTo: binDir) let dstURL = URL(fileURLWithPath: dstName ?? srcURL.lastPathComponent, relativeTo: outputURL) try? FileManager.default.createDirectory(at: dstURL.deletingLastPathComponent(), withIntermediateDirectories: true) try FileManager.default.copyItem(at: srcURL, to: dstURL) try Task.checkCancellation() } // Ensure output directory is available try? FileManager.default.createDirectory(at: outputURL, withIntermediateDirectories: true) for command in product.resources { group.addTask { switch command { case .bundle(let package, let target): try await packFile(srcName: "\(package)_\(target).bundle") case .binaryTarget(let name): let src = URL(fileURLWithPath: "\(name).framework/\(name)", relativeTo: binDir) let magic = Data("!\n".utf8) let thinMagic = Data("!\n".utf8) guard let bytes = try? FileHandle(forReadingFrom: src).read(upToCount: magic.count) else { // if we can't find the binary, it might be a static framework that SwiftPM // did not copy into the .build directory. we don't need to pack it anyway. break } // if the magic matches one of these it's a static archive; don't embed it. // https://github.com/apple/llvm-project/blob/e716ff14c46490d2da6b240806c04e2beef01f40/llvm/include/llvm/Object/Archive.h#L33 // swiftlint:disable:previous line_length if bytes != magic && bytes != thinMagic { try await packFile(srcName: "\(name).framework", dstName: "Frameworks/\(name).framework", sign: true) } case .library(let name): try await packFile(srcName: "lib\(name).dylib", dstName: "Frameworks/lib\(name).dylib", sign: true) case .root(let source): try await packFileToRoot(srcName: source) } } } if let iconPath = product.iconPath { group.addTask { try await packFileToRoot(srcName: iconPath) } } if let compiledAssetDir = product.compiledAssetDir { group.addTask { try await Packer.copyCompiledAssets(from: URL(fileURLWithPath: compiledAssetDir), to: outputURL) } } group.addTask { try await packFile(srcName: product.targetName, dstName: product.product) } group.addTask { var info = product.infoPlist if product.type == .application { info["UIRequiredDeviceCapabilities"] = ["arm64"] info["LSRequiresIPhoneOS"] = true info["CFBundleSupportedPlatforms"] = Packer.cfBundleSupportedPlatforms(for: buildSettings.triple) // App Store upload validation requires the DT* keys Xcode // stamps (missing DTPlatformName is error 90507, and an // unrecognized SDK is 90534). let simulator = buildSettings.triple.contains("simulator") info["DTPlatformName"] = simulator ? "iphonesimulator" : "iphoneos" if let sdk = Packer.darwinSDKInfo() { info["DTPlatformVersion"] = sdk.version info["DTSDKName"] = "\(simulator ? "iphonesimulator" : "iphoneos")\(sdk.version)" // DTSDKBuild must be the SDK's ProductBuildVersion // (e.g. 24A94232), not the marketing version — App Store // rejects unknown values (BUILD_SDK_NOT_ALLOWED). info["DTSDKBuild"] = sdk.sdkBuild ?? sdk.xcodeBuild ?? sdk.version info["DTPlatformBuild"] = sdk.sdkBuild ?? sdk.xcodeBuild ?? sdk.version if let xcode = sdk.xcode { info["DTXcode"] = xcode } if let xcodeBuild = sdk.xcodeBuild { info["DTXcodeBuild"] = xcodeBuild } } info["DTCompiler"] = "com.apple.compilers.llvm.clang.1_0" } if let iconPath = product.iconPath { let iconName = URL(fileURLWithPath: iconPath).deletingPathExtension().lastPathComponent info["CFBundleIconFile"] = iconName } if let compiledAssetDir = product.compiledAssetDir { let partialURL = URL(fileURLWithPath: compiledAssetDir) .appendingPathComponent("assets-partial-Info.plist") if FileManager.default.fileExists(atPath: partialURL.path) { let data = try Data(contentsOf: partialURL) let partial = try PropertyListSerialization.propertyList(from: data, format: nil) guard let partial = partial as? [String: any Sendable] else { throw StringError("assets-partial-Info.plist has invalid format: expected a dictionary.") } info.merge(partial, uniquingKeysWith: { $1 }) } } let infoPath = outputURL.appendingPathComponent("Info.plist") let encodedPlist = try PropertyListSerialization.data( fromPropertyList: info, format: .xml, options: 0 ) try encodedPlist.write(to: infoPath) } } public struct DarwinSDKInfo: Sendable { public var version: String public var sdkBuild: String? public var xcode: String? public var xcodeBuild: String? } /// Version/build of the installed iPhoneOS SDK (version from its /// directory name, e.g. `iPhoneOS27.1.sdk`; build from the sibling /// Xcode.app when present), used for the `DT*` Info.plist keys and the /// SDK-versioned build triple. public static func darwinSDKInfo() -> DarwinSDKInfo? { guard let sdk = try? DarwinSDK.current() else { return nil } let sdksDir = sdk.bundle .appendingPathComponent("Developer/Platforms/iPhoneOS.platform/Developer/SDKs") guard let names = try? FileManager.default.contentsOfDirectory(atPath: sdksDir.path) else { return nil } var version: String? for name in names.sorted() { // iPhoneOS27.1.sdk (skip the iPhoneOS.sdk alias) guard name.hasPrefix("iPhoneOS"), name.hasSuffix(".sdk") else { continue } let candidate = name.dropFirst("iPhoneOS".count).dropLast(".sdk".count) guard !candidate.isEmpty, candidate.first?.isNumber == true else { continue } version = String(candidate) break } guard let version else { return nil } var sdkBuild: String? let sdkVersionPlist = sdksDir .appendingPathComponent("iPhoneOS\(version).sdk/System/Library/CoreServices/SystemVersion.plist") if let data = try? Data(contentsOf: sdkVersionPlist), let plist = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any] { sdkBuild = plist["ProductBuildVersion"] as? String } var xcode: String? var xcodeBuild: String? let xcodeInfo = sdk.bundle.appendingPathComponent("Xcode.app/Contents/Info.plist") if let data = try? Data(contentsOf: xcodeInfo), let plist = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any] { xcode = plist["DTXcode"] as? String xcodeBuild = plist["DTXcodeBuild"] as? String } // The build number Xcode stamps into apps (DTXcodeBuild) is the // version.plist ProductBuildVersion (e.g. 27A9275); the Info.plist // DTXcodeBuild in the SDK bundle lags it by one and is rejected by // App Store Connect as an unknown Xcode build. let xcodeVersion = sdk.bundle.appendingPathComponent("Xcode.app/Contents/version.plist") if let data = try? Data(contentsOf: xcodeVersion), let plist = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any], let productBuild = plist["ProductBuildVersion"] as? String { xcodeBuild = productBuild } return DarwinSDKInfo(version: version, sdkBuild: sdkBuild, xcode: xcode, xcodeBuild: xcodeBuild) } /// Files in a compiled asset directory that belong in the `.app`: /// everything except `*.sha256` sidecars and the partial Info.plist /// (the latter is merged into `Info.plist`, not copied). static func compiledAssetFileNames(in dir: URL) throws -> [String] { guard FileManager.default.fileExists(atPath: dir.path) else { throw StringError("assetCatalog.compiledDir not found: '\(dir.path)'") } return try FileManager.default.contentsOfDirectory(atPath: dir.path) .filter { !$0.hasSuffix(".sha256") && $0 != "assets-partial-Info.plist" } .sorted() } static func copyCompiledAssets(from dir: URL, to outputURL: URL) async throws { for name in try compiledAssetFileNames(in: dir) { let src = dir.appendingPathComponent(name) var isDir: ObjCBool = false guard FileManager.default.fileExists(atPath: src.path, isDirectory: &isDir) else { continue } let dest = outputURL.appendingPathComponent(name) if isDir.boolValue { try FileManager.default.copyItem(at: src, to: dest) } else { try FileManager.default.copyItem(at: src, to: dest) } try Task.checkCancellation() } } static func cfBundleSupportedPlatforms(for triple: String) -> [String] { let components = triple.split(separator: "-").map(String.init) guard let appleIndex = components.firstIndex(of: "apple"), components.indices.contains(appleIndex + 1) else { return ["iPhoneOS"] } let os = components[appleIndex + 1].prefix { !$0.isNumber } switch os { case "ios" where components.contains("simulator"): return ["iPhoneSimulator"] case "ios": return ["iPhoneOS"] case "macos", "macosx": return ["MacOSX"] default: return ["iPhoneOS"] } } } extension Plan.Product { fileprivate var linkerSettings: String { switch self.type { case .application: """ [ .unsafeFlags([ "-Xlinker", "-rpath", "-Xlinker", "@executable_path/Frameworks", // Decouple LC_BUILD_VERSION's minos from its sdk: the build // triple carries the SDK version (so App Store sees a current // SDK, error 90725), while this pins the deployment target. "-Xlinker", "-platform_version", "-Xlinker", "ios", "-Xlinker", "\(deploymentTarget)", "-Xlinker", "\(Packer.darwinSDKInfo()?.version ?? deploymentTarget)", ]), ] """ case .appExtension: """ [ // Link to Foundation framework which implements the _NSExtensionMain entrypoint .linkedFramework("Foundation"), .unsafeFlags([ // Set the entry point to Foundation`_NSExtensionMain "-Xlinker", "-e", "-Xlinker", "_NSExtensionMain", // Include frameworks that the host app may use "-Xlinker", "-rpath", "-Xlinker", "@executable_path/../../Frameworks", // ...as well as our own "-Xlinker", "-rpath", "-Xlinker", "@executable_path/Frameworks", ]), ] """ } } }