From f43feb498ae53a29bbd684338126e012efb19689 Mon Sep 17 00:00:00 2001 From: kudit Date: Sat, 25 Jul 2026 22:04:44 -0400 Subject: [PATCH 01/29] Consolidate TestCase execution and preserve diagnostics --- Sources/Core/Test.swift | 407 ++++++++++++++++++++++------------------ 1 file changed, 223 insertions(+), 184 deletions(-) diff --git a/Sources/Core/Test.swift b/Sources/Core/Test.swift index b0973ad..e9b5f46 100644 --- a/Sources/Core/Test.swift +++ b/Sources/Core/Test.swift @@ -1,18 +1,12 @@ -// TODO: Once Swift Testing is available, can re-write all this code into test classes that conform to Swift Testing so that we can also run code in Previews and Test Applications? Use macros to duplicate #expect( functionality syntax? Or can we use somehow in UI still? public typealias TestClosure = @Sendable () async throws -> Void /// A portable snapshot of the source location that initiated an operation. -/// -/// Passing one value is useful when an asynchronous helper needs to retain and forward a caller's -/// location. Existing APIs continue exposing individual source arguments for source compatibility, -/// while new APIs can accept `SourceContext` when carrying the complete location is clearer. -public struct SourceContext: Sendable { +public struct SourceContext: Sendable, CustomStringConvertible { public let file: String public let function: String public let line: Int public let column: Int - /// Captures the call site by default. public init( file: String = #file, function: String = #function, @@ -24,294 +18,347 @@ public struct SourceContext: Sendable { self.line = line self.column = column } + + public var description: String { + "\(file):\(line):\(column) in \(function)" + } } -// This could be anything, not necessary a struct or class, so if we need this, have a list of tests rather than a Testable object -//// don't make this public to avoid compiling test stuff into framework, however, do make public so apps can add in their own tests. -//public protocol Testable { -// // actor isolated since each Test is @MainActor isolated due to being an ObservableObject. -// @available(watchOS 6, *) -// @MainActor static var tests: [Test] { get } -//} +/// An expectation failure that retains the original source location for command-line and external test runners. +public struct TestFailure: Error, Sendable, CustomStringConvertible { + public let message: String + public let source: SourceContext + + public init(_ message: String, source: SourceContext = SourceContext()) { + self.message = message + self.source = source + } + + public var description: String { + "\(message) [\(source)]" + } +} + +#if canImport(Foundation) +extension TestFailure: LocalizedError { + public var errorDescription: String? { description } +} +#endif -// TODO: NEXT: Convert these to Testing expectations so we don't have to write custom error descriptions. Also move to Test static method that is shadowed in the global space. /// Sets an expectation for a reusable Compatibility test. -/// -/// The source location defaults mirror Swift Testing's diagnostics while remaining callable from -/// live applications, previews, older systems, and test runners that do not provide Swift Testing. -public func expect(_ condition: Bool, _ debugString: String? = nil, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) throws { +public func expect( + _ condition: Bool, + _ debugString: String? = nil, + file: String = #file, + function: String = #function, + line: Int = #line, + column: Int = #column +) throws { guard condition else { - // set breakpoint on this line if we want to debug/inspect errors (note that this slows enough to mess with time stamp checks so disable once we know everything is working). + let source = SourceContext(file: file, function: function, line: line, column: column) + let message: String if let debugString { - throw CustomError(debugString) + message = debugString } else { #if canImport(Foundation) let isMainThread = Thread.isMainThread #else let isMainThread = true #endif - let context = Compatibility.settings.debugFormat( - "", - DebugLevel.OFF, + message = Compatibility.settings.debugFormat( + "Expectation failed", + .ERROR, isMainThread, Compatibility.settings.debugEmojiSupported, true, true, - file, function, line, column) - - throw CustomError(context) + file, + function, + line, + column + ) } + debug(message, level: .ERROR, file: file, function: function, line: line, column: column) + throw TestFailure(message, source: source) } } /// Requires two equatable values to be equal and reports both values when they differ. -/// -/// - Parameters: -/// - actual: The value produced by the code under test. -/// - expected: The value the test requires. -/// - message: Optional context appended to the generated actual-versus-expected diagnostic. -public func expectEqual(_ actual: Value, _ expected: Value, _ message: String? = nil, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) throws { - // Build the comparison text here so UI runs receive the same useful values that Swift Testing displays. +public func expectEqual( + _ actual: Value, + _ expected: Value, + _ message: String? = nil, + file: String = #file, + function: String = #function, + line: Int = #line, + column: Int = #column +) throws { let context = message.map { " \($0)" } ?? "" - try expect(actual == expected, "Expected \(String(reflecting: expected)), but received \(String(reflecting: actual)).\(context)", file: file, function: function, line: line, column: column) + try expect( + actual == expected, + "Expected \(String(reflecting: expected)), but received \(String(reflecting: actual)).\(context)", + file: file, + function: function, + line: line, + column: column + ) } /// Requires two equatable values to differ and reports the shared value when they do not. -public func expectNotEqual(_ actual: Value, _ unexpected: Value, _ message: String? = nil, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) throws { - // Include the unexpected value so a failure remains actionable outside a debugger. +public func expectNotEqual( + _ actual: Value, + _ unexpected: Value, + _ message: String? = nil, + file: String = #file, + function: String = #function, + line: Int = #line, + column: Int = #column +) throws { let context = message.map { " \($0)" } ?? "" - try expect(actual != unexpected, "Expected a value other than \(String(reflecting: unexpected)), but received it.\(context)", file: file, function: function, line: line, column: column) + try expect( + actual != unexpected, + "Expected a value other than \(String(reflecting: unexpected)), but received it.\(context)", + file: file, + function: function, + line: line, + column: column + ) } -// NOTE: Really wish there was a way of writing a possibly async function or doing this using a generic so we don't have to duplicate code. -// TODO: Find a way to prevent conflicts here when run simultaneously. This really should only be used for testing. -/// Suppress debug messages during this execution block. Allows fetching the debug string as normal. +/// Suppresses debug messages during a synchronous execution block and always restores the prior logger. public func debugSuppress(_ block: () throws -> Void) rethrows { let log = Compatibility.settings.debugLog - #if canImport(Foundation) - let suppressThread = Thread.current // restrict the silencing to this thread/closure assuming no background tasks are doing printing - #endif +#if canImport(Foundation) + let suppressThread = Thread.current +#endif Compatibility.settings.debugLog = { message in - #if canImport(Foundation) - if Thread.current != suppressThread { - log(message) // do normal logging - } - #else +#if canImport(Foundation) + if Thread.current != suppressThread { log(message) } +#else log(message) - #endif - } - defer { - Compatibility.settings.debugLog = log +#endif } + defer { Compatibility.settings.debugLog = log } try block() } -/// Suppress debug messages during this async execution block. Allows fetching the debug string as normal. -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) // due to Concurrency -//@MainActor + +/// Suppresses debug messages during an asynchronous execution block and always restores the prior logger. +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func debugSuppress(_ block: () async throws -> Void) async rethrows { let log = Compatibility.settings.debugLog - // unable to get thread in async functions so just ignore and hope it doesn't run concurrently interrupting other debug messages. Compatibility.settings.debugLog = { _ in } - defer { - Compatibility.settings.debugLog = log - } + defer { Compatibility.settings.debugLog = log } try await block() } -// Testing is only supported with Swift 5.9+ #if compiler(>=5.9) -// Test Handlers + +/// Controls whether a reusable test may overlap other reusable tests. +public enum TestExecutionMode: Sendable { + case parallel + case serialized +} + +private actor TestExecutionGate { + static let shared = TestExecutionGate() + private var isRunning = false + private var waiters: [CheckedContinuation] = [] + + func acquire() async { + if !isRunning { + isRunning = true + return + } + await withCheckedContinuation { waiters.append($0) } + } + + func release() { + if waiters.isEmpty { + isRunning = false + } else { + waiters.removeFirst().resume() + } + } +} + +private struct TestExecution: Sendable { + let title: String + let setUp: TestClosure? + let test: TestClosure + let tearDown: TestClosure? + let mode: TestExecutionMode + + func perform() async throws { + if mode == .serialized { + await TestExecutionGate.shared.acquire() + } + + do { + try await performLifecycle() + if mode == .serialized { + await TestExecutionGate.shared.release() + } + } catch { + if mode == .serialized { + await TestExecutionGate.shared.release() + } + throw error + } + } + + private func performLifecycle() async throws { + let previousSettings = Compatibility.settings + defer { Compatibility.settings = previousSettings } + + var primaryError: (any Error)? + do { + try await setUp?() + try await test() + } catch { + primaryError = error + } + + do { + try await tearDown?() + } catch { + if let primaryError { + debug("\(title) teardown also failed: \(error)", level: .ERROR) + throw primaryError + } + throw error + } + + if let primaryError { + throw primaryError + } + } +} + @MainActor @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) -/// A reusable named test that can run in Compatibility's live UI or an external test framework. -/// -/// `TestCase` intentionally borrows XCTest's familiar terminology, but it is not an -/// `XCTestCase` subclass or a drop-in replacement. Each value describes one closure-based test, -/// while optional setup and teardown closures provide lightweight lifecycle hooks. public final class TestCase: ObservableObject, @unchecked Sendable { private final class WeakReference: @unchecked Sendable { weak var value: T? - - init(_ value: T?) { - self.value = value - } + init(_ value: T?) { self.value = value } } public enum TestProgress: Sendable { case notStarted case running case pass - case fail(String) // for error message + case fail(String) + public var symbol: String { switch self { - case .notStarted: - return "❇️" - case .running: - return "🔄" - case .pass: - return "✅" - case .fail: - return "⛔" + case .notStarted: "❇️" + case .running: "🔄" + case .pass: "✅" + case .fail: "⛔" } } + public var errorMessage: String? { - if case let .fail(string) = self { - return string - } - return nil + if case let .fail(message) = self { message } else { nil } } } + public let title: String public let setUp: TestClosure? public var test: TestClosure public let tearDown: TestClosure? - /// Source-compatible name for the test closure. - /// - /// `test` reads more naturally beside `setUp` and `tearDown`, while `task` remains available - /// because it was public before `TestCase` adopted lifecycle terminology. + public let executionMode: TestExecutionMode + @available(*, deprecated, renamed: "test") public var task: TestClosure { get { test } set { test = newValue } } + @Published public var progress: TestProgress = .notStarted - - /// Creates a reusable test with optional lifecycle closures. - /// - /// Teardown is attempted even when setup or the test throws, matching the cleanup expectation - /// familiar from XCTest without claiming `XCTestCase` API or inheritance compatibility. + public init( _ title: String, + executionMode: TestExecutionMode = .parallel, setUp: TestClosure? = nil, test: @escaping TestClosure, tearDown: TestClosure? = nil ) { self.title = title + self.executionMode = executionMode self.setUp = setUp self.test = test self.tearDown = tearDown } - /// Creates a reusable test without separate setup or teardown work. - public convenience init(_ title: String, _ test: @escaping TestClosure) { - self.init(title, test: test) + public convenience init( + _ title: String, + executionMode: TestExecutionMode = .parallel, + _ test: @escaping TestClosure + ) { + self.init(title, executionMode: executionMode, test: test) + } + + private var execution: TestExecution { + TestExecution(title: title, setUp: setUp, test: test, tearDown: tearDown, mode: executionMode) } - /// Executes the test closure directly for an external test framework. - /// - /// Swift Testing and XCTest adapters should prefer this awaited path because thrown expectation - /// failures retain the external runner's native test context without polling observable UI state. public func execute() async throws { - do { - try await setUp?() - try await test() - } catch { - // Cleanup should still run after a failure; preserve the original failure when cleanup succeeds. - do { - try await tearDown?() - } catch { - debug("Test teardown also failed: \(error)", level: .ERROR) - } - throw error - } - try await tearDown?() + try await execution.perform() } - - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) + public func run() { - if case .running = progress { - return - } - let setUp = self.setUp - let test = self.test - let tearDown = self.tearDown + guard progress != .running else { return } + let execution = execution let weakSelf = WeakReference(self) progress = .running - // Run on the detached executor, then publish the result back on the main actor. WebAssembly's - // cooperative executor preserves the same actor semantics even when its host is single threaded. - Task.detached(priority: .userInitiated) { [setUp, test, tearDown, weakSelf] in + + Task.detached(priority: .userInitiated) { do { - do { - try await setUp?() - try await test() - } catch { - // Mirror execute() cleanup while keeping this detached UI path independent of self. - do { - try await tearDown?() - } catch { - debug("Test teardown also failed: \(error)", level: .ERROR) - } - throw error - } - try await tearDown?() - await MainActor.run { - weakSelf.value?.progress = .pass - } + try await execution.perform() + await MainActor.run { weakSelf.value?.progress = .pass } } catch { - await MainActor.run { - debug(error.localizedDescription, level: .ERROR) - weakSelf.value?.progress = .fail("\(error.localizedDescription)") - } + let message = String(describing: error) + debug("\(execution.title) failed: \(message)", level: .ERROR) + await MainActor.run { weakSelf.value?.progress = .fail(message) } } } } - + public func isFinished() -> Bool { switch progress { - case .pass, .fail: - return true - default: - return false + case .pass, .fail: true + default: false } } public func succeeded() -> Bool { - switch progress { - case .pass: - return true - default: - return false - } + if case .pass = progress { true } else { false } } - public var errorMessage: String? { - progress.errorMessage - } - + public var errorMessage: String? { progress.errorMessage } + public var description: String { - var errorString = "" - if let errorMessage = progress.errorMessage { - errorString = "\n\t\(errorMessage)" - } - return "\(progress): \(title)\(errorString)" + let error = progress.errorMessage.map { "\n\t\($0)" } ?? "" + return "\(progress): \(title)\(error)" } } -/// The original test type name retained for source compatibility with Compatibility 1.16. -/// -/// Use ``TestCase`` in new code to avoid colliding with Swift Testing's `Test` type. @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) @available(*, deprecated, renamed: "TestCase") public typealias Test = TestCase @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public extension TestCase { - static func dummyAsyncThrows() async throws { - } + static func dummyAsyncThrows() async throws {} } @available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) public extension TestCase { - /// Every reusable Compatibility test, grouped in deterministic display and execution order. - /// - /// This is the package's canonical test catalog. The in-app UI and Swift Testing bridge both - /// consume this property so a test is authored once and remains runnable in either environment. @MainActor static let namedTests: OrderedDictionary = { var tests: OrderedDictionary = [ "Expectation Tests": [ TestCase("Equality diagnostics") { - // Exercise the public comparison helpers on their success paths without intentionally failing the shared suite. try expectEqual(["Compatibility", "TestCase"], ["Compatibility", "TestCase"]) try expectNotEqual(Compatibility.version, Version("0.0.0")) }, @@ -329,11 +376,7 @@ public extension TestCase { "Application Tests": Application.tests, ] #if canImport(Foundation) - tests.merge([ - "Coding Tests": codingTests, - ]) { current, _ in current } -#endif -#if canImport(Foundation) + tests.merge(["Coding Tests": codingTests]) { current, _ in current } tests["Bundle Tests"] = Bundle.tests tests["File Manager Tests"] = FileManager.tests tests["Pasteboard Tests"] = Pasteboard.tests @@ -342,7 +385,6 @@ public extension TestCase { tests["Date Tests"] = Date.tests tests["Threading Tests"] = Compatibility.threadingTests #if canImport(Combine) || canImport(FoundationNetworking) - // FoundationNetworking supplies URLSession through libcurl on Linux. tests["Network Tests"] = PostData.tests #endif #endif @@ -352,11 +394,8 @@ public extension TestCase { @available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) public extension Compatibility { - /// Compatibility's global test catalog. @MainActor - static var tests: OrderedDictionary { - TestCase.namedTests - } + static var tests: OrderedDictionary { TestCase.namedTests } } #if canImport(SwiftUI) && canImport(Foundation) From c6c86f1d8d4ff4c8bd2d983fc304ed1391dd0a13 Mon Sep 17 00:00:00 2001 From: kudit Date: Sat, 25 Jul 2026 22:08:12 -0400 Subject: [PATCH 02/29] Add reusable Swift Testing module adapter --- Package.swift | 182 ++++++++---------- .../ModuleTestEntry.swift | 68 +++++++ .../Core/TestExecutionMode+Equatable.swift | 3 + 3 files changed, 147 insertions(+), 106 deletions(-) create mode 100644 Sources/CompatibilityTesting/ModuleTestEntry.swift create mode 100644 Sources/Core/TestExecutionMode+Equatable.swift diff --git a/Package.swift b/Package.swift index de0d7b2..5e7f56c 100644 --- a/Package.swift +++ b/Package.swift @@ -15,56 +15,39 @@ import PackageDescription import AppleProductTypes #endif -// Products define the executables and libraries a package produces, making them visible to other packages. var products = [ - Product.library( - name: "\(packageLibraryName) Library", // has to be named different from the iOSApplication or Swift Playgrounds won't open correctly - targets: [packageLibraryName] - ), + Product.library( + name: "\(packageLibraryName) Library", + targets: [packageLibraryName] + ), ] -// Targets are the basic building blocks of a package, defining a module or a test suite. -// Targets can depend on other targets in this package and products from dependencies. var targets = [ - Target.target( - name: packageLibraryName, - dependencies: [ -// .product(name: "Compatibility Library", package: "compatibility"), // apparently needs to be lowercase. Also note this is "Compatibility Library" not "Compatibility" - ], - path: "Sources" - // If resources need to be included in the module, include here -// ,resources: [ // unfortuantely cannot be conditionally compiled based on Swift version since the tool seems to be run on latest version. -// Resource.process("Resources"), -// ] -// ,swiftSettings: [ -// .enableUpcomingFeature("BareSlashRegexLiterals") -// ] - ), + Target.target( + name: packageLibraryName, + dependencies: [], + path: "Sources", + exclude: ["CompatibilityTesting"] + ), ] var platforms: [SupportedPlatform] = [ - .macOS("10.10"), // SwiftPM's oldest supported macOS declaration; newer APIs remain availability-gated. - .tvOS("11"), // 13 minimum for SwiftUI, 15 minimum for Date.now, 17 minimum for Menu - .watchOS("4"), // 6 minimum for SwiftUI, watchOS 7 typically needed for most UI, 8 for Date.now, however (for #buildAvailability) so really should be watchOS 9+. + .macOS("10.10"), + .tvOS("11"), + .watchOS("4"), ] #if SwiftPlaygrounds || canImport(PlaygroundSupport) -platforms += [ - .iOS("15.2"), // minimum for Swift Playgrounds support (maximum version for test iPhone 7) -] +platforms += [.iOS("15.2")] #else -platforms += [ - .iOS("11"), // 13 minimum for Combine/SwiftUI, 15 minimum for Date.now, (maximum version for test iPhone 7) -] +platforms += [.iOS("11")] #endif #if compiler(>=5.9) && os(visionOS) -platforms += [ - .visionOS("1.0"), // PackageDescription 5.9 supports visionOS, so SPI and visionOS clients can see the platform explicitly. -] +platforms += [.visionOS("1.0")] #endif -#if canImport(AppleProductTypes) // swift package dump-package fails because of this +#if canImport(AppleProductTypes) import AppleProductTypes let executableTargetName = "\(packageLibraryName)TestAppModule" @@ -76,90 +59,77 @@ let appName = "\(packageLibraryName) App" #endif products += [ - .iOSApplication( - name: appName, // needs to match package name to open properly in Swift Playgrounds =5.9) && canImport(Testing) +import Compatibility +import Testing + +/// One reusable Compatibility `TestCase` presented as an individual Swift Testing argument. +public struct ModuleTestEntry: Sendable, Identifiable { + public let moduleIdentifier: String + public let moduleName: String + public let section: String + public let testTitle: String + public let index: Int + + private let testCase: TestCase + + public var id: String { + "\(moduleIdentifier)/\(section)/\(index)" + } + + @MainActor + init(module: Module.Type, section: String, index: Int, testCase: TestCase) { + self.moduleIdentifier = module.moduleIdentifier + self.moduleName = module.moduleName + self.section = section + self.testTitle = testCase.title + self.index = index + self.testCase = testCase + } + + /// Executes the original shared test and propagates its detailed error into Swift Testing and Xcode. + @MainActor + public func execute() async throws { + try await testCase.execute() + } +} + +extension ModuleTestEntry: CustomTestStringConvertible { + public var testDescription: String { + "\(moduleName) › \(section) › \(testTitle)" + } +} + +extension ModuleTestEntry: CustomTestArgumentEncodable { + public func encodeTestArgument(to encoder: some Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(id) + } +} + +public extension ModuleTestEntry { + /// Registers the supplied top-level modules and flattens every module test into a named argument. + @MainActor + static func entries(including modules: Module.Type...) -> [ModuleTestEntry] { + Build.register(modules) + return Build.allModules.flatMap { module in + module.tests.flatMap { section, tests in + tests.enumerated().map { index, testCase in + ModuleTestEntry( + module: module, + section: section, + index: index, + testCase: testCase + ) + } + } + } + } +} +#endif diff --git a/Sources/Core/TestExecutionMode+Equatable.swift b/Sources/Core/TestExecutionMode+Equatable.swift new file mode 100644 index 0000000..d735842 --- /dev/null +++ b/Sources/Core/TestExecutionMode+Equatable.swift @@ -0,0 +1,3 @@ +#if compiler(>=5.9) +extension TestExecutionMode: Equatable {} +#endif From 69e9f64309dfe6641ff203edcf76c919c0f60973 Mon Sep 17 00:00:00 2001 From: kudit Date: Mon, 27 Jul 2026 10:32:30 -0400 Subject: [PATCH 03/29] Fix test execution availability and exclusivity --- Sources/Core/Test.swift | 366 +++++++++++++++++++++++++--------------- 1 file changed, 228 insertions(+), 138 deletions(-) diff --git a/Sources/Core/Test.swift b/Sources/Core/Test.swift index e9b5f46..98e8b83 100644 --- a/Sources/Core/Test.swift +++ b/Sources/Core/Test.swift @@ -1,12 +1,18 @@ +// TODO: Once Swift Testing is available, can re-write all this code into test classes that conform to Swift Testing so that we can also run code in Previews and Test Applications? Use macros to duplicate #expect( functionality syntax? Or can we use somehow in UI still? public typealias TestClosure = @Sendable () async throws -> Void /// A portable snapshot of the source location that initiated an operation. +/// +/// Passing one value is useful when an asynchronous helper needs to retain and forward a caller's +/// location. Existing APIs continue exposing individual source arguments for source compatibility, +/// while new APIs can accept `SourceContext` when carrying the complete location is clearer. public struct SourceContext: Sendable, CustomStringConvertible { public let file: String public let function: String public let line: Int public let column: Int + /// Captures the call site by default. public init( file: String = #file, function: String = #function, @@ -24,7 +30,7 @@ public struct SourceContext: Sendable, CustomStringConvertible { } } -/// An expectation failure that retains the original source location for command-line and external test runners. +/// An expectation failure that retains the original source location. public struct TestFailure: Error, Sendable, CustomStringConvertible { public let message: String public let source: SourceContext @@ -41,273 +47,324 @@ public struct TestFailure: Error, Sendable, CustomStringConvertible { #if canImport(Foundation) extension TestFailure: LocalizedError { - public var errorDescription: String? { description } + public var errorDescription: String? { + description + } } #endif +// This could be anything, not necessary a struct or class, so if we need this, have a list of tests rather than a Testable object +//// don't make this public to avoid compiling test stuff into framework, however, do make public so apps can add in their own tests. +//public protocol Testable { +// // actor isolated since each Test is @MainActor isolated due to being an ObservableObject. +// @available(watchOS 6, *) +// @MainActor static var tests: [Test] { get } +//} + +// TODO: NEXT: Convert these to Testing expectations so we don't have to write custom error descriptions. Also move to Test static method that is shadowed in the global space. /// Sets an expectation for a reusable Compatibility test. -public func expect( - _ condition: Bool, - _ debugString: String? = nil, - file: String = #file, - function: String = #function, - line: Int = #line, - column: Int = #column -) throws { +/// +/// The source location defaults mirror Swift Testing's diagnostics while remaining callable from +/// live applications, previews, older systems, and test runners that do not provide Swift Testing. +public func expect(_ condition: Bool, _ debugString: String? = nil, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) throws { guard condition else { + let message = debugString ?? "Expectation failed" let source = SourceContext(file: file, function: function, line: line, column: column) - let message: String - if let debugString { - message = debugString - } else { -#if canImport(Foundation) - let isMainThread = Thread.isMainThread -#else - let isMainThread = true -#endif - message = Compatibility.settings.debugFormat( - "Expectation failed", - .ERROR, - isMainThread, - Compatibility.settings.debugEmojiSupported, - true, - true, - file, - function, - line, - column - ) - } debug(message, level: .ERROR, file: file, function: function, line: line, column: column) throw TestFailure(message, source: source) } } /// Requires two equatable values to be equal and reports both values when they differ. -public func expectEqual( - _ actual: Value, - _ expected: Value, - _ message: String? = nil, - file: String = #file, - function: String = #function, - line: Int = #line, - column: Int = #column -) throws { +/// +/// - Parameters: +/// - actual: The value produced by the code under test. +/// - expected: The value the test requires. +/// - message: Optional context appended to the generated actual-versus-expected diagnostic. +public func expectEqual(_ actual: Value, _ expected: Value, _ message: String? = nil, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) throws { + // Build the comparison text here so UI runs receive the same useful values that Swift Testing displays. let context = message.map { " \($0)" } ?? "" - try expect( - actual == expected, - "Expected \(String(reflecting: expected)), but received \(String(reflecting: actual)).\(context)", - file: file, - function: function, - line: line, - column: column - ) + try expect(actual == expected, "Expected \(String(reflecting: expected)), but received \(String(reflecting: actual)).\(context)", file: file, function: function, line: line, column: column) } /// Requires two equatable values to differ and reports the shared value when they do not. -public func expectNotEqual( - _ actual: Value, - _ unexpected: Value, - _ message: String? = nil, - file: String = #file, - function: String = #function, - line: Int = #line, - column: Int = #column -) throws { +public func expectNotEqual(_ actual: Value, _ unexpected: Value, _ message: String? = nil, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) throws { + // Include the unexpected value so a failure remains actionable outside a debugger. let context = message.map { " \($0)" } ?? "" - try expect( - actual != unexpected, - "Expected a value other than \(String(reflecting: unexpected)), but received it.\(context)", - file: file, - function: function, - line: line, - column: column - ) + try expect(actual != unexpected, "Expected a value other than \(String(reflecting: unexpected)), but received it.\(context)", file: file, function: function, line: line, column: column) } -/// Suppresses debug messages during a synchronous execution block and always restores the prior logger. +// NOTE: Really wish there was a way of writing a possibly async function or doing this using a generic so we don't have to duplicate code. +// TODO: Find a way to prevent conflicts here when run simultaneously. This really should only be used for testing. +/// Suppress debug messages during this execution block. Allows fetching the debug string as normal. public func debugSuppress(_ block: () throws -> Void) rethrows { let log = Compatibility.settings.debugLog -#if canImport(Foundation) - let suppressThread = Thread.current -#endif + #if canImport(Foundation) + let suppressThread = Thread.current // restrict the silencing to this thread/closure assuming no background tasks are doing printing + #endif Compatibility.settings.debugLog = { message in -#if canImport(Foundation) - if Thread.current != suppressThread { log(message) } -#else + #if canImport(Foundation) + if Thread.current != suppressThread { + log(message) // do normal logging + } + #else log(message) -#endif + #endif + } + defer { + Compatibility.settings.debugLog = log } - defer { Compatibility.settings.debugLog = log } try block() } - -/// Suppresses debug messages during an asynchronous execution block and always restores the prior logger. -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) +/// Suppress debug messages during this async execution block. Allows fetching the debug string as normal. +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) // due to Concurrency +//@MainActor public func debugSuppress(_ block: () async throws -> Void) async rethrows { let log = Compatibility.settings.debugLog + // unable to get thread in async functions so just ignore and hope it doesn't run concurrently interrupting other debug messages. Compatibility.settings.debugLog = { _ in } - defer { Compatibility.settings.debugLog = log } + defer { + Compatibility.settings.debugLog = log + } try await block() } - +// Testing is only supported with Swift 5.9+ #if compiler(>=5.9) /// Controls whether a reusable test may overlap other reusable tests. -public enum TestExecutionMode: Sendable { +public enum TestExecutionMode: Sendable, Equatable { case parallel case serialized } +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) private actor TestExecutionGate { static let shared = TestExecutionGate() - private var isRunning = false - private var waiters: [CheckedContinuation] = [] - func acquire() async { - if !isRunning { - isRunning = true - return + private var activeParallelCount = 0 + private var serializedRunning = false + private var parallelWaiters: [CheckedContinuation] = [] + private var serializedWaiters: [CheckedContinuation] = [] + + func acquire(_ mode: TestExecutionMode) async { + switch mode { + case .parallel: + if !serializedRunning && serializedWaiters.isEmpty { + activeParallelCount += 1 + return + } + await withCheckedContinuation { continuation in + parallelWaiters.append(continuation) + } + + case .serialized: + if !serializedRunning && activeParallelCount == 0 { + serializedRunning = true + return + } + await withCheckedContinuation { continuation in + serializedWaiters.append(continuation) + } + } + } + + func release(_ mode: TestExecutionMode) { + switch mode { + case .parallel: + activeParallelCount -= 1 + if activeParallelCount == 0 { + resumeWaitingTests() + } + + case .serialized: + serializedRunning = false + resumeWaitingTests() } - await withCheckedContinuation { waiters.append($0) } } - func release() { - if waiters.isEmpty { - isRunning = false - } else { - waiters.removeFirst().resume() + private func resumeWaitingTests() { + if !serializedWaiters.isEmpty { + serializedRunning = true + serializedWaiters.removeFirst().resume() + return + } + + let waiters = parallelWaiters + parallelWaiters.removeAll() + activeParallelCount += waiters.count + for waiter in waiters { + waiter.resume() } } } +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) private struct TestExecution: Sendable { let title: String + let source: SourceContext let setUp: TestClosure? let test: TestClosure let tearDown: TestClosure? let mode: TestExecutionMode func perform() async throws { - if mode == .serialized { - await TestExecutionGate.shared.acquire() - } - + await TestExecutionGate.shared.acquire(mode) do { try await performLifecycle() - if mode == .serialized { - await TestExecutionGate.shared.release() - } + await TestExecutionGate.shared.release(mode) } catch { - if mode == .serialized { - await TestExecutionGate.shared.release() - } + await TestExecutionGate.shared.release(mode) throw error } } private func performLifecycle() async throws { - let previousSettings = Compatibility.settings - defer { Compatibility.settings = previousSettings } - var primaryError: (any Error)? + do { try await setUp?() try await test() } catch { - primaryError = error + primaryError = normalized(error) } do { try await tearDown?() } catch { + let teardownError = normalized(error) if let primaryError { - debug("\(title) teardown also failed: \(error)", level: .ERROR) + debug("\(title) teardown also failed: \(teardownError)", level: .ERROR) throw primaryError } - throw error + throw teardownError } if let primaryError { throw primaryError } } + + private func normalized(_ error: any Error) -> any Error { + if error is TestFailure { + return error + } + return TestFailure("\(title) failed: \(error)", source: source) + } } +// Test Handlers @MainActor @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) +/// A reusable named test that can run in Compatibility's live UI or an external test framework. +/// +/// `TestCase` intentionally borrows XCTest's familiar terminology, but it is not an +/// `XCTestCase` subclass or a drop-in replacement. Each value describes one closure-based test, +/// while optional setup and teardown closures provide lightweight lifecycle hooks. public final class TestCase: ObservableObject, @unchecked Sendable { private final class WeakReference: @unchecked Sendable { weak var value: T? - init(_ value: T?) { self.value = value } + + init(_ value: T?) { + self.value = value + } } public enum TestProgress: Sendable { case notStarted case running case pass - case fail(String) - + case fail(String) // for error message public var symbol: String { switch self { - case .notStarted: "❇️" - case .running: "🔄" - case .pass: "✅" - case .fail: "⛔" + case .notStarted: + return "❇️" + case .running: + return "🔄" + case .pass: + return "✅" + case .fail: + return "⛔" } } - public var errorMessage: String? { - if case let .fail(message) = self { message } else { nil } + if case let .fail(string) = self { + return string + } + return nil } } - public let title: String + public let source: SourceContext + public let executionMode: TestExecutionMode public let setUp: TestClosure? public var test: TestClosure public let tearDown: TestClosure? - public let executionMode: TestExecutionMode - + /// Source-compatible name for the test closure. + /// + /// `test` reads more naturally beside `setUp` and `tearDown`, while `task` remains available + /// because it was public before `TestCase` adopted lifecycle terminology. @available(*, deprecated, renamed: "test") public var task: TestClosure { get { test } set { test = newValue } } - @Published public var progress: TestProgress = .notStarted + /// Creates a reusable test with optional lifecycle closures. + /// + /// Teardown is attempted even when setup or the test throws, matching the cleanup expectation + /// familiar from XCTest without claiming `XCTestCase` API or inheritance compatibility. public init( _ title: String, executionMode: TestExecutionMode = .parallel, setUp: TestClosure? = nil, test: @escaping TestClosure, - tearDown: TestClosure? = nil + tearDown: TestClosure? = nil, + source: SourceContext = SourceContext() ) { self.title = title + self.source = source self.executionMode = executionMode self.setUp = setUp self.test = test self.tearDown = tearDown } + /// Creates a reusable test without separate setup or teardown work. public convenience init( _ title: String, executionMode: TestExecutionMode = .parallel, + source: SourceContext = SourceContext(), _ test: @escaping TestClosure ) { - self.init(title, executionMode: executionMode, test: test) + self.init(title, executionMode: executionMode, test: test, source: source) } private var execution: TestExecution { - TestExecution(title: title, setUp: setUp, test: test, tearDown: tearDown, mode: executionMode) + TestExecution( + title: title, + source: source, + setUp: setUp, + test: test, + tearDown: tearDown, + mode: executionMode + ) } + /// Executes the test closure directly for an external test framework. + /// + /// Swift Testing and XCTest adapters should prefer this awaited path because thrown expectation + /// failures retain the external runner's native test context without polling observable UI state. public func execute() async throws { try await execution.perform() } + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func run() { - guard progress != .running else { return } + if case .running = progress { + return + } + let execution = execution let weakSelf = WeakReference(self) progress = .running @@ -315,50 +372,75 @@ public final class TestCase: ObservableObject, @unchecked Sendable { Task.detached(priority: .userInitiated) { do { try await execution.perform() - await MainActor.run { weakSelf.value?.progress = .pass } + await MainActor.run { + weakSelf.value?.progress = .pass + } } catch { let message = String(describing: error) - debug("\(execution.title) failed: \(message)", level: .ERROR) - await MainActor.run { weakSelf.value?.progress = .fail(message) } + debug(message, level: .ERROR) + await MainActor.run { + weakSelf.value?.progress = .fail(message) + } } } } public func isFinished() -> Bool { switch progress { - case .pass, .fail: true - default: false + case .pass, .fail: + return true + default: + return false } } public func succeeded() -> Bool { - if case .pass = progress { true } else { false } + switch progress { + case .pass: + return true + default: + return false + } } - public var errorMessage: String? { progress.errorMessage } + public var errorMessage: String? { + progress.errorMessage + } public var description: String { - let error = progress.errorMessage.map { "\n\t\($0)" } ?? "" - return "\(progress): \(title)\(error)" + var errorString = "" + if let errorMessage = progress.errorMessage { + errorString = "\n\t\(errorMessage)" + } + return "\(progress): \(title)\(errorString)" } } +/// The original test type name retained for source compatibility with Compatibility 1.16. +/// +/// Use ``TestCase`` in new code to avoid colliding with Swift Testing's `Test` type. @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) @available(*, deprecated, renamed: "TestCase") public typealias Test = TestCase @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public extension TestCase { - static func dummyAsyncThrows() async throws {} + static func dummyAsyncThrows() async throws { + } } @available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) public extension TestCase { + /// Every reusable Compatibility test, grouped in deterministic display and execution order. + /// + /// This is the package's canonical test catalog. The in-app UI and Swift Testing bridge both + /// consume this property so a test is authored once and remains runnable in either environment. @MainActor static let namedTests: OrderedDictionary = { var tests: OrderedDictionary = [ "Expectation Tests": [ TestCase("Equality diagnostics") { + // Exercise the public comparison helpers on their success paths without intentionally failing the shared suite. try expectEqual(["Compatibility", "TestCase"], ["Compatibility", "TestCase"]) try expectNotEqual(Compatibility.version, Version("0.0.0")) }, @@ -376,7 +458,11 @@ public extension TestCase { "Application Tests": Application.tests, ] #if canImport(Foundation) - tests.merge(["Coding Tests": codingTests]) { current, _ in current } + tests.merge([ + "Coding Tests": codingTests, + ]) { current, _ in current } +#endif +#if canImport(Foundation) tests["Bundle Tests"] = Bundle.tests tests["File Manager Tests"] = FileManager.tests tests["Pasteboard Tests"] = Pasteboard.tests @@ -385,6 +471,7 @@ public extension TestCase { tests["Date Tests"] = Date.tests tests["Threading Tests"] = Compatibility.threadingTests #if canImport(Combine) || canImport(FoundationNetworking) + // FoundationNetworking supplies URLSession through libcurl on Linux. tests["Network Tests"] = PostData.tests #endif #endif @@ -394,8 +481,11 @@ public extension TestCase { @available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) public extension Compatibility { + /// Compatibility's global test catalog. @MainActor - static var tests: OrderedDictionary { TestCase.namedTests } + static var tests: OrderedDictionary { + TestCase.namedTests + } } #if canImport(SwiftUI) && canImport(Foundation) From a2624140efcef20532113f65deca63191a356f37 Mon Sep 17 00:00:00 2001 From: kudit Date: Mon, 27 Jul 2026 10:33:47 -0400 Subject: [PATCH 04/29] Keep testing product manifest changes focused --- Package.swift | 189 +++++++++++++++++++++++++++++++------------------- 1 file changed, 116 insertions(+), 73 deletions(-) diff --git a/Package.swift b/Package.swift index 5e7f56c..96c3426 100644 --- a/Package.swift +++ b/Package.swift @@ -15,39 +15,57 @@ import PackageDescription import AppleProductTypes #endif +// Products define the executables and libraries a package produces, making them visible to other packages. var products = [ - Product.library( - name: "\(packageLibraryName) Library", - targets: [packageLibraryName] - ), + Product.library( + name: "\(packageLibraryName) Library", // has to be named different from the iOSApplication or Swift Playgrounds won't open correctly + targets: [packageLibraryName] + ), ] +// Targets are the basic building blocks of a package, defining a module or a test suite. +// Targets can depend on other targets in this package and products from dependencies. var targets = [ - Target.target( - name: packageLibraryName, - dependencies: [], - path: "Sources", - exclude: ["CompatibilityTesting"] - ), + Target.target( + name: packageLibraryName, + dependencies: [ +// .product(name: "Compatibility Library", package: "compatibility"), // apparently needs to be lowercase. Also note this is "Compatibility Library" not "Compatibility" + ], + path: "Sources", + exclude: ["CompatibilityTesting"] + // If resources need to be included in the module, include here +// ,resources: [ // unfortuantely cannot be conditionally compiled based on Swift version since the tool seems to be run on latest version. +// Resource.process("Resources"), +// ] +// ,swiftSettings: [ +// .enableUpcomingFeature("BareSlashRegexLiterals") +// ] + ), ] var platforms: [SupportedPlatform] = [ - .macOS("10.10"), - .tvOS("11"), - .watchOS("4"), + .macOS("10.10"), // SwiftPM's oldest supported macOS declaration; newer APIs remain availability-gated. + .tvOS("11"), // 13 minimum for SwiftUI, 15 minimum for Date.now, 17 minimum for Menu + .watchOS("4"), // 6 minimum for SwiftUI, watchOS 7 typically needed for most UI, 8 for Date.now, however (for #buildAvailability) so really should be watchOS 9+. ] #if SwiftPlaygrounds || canImport(PlaygroundSupport) -platforms += [.iOS("15.2")] +platforms += [ + .iOS("15.2"), // minimum for Swift Playgrounds support (maximum version for test iPhone 7) +] #else -platforms += [.iOS("11")] +platforms += [ + .iOS("11"), // 13 minimum for Combine/SwiftUI, 15 minimum for Date.now, (maximum version for test iPhone 7) +] #endif #if compiler(>=5.9) && os(visionOS) -platforms += [.visionOS("1.0")] +platforms += [ + .visionOS("1.0"), // PackageDescription 5.9 supports visionOS, so SPI and visionOS clients can see the platform explicitly. +] #endif -#if canImport(AppleProductTypes) +#if canImport(AppleProductTypes) // swift package dump-package fails because of this import AppleProductTypes let executableTargetName = "\(packageLibraryName)TestAppModule" @@ -59,77 +77,102 @@ let appName = "\(packageLibraryName) App" #endif products += [ - .iOSApplication( - name: appName, - targets: [executableTargetName], - teamIdentifier: "3QPV894C33", - displayVersion: version, - bundleVersion: "1", - appIcon: .asset("AppIcon"), - accentColor: .presetColor(.orange), - supportedDeviceFamilies: [.pad, .phone], - supportedInterfaceOrientations: [ - .portrait, - .landscapeRight, - .landscapeLeft, - .portraitUpsideDown(.when(deviceFamilies: [.pad])), - ], - capabilities: [.outgoingNetworkConnections()], - appCategory: .developerTools - ), + .iOSApplication( + name: appName, // needs to match package name to open properly in Swift Playgrounds Date: Mon, 27 Jul 2026 10:34:02 -0400 Subject: [PATCH 05/29] Fold execution mode conformance into its declaration --- Sources/Core/TestExecutionMode+Equatable.swift | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 Sources/Core/TestExecutionMode+Equatable.swift diff --git a/Sources/Core/TestExecutionMode+Equatable.swift b/Sources/Core/TestExecutionMode+Equatable.swift deleted file mode 100644 index d735842..0000000 --- a/Sources/Core/TestExecutionMode+Equatable.swift +++ /dev/null @@ -1,3 +0,0 @@ -#if compiler(>=5.9) -extension TestExecutionMode: Equatable {} -#endif From 49bff8adb491e2eff054a18149ccaedfa0bca917 Mon Sep 17 00:00:00 2001 From: kudit Date: Mon, 27 Jul 2026 11:26:35 -0400 Subject: [PATCH 06/29] Fix test infrastructure availability Fix test infrastructure availability --- Sources/CompatibilityTesting/ModuleTestEntry.swift | 4 ++++ Sources/Core/Test.swift | 1 + 2 files changed, 5 insertions(+) diff --git a/Sources/CompatibilityTesting/ModuleTestEntry.swift b/Sources/CompatibilityTesting/ModuleTestEntry.swift index 7158451..eaddcb9 100644 --- a/Sources/CompatibilityTesting/ModuleTestEntry.swift +++ b/Sources/CompatibilityTesting/ModuleTestEntry.swift @@ -3,6 +3,7 @@ import Compatibility import Testing /// One reusable Compatibility `TestCase` presented as an individual Swift Testing argument. +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public struct ModuleTestEntry: Sendable, Identifiable { public let moduleIdentifier: String public let moduleName: String @@ -33,12 +34,14 @@ public struct ModuleTestEntry: Sendable, Identifiable { } } +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension ModuleTestEntry: CustomTestStringConvertible { public var testDescription: String { "\(moduleName) › \(section) › \(testTitle)" } } +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension ModuleTestEntry: CustomTestArgumentEncodable { public func encodeTestArgument(to encoder: some Encoder) throws { var container = encoder.singleValueContainer() @@ -46,6 +49,7 @@ extension ModuleTestEntry: CustomTestArgumentEncodable { } } +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public extension ModuleTestEntry { /// Registers the supplied top-level modules and flattens every module test into a named argument. @MainActor diff --git a/Sources/Core/Test.swift b/Sources/Core/Test.swift index 98e8b83..f7f5d18 100644 --- a/Sources/Core/Test.swift +++ b/Sources/Core/Test.swift @@ -128,6 +128,7 @@ public func debugSuppress(_ block: () async throws -> Void) async rethrows { } try await block() } + // Testing is only supported with Swift 5.9+ #if compiler(>=5.9) From 5a8f751d00384b1ddae5efacbbac7b98a7c1eb96 Mon Sep 17 00:00:00 2001 From: kudit Date: Mon, 27 Jul 2026 11:33:34 -0400 Subject: [PATCH 07/29] Add source-based debug formatting conveniences --- Sources/Core/DebugFormatContext.swift | 159 ++++++++++++++++++++++++++ 1 file changed, 159 insertions(+) create mode 100644 Sources/Core/DebugFormatContext.swift diff --git a/Sources/Core/DebugFormatContext.swift b/Sources/Core/DebugFormatContext.swift new file mode 100644 index 0000000..30a9a10 --- /dev/null +++ b/Sources/Core/DebugFormatContext.swift @@ -0,0 +1,159 @@ +/// Named values supplied to a custom debug formatter. +/// +/// Use `Compatibility.settings.debugFormatter` for new code. The existing +/// positional `debugFormat` closure remains source-compatible. +public struct DebugFormatContext: Sendable { + public let message: String + public let level: DebugLevel + public let isMainThread: Bool + public let emojiSupported: Bool + public let includeContext: Bool + public let includeTimestamp: Bool + public let source: SourceContext + + public init( + message: String, + level: DebugLevel, + isMainThread: Bool, + emojiSupported: Bool, + includeContext: Bool, + includeTimestamp: Bool, + source: SourceContext + ) { + self.message = message + self.level = level + self.isMainThread = isMainThread + self.emojiSupported = emojiSupported + self.includeContext = includeContext + self.includeTimestamp = includeTimestamp + self.source = source + } +} + +public typealias DebugFormatter = (DebugFormatContext) -> String + +public extension CompatibilityConfiguration { + /// Preferred labeled alternative to the legacy positional `debugFormat` closure. + /// + /// Assigning either property updates the same underlying formatter, so existing + /// `debugFormat = { message, level, ... }` call sites continue to compile. + var debugFormatter: DebugFormatter { + get { + let legacyFormatter = debugFormat + return { context in + legacyFormatter( + context.message, + context.level, + context.isMainThread, + context.emojiSupported, + context.includeContext, + context.includeTimestamp, + context.source.file, + context.source.function, + context.source.line, + context.source.column + ) + } + } + set { + debugFormat = { + message, + level, + isMainThread, + emojiSupported, + includeContext, + includeTimestamp, + file, + function, + line, + column in + newValue( + DebugFormatContext( + message: message, + level: level, + isMainThread: isMainThread, + emojiSupported: emojiSupported, + includeContext: includeContext, + includeTimestamp: includeTimestamp, + source: SourceContext( + file: file, + function: function, + line: line, + column: column + ) + ) + ) + } + } + } +} + +#if !hasFeature(Embedded) +public extension Compatibility { + /// Logs a message using an already-captured source location. + @discardableResult + static func debug( + _ message: Any, + level: DebugLevel = .defaultLevel, + source: SourceContext + ) -> String { + debug( + message, + level: level, + file: source.file, + function: source.function, + line: source.line, + column: source.column + ) + } +} + +/// Logs a message using an already-captured source location. +@discardableResult +public func debug( + _ message: Any, + level: DebugLevel = .defaultLevel, + source: SourceContext +) -> String { + Compatibility.debug(message, level: level, source: source) +} +#else +public extension Compatibility { + /// Logs a message using an already-captured source location. + @discardableResult + static func debug( + _ message: String, + level: DebugLevel = .defaultLevel, + source: SourceContext + ) -> String { + debug( + message, + isMainThread: true, + level: level, + file: source.file, + function: source.function, + line: source.line, + column: source.column + ) + } +} + +/// Logs a message using an already-captured source location. +@discardableResult +public func debug( + _ message: String, + level: DebugLevel = .defaultLevel, + source: SourceContext +) -> String { + Compatibility.debug(message, level: level, source: source) +} +#endif + +public extension TestFailure { + /// Logs this failure at its original source location and returns it for throwing. + @discardableResult + func debug(level: DebugLevel = .ERROR) -> Self { + Compatibility.debug(message, level: level, source: source) + return self + } +} From ce3fa40fdb5c18770e2cadf8f2f7ebc5f9bc9fe4 Mon Sep 17 00:00:00 2001 From: kudit Date: Mon, 27 Jul 2026 12:28:26 -0400 Subject: [PATCH 08/29] Move debug formatting helpers into Debug.swift --- Sources/Core/DebugFormatContext.swift | 159 -------------------------- 1 file changed, 159 deletions(-) delete mode 100644 Sources/Core/DebugFormatContext.swift diff --git a/Sources/Core/DebugFormatContext.swift b/Sources/Core/DebugFormatContext.swift deleted file mode 100644 index 30a9a10..0000000 --- a/Sources/Core/DebugFormatContext.swift +++ /dev/null @@ -1,159 +0,0 @@ -/// Named values supplied to a custom debug formatter. -/// -/// Use `Compatibility.settings.debugFormatter` for new code. The existing -/// positional `debugFormat` closure remains source-compatible. -public struct DebugFormatContext: Sendable { - public let message: String - public let level: DebugLevel - public let isMainThread: Bool - public let emojiSupported: Bool - public let includeContext: Bool - public let includeTimestamp: Bool - public let source: SourceContext - - public init( - message: String, - level: DebugLevel, - isMainThread: Bool, - emojiSupported: Bool, - includeContext: Bool, - includeTimestamp: Bool, - source: SourceContext - ) { - self.message = message - self.level = level - self.isMainThread = isMainThread - self.emojiSupported = emojiSupported - self.includeContext = includeContext - self.includeTimestamp = includeTimestamp - self.source = source - } -} - -public typealias DebugFormatter = (DebugFormatContext) -> String - -public extension CompatibilityConfiguration { - /// Preferred labeled alternative to the legacy positional `debugFormat` closure. - /// - /// Assigning either property updates the same underlying formatter, so existing - /// `debugFormat = { message, level, ... }` call sites continue to compile. - var debugFormatter: DebugFormatter { - get { - let legacyFormatter = debugFormat - return { context in - legacyFormatter( - context.message, - context.level, - context.isMainThread, - context.emojiSupported, - context.includeContext, - context.includeTimestamp, - context.source.file, - context.source.function, - context.source.line, - context.source.column - ) - } - } - set { - debugFormat = { - message, - level, - isMainThread, - emojiSupported, - includeContext, - includeTimestamp, - file, - function, - line, - column in - newValue( - DebugFormatContext( - message: message, - level: level, - isMainThread: isMainThread, - emojiSupported: emojiSupported, - includeContext: includeContext, - includeTimestamp: includeTimestamp, - source: SourceContext( - file: file, - function: function, - line: line, - column: column - ) - ) - ) - } - } - } -} - -#if !hasFeature(Embedded) -public extension Compatibility { - /// Logs a message using an already-captured source location. - @discardableResult - static func debug( - _ message: Any, - level: DebugLevel = .defaultLevel, - source: SourceContext - ) -> String { - debug( - message, - level: level, - file: source.file, - function: source.function, - line: source.line, - column: source.column - ) - } -} - -/// Logs a message using an already-captured source location. -@discardableResult -public func debug( - _ message: Any, - level: DebugLevel = .defaultLevel, - source: SourceContext -) -> String { - Compatibility.debug(message, level: level, source: source) -} -#else -public extension Compatibility { - /// Logs a message using an already-captured source location. - @discardableResult - static func debug( - _ message: String, - level: DebugLevel = .defaultLevel, - source: SourceContext - ) -> String { - debug( - message, - isMainThread: true, - level: level, - file: source.file, - function: source.function, - line: source.line, - column: source.column - ) - } -} - -/// Logs a message using an already-captured source location. -@discardableResult -public func debug( - _ message: String, - level: DebugLevel = .defaultLevel, - source: SourceContext -) -> String { - Compatibility.debug(message, level: level, source: source) -} -#endif - -public extension TestFailure { - /// Logs this failure at its original source location and returns it for throwing. - @discardableResult - func debug(level: DebugLevel = .ERROR) -> Self { - Compatibility.debug(message, level: level, source: source) - return self - } -} From 60b7b9ead77d12509c1753bfb8816eb7ad54a414 Mon Sep 17 00:00:00 2001 From: kudit Date: Mon, 27 Jul 2026 12:29:46 -0400 Subject: [PATCH 09/29] Consolidate debug message and formatting APIs --- Sources/Core/Debug.swift | 149 +++++++++++++++++++++++++++++++++------ 1 file changed, 128 insertions(+), 21 deletions(-) diff --git a/Sources/Core/Debug.swift b/Sources/Core/Debug.swift index c1ac45d..08f9bad 100644 --- a/Sources/Core/Debug.swift +++ b/Sources/Core/Debug.swift @@ -1,6 +1,43 @@ // Here since all releated to Debug code. +#if hasFeature(Embedded) +public typealias DebugMessage = String +#else +public typealias DebugMessage = Any +#endif + +/// Named values supplied to a custom debug formatter. +public struct DebugFormatContext: Sendable { + public let message: String + public let level: DebugLevel + public let isMainThread: Bool + public let emojiSupported: Bool + public let includeContext: Bool + public let includeTimestamp: Bool + public let source: SourceContext + + public init( + message: String, + level: DebugLevel, + isMainThread: Bool, + emojiSupported: Bool, + includeContext: Bool, + includeTimestamp: Bool, + source: SourceContext + ) { + self.message = message + self.level = level + self.isMainThread = isMainThread + self.emojiSupported = emojiSupported + self.includeContext = includeContext + self.includeTimestamp = includeTimestamp + self.source = source + } +} + +public typealias DebugFormatter = (DebugFormatContext) -> String + public struct CompatibilityConfiguration: PropertyIterable { /// Override to change the which debug levels are output. This level and higher (more important) will be output. public var debugLevelCurrent: DebugLevel = Build.isDebug ? .DEBUG : .WARNING @@ -51,6 +88,58 @@ public struct CompatibilityConfiguration: PropertyIterable { return "\(timestamp)\(message)" } } + + /// Preferred labeled alternative to the legacy positional `debugFormat` closure. + /// Assigning either property updates the same underlying formatter. + public var debugFormatter: DebugFormatter { + get { + let legacyFormatter = debugFormat + return { context in + legacyFormatter( + context.message, + context.level, + context.isMainThread, + context.emojiSupported, + context.includeContext, + context.includeTimestamp, + context.source.file, + context.source.function, + context.source.line, + context.source.column + ) + } + } + set { + debugFormat = { + message, + level, + isMainThread, + emojiSupported, + includeContext, + includeTimestamp, + file, + function, + line, + column in + newValue( + DebugFormatContext( + message: message, + level: level, + isMainThread: isMainThread, + emojiSupported: emojiSupported, + includeContext: includeContext, + includeTimestamp: includeTimestamp, + source: SourceContext( + file: file, + function: function, + line: line, + column: column + ) + ) + ) + } + } + } /// Function to handle how the debug messages are logged. Can change to have the messages logged to a file or a string. Default is to print to the console. public var debugLog = { (message: String) in @@ -114,11 +203,11 @@ public struct CustomError: Error, Sendable { } @discardableResult func debug() -> String { -#if !hasFeature(Embedded) - return Compatibility.debug(description, level: level ?? DebugLevel.defaultLevel, file: file, function: function, line: line, column: column) -#else - return Compatibility.debug(description, isMainThread: true, level: level ?? DebugLevel.defaultLevel, file: file, function: function, line: line, column: column) -#endif + Compatibility.debug( + description, + level: level ?? DebugLevel.defaultLevel, + source: SourceContext(file: file, function: function, line: line, column: column) + ) } } extension CustomError: CustomStringConvertible { @@ -265,19 +354,34 @@ public extension Compatibility { - Parameter line: For bubbling down the #line number from a call site. - Parameter column: For bubbling down the #column number from a call site. (Not used currently but here for completeness). */ -#if !hasFeature(Embedded) @discardableResult - static func debug(_ message: Any, level: DebugLevel = .defaultLevel, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) -> String { + static func debug(_ message: DebugMessage, level: DebugLevel = .defaultLevel, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) -> String { +#if hasFeature(Embedded) + return debug(message, isMainThread: true, level: level, file: file, function: function, line: line, column: column) +#else #if canImport(Foundation) let isMainThread = Thread.isMainThread // capture before we switch to main thread for printing #else let isMainThread = true #endif let message = String(describing: message) // convert to sendable item to avoid any thread issues. - return debug(message, isMainThread: isMainThread, level: level, file: file, function: function, line: line, column: column) - } #endif + } + + /// Logs a message using an already-captured source location. + @discardableResult + static func debug(_ message: DebugMessage, level: DebugLevel = .defaultLevel, source: SourceContext) -> String { + debug( + message, + level: level, + file: source.file, + function: source.function, + line: source.line, + column: source.column + ) + } + /// Put most of the business logic here for compatibility with WASM. isMainThread: is required to differentiate but can be removed in global definition @discardableResult static func debug(_ message: String, isMainThread: Bool, level: DebugLevel = .defaultLevel, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) -> String { @@ -313,18 +417,16 @@ public extension Compatibility { - Parameter line: For bubbling down the #line number from a call site. - Parameter column: For bubbling down the #column number from a call site. (Not used currently but here for completeness). */ -#if !hasFeature(Embedded) @discardableResult -public func debug(_ message: Any, level: DebugLevel = .defaultLevel, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) -> String { - return Compatibility.debug(message, level: level, file: file, function: function, line: line, column: column) +public func debug(_ message: DebugMessage, level: DebugLevel = .defaultLevel, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) -> String { + Compatibility.debug(message, level: level, file: file, function: function, line: line, column: column) } -#else + +/// Logs a message using an already-captured source location. @discardableResult -public func debug(_ message: String, level: DebugLevel = .defaultLevel, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) -> String { - // go directly to alternate version since dynamic casting is unavailable in WASM - return Compatibility.debug(message, isMainThread: true, level: level, file: file, function: function, line: line, column: column) +public func debug(_ message: DebugMessage, level: DebugLevel = .defaultLevel, source: SourceContext) -> String { + Compatibility.debug(message, level: level, source: source) } -#endif // MARK: Debug(error) // This is to provide debugging at calltime when creating errors. @@ -339,11 +441,7 @@ public extension Error { - Parameter column: For bubbling down the #column number from a call site. (Not used currently but here for completeness). */ func debug(level: DebugLevel = .defaultLevel, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) -> Self { -#if !hasFeature(Embedded) Compatibility.debug(self.localizedDescription, level: level, file: file, function: function, line: line, column: column) -#else - Compatibility.debug(self.localizedDescription, isMainThread: true, level: level, file: file, function: function, line: line, column: column) -#endif return self } #if !canImport(Foundation) @@ -353,6 +451,15 @@ public extension Error { #endif } +public extension TestFailure { + /// Logs this failure at its original source location and returns it for throwing. + @discardableResult + func debug(level: DebugLevel = .ERROR) -> Self { + Compatibility.debug(message, level: level, source: source) + return self + } +} + // Testing and main-actor isolation are supported on current full-runtime WASM builds. #if compiler(>=5.9) From 04e75c73a1f24140b3341332044ae3bd4d3ce658 Mon Sep 17 00:00:00 2001 From: kudit Date: Tue, 28 Jul 2026 10:05:07 -0400 Subject: [PATCH 10/29] Simplified code duplication Simplified code duplication and context description. --- Sources/Core/Debug.swift | 27 ++++++++++++--------------- Sources/Core/Test.swift | 2 +- 2 files changed, 13 insertions(+), 16 deletions(-) diff --git a/Sources/Core/Debug.swift b/Sources/Core/Debug.swift index 08f9bad..97f5e8d 100644 --- a/Sources/Core/Debug.swift +++ b/Sources/Core/Debug.swift @@ -1,6 +1,6 @@ +// TODO: Needs a real file header documentation/comment. - -// Here since all releated to Debug code. +// Here since all releated to Debug code to simplify conditional code gates. #if hasFeature(Embedded) public typealias DebugMessage = String #else @@ -328,9 +328,9 @@ public enum DebugLevel: Comparable, CustomStringConvertible, CaseIterable, Senda } /// Generates context string -#if !DEBUG @available(*, deprecated, message: "Use Compatibility.settings.debugFormat with the desired formatting options instead.") public func debugContext(isMainThread: Bool, file: String, function: String, line: Int, column: Int) -> String { + // TODO: Convert this to the debugFormatter callsite for clarity Compatibility.settings.debugFormat( "", .OFF, @@ -340,12 +340,11 @@ public func debugContext(isMainThread: Bool, file: String, function: String, lin Compatibility.settings.debugIncludeTimestamp, file, function, line, column) } -#endif // MARK: - Debug public extension Compatibility { /** - Ku: Debug helper for printing info to screen including file and line info of call site. Also can provide a log level for use in loggers or for globally turning on/off logging. (Modify DebugLevel.currentLevel to set level to output. When launching app, probably can set this to DebugLevel.OFF + Debug helper for printing info to screen including file and line info of call site. Also can provide a log level for use in loggers or for globally turning on/off logging. (Modify DebugLevel.currentLevel to set level to output. When launching app, set this to DebugLevel.OFF for release builds. - Parameter message: The message to report. - Parameter level: The logging level to use. @@ -356,17 +355,15 @@ public extension Compatibility { */ @discardableResult static func debug(_ message: DebugMessage, level: DebugLevel = .defaultLevel, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) -> String { -#if hasFeature(Embedded) - return debug(message, isMainThread: true, level: level, file: file, function: function, line: line, column: column) +#if hasFeature(Embedded) || !canImport(Foundation) + let isMainThread = true #else -#if canImport(Foundation) let isMainThread = Thread.isMainThread // capture before we switch to main thread for printing -#else - let isMainThread = true #endif +#if canImport(Foundation) let message = String(describing: message) // convert to sendable item to avoid any thread issues. - return debug(message, isMainThread: isMainThread, level: level, file: file, function: function, line: line, column: column) #endif + return debug(message, isMainThread: isMainThread, level: level, file: file, function: function, line: line, column: column) } /// Logs a message using an already-captured source location. @@ -408,8 +405,8 @@ public extension Compatibility { } //DebugLevel.currentLevel = .ERROR /** - Ku: Debug helper for printing info to screen including file and line info of call site. Also can provide a log level for use in loggers or for globally turning on/off logging. (Modify DebugLevel.currentLevel to set level to output. When launching app, probably can set this to DebugLevel.OFF - + Debug helper for printing info to screen including file and line info of call site. Also can provide a log level for use in loggers or for globally turning on/off logging. (Modify DebugLevel.currentLevel to set level to output. When launching app, set this to DebugLevel.OFF for release builds. + - Parameter message: The message to report. - Parameter level: The logging level to use. - Parameter file: For bubbling down the #file name from a call site. @@ -419,13 +416,13 @@ public extension Compatibility { */ @discardableResult public func debug(_ message: DebugMessage, level: DebugLevel = .defaultLevel, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) -> String { - Compatibility.debug(message, level: level, file: file, function: function, line: line, column: column) + return Compatibility.debug(message, level: level, file: file, function: function, line: line, column: column) } /// Logs a message using an already-captured source location. @discardableResult public func debug(_ message: DebugMessage, level: DebugLevel = .defaultLevel, source: SourceContext) -> String { - Compatibility.debug(message, level: level, source: source) + return Compatibility.debug(message, level: level, source: source) } // MARK: Debug(error) diff --git a/Sources/Core/Test.swift b/Sources/Core/Test.swift index f7f5d18..aee2ca1 100644 --- a/Sources/Core/Test.swift +++ b/Sources/Core/Test.swift @@ -26,7 +26,7 @@ public struct SourceContext: Sendable, CustomStringConvertible { } public var description: String { - "\(file):\(line):\(column) in \(function)" + "\(file.lastPathComponent):\(line):\(column) in \(function)" } } From 23b6f564aa26b2bb9ededb249041c39f8888c95c Mon Sep 17 00:00:00 2001 From: kudit Date: Tue, 28 Jul 2026 11:53:51 -0400 Subject: [PATCH 11/29] Included expanded support for lastPathComponent --- Sources/Core/Debug.swift | 2 -- Sources/Foundation/String.swift | 9 +++++++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/Sources/Core/Debug.swift b/Sources/Core/Debug.swift index 97f5e8d..91aeaf5 100644 --- a/Sources/Core/Debug.swift +++ b/Sources/Core/Debug.swift @@ -359,8 +359,6 @@ public extension Compatibility { let isMainThread = true #else let isMainThread = Thread.isMainThread // capture before we switch to main thread for printing -#endif -#if canImport(Foundation) let message = String(describing: message) // convert to sendable item to avoid any thread issues. #endif return debug(message, isMainThread: isMainThread, level: level, file: file, function: function, line: line, column: column) diff --git a/Sources/Foundation/String.swift b/Sources/Foundation/String.swift index 028e7af..156296b 100644 --- a/Sources/Foundation/String.swift +++ b/Sources/Foundation/String.swift @@ -534,14 +534,19 @@ public extension String { #endif return URL(string: self) } - +#endif + /// Get last "path" component of a string (basically everything from the last `/` to the end) var lastPathComponent: String { + // ensure lastPathComponent is always available regardless of Foundation support by moving fallback code into the function. + #if canImport(Foundation) let parts = self.components(separatedBy: "/") let last = parts.last ?? self + #else + let last = self.split(whereSeparator: { $0 == "/" || $0 == "\\" }).last.map(String.init) ?? self + #endif return last } -#endif /// `true` if the byte length of the `String` is larger than 100k (the exact threashold may change) var isLarge: Bool { From 60ed6cf17206a798716033f591c39394e61942a9 Mon Sep 17 00:00:00 2001 From: kudit Date: Tue, 28 Jul 2026 15:28:14 -0400 Subject: [PATCH 12/29] Improve lastPathComponent for cross-platform compatibility Refactor lastPathComponent to support Windows-style paths and remove Foundation dependency. --- Sources/Foundation/String.swift | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/Sources/Foundation/String.swift b/Sources/Foundation/String.swift index 156296b..c6bb787 100644 --- a/Sources/Foundation/String.swift +++ b/Sources/Foundation/String.swift @@ -538,13 +538,8 @@ public extension String { /// Get last "path" component of a string (basically everything from the last `/` to the end) var lastPathComponent: String { - // ensure lastPathComponent is always available regardless of Foundation support by moving fallback code into the function. - #if canImport(Foundation) - let parts = self.components(separatedBy: "/") - let last = parts.last ?? self - #else + // enables support on all platforms and handles Windows-style \ paths unlike the previous Foundation-only implementation. let last = self.split(whereSeparator: { $0 == "/" || $0 == "\\" }).last.map(String.init) ?? self - #endif return last } From a55ac765d8c159c40db6468f9971fdefa5f66dd7 Mon Sep 17 00:00:00 2001 From: kudit Date: Tue, 28 Jul 2026 15:31:50 -0400 Subject: [PATCH 13/29] Enhance CONTRIBUTING.md with collaborative coding workflow Added guidelines for collaborative coding workflow to improve interaction with maintainers. --- CONTRIBUTING.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2a74d3d..94c6617 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,6 +10,19 @@ PROMPT for updating Module packages: Review this Swift package for adoption of the Module APIs introduced in github.com/kudit/Compatibility v1.16.0 or later. Inspect the package’s existing architecture and preserve its public behavior and platform compatibility. Add or update its Compatibility dependency if necessary. Apply an appropriate Module conformance, including its version, direct Compatibility dependency, module dependencies, immediately available moduleInfo, ordered TestCase sections, and opt-in open-source repository metadata when applicable. Register the package from its highest-level module or document how an application should register it through Application.track(including:). Add complete inline DocC comments to the relevant public APIs so generated documentation can discover them. Do not create a .docc catalog, separate documentation articles, or another documentation folder. Preserve existing comments unless they are missing, unclear, or inaccurate. Put reusable tests in the module's TestCase collections so they run both in the in-app test UI and through the Swift Testing bridge; retain target-specific tests only where infrastructure requires them. Follow this package’s existing CONTRIBUTING.md, changelog, versioning, formatting, availability, and compatibility conventions. Avoid unrelated reformatting and whitespace-only changes. Before changing version numbers, compare the current changelog version with the latest committed Git version. If the active working-tree changelog is already ahead of Git, do not choose another version; synchronize that active version across every package manifest, Xcode project, public source constant, test fixture or suite heading, README or documentation display, and other hard-coded version surface. Please check that all deprecations (that can) have appropriate renamed clauses for easy fixits. +## Collaborative coding workflow + +When working interactively with a maintainer, generally (this shouldn't be meant to override thread instructions but are here as a default): +- Work in small, reviewable stages rather than delivering a large implementation all at once. +- Present one immediate decision or action at a time and pause for maintainer feedback unless instructed to do a batch. +- Explain design choices briefly and answer questions before continuing implementation. +- Preserve and review the maintainer's local edits before adding further changes. +- Let the maintainer build, edit, commit, and push between stages when practical. +- After each pushed maintainer change, review the latest commit before proposing or applying the next change. +- Keep pull requests in draft until the implementation is compiled, exercised by real tests, and fully reviewed. +- Avoid unrelated cleanup, broad reformatting, and speculative changes that make the diff harder to reason about. + + ## Version and changelog rules - Keep changelog entries in `## vX.X.X YYYY-MM-DD` format, with short line-separated notes under the current version. From cd9661753ba1fdbe9e5f47accfa9d60b7563e593 Mon Sep 17 00:00:00 2001 From: kudit Date: Tue, 28 Jul 2026 15:39:03 -0400 Subject: [PATCH 14/29] Exercise ModuleTestEntry through Swift Testing --- .../ModuleTestEntryTests.swift | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Development/CompatibilityTests/ModuleTestEntryTests.swift diff --git a/Development/CompatibilityTests/ModuleTestEntryTests.swift b/Development/CompatibilityTests/ModuleTestEntryTests.swift new file mode 100644 index 0000000..4d1594b --- /dev/null +++ b/Development/CompatibilityTests/ModuleTestEntryTests.swift @@ -0,0 +1,28 @@ +// +// ModuleTestEntryTests.swift +// CompatibilityTests +// +// Exercises the reusable CompatibilityTesting adapter through Swift Testing. +// + +#if compiler(>=5.9) && canImport(Compatibility) && canImport(CompatibilityTesting) && canImport(Testing) +import Compatibility +import CompatibilityTesting +import Testing + +@Suite("Compatibility Module Test Entries") +struct ModuleTestEntryTests { + /// Presents every reusable Compatibility `TestCase` as its own named Swift Testing argument. + @Test( + "Compatibility Module Test", + arguments: await MainActor.run { + ModuleTestEntry.entries(including: Compatibility.self) + } + ) + @MainActor + @available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) + func moduleTest(entry: ModuleTestEntry) async throws { + try await entry.execute() + } +} +#endif From d6b97cae8498ef15c16a0e02058aba14d3e58bf2 Mon Sep 17 00:00:00 2001 From: kudit Date: Tue, 28 Jul 2026 15:52:43 -0400 Subject: [PATCH 15/29] Update CHANGELOG with testing requirements Added testing requirements and TODOs for release preparation. --- CHANGELOG.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 78aeff7..5607f74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +# TODO: +Testing required before release: + +- Build the package in Xcode with ⌘B. +- Run the full test plan with ⌘U. +- Confirm `Compatibility Module Test Entries` displays each reusable `TestCase` separately. +- Confirm the new entries execute successfully and preserve readable module, section, and test names. +- Remove the older grouped module-test bridge after the new adapter is verified, then rerun the tests. +- Run SwiftPM and supported-platform validation before tagging the release. + +## v1.18.3 2026-07-28 +TODO: Implement a comment matching this pull request changes. + ## v1.18.2 2026-07-23 Fixed Swift Package Index build errors and warnings across SwiftUI and WebAssembly targets. Replaced conditional SwiftUI `Group` wrappers with direct `@ViewBuilder` results and concrete text-selection types. From e03065f75eedf7b710abc673337618ec7b8c4ae7 Mon Sep 17 00:00:00 2001 From: kudit Date: Tue, 28 Jul 2026 20:01:04 -0400 Subject: [PATCH 16/29] Serialize debug tests and restore settings safely --- Sources/Core/Debug.swift | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/Sources/Core/Debug.swift b/Sources/Core/Debug.swift index 91aeaf5..51e0e90 100644 --- a/Sources/Core/Debug.swift +++ b/Sources/Core/Debug.swift @@ -462,9 +462,18 @@ public extension TestFailure { public extension DebugLevel { @MainActor internal static let testDebugConfig: TestClosure = { - // NOTE: This might happen concurrently with other tests so could cause issues with output... - // preserve original settings + // These tests temporarily replace process-global debug settings. Capture the complete + // configuration before making any changes so the surrounding application or test suite + // observes exactly the same settings after this test finishes. let previousSettings = Compatibility.settings + + // `defer` runs whether the test succeeds or throws. This is important because an + // expectation failure exits the closure immediately; a normal assignment at the bottom + // would be skipped and could leave later tests using this temporary logger or formatter. + defer { + Compatibility.settings = previousSettings + } + DebugLevel.defaultLevel = .WARNING // testing override default level DebugLevel.currentLevel = .NOTICE // testing override current level @@ -506,10 +515,9 @@ Normal output: \(defaultOutput) let blankText = debug("TestCase return output", level: .DEBUG) // less than the current level so should be silent try expect(blankText == "", "expected empty string but found \(blankText)") - - // reset settings for other tests - Compatibility.settings = previousSettings - // output messages that happened concurrently + + // `previousSettings` is restored automatically by the `defer` above. + // Output captured while the temporary logger was active remains intentionally suppressed. // Compatibility.settings.debugLog(concurrentOutput) // debug("TEST OUTPUT", level: .ERROR) } @@ -540,8 +548,11 @@ Normal output: \(defaultOutput) @MainActor static let tests = [ - TestCase("debug configuration tests", testDebugConfig), - TestCase("debug tests", testDebug), + // Both tests mutate process-global debug state (`Compatibility.settings` or the + // logger used by `debugSuppress`). Serialized mode prevents them from overlapping + // each other or any parallel reusable test while those temporary changes are active. + TestCase("debug configuration tests", executionMode: .serialized, testDebugConfig), + TestCase("debug tests", executionMode: .serialized, testDebug), ] } #endif From c9bfda2cf55c58d0274ddfbec63efa846b618488 Mon Sep 17 00:00:00 2001 From: kudit Date: Tue, 28 Jul 2026 20:02:28 -0400 Subject: [PATCH 17/29] Remove duplicated grouped module test bridge --- .../CompatibilityTests.swift | 23 +++---------------- 1 file changed, 3 insertions(+), 20 deletions(-) diff --git a/Development/CompatibilityTests/CompatibilityTests.swift b/Development/CompatibilityTests/CompatibilityTests.swift index b991bb8..a15bf8b 100644 --- a/Development/CompatibilityTests/CompatibilityTests.swift +++ b/Development/CompatibilityTests/CompatibilityTests.swift @@ -446,25 +446,8 @@ struct CompatibilityTests { } } - /// Runs every public module section through the same TestCase values used by the live UI. - @Test( - "Compatibility Module Tests", - arguments: await MainActor.run { Compatibility.tests.keys.elements } - ) - @MainActor - @available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) - func moduleTests(section: String) async throws { - // Compatibility.tests is the authoritative package-wide test collection. - let tests = Compatibility.tests[section] ?? [] - try await withThrowingTaskGroup(of: Void.self) { group in - for test in tests { - // Each case is independently isolated by TestCase, so long-running rows can overlap. - group.addTask { - try await test.execute() - } - } - try await group.waitForAll() - } - } + // Reusable module tests now live in ModuleTestEntryTests.swift. That adapter creates one + // Swift Testing argument per TestCase, so keeping the former section-based bridge here would + // execute the same Compatibility tests twice and hide individual test names beneath a section. } #endif From fd1bf225ecd96d9517013fa258f236689438ac64 Mon Sep 17 00:00:00 2001 From: kudit Date: Tue, 28 Jul 2026 20:06:39 -0400 Subject: [PATCH 18/29] Document v1.19.0 test infrastructure changes --- CHANGELOG.md | 38 +++++++++++++++++++++----------------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5607f74..d3d1eab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,11 +7,15 @@ Testing required before release: - Run the full test plan with ⌘U. - Confirm `Compatibility Module Test Entries` displays each reusable `TestCase` separately. - Confirm the new entries execute successfully and preserve readable module, section, and test names. -- Remove the older grouped module-test bridge after the new adapter is verified, then rerun the tests. +- Confirm the serialized debug tests restore `Compatibility.settings` even when an expectation throws. - Run SwiftPM and supported-platform validation before tagging the release. -## v1.18.3 2026-07-28 -TODO: Implement a comment matching this pull request changes. +## v1.19.0 2026-07-28 +Added the reusable `Compatibility Testing Library` product and `ModuleTestEntry` adapter so each module `TestCase` appears as an individually named Swift Testing result. +Unified `TestCase.execute()` and live test execution through one lifecycle implementation with explicit parallel and serialized execution modes. +Added source-aware test failures, labeled debug-format context, and source-context debugging conveniences while preserving existing debug-format call sites. +Made debug tests run exclusively and restore process-global debug settings with `defer`, including when an expectation throws. +Expanded contributor guidance for short, staged, maintainer-reviewed coding workflows. ## v1.18.2 2026-07-23 Fixed Swift Package Index build errors and warnings across SwiftUI and WebAssembly targets. @@ -166,7 +170,7 @@ Fixed documentation warnings (Swift 6.2 on macOS). Fixed typo with last changelog date. Added simpleTitleCase() function that just makes the first letter of each word capitalized. Don't affect other characters (if you want that, you can lowercase() and then titleCase()). ## v1.12.0 2025-10-13 -Refactored build flags into a `Build` struct so that we can use in legacy versions that don't support `ObservableObject` required by `Application` (which also allows us to simplify configurations since these values no longer require Foundation). Added `floor()` function when not available (like in WASM). Added `widgetAccentable()` backport. Added Build.Environment enum to facilitate iteration of build properties. ** Passes all Swift Package Index Checks! ** +Refactored build flags into a `Build` struct so that we can use in legacy versions that don't support `ObservableObject` required by `Application` (which also allows us to simplify configurations since these values no longer require Foundation). Added `floor()` function when not available (like in WASM). Added `widgetAccentable()` backport. ** Passes all Swift Package Index Checks! ** ## v1.11.32 2025-10-08 Old Linux support for Swift 5.10. **Supports all platforms including WASM and Android and passes all Swift Package Index Checks!** @@ -178,7 +182,7 @@ Added stub mock conformance of Version to Codable on WASM. Additional WASM conditional checks. ## v1.11.29 2025-10-06 -Added precision backport for Double in WASM. Added backports for `replacingOccurrences(of:[String])` for WASM. Migrated `CharacterSet` additions and backport to separate file. **Supports all platforms EXCEPT WASM but passes all other Swift Package Index Checks!** +Added precision backport for Double in WASM. Added backports for `replacingOccurrences(of:[String])` for WASM. Migrated CharacterSet additions and backport to separate file. **Supports all platforms EXCEPT WASM but passes all other Swift Package Index Checks!** ## v1.11.28 2025-10-06 Added Codable protocol for WASM so that we don't have to conditionally conform in WASM. **Supports all platforms including WASM and Android and passes all Swift Package Index Checks!** @@ -187,7 +191,7 @@ Added Codable protocol for WASM so that we don't have to conditionally conform i Missed a conditional check around the date requirement of `DateStringRepresentation` since this isn't present in WASM. **Supports all platforms including WASM and Android and passes all Swift Package Index Checks!** ## v1.11.26 2025-10-05 -Added back `DateString` as a type so that we can use in WASM as a type (but without working date features). +Added back `DateString` as a type so that it can be used but until we have a backport, there will not be a way to get this to work on WASM. ## v1.11.25 2025-10-05 Added `CaseNameConvertible` stub for WASM so that it can be used but until we have a backport, there will not be a way to get this to work on WASM. @@ -292,7 +296,7 @@ Fixed issue where [Color] not available on non-Apple platforms. Added missing T Extracted `.rainbow` included for previews to use the Color version when available. Improved RadialLayout preview. Added public initializer for RadialLayout so can be used outside project. Removed warnings running in Swift Playgrounds for Application tests. Note: When building, Swift Playgrounds 4.6.4 currently has a bug where it has trouble choosing the root application target rather than included module app targets which causes issues for #Previews. Removed requirement of Darwin.C when not Linux and can't import Darwin (was the cause of WASM and Android compile failures). Removed odd instances of availability checking for tvOS 20 (which now that we have tvOS 26, that passes). Added Collection conformance to OrderedSet. Added tests to bring test coverage to 47%. (Failed Linux, WASM, Android) ## v1.10.10 2025-06-06 -Added public visibility of Visibility backport. Added `persistentSystemOverlays` backport. Added tests to bring test coverage to 46%. Updated Version string parsing. Added a failable initializer for parsing strings. Updated the implementation of the `string:defaultValue:` initializer. Fixed so version character stripping isn't just trimming. +Added public visibility of Visibility backport. Added `persistentSystemOverlays` backport. Added tests to bring test coverage to 46%. Updated Version string parsing. Added a failable initializer for parsing strings. Updated the implementation of the `string:defaultValue:` initializer. ## v1.10.9 2025-05-14 re-worked compiler directives to fix issues with Linux visibility. @@ -370,7 +374,7 @@ Changed so `normalized` returns a non-optional. This is technically a breaking Fixed since `.focusable` is not available in iOS < 17. Fixed missing package version update in v1.6.7. Found a fix for packages and Swift Playgrounds v4.6+ (the iOSApplication name needs to be DIFFERENT whereas previous versions required it to be the SAME). ## v1.6.7 2025-03-10 -Shifted around `Version.zero` to non-constrained extension to make more sense. Added `resetVersionsRun()` for testing. Fixed internal scoping of String versions run keys just in case we need to use outside the framework. Added `tomorrow` and `tomorrowMidnight` date values. Added test section for output formats. Improved `Backport.LabeledContent` for compatibility with older devices (but now requires iOS 15 to use). Removed pageViewStyle from TabViews on tvOS since it doesn't really work. +Shifted around `Version.zero` to non-constrained extension to make more sense. Works fine under Swift Playgrounds 4.5.1 but not under Swift Playgrounds 4.6.2 (and 4.6?). Added `Version.zero`. ## v1.6.6 2025-02-28 Fixed internal `Version.zero` (doh!). @@ -379,7 +383,7 @@ Fixed internal `Version.zero` (doh!). Cleaned up redundant code for `Date.pretty()`. Works fine under Swift Playgrounds 4.5.1 but not under Swift Playgrounds 4.6.2 (and 4.6?). Added `Version.zero`. ## v1.6.4 2025-01-17 -Added debugging output when replacing the identifier in preview/playground environment to fix issue with Score identifier being com.kudit.Score-. Added check to prevent preview output alerting that iCloud doesn't work from spamming the logs. Added in app name and identifier to compatibility info. Fixed unnecessary check for iOS warning in Backport. +Added debugging output when replacing the identifier in preview/playground environment to fix issue with Score identifier being com.kudit.Score-. Added check to prevent preview output alerting that iCloud doesn't work from spamming the logs. ## v1.6.3 2025-01-15 Added some documentation to `asJSON()` function. Fixed internal definition of Triangle initializer. @@ -388,7 +392,7 @@ Added some documentation to `asJSON()` function. Fixed internal definition of T Fixed double encoding of ampersands in `htmlEncoded` strings due to random access nature of dictionaries. Added test. Added double quote `"` to `"` encoding. ## v1.6.1 2025-01-14 -Fixed build limited availablility issue with watchOS. +Fixed Linux compile error. ## v1.6.0 2025-01-14 Added `pluralEnding()`. Added `.backport.onTapGesture {}`. @@ -403,7 +407,7 @@ Attempted additional fixes to support Swift 5.8. Assumed returns are made expli #Preview isn't the issue, it's literally the @available checks we need to filter out. `swift(` doesn't seem to work so trying replacing them all with `compiler(`. ## v1.5.1 2024-11-26 -Added `#if swift(>=5.9)` checks around `#Preview` macros which aren't supported in Swift 5.8. If this doesn't work, try replacing `#if swift(` with `#if compiler(`. +Added `#if swift(>=5.9)` checks around `#Preview` macros which aren't supported in Swift 5.8. If this doesn't work, try replacing `#if swift(`. ## v1.5.0 2024-11-26 Removed duplicate `delay` code to fix errors with Swift 6. Does mean that some code may not work and will need to be adjusted (if you need `delay { @MainActor in`, simply do `delay { main {` instead). @@ -439,7 +443,7 @@ Added import of Color when available in Radial Layout previews. Added OverlappingStack and RadialLayout. ## v1.4.1 2024-11-04 -Added compiler check for Threading `background` tasks so that warnings are silenced in Swift 6 but still works in Swift Playgrounds. Removed URL comparison since causes warnings in Swift 6 and doesn't seem used most places (and where used, can simply reference the path comparison that it wraps). Fixed issues with watchOS. Fixed compile issues with Linux by removing `iCloudToken` variable. Addressed @retroactive warnings in a way that works with Swift Playgrounds. Added Embossed modifier. +Added compiler check for Threading `background` tasks so that warnings are silenced in Swift 6 but still works in Swift Playgrounds. Removed URL comparison since causes warnings in Swift 6 and doesn't seem used most places (and where used, can simply reference the path comparison that it wraps). Fixed issues with watchOS. Added Embossed modifier. ## v1.4.0 2024-11-04 Fixed some preview issues with legacy deprecated compatibility code. Added `scrollContentBackground` backport. Added `safeAreaPadding` backport. Added `disableSmartQuotes` view modifier. Can simulate @CloudStorage acting like UserDefaults by setting `Application.iCloudSupported = false`. Removed cloud monitoring notifications when using UserDefaults. Added `.precision(significantFigures)` output for Doubles. @@ -514,13 +518,13 @@ Fixed several data race safety issues. Fixed linux support. Standardized Package.swift, CHANGELOG.md, README.md, and LICENSE.txt files. Standardized deployment targets. Added DataStore code and added tests. Added Date.nowBackport for supporting earlier versions. Moved Environmental checks from Device so we can use in more places and needed for testing DataStores in previews. Added `asDictionary()` method for Codable objects similar to `asJSON()`. Standardized ordering and labelling of all `available` checks to iOS, macOS, tvOS, watchOS, visionOS (the order in which each platform got swift language support). Also removed unnecessary `.0` from versions and unnecessary `macCatalyst` checks. Fixed `Version` so that when encoded it stores as a `String` instead of as a struct. Changed `Compatibility` to enum since it isn't really a structure and avoids accidentally instantiating. Updated `ClearableTextField` to only update value when the field looses focus instead of every character (also fixed issue where that was not public). ## v1.2.1 2024-07-27 -Moved fetchURL code into a Compatibility extension so can specifically target. Doh! Debug was printing at the right time I think, they were just set to .SILENT! Fix for data race error. Added additional sendable conformances on enums and made FileManager extension public. Changed documentation for delay to be clear it runs on the same thread and doesn't force to main or background. +Moved fetchURL code into a Compatibility extension so can specifically target. Doh! Debug was printing at the right time I think, they were just set to .SILENT! Fix for data race error. Made `FileManager` extension public. Changed documentation for delay to be clear it runs on the same thread and doesn't force to main or background. ## v1.2.0 2024-07-25 Added additional onChange 2 parameter compatibility version and added ability to specify initial setting (and added documentation to match the new (current) implementations). Moved threading functions into static Compatibility functions so that we can reference in case we're in a class that shadows the same function name (like running background {} from within a view that is trying to create a view). Added returning background { } calls for cases where we need to await the results of the long-running background task. Re-worked debugLevel features of debug statements so we aren't switching threads with the print statement to ensure debug statements output immediately and don't get printed out of order. Added Compatibility.isDebug flag for testing if we've built for release or debug. Added additional Backport code including `scrollClipDisabled()`. Added set additions for OrderedSet and OrderedDictionary and added merging/interoperability between OrderedDictionary and Dictionary. ## v1.1.0 2024-07-19 -Added withoutZeros function to Double. Added .backport.navigationTitle() function for older iOS. Fixed JSON coding issue (since we're using codable, don't need to verify that all the contents are actually JSON supported NSObjects). Added additional version tests. Added injection tests with a count to include expected failure and run count. Fixed so debug breakpoints are accessible from the proper thread instead of being stranded on the main thread. Added Placard shape. Added Triangle shaped. Fixed .backport.background(color) +Added withoutZeros function to Double. Added `.backport.navigationTitle()` function for older iOS. Fixed JSON coding issue (since we're using codable, don't need to verify that all the contents are actually JSON supported NSObjects). Added additional version tests. Added injection tests with a count to include expected failure and run count. Fixed so debug breakpoints are accessible from the proper thread instead of being stranded on the main thread. Added Placard shape. Added Triangle shaped. Fixed `.backport.background(color)`. ## v1.0.18 2024-07-17 Added license usage example. Added ability to pass in additional tests to the AllTestsListView(["Section Name": tests, "Section Name 2": tests2]). Added fix for OperatingSystemVersion in swift Playgrounds (needed to do typalias wrapper trick). Needed to make Linux hack of ObservableObject have public send() function to prevent complaints about internal acccess. Added OrderedDictionary and OrderedSet based on swift-collections code but simplified (originally tried adding swift-collections as a dependency but it doesn't support watchOS 4). @@ -535,7 +539,7 @@ Added public intializer for BytesView. Added check for macOS 12 in Development app. Improved demo app. Added BytesView. Added improved test views. ## v1.0.14 2024-07-12 -Removed unnecessary utf8data extension since Data(String.utf8) works as a non-optional. Added Codable conformance for Version. Updated/enhanced Version tests. Added JSON encoding/decoding simple functions and removed unnecessary similar code. Removed unnecessary Foundation imports. Made changes to get Linux support validation (passes all SwiftPackageIndex tests for all platforms and safe from data races!). +Removed unnecessary utf8data extension since Data(String.utf8) works as a non-optional. Added Codable conformance for Version. Updated/enhanced Version tests. Added JSON encoding/decoding simple functions and removed unnecessary similar code. Made changes to get Linux support validation (passes all SwiftPackageIndex tests for all platforms and safe from data races!). ## v1.0.13 2024-07-11 Undid structure form of HTML and PostData since it won't code/decode properly automatically in KuditFrameworks. Seeing if typealias will work again (it does if we wrap the typealias in a structure). Added an HTML test for attributedString. Removed redundant old attributedStringFromHTML code. @@ -565,13 +569,13 @@ Broke macOS and watchOS with last update. Re-worked TabView Backport to be more Updated Xcode minimum versions to match package. Added Backport .overlay and .foregroundStyle and .background for older tvOS. ## v1.0.4 2024-07-08 -Attempted to fix issues with Linux compatibility (swapped legacyData around so extension of URLRequest instead of URLSession). Added additional #if canImport(Combine) checks. +Attempted to fix issues with Linux compatibility (swapped legacyData around so extension of URLRequest instead of URLSession). Fixed target versions (Xcode project). ## v1.0.3 2024-07-08 Reduced tvOS version requirements to tvOS 13 (though menu and other UI features are not supported). ## v1.0.2 2024-07-08 -Fixed some data race issues and fixed breaking support for watchOS and Linux. Added condition for @Published to ensure compilation on Linux. Made PostData require a Sendable type and added Sendable conformance to NetworkError. Fixed sendability of Message to prevent issues using `debug()`. +Fixed several data race safety issues and fixed breaking support for watchOS and Linux. Added condition for @Published to ensure compilation on Linux. Made PostData require a Sendable type and added Sendable conformance to NetworkError. Fixed sendability of Message to prevent issues using `debug()`. ## v1.0.1 2024-07-07 Fixed missing date in changelog. Moved DebugLevel.defaultLevel in initializers into nil initializers so can make sure to reference static property not in the initializer. Changed default color to orange. Changed several static vars to lets for concurrency safety. Enabled `main {}` to be used with throwing functions. Added `.spi.yml` file for Swift Package Index compiler. From 6f6a24e2bc700577fcf258f230f98eb0d0a60252 Mon Sep 17 00:00:00 2001 From: kudit Date: Tue, 28 Jul 2026 20:08:04 -0400 Subject: [PATCH 19/29] Restore changelog history before focused update --- CHANGELOG.md | 38 +++++++++++++++++--------------------- 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d3d1eab..5607f74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,15 +7,11 @@ Testing required before release: - Run the full test plan with ⌘U. - Confirm `Compatibility Module Test Entries` displays each reusable `TestCase` separately. - Confirm the new entries execute successfully and preserve readable module, section, and test names. -- Confirm the serialized debug tests restore `Compatibility.settings` even when an expectation throws. +- Remove the older grouped module-test bridge after the new adapter is verified, then rerun the tests. - Run SwiftPM and supported-platform validation before tagging the release. -## v1.19.0 2026-07-28 -Added the reusable `Compatibility Testing Library` product and `ModuleTestEntry` adapter so each module `TestCase` appears as an individually named Swift Testing result. -Unified `TestCase.execute()` and live test execution through one lifecycle implementation with explicit parallel and serialized execution modes. -Added source-aware test failures, labeled debug-format context, and source-context debugging conveniences while preserving existing debug-format call sites. -Made debug tests run exclusively and restore process-global debug settings with `defer`, including when an expectation throws. -Expanded contributor guidance for short, staged, maintainer-reviewed coding workflows. +## v1.18.3 2026-07-28 +TODO: Implement a comment matching this pull request changes. ## v1.18.2 2026-07-23 Fixed Swift Package Index build errors and warnings across SwiftUI and WebAssembly targets. @@ -170,7 +166,7 @@ Fixed documentation warnings (Swift 6.2 on macOS). Fixed typo with last changelog date. Added simpleTitleCase() function that just makes the first letter of each word capitalized. Don't affect other characters (if you want that, you can lowercase() and then titleCase()). ## v1.12.0 2025-10-13 -Refactored build flags into a `Build` struct so that we can use in legacy versions that don't support `ObservableObject` required by `Application` (which also allows us to simplify configurations since these values no longer require Foundation). Added `floor()` function when not available (like in WASM). Added `widgetAccentable()` backport. ** Passes all Swift Package Index Checks! ** +Refactored build flags into a `Build` struct so that we can use in legacy versions that don't support `ObservableObject` required by `Application` (which also allows us to simplify configurations since these values no longer require Foundation). Added `floor()` function when not available (like in WASM). Added `widgetAccentable()` backport. Added Build.Environment enum to facilitate iteration of build properties. ** Passes all Swift Package Index Checks! ** ## v1.11.32 2025-10-08 Old Linux support for Swift 5.10. **Supports all platforms including WASM and Android and passes all Swift Package Index Checks!** @@ -182,7 +178,7 @@ Added stub mock conformance of Version to Codable on WASM. Additional WASM conditional checks. ## v1.11.29 2025-10-06 -Added precision backport for Double in WASM. Added backports for `replacingOccurrences(of:[String])` for WASM. Migrated CharacterSet additions and backport to separate file. **Supports all platforms EXCEPT WASM but passes all other Swift Package Index Checks!** +Added precision backport for Double in WASM. Added backports for `replacingOccurrences(of:[String])` for WASM. Migrated `CharacterSet` additions and backport to separate file. **Supports all platforms EXCEPT WASM but passes all other Swift Package Index Checks!** ## v1.11.28 2025-10-06 Added Codable protocol for WASM so that we don't have to conditionally conform in WASM. **Supports all platforms including WASM and Android and passes all Swift Package Index Checks!** @@ -191,7 +187,7 @@ Added Codable protocol for WASM so that we don't have to conditionally conform i Missed a conditional check around the date requirement of `DateStringRepresentation` since this isn't present in WASM. **Supports all platforms including WASM and Android and passes all Swift Package Index Checks!** ## v1.11.26 2025-10-05 -Added back `DateString` as a type so that it can be used but until we have a backport, there will not be a way to get this to work on WASM. +Added back `DateString` as a type so that we can use in WASM as a type (but without working date features). ## v1.11.25 2025-10-05 Added `CaseNameConvertible` stub for WASM so that it can be used but until we have a backport, there will not be a way to get this to work on WASM. @@ -296,7 +292,7 @@ Fixed issue where [Color] not available on non-Apple platforms. Added missing T Extracted `.rainbow` included for previews to use the Color version when available. Improved RadialLayout preview. Added public initializer for RadialLayout so can be used outside project. Removed warnings running in Swift Playgrounds for Application tests. Note: When building, Swift Playgrounds 4.6.4 currently has a bug where it has trouble choosing the root application target rather than included module app targets which causes issues for #Previews. Removed requirement of Darwin.C when not Linux and can't import Darwin (was the cause of WASM and Android compile failures). Removed odd instances of availability checking for tvOS 20 (which now that we have tvOS 26, that passes). Added Collection conformance to OrderedSet. Added tests to bring test coverage to 47%. (Failed Linux, WASM, Android) ## v1.10.10 2025-06-06 -Added public visibility of Visibility backport. Added `persistentSystemOverlays` backport. Added tests to bring test coverage to 46%. Updated Version string parsing. Added a failable initializer for parsing strings. Updated the implementation of the `string:defaultValue:` initializer. +Added public visibility of Visibility backport. Added `persistentSystemOverlays` backport. Added tests to bring test coverage to 46%. Updated Version string parsing. Added a failable initializer for parsing strings. Updated the implementation of the `string:defaultValue:` initializer. Fixed so version character stripping isn't just trimming. ## v1.10.9 2025-05-14 re-worked compiler directives to fix issues with Linux visibility. @@ -374,7 +370,7 @@ Changed so `normalized` returns a non-optional. This is technically a breaking Fixed since `.focusable` is not available in iOS < 17. Fixed missing package version update in v1.6.7. Found a fix for packages and Swift Playgrounds v4.6+ (the iOSApplication name needs to be DIFFERENT whereas previous versions required it to be the SAME). ## v1.6.7 2025-03-10 -Shifted around `Version.zero` to non-constrained extension to make more sense. Works fine under Swift Playgrounds 4.5.1 but not under Swift Playgrounds 4.6.2 (and 4.6?). Added `Version.zero`. +Shifted around `Version.zero` to non-constrained extension to make more sense. Added `resetVersionsRun()` for testing. Fixed internal scoping of String versions run keys just in case we need to use outside the framework. Added `tomorrow` and `tomorrowMidnight` date values. Added test section for output formats. Improved `Backport.LabeledContent` for compatibility with older devices (but now requires iOS 15 to use). Removed pageViewStyle from TabViews on tvOS since it doesn't really work. ## v1.6.6 2025-02-28 Fixed internal `Version.zero` (doh!). @@ -383,7 +379,7 @@ Fixed internal `Version.zero` (doh!). Cleaned up redundant code for `Date.pretty()`. Works fine under Swift Playgrounds 4.5.1 but not under Swift Playgrounds 4.6.2 (and 4.6?). Added `Version.zero`. ## v1.6.4 2025-01-17 -Added debugging output when replacing the identifier in preview/playground environment to fix issue with Score identifier being com.kudit.Score-. Added check to prevent preview output alerting that iCloud doesn't work from spamming the logs. +Added debugging output when replacing the identifier in preview/playground environment to fix issue with Score identifier being com.kudit.Score-. Added check to prevent preview output alerting that iCloud doesn't work from spamming the logs. Added in app name and identifier to compatibility info. Fixed unnecessary check for iOS warning in Backport. ## v1.6.3 2025-01-15 Added some documentation to `asJSON()` function. Fixed internal definition of Triangle initializer. @@ -392,7 +388,7 @@ Added some documentation to `asJSON()` function. Fixed internal definition of T Fixed double encoding of ampersands in `htmlEncoded` strings due to random access nature of dictionaries. Added test. Added double quote `"` to `"` encoding. ## v1.6.1 2025-01-14 -Fixed Linux compile error. +Fixed build limited availablility issue with watchOS. ## v1.6.0 2025-01-14 Added `pluralEnding()`. Added `.backport.onTapGesture {}`. @@ -407,7 +403,7 @@ Attempted additional fixes to support Swift 5.8. Assumed returns are made expli #Preview isn't the issue, it's literally the @available checks we need to filter out. `swift(` doesn't seem to work so trying replacing them all with `compiler(`. ## v1.5.1 2024-11-26 -Added `#if swift(>=5.9)` checks around `#Preview` macros which aren't supported in Swift 5.8. If this doesn't work, try replacing `#if swift(`. +Added `#if swift(>=5.9)` checks around `#Preview` macros which aren't supported in Swift 5.8. If this doesn't work, try replacing `#if swift(` with `#if compiler(`. ## v1.5.0 2024-11-26 Removed duplicate `delay` code to fix errors with Swift 6. Does mean that some code may not work and will need to be adjusted (if you need `delay { @MainActor in`, simply do `delay { main {` instead). @@ -443,7 +439,7 @@ Added import of Color when available in Radial Layout previews. Added OverlappingStack and RadialLayout. ## v1.4.1 2024-11-04 -Added compiler check for Threading `background` tasks so that warnings are silenced in Swift 6 but still works in Swift Playgrounds. Removed URL comparison since causes warnings in Swift 6 and doesn't seem used most places (and where used, can simply reference the path comparison that it wraps). Fixed issues with watchOS. Added Embossed modifier. +Added compiler check for Threading `background` tasks so that warnings are silenced in Swift 6 but still works in Swift Playgrounds. Removed URL comparison since causes warnings in Swift 6 and doesn't seem used most places (and where used, can simply reference the path comparison that it wraps). Fixed issues with watchOS. Fixed compile issues with Linux by removing `iCloudToken` variable. Addressed @retroactive warnings in a way that works with Swift Playgrounds. Added Embossed modifier. ## v1.4.0 2024-11-04 Fixed some preview issues with legacy deprecated compatibility code. Added `scrollContentBackground` backport. Added `safeAreaPadding` backport. Added `disableSmartQuotes` view modifier. Can simulate @CloudStorage acting like UserDefaults by setting `Application.iCloudSupported = false`. Removed cloud monitoring notifications when using UserDefaults. Added `.precision(significantFigures)` output for Doubles. @@ -518,13 +514,13 @@ Fixed several data race safety issues. Fixed linux support. Standardized Package.swift, CHANGELOG.md, README.md, and LICENSE.txt files. Standardized deployment targets. Added DataStore code and added tests. Added Date.nowBackport for supporting earlier versions. Moved Environmental checks from Device so we can use in more places and needed for testing DataStores in previews. Added `asDictionary()` method for Codable objects similar to `asJSON()`. Standardized ordering and labelling of all `available` checks to iOS, macOS, tvOS, watchOS, visionOS (the order in which each platform got swift language support). Also removed unnecessary `.0` from versions and unnecessary `macCatalyst` checks. Fixed `Version` so that when encoded it stores as a `String` instead of as a struct. Changed `Compatibility` to enum since it isn't really a structure and avoids accidentally instantiating. Updated `ClearableTextField` to only update value when the field looses focus instead of every character (also fixed issue where that was not public). ## v1.2.1 2024-07-27 -Moved fetchURL code into a Compatibility extension so can specifically target. Doh! Debug was printing at the right time I think, they were just set to .SILENT! Fix for data race error. Made `FileManager` extension public. Changed documentation for delay to be clear it runs on the same thread and doesn't force to main or background. +Moved fetchURL code into a Compatibility extension so can specifically target. Doh! Debug was printing at the right time I think, they were just set to .SILENT! Fix for data race error. Added additional sendable conformances on enums and made FileManager extension public. Changed documentation for delay to be clear it runs on the same thread and doesn't force to main or background. ## v1.2.0 2024-07-25 Added additional onChange 2 parameter compatibility version and added ability to specify initial setting (and added documentation to match the new (current) implementations). Moved threading functions into static Compatibility functions so that we can reference in case we're in a class that shadows the same function name (like running background {} from within a view that is trying to create a view). Added returning background { } calls for cases where we need to await the results of the long-running background task. Re-worked debugLevel features of debug statements so we aren't switching threads with the print statement to ensure debug statements output immediately and don't get printed out of order. Added Compatibility.isDebug flag for testing if we've built for release or debug. Added additional Backport code including `scrollClipDisabled()`. Added set additions for OrderedSet and OrderedDictionary and added merging/interoperability between OrderedDictionary and Dictionary. ## v1.1.0 2024-07-19 -Added withoutZeros function to Double. Added `.backport.navigationTitle()` function for older iOS. Fixed JSON coding issue (since we're using codable, don't need to verify that all the contents are actually JSON supported NSObjects). Added additional version tests. Added injection tests with a count to include expected failure and run count. Fixed so debug breakpoints are accessible from the proper thread instead of being stranded on the main thread. Added Placard shape. Added Triangle shaped. Fixed `.backport.background(color)`. +Added withoutZeros function to Double. Added .backport.navigationTitle() function for older iOS. Fixed JSON coding issue (since we're using codable, don't need to verify that all the contents are actually JSON supported NSObjects). Added additional version tests. Added injection tests with a count to include expected failure and run count. Fixed so debug breakpoints are accessible from the proper thread instead of being stranded on the main thread. Added Placard shape. Added Triangle shaped. Fixed .backport.background(color) ## v1.0.18 2024-07-17 Added license usage example. Added ability to pass in additional tests to the AllTestsListView(["Section Name": tests, "Section Name 2": tests2]). Added fix for OperatingSystemVersion in swift Playgrounds (needed to do typalias wrapper trick). Needed to make Linux hack of ObservableObject have public send() function to prevent complaints about internal acccess. Added OrderedDictionary and OrderedSet based on swift-collections code but simplified (originally tried adding swift-collections as a dependency but it doesn't support watchOS 4). @@ -539,7 +535,7 @@ Added public intializer for BytesView. Added check for macOS 12 in Development app. Improved demo app. Added BytesView. Added improved test views. ## v1.0.14 2024-07-12 -Removed unnecessary utf8data extension since Data(String.utf8) works as a non-optional. Added Codable conformance for Version. Updated/enhanced Version tests. Added JSON encoding/decoding simple functions and removed unnecessary similar code. Made changes to get Linux support validation (passes all SwiftPackageIndex tests for all platforms and safe from data races!). +Removed unnecessary utf8data extension since Data(String.utf8) works as a non-optional. Added Codable conformance for Version. Updated/enhanced Version tests. Added JSON encoding/decoding simple functions and removed unnecessary similar code. Removed unnecessary Foundation imports. Made changes to get Linux support validation (passes all SwiftPackageIndex tests for all platforms and safe from data races!). ## v1.0.13 2024-07-11 Undid structure form of HTML and PostData since it won't code/decode properly automatically in KuditFrameworks. Seeing if typealias will work again (it does if we wrap the typealias in a structure). Added an HTML test for attributedString. Removed redundant old attributedStringFromHTML code. @@ -569,13 +565,13 @@ Broke macOS and watchOS with last update. Re-worked TabView Backport to be more Updated Xcode minimum versions to match package. Added Backport .overlay and .foregroundStyle and .background for older tvOS. ## v1.0.4 2024-07-08 -Attempted to fix issues with Linux compatibility (swapped legacyData around so extension of URLRequest instead of URLSession). Fixed target versions (Xcode project). +Attempted to fix issues with Linux compatibility (swapped legacyData around so extension of URLRequest instead of URLSession). Added additional #if canImport(Combine) checks. ## v1.0.3 2024-07-08 Reduced tvOS version requirements to tvOS 13 (though menu and other UI features are not supported). ## v1.0.2 2024-07-08 -Fixed several data race safety issues and fixed breaking support for watchOS and Linux. Added condition for @Published to ensure compilation on Linux. Made PostData require a Sendable type and added Sendable conformance to NetworkError. Fixed sendability of Message to prevent issues using `debug()`. +Fixed some data race issues and fixed breaking support for watchOS and Linux. Added condition for @Published to ensure compilation on Linux. Made PostData require a Sendable type and added Sendable conformance to NetworkError. Fixed sendability of Message to prevent issues using `debug()`. ## v1.0.1 2024-07-07 Fixed missing date in changelog. Moved DebugLevel.defaultLevel in initializers into nil initializers so can make sure to reference static property not in the initializer. Changed default color to orange. Changed several static vars to lets for concurrency safety. Enabled `main {}` to be used with throwing functions. Added `.spi.yml` file for Swift Package Index compiler. From 6f9ec99893f0010e612997697a2594d0a9c5da03 Mon Sep 17 00:00:00 2001 From: kudit Date: Wed, 29 Jul 2026 00:02:04 -0400 Subject: [PATCH 20/29] Updated module requirements --- CHANGELOG.md | 8 ++++++-- Sources/Core/Module.swift | 4 ++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5607f74..5f22150 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,11 +7,15 @@ Testing required before release: - Run the full test plan with ⌘U. - Confirm `Compatibility Module Test Entries` displays each reusable `TestCase` separately. - Confirm the new entries execute successfully and preserve readable module, section, and test names. -- Remove the older grouped module-test bridge after the new adapter is verified, then rerun the tests. +- Confirm the serialized debug tests restore `Compatibility.settings` even when an expectation throws. - Run SwiftPM and supported-platform validation before tagging the release. ## v1.18.3 2026-07-28 -TODO: Implement a comment matching this pull request changes. +Added the reusable `Compatibility Testing Library` product and `ModuleTestEntry` adapter so each module `TestCase` appears as an individually named Swift Testing result. +Unified `TestCase.execute()` and live test execution through one lifecycle implementation with explicit parallel and serialized execution modes. +Added source-aware test failures, labeled debug-format context, and source-context debugging conveniences while preserving existing debug-format call sites. +Made debug tests run exclusively and restore process-global debug settings with `defer`, including when an expectation throws. +Expanded contributor guidance for short, staged, maintainer-reviewed coding workflows. ## v1.18.2 2026-07-23 Fixed Swift Package Index build errors and warnings across SwiftUI and WebAssembly targets. diff --git a/Sources/Core/Module.swift b/Sources/Core/Module.swift index fd753e5..790844c 100644 --- a/Sources/Core/Module.swift +++ b/Sources/Core/Module.swift @@ -35,7 +35,7 @@ public protocol Module { /// The default is empty, so production-only modules do not need to declare tests. TestCase UI still /// presents the module identity and an empty state, making installed-module diagnostics complete. @MainActor - @available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) static var tests: OrderedDictionary { get } #endif @@ -122,7 +122,7 @@ public extension Module { #if compiler(>=5.9) /// Modules expose no tests unless the conformer provides ordered test sections. @MainActor - @available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) static var tests: OrderedDictionary { return [:] } From a5ba7978779bfe00135fe112f452bbbdd0c356de Mon Sep 17 00:00:00 2001 From: kudit Date: Wed, 29 Jul 2026 00:04:05 -0400 Subject: [PATCH 21/29] Discover module tests without global registration --- .../ModuleTestEntry.swift | 40 +++++++++++++++++-- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/Sources/CompatibilityTesting/ModuleTestEntry.swift b/Sources/CompatibilityTesting/ModuleTestEntry.swift index eaddcb9..d102a34 100644 --- a/Sources/CompatibilityTesting/ModuleTestEntry.swift +++ b/Sources/CompatibilityTesting/ModuleTestEntry.swift @@ -51,11 +51,45 @@ extension ModuleTestEntry: CustomTestArgumentEncodable { @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public extension ModuleTestEntry { - /// Registers the supplied top-level modules and flattens every module test into a named argument. + /// Flattens the supplied modules and their dependencies into individually named test arguments. + /// + /// Test discovery intentionally builds a local module list instead of mutating `Build.allModules`. + /// A test process may have already finished application module registration before Swift Testing + /// evaluates parameterized arguments; relying on that process-global registry could therefore + /// produce an empty argument list and cause the entire parameterized test to be skipped. @MainActor static func entries(including modules: Module.Type...) -> [ModuleTestEntry] { - Build.register(modules) - return Build.allModules.flatMap { module in + var orderedModules = [Module.Type]() + var includedIdentifiers = Set() + var visitingIdentifiers = Set() + + func include(_ module: Module.Type) { + let identifier = module.moduleIdentifier + + // Ignore modules already emitted and stop circular dependency traversal. + guard !includedIdentifiers.contains(identifier), + !visitingIdentifiers.contains(identifier) else { + return + } + + visitingIdentifiers.insert(identifier) + for dependency in module.dependencies { + include(dependency) + } + visitingIdentifiers.remove(identifier) + + // A sibling dependency may have emitted this module during recursive traversal. + guard includedIdentifiers.insert(identifier).inserted else { + return + } + orderedModules.append(module) + } + + for module in modules { + include(module) + } + + return orderedModules.flatMap { module in module.tests.flatMap { section, tests in tests.enumerated().map { index, testCase in ModuleTestEntry( From 61e59ba3ed948ca3a354f9bd06e41b04827c67d6 Mon Sep 17 00:00:00 2001 From: kudit Date: Wed, 29 Jul 2026 00:05:50 -0400 Subject: [PATCH 22/29] Set package version to 1.18.3 --- Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 96c3426..e722e6b 100644 --- a/Package.swift +++ b/Package.swift @@ -5,7 +5,7 @@ // This file is automatically generated. // Do not edit it by hand because the contents will be replaced. -let version = "1.18.2" +let version = "1.18.3" let packageLibraryName = "Compatibility" #if canImport(PackageDescription) From d82e8c035965a52cd2954ddbec716882df2bfe92 Mon Sep 17 00:00:00 2001 From: kudit Date: Wed, 29 Jul 2026 00:06:10 -0400 Subject: [PATCH 23/29] Set Compatibility version to 1.18.3 --- Sources/Compatibility.swift | 333 +----------------------------------- 1 file changed, 2 insertions(+), 331 deletions(-) diff --git a/Sources/Compatibility.swift b/Sources/Compatibility.swift index 90cef8c..724fdcc 100644 --- a/Sources/Compatibility.swift +++ b/Sources/Compatibility.swift @@ -8,7 +8,7 @@ public enum Compatibility: Module { /// The version of the Compatibility Library since cannot get directly from Package.swift. - public static let version: Version = "1.18.2" + public static let version: Version = "1.18.3" /// Public source repository for Compatibility so support reports can direct developers to its source and issue history. /// @@ -44,340 +44,11 @@ public enum Compatibility: Module { Field("iCloud status", Application.iCloudStatus), ] } - details += moduleInfo return details } - return applicationDetails + return applicationDetails + moduleInfo #else - // Non-Foundation environments still receive every portable field without referencing Application. return moduleInfo #endif } } - -#if canImport(Foundation) -@_exported import Foundation -// The following can be added if we want to add back in some funtions for Android or Linux (we're not currently using these personally, so if you do, please feel free to file a pull request). -//#elseif canImport(FoundationNetworking) && canImport(FoundationEssentials) && canImport(FoundationInternationalization) && canImport(FoundationXML) -///* -// Android compatibility: https://skip.tools/blog/android-native-swift-packages/#conditionally-importing-and-using-platform-specific-modules -// */ -//@_exported import FoundationNetworking -//@_exported import FoundationEssentials -//@_exported import FoundationInternationalization -//@_exported import FoundationXML -#if canImport(FoundationNetworking) -// Linux separates URLSession and related HTTP types from Foundation; the implementation uses libcurl. -@_exported import FoundationNetworking -#endif -#endif - -// NOTE: UNAVAILABLE to mark API as unavailabe for specific versions. -//@available(*, unavailable, message: "use native function rather than backport?") - -/* - - For module checks to conditionally compile for versions: - - canImport(StoreKit) - iOS 3.0+ - iPadOS 3.0+ - macOS 10.7+ - Mac Catalyst 13.0+ - tvOS 9.0+ - watchOS 6.2+ - visionOS 1.0+ - - 2014 (Swift announced, for OperatingSystemVersion) - canImport(HealthKit) || canImport(Metal) - iOS 8.0+ // Health, Metal - iPadOS 8.0+ // Health, Metal - macOS 10.10+ - Mac Catalyst 13.0+ // Metal - tvOS 9.0+ // Metal - watchOS 2.0+ // Health - visionOS 1.0+ // Health, Metal - - 2015 (initial relase of tvOS) - iOS 9 - macOS 10.11 - - 2016 - iOS 10 - macOS 10.12 - - 2017 - canImport(CoreML) - iOS 11 - macOS 10.13 (High Sierra) - tvOS 11 - watchOS 4 - - 2018 - iOS 12 - macOS 10.14 - tvOS 12 - watchOS 5 - - 2019 (first year macCatalyst and SwiftUI available) - canImport(SwiftUI) || canImport(Combine) - iOS 13+ - iPadOS 13.0+ - macOS 10.15+ - Mac Catalyst 13.0+ - tvOS 13+ - watchOS 6+ - visionOS 1.0+ - SF Symbols 1.0 - - 2020 - canImport(AppleArchive) - iOS 14+ - iPadOS 14.0+ - macOS 11+ - Mac Catalyst 14.0+ - tvOS 14+ - watchOS 7+ - visionOS 1.0+ - SF Symbols 2.0 - - 2021 - canImport(GroupActivities) - iOS 15+ (last supported by iPhone 7) - iPadOS 15.0+ - macOS 12+ (last supported by Touchbook) - Mac Catalyst 15.0+ - tvOS 15+ - NOTE: NO WATCH OS SUPPORT (watchOS 8 is the last supported by Series 3) - visionOS 1.0+ - SF Symbols 3.0 - - 2022 Swift 5.7 (September) - canImport(Charts) canImport(AppIntents) canImport(CoreTransferable) - iOS 16+ - iPadOS 16.0+ - macOS 13+ - Mac Catalyst 16.0+ - tvOS 16+ - watchOS 9+ (minimum for WidgetKit on watchOS - supported in iOS 14 and macOS 11) - visionOS 1.0+ - SF Symbols 4.0 - - 2023 Swift 5.8 (March), Swift 5.9 (September) (added #Preview syntax and @availability syntax) - canImport(SwiftData) - iOS 17+ - iPadOS 17.0+ - macOS 14+ - Mac Catalyst 17.0+ - tvOS 17+ - watchOS 10+ (practical minimum for WidgetKit (due to requirement of WidgetConfigurationIntent which is only available on iOS 17, macOS 14, and watchOS 10) - visionOS 1.0+ - SF Symbols 5.0 - -2024 Swift 5.10 (March), Swift 6 (September) -canImport(Testing) - iOS 18+ - iPadOS 18+ - macOS 15+ - Mac Catalyst 18+ - tvOS 18+ - watchOS 11+ - visionOS 2+ - SF Symbols 6.0 - Xcode 16 - - Swift Playgrounds 4.6.4 - Swift 6.0 Compiler - - 2025 Swift 6.1 (March), Swift 6.2 (September) - iOS 26+ - iPadOS 26+ - macOS 26+ - Mac Catalyst 26+ - tvOS 26+ - watchOS 26+ - visionOS 26+ - SF Symbols 7.0 - Xcode 26 - - In Swift 6.2, Foundation is not available in WASM - - */ -// MARK: - Configuration - -public extension Compatibility { - // https://medium.com/@aliyasirali/understanding-nonisolated-unsafe-in-swift-incremental-adoption-of-strict-concurrency-2cbb61c9adf4 - // This generates unsafe warnings anyways, so use the simpler version and hope there are no data races (theoretically, if we're only changing on the main thread first thing at init, this shouldn't be a problem) -// private static var lock = NSLock() -// private static var _settings = CompatibilityConfiguration() -// static var settings: CompatibilityConfiguration { -// get { -// lock.lock() -// defer { lock.unlock() } -// return _settings -// } -// set { -// lock.lock() -// defer { lock.unlock() } -// _settings = newValue -// } -// } -// -#if compiler(>=5.10) - static nonisolated(unsafe) var settings = CompatibilityConfiguration() -#else - static var settings = CompatibilityConfiguration() -#endif -} - -// for flags in swift packages: https://stackoverflow.com/questions/38813906/swift-how-to-use-preprocessor-flags-like-if-debug-to-implement-api-keys -//swiftSettings: [ -// .define("VAPOR") -//] -// https://medium.com/@ytyubox/xcode-preprocessing-with-custom-flags-in-swift-4bfde6e7a608 - -// MARK: - legacy compatibility code deprecations and support -public extension Compatibility { // for brief period where Application wasn't available - @available(*, deprecated, renamed: "Application.isDebug") - static let isDebug = _isDebugAssertConfiguration() -} -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) -public extension Compatibility { // for brief period where Application and Build wasn't available. Static computed properties apparently aren't supported in extensions in iOS <13? - // MARK: - Entitlements Information -#if canImport(Foundation) - @available(*, deprecated, renamed: "Application.iCloudSupported") - @MainActor - static var iCloudSupported: Bool { - get { - Application.iCloudSupported - } - set { - Application.iCloudSupported = newValue - } - } - - @available(*, deprecated, renamed: "Application.iCloudIsEnabled") - @MainActor - static var iCloudIsEnabled: Bool { - Application.iCloudIsEnabled - } - - @available(*, deprecated, renamed: "Application.iCloudStatus") - @MainActor - static var iCloudStatus: CloudStatus { - Application.iCloudStatus - } -#endif - - @available(*, deprecated, renamed: "Build.isSimulator") - static let isSimulator = Build.isSimulator - - @available(*, deprecated, renamed: "Build.isPlayground") - static let isPlayground = Build.isPlayground - - @available(*, deprecated, renamed: "Build.isPreview") - static let isPreview = Build.isPreview - - @available(*, deprecated, renamed: "Build.isMacCatalyst") - static let isMacCatalyst = Build.isMacCatalyst -} - -#if canImport(SwiftUI) && compiler(>=5.9) && canImport(Foundation) -import SwiftUI - -@available(iOS 15, macOS 12, tvOS 15, watchOS 9, *) -public struct CompatibilityEnvironmentTestView: View { -#if compiler(>=5.9) && canImport(Combine) - @CloudStorage(.compatibilityVersionsRunKey) var previouslyRunCompatibilityVersions = Compatibility.version.rawValue -#endif - /// Complete deferred module information; `nil` keeps the loading state distinct from the portable baseline. - @State private var loadedModuleInfo: [Field]? - - /// Creates an environment view whose module metadata is loaded after the UI first appears. - public init() {} - - /// Structured application fields displayed by the environment test view. - public var applicationInfo: [Field] { - var info = [ - Field("Name", "\(Application.main.name) (\(Application.main.appName).app)"), - Field("App Identifier", Application.main.appIdentifier), - Field("App Version", "v\(Application.main.debugVersion)"), - Field("is first run", Application.main.isFirstRun), - ] - let previousVersions = Application.main.previouslyRunVersions - if previousVersions.count > 0 { - info.append(Field("Previously run versions", previousVersions.pretty)) - } - return info - } - - /// Structured Compatibility-version and build-mode fields displayed by the environment test view. - public var compatibilityInfo: [Field] { - var info = [ - Field("\(Compatibility.moduleName) Version", Compatibility.version), - Field("is Debug", Build.isDebug), - ] -#if compiler(>=5.9) && canImport(Combine) - if previouslyRunCompatibilityVersions != "" && previouslyRunCompatibilityVersions != "\(Compatibility.version.rawValue)" { - info += [ - Field("Previously run Compatibility versions", previouslyRunCompatibilityVersions), - Field(nil, "NOTE: This only updates if we're running the DataStore test view and is not guaranteed to be run any other time or from any other app."), - ] - } -#endif - return info - } - - public var body: some View { - List { - FieldSections([ - "Application": applicationInfo, - Compatibility.moduleName: compatibilityInfo, - "iCloud": [ - Field("Supported by app", Application.iCloudSupported), - Field("Enabled", Application.iCloudIsEnabled), - Field("iCloud status", Application.iCloudStatus), - ], - ]) - Section("Module Info") { - // Show the portable baseline immediately, then replace it with the complete loaded result. - // This is example code. Really this only needs to include moduleInfo since the detailed info is already included in other sections. - let displayedModuleInfo = loadedModuleInfo ?? Compatibility.moduleInfo - ForEach(displayedModuleInfo.indices, id: \.self) { index in - FieldView(displayedModuleInfo[index]) - } - if loadedModuleInfo == nil { - ProgressView("Loading module details…") - } - } - Section("Environment") { - FieldView(Field("Swift Version", Build.swiftVersion, symbol: "swift")) - FieldView(Field("Compiler Version", Build.compilerVersion)) - EnvironmentsView(Build.environments()) - .frame(maxWidth: .infinity, alignment: .leading) - .contentShape(Rectangle()) - } - FieldSections([ - "Dates": [ - Field("Now Backport", Date.nowBackport.pretty), - Field("Now MySQL", Date.nowBackport.mysqlDateTime), - Field("Now Numeric", Date.nowBackport.numericDateTime), - Field("Tomorrow", Date.tomorrow.pretty), - Field("Tomorrow Midnight", Date.tomorrowMidnight.pretty), - Field("Yesterday", Date.yesterday.pretty), - ], - ]) - } - .task { - // Await potentially slow details without delaying the portable module fields above. - loadedModuleInfo = await Compatibility.loadDetailedModuleInfo() - } - } -} - -@available(iOS 15, macOS 12, tvOS 15, watchOS 9, *) -#Preview { - CompatibilityEnvironmentTestView() - .backport.scrollContentBackground(.hidden) - .background(.red) -} -#endif From 7935f7acea8dbcd9bc37f4af21464c34f1a68f94 Mon Sep 17 00:00:00 2001 From: kudit Date: Wed, 29 Jul 2026 00:19:13 -0400 Subject: [PATCH 24/29] Revert "Set Compatibility version to 1.18.3" This reverts commit d82e8c035965a52cd2954ddbec716882df2bfe92. --- Sources/Compatibility.swift | 333 +++++++++++++++++++++++++++++++++++- 1 file changed, 331 insertions(+), 2 deletions(-) diff --git a/Sources/Compatibility.swift b/Sources/Compatibility.swift index 724fdcc..90cef8c 100644 --- a/Sources/Compatibility.swift +++ b/Sources/Compatibility.swift @@ -8,7 +8,7 @@ public enum Compatibility: Module { /// The version of the Compatibility Library since cannot get directly from Package.swift. - public static let version: Version = "1.18.3" + public static let version: Version = "1.18.2" /// Public source repository for Compatibility so support reports can direct developers to its source and issue history. /// @@ -44,11 +44,340 @@ public enum Compatibility: Module { Field("iCloud status", Application.iCloudStatus), ] } + details += moduleInfo return details } - return applicationDetails + moduleInfo + return applicationDetails #else + // Non-Foundation environments still receive every portable field without referencing Application. return moduleInfo #endif } } + +#if canImport(Foundation) +@_exported import Foundation +// The following can be added if we want to add back in some funtions for Android or Linux (we're not currently using these personally, so if you do, please feel free to file a pull request). +//#elseif canImport(FoundationNetworking) && canImport(FoundationEssentials) && canImport(FoundationInternationalization) && canImport(FoundationXML) +///* +// Android compatibility: https://skip.tools/blog/android-native-swift-packages/#conditionally-importing-and-using-platform-specific-modules +// */ +//@_exported import FoundationNetworking +//@_exported import FoundationEssentials +//@_exported import FoundationInternationalization +//@_exported import FoundationXML +#if canImport(FoundationNetworking) +// Linux separates URLSession and related HTTP types from Foundation; the implementation uses libcurl. +@_exported import FoundationNetworking +#endif +#endif + +// NOTE: UNAVAILABLE to mark API as unavailabe for specific versions. +//@available(*, unavailable, message: "use native function rather than backport?") + +/* + + For module checks to conditionally compile for versions: + + canImport(StoreKit) + iOS 3.0+ + iPadOS 3.0+ + macOS 10.7+ + Mac Catalyst 13.0+ + tvOS 9.0+ + watchOS 6.2+ + visionOS 1.0+ + + 2014 (Swift announced, for OperatingSystemVersion) + canImport(HealthKit) || canImport(Metal) + iOS 8.0+ // Health, Metal + iPadOS 8.0+ // Health, Metal + macOS 10.10+ + Mac Catalyst 13.0+ // Metal + tvOS 9.0+ // Metal + watchOS 2.0+ // Health + visionOS 1.0+ // Health, Metal + + 2015 (initial relase of tvOS) + iOS 9 + macOS 10.11 + + 2016 + iOS 10 + macOS 10.12 + + 2017 + canImport(CoreML) + iOS 11 + macOS 10.13 (High Sierra) + tvOS 11 + watchOS 4 + + 2018 + iOS 12 + macOS 10.14 + tvOS 12 + watchOS 5 + + 2019 (first year macCatalyst and SwiftUI available) + canImport(SwiftUI) || canImport(Combine) + iOS 13+ + iPadOS 13.0+ + macOS 10.15+ + Mac Catalyst 13.0+ + tvOS 13+ + watchOS 6+ + visionOS 1.0+ + SF Symbols 1.0 + + 2020 + canImport(AppleArchive) + iOS 14+ + iPadOS 14.0+ + macOS 11+ + Mac Catalyst 14.0+ + tvOS 14+ + watchOS 7+ + visionOS 1.0+ + SF Symbols 2.0 + + 2021 + canImport(GroupActivities) + iOS 15+ (last supported by iPhone 7) + iPadOS 15.0+ + macOS 12+ (last supported by Touchbook) + Mac Catalyst 15.0+ + tvOS 15+ + NOTE: NO WATCH OS SUPPORT (watchOS 8 is the last supported by Series 3) + visionOS 1.0+ + SF Symbols 3.0 + + 2022 Swift 5.7 (September) + canImport(Charts) canImport(AppIntents) canImport(CoreTransferable) + iOS 16+ + iPadOS 16.0+ + macOS 13+ + Mac Catalyst 16.0+ + tvOS 16+ + watchOS 9+ (minimum for WidgetKit on watchOS - supported in iOS 14 and macOS 11) + visionOS 1.0+ + SF Symbols 4.0 + + 2023 Swift 5.8 (March), Swift 5.9 (September) (added #Preview syntax and @availability syntax) + canImport(SwiftData) + iOS 17+ + iPadOS 17.0+ + macOS 14+ + Mac Catalyst 17.0+ + tvOS 17+ + watchOS 10+ (practical minimum for WidgetKit (due to requirement of WidgetConfigurationIntent which is only available on iOS 17, macOS 14, and watchOS 10) + visionOS 1.0+ + SF Symbols 5.0 + +2024 Swift 5.10 (March), Swift 6 (September) +canImport(Testing) + iOS 18+ + iPadOS 18+ + macOS 15+ + Mac Catalyst 18+ + tvOS 18+ + watchOS 11+ + visionOS 2+ + SF Symbols 6.0 + Xcode 16 + + Swift Playgrounds 4.6.4 - Swift 6.0 Compiler + + 2025 Swift 6.1 (March), Swift 6.2 (September) + iOS 26+ + iPadOS 26+ + macOS 26+ + Mac Catalyst 26+ + tvOS 26+ + watchOS 26+ + visionOS 26+ + SF Symbols 7.0 + Xcode 26 + + In Swift 6.2, Foundation is not available in WASM + + */ +// MARK: - Configuration + +public extension Compatibility { + // https://medium.com/@aliyasirali/understanding-nonisolated-unsafe-in-swift-incremental-adoption-of-strict-concurrency-2cbb61c9adf4 + // This generates unsafe warnings anyways, so use the simpler version and hope there are no data races (theoretically, if we're only changing on the main thread first thing at init, this shouldn't be a problem) +// private static var lock = NSLock() +// private static var _settings = CompatibilityConfiguration() +// static var settings: CompatibilityConfiguration { +// get { +// lock.lock() +// defer { lock.unlock() } +// return _settings +// } +// set { +// lock.lock() +// defer { lock.unlock() } +// _settings = newValue +// } +// } +// +#if compiler(>=5.10) + static nonisolated(unsafe) var settings = CompatibilityConfiguration() +#else + static var settings = CompatibilityConfiguration() +#endif +} + +// for flags in swift packages: https://stackoverflow.com/questions/38813906/swift-how-to-use-preprocessor-flags-like-if-debug-to-implement-api-keys +//swiftSettings: [ +// .define("VAPOR") +//] +// https://medium.com/@ytyubox/xcode-preprocessing-with-custom-flags-in-swift-4bfde6e7a608 + +// MARK: - legacy compatibility code deprecations and support +public extension Compatibility { // for brief period where Application wasn't available + @available(*, deprecated, renamed: "Application.isDebug") + static let isDebug = _isDebugAssertConfiguration() +} +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) +public extension Compatibility { // for brief period where Application and Build wasn't available. Static computed properties apparently aren't supported in extensions in iOS <13? + // MARK: - Entitlements Information +#if canImport(Foundation) + @available(*, deprecated, renamed: "Application.iCloudSupported") + @MainActor + static var iCloudSupported: Bool { + get { + Application.iCloudSupported + } + set { + Application.iCloudSupported = newValue + } + } + + @available(*, deprecated, renamed: "Application.iCloudIsEnabled") + @MainActor + static var iCloudIsEnabled: Bool { + Application.iCloudIsEnabled + } + + @available(*, deprecated, renamed: "Application.iCloudStatus") + @MainActor + static var iCloudStatus: CloudStatus { + Application.iCloudStatus + } +#endif + + @available(*, deprecated, renamed: "Build.isSimulator") + static let isSimulator = Build.isSimulator + + @available(*, deprecated, renamed: "Build.isPlayground") + static let isPlayground = Build.isPlayground + + @available(*, deprecated, renamed: "Build.isPreview") + static let isPreview = Build.isPreview + + @available(*, deprecated, renamed: "Build.isMacCatalyst") + static let isMacCatalyst = Build.isMacCatalyst +} + +#if canImport(SwiftUI) && compiler(>=5.9) && canImport(Foundation) +import SwiftUI + +@available(iOS 15, macOS 12, tvOS 15, watchOS 9, *) +public struct CompatibilityEnvironmentTestView: View { +#if compiler(>=5.9) && canImport(Combine) + @CloudStorage(.compatibilityVersionsRunKey) var previouslyRunCompatibilityVersions = Compatibility.version.rawValue +#endif + /// Complete deferred module information; `nil` keeps the loading state distinct from the portable baseline. + @State private var loadedModuleInfo: [Field]? + + /// Creates an environment view whose module metadata is loaded after the UI first appears. + public init() {} + + /// Structured application fields displayed by the environment test view. + public var applicationInfo: [Field] { + var info = [ + Field("Name", "\(Application.main.name) (\(Application.main.appName).app)"), + Field("App Identifier", Application.main.appIdentifier), + Field("App Version", "v\(Application.main.debugVersion)"), + Field("is first run", Application.main.isFirstRun), + ] + let previousVersions = Application.main.previouslyRunVersions + if previousVersions.count > 0 { + info.append(Field("Previously run versions", previousVersions.pretty)) + } + return info + } + + /// Structured Compatibility-version and build-mode fields displayed by the environment test view. + public var compatibilityInfo: [Field] { + var info = [ + Field("\(Compatibility.moduleName) Version", Compatibility.version), + Field("is Debug", Build.isDebug), + ] +#if compiler(>=5.9) && canImport(Combine) + if previouslyRunCompatibilityVersions != "" && previouslyRunCompatibilityVersions != "\(Compatibility.version.rawValue)" { + info += [ + Field("Previously run Compatibility versions", previouslyRunCompatibilityVersions), + Field(nil, "NOTE: This only updates if we're running the DataStore test view and is not guaranteed to be run any other time or from any other app."), + ] + } +#endif + return info + } + + public var body: some View { + List { + FieldSections([ + "Application": applicationInfo, + Compatibility.moduleName: compatibilityInfo, + "iCloud": [ + Field("Supported by app", Application.iCloudSupported), + Field("Enabled", Application.iCloudIsEnabled), + Field("iCloud status", Application.iCloudStatus), + ], + ]) + Section("Module Info") { + // Show the portable baseline immediately, then replace it with the complete loaded result. + // This is example code. Really this only needs to include moduleInfo since the detailed info is already included in other sections. + let displayedModuleInfo = loadedModuleInfo ?? Compatibility.moduleInfo + ForEach(displayedModuleInfo.indices, id: \.self) { index in + FieldView(displayedModuleInfo[index]) + } + if loadedModuleInfo == nil { + ProgressView("Loading module details…") + } + } + Section("Environment") { + FieldView(Field("Swift Version", Build.swiftVersion, symbol: "swift")) + FieldView(Field("Compiler Version", Build.compilerVersion)) + EnvironmentsView(Build.environments()) + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) + } + FieldSections([ + "Dates": [ + Field("Now Backport", Date.nowBackport.pretty), + Field("Now MySQL", Date.nowBackport.mysqlDateTime), + Field("Now Numeric", Date.nowBackport.numericDateTime), + Field("Tomorrow", Date.tomorrow.pretty), + Field("Tomorrow Midnight", Date.tomorrowMidnight.pretty), + Field("Yesterday", Date.yesterday.pretty), + ], + ]) + } + .task { + // Await potentially slow details without delaying the portable module fields above. + loadedModuleInfo = await Compatibility.loadDetailedModuleInfo() + } + } +} + +@available(iOS 15, macOS 12, tvOS 15, watchOS 9, *) +#Preview { + CompatibilityEnvironmentTestView() + .backport.scrollContentBackground(.hidden) + .background(.red) +} +#endif From c891def7ff491f95f7882daaab53e2d31ed0b5d1 Mon Sep 17 00:00:00 2001 From: kudit Date: Wed, 29 Jul 2026 00:24:56 -0400 Subject: [PATCH 25/29] fixed version surfaces --- Development/Compatibility.xcodeproj/project.pbxproj | 4 ++-- Sources/Compatibility.swift | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Development/Compatibility.xcodeproj/project.pbxproj b/Development/Compatibility.xcodeproj/project.pbxproj index 850eac0..2a51e0a 100644 --- a/Development/Compatibility.xcodeproj/project.pbxproj +++ b/Development/Compatibility.xcodeproj/project.pbxproj @@ -488,7 +488,7 @@ IPHONEOS_DEPLOYMENT_TARGET = 12.0; LOCALIZATION_PREFERS_STRING_CATALOGS = YES; MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 1.18.2; + MARKETING_VERSION = 1.18.3; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_FAST_MATH = YES; ONLY_ACTIVE_ARCH = YES; @@ -559,7 +559,7 @@ IPHONEOS_DEPLOYMENT_TARGET = 12.0; LOCALIZATION_PREFERS_STRING_CATALOGS = YES; MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 1.18.2; + MARKETING_VERSION = 1.18.3; MTL_ENABLE_DEBUG_INFO = NO; MTL_FAST_MATH = YES; OTHER_SWIFT_FLAGS = ""; diff --git a/Sources/Compatibility.swift b/Sources/Compatibility.swift index 90cef8c..2afbbb1 100644 --- a/Sources/Compatibility.swift +++ b/Sources/Compatibility.swift @@ -8,7 +8,7 @@ public enum Compatibility: Module { /// The version of the Compatibility Library since cannot get directly from Package.swift. - public static let version: Version = "1.18.2" + public static let version: Version = "1.18.3" /// Public source repository for Compatibility so support reports can direct developers to its source and issue history. /// From b79fcb62385a21985d6797cf19ced4a9f2243fb3 Mon Sep 17 00:00:00 2001 From: kudit Date: Wed, 29 Jul 2026 00:40:05 -0400 Subject: [PATCH 26/29] added compatibility testing library --- .../Compatibility.xcodeproj/project.pbxproj | 7 + .../xcdebugger/Breakpoints_v2.xcbkptlist | 120 ++++++++++++++++++ 2 files changed, 127 insertions(+) diff --git a/Development/Compatibility.xcodeproj/project.pbxproj b/Development/Compatibility.xcodeproj/project.pbxproj index 2a51e0a..16887bc 100644 --- a/Development/Compatibility.xcodeproj/project.pbxproj +++ b/Development/Compatibility.xcodeproj/project.pbxproj @@ -14,6 +14,7 @@ B5209EE32C431CF800FBA30B /* CompatibilityDemoView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5209EE22C431CF800FBA30B /* CompatibilityDemoView.swift */; }; B5209EE42C431CF800FBA30B /* CompatibilityDemoView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5209EE22C431CF800FBA30B /* CompatibilityDemoView.swift */; }; B52C8E0F2C38CA76008EBD2D /* MyApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5E5FC3A2C3860EC004F2009 /* MyApp.swift */; }; + B52DEB233019BA54003291D0 /* Compatibility Testing Library in Frameworks */ = {isa = PBXBuildFile; productRef = B52DEB223019BA54003291D0 /* Compatibility Testing Library */; }; B569253B2E8715550045FFC6 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = B5E5FC822C3863B9004F2009 /* Assets.xcassets */; }; B579D4A52C46FF1A009A037A /* Compatibility Library in Frameworks */ = {isa = PBXBuildFile; productRef = B579D4A42C46FF1A009A037A /* Compatibility Library */; }; B58B5C452C38F98800689837 /* (null) in Sources */ = {isa = PBXBuildFile; }; @@ -91,6 +92,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + B52DEB233019BA54003291D0 /* Compatibility Testing Library in Frameworks */, B594CFB72DB0BACA001E8658 /* Compatibility Library in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -227,6 +229,7 @@ name = CompatibilityTests; packageProductDependencies = ( B594CFB62DB0BACA001E8658 /* Compatibility Library */, + B52DEB223019BA54003291D0 /* Compatibility Testing Library */, ); productName = CompatibilityTests; productReference = B594CFA92DB0B838001E8658 /* CompatibilityTests.xctest */; @@ -814,6 +817,10 @@ package = B52C8E0D2C3886E6008EBD2D /* XCLocalSwiftPackageReference ".." */; productName = "Compatibility Library"; }; + B52DEB223019BA54003291D0 /* Compatibility Testing Library */ = { + isa = XCSwiftPackageProductDependency; + productName = "Compatibility Testing Library"; + }; B579D4A42C46FF1A009A037A /* Compatibility Library */ = { isa = XCSwiftPackageProductDependency; package = B52C8E0D2C3886E6008EBD2D /* XCLocalSwiftPackageReference ".." */; diff --git a/Development/Compatibility.xcodeproj/xcuserdata/ben.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist b/Development/Compatibility.xcodeproj/xcuserdata/ben.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist index 5f1efac..a77e84d 100644 --- a/Development/Compatibility.xcodeproj/xcuserdata/ben.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist +++ b/Development/Compatibility.xcodeproj/xcuserdata/ben.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist @@ -18,6 +18,36 @@ endingLineNumber = "319" landmarkName = "pretty" landmarkType = "24"> + + + + + + + + + + + + + + + + + + + + + + + + From 2b1541812431ce4db9b72cc0a0b35526115a7781 Mon Sep 17 00:00:00 2001 From: kudit Date: Wed, 29 Jul 2026 00:40:24 -0400 Subject: [PATCH 27/29] Remove duplicate module graph traversal --- .../ModuleTestEntry.swift | 71 +++++++------------ 1 file changed, 27 insertions(+), 44 deletions(-) diff --git a/Sources/CompatibilityTesting/ModuleTestEntry.swift b/Sources/CompatibilityTesting/ModuleTestEntry.swift index d102a34..41fc907 100644 --- a/Sources/CompatibilityTesting/ModuleTestEntry.swift +++ b/Sources/CompatibilityTesting/ModuleTestEntry.swift @@ -51,55 +51,38 @@ extension ModuleTestEntry: CustomTestArgumentEncodable { @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public extension ModuleTestEntry { - /// Flattens the supplied modules and their dependencies into individually named test arguments. + /// Flattens an explicitly supplied module test catalog into individually named test arguments. /// - /// Test discovery intentionally builds a local module list instead of mutating `Build.allModules`. - /// A test process may have already finished application module registration before Swift Testing - /// evaluates parameterized arguments; relying on that process-global registry could therefore - /// produce an empty argument list and cause the entire parameterized test to be skipped. + /// The caller supplies the concrete module's `tests` value so Swift does not fall back to a + /// protocol-extension default when a downstream package has an overly restrictive availability + /// annotation. Dependency traversal remains the responsibility of Compatibility's existing + /// `Build` registration graph rather than being duplicated in the testing adapter. @MainActor - static func entries(including modules: Module.Type...) -> [ModuleTestEntry] { - var orderedModules = [Module.Type]() - var includedIdentifiers = Set() - var visitingIdentifiers = Set() - - func include(_ module: Module.Type) { - let identifier = module.moduleIdentifier - - // Ignore modules already emitted and stop circular dependency traversal. - guard !includedIdentifiers.contains(identifier), - !visitingIdentifiers.contains(identifier) else { - return - } - - visitingIdentifiers.insert(identifier) - for dependency in module.dependencies { - include(dependency) - } - visitingIdentifiers.remove(identifier) - - // A sibling dependency may have emitted this module during recursive traversal. - guard includedIdentifiers.insert(identifier).inserted else { - return + static func entries( + for module: Module.Type, + tests: OrderedDictionary + ) -> [ModuleTestEntry] { + tests.flatMap { section, tests in + tests.enumerated().map { index, testCase in + ModuleTestEntry( + module: module, + section: section, + index: index, + testCase: testCase + ) } - orderedModules.append(module) - } - - for module in modules { - include(module) } + } - return orderedModules.flatMap { module in - module.tests.flatMap { section, tests in - tests.enumerated().map { index, testCase in - ModuleTestEntry( - module: module, - section: section, - index: index, - testCase: testCase - ) - } - } + /// Flattens each supplied module's protocol-visible catalog. + /// + /// This convenience remains useful once conforming modules expose `tests` at the same + /// availability as the `Module` requirement. Call ``entries(for:tests:)`` while migrating an + /// older conformer whose test catalog has a stricter availability annotation. + @MainActor + static func entries(including modules: Module.Type...) -> [ModuleTestEntry] { + modules.flatMap { module in + entries(for: module, tests: module.tests) } } } From 53628d6bf99159e5047a9a478ca25c4a507de6e3 Mon Sep 17 00:00:00 2001 From: kudit Date: Wed, 29 Jul 2026 00:40:39 -0400 Subject: [PATCH 28/29] Use concrete Compatibility test catalog --- Development/CompatibilityTests/ModuleTestEntryTests.swift | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Development/CompatibilityTests/ModuleTestEntryTests.swift b/Development/CompatibilityTests/ModuleTestEntryTests.swift index 4d1594b..8f097eb 100644 --- a/Development/CompatibilityTests/ModuleTestEntryTests.swift +++ b/Development/CompatibilityTests/ModuleTestEntryTests.swift @@ -16,11 +16,14 @@ struct ModuleTestEntryTests { @Test( "Compatibility Module Test", arguments: await MainActor.run { - ModuleTestEntry.entries(including: Compatibility.self) + ModuleTestEntry.entries( + for: Compatibility.self, + tests: Compatibility.tests + ) } ) @MainActor - @available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) + @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func moduleTest(entry: ModuleTestEntry) async throws { try await entry.execute() } From ae7c4eef2ede2da2665747375428576ba208e5c6 Mon Sep 17 00:00:00 2001 From: kudit Date: Wed, 29 Jul 2026 01:00:21 -0400 Subject: [PATCH 29/29] fixed @available checks for macOS 12 fix @available where macOS 12 was paired with watchOS 8 --- CHANGELOG.md | 2 - .../xcdebugger/Breakpoints_v2.xcbkptlist | 120 ------------------ Sources/Core/Build.swift | 2 +- Sources/Core/CloudStatus.swift | 2 +- Sources/Core/Debug.swift | 2 +- Sources/Core/FileManager.swift | 2 +- Sources/Core/Module.swift | 6 +- Sources/Core/Test.swift | 4 +- Sources/Foundation/CodingMixedTypes.swift | 2 +- Sources/Foundation/Date.swift | 6 +- Sources/Foundation/DateString.swift | 2 +- Sources/Foundation/Double.swift | 2 +- Sources/UI/Backport.swift | 2 +- Sources/UI/OverlappingStack.swift | 2 +- Sources/UI/Pasteboard.swift | 2 +- 15 files changed, 18 insertions(+), 140 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f22150..3138e6f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,8 +3,6 @@ # TODO: Testing required before release: -- Build the package in Xcode with ⌘B. -- Run the full test plan with ⌘U. - Confirm `Compatibility Module Test Entries` displays each reusable `TestCase` separately. - Confirm the new entries execute successfully and preserve readable module, section, and test names. - Confirm the serialized debug tests restore `Compatibility.settings` even when an expectation throws. diff --git a/Development/Compatibility.xcodeproj/xcuserdata/ben.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist b/Development/Compatibility.xcodeproj/xcuserdata/ben.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist index a77e84d..5f1efac 100644 --- a/Development/Compatibility.xcodeproj/xcuserdata/ben.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist +++ b/Development/Compatibility.xcodeproj/xcuserdata/ben.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist @@ -18,36 +18,6 @@ endingLineNumber = "319" landmarkName = "pretty" landmarkType = "24"> - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Sources/Core/Build.swift b/Sources/Core/Build.swift index d856595..5233edd 100644 --- a/Sources/Core/Build.swift +++ b/Sources/Core/Build.swift @@ -523,7 +523,7 @@ public extension Build.Environment { case .designedForiPad: return .purple case .macCatalyst: - if #available(iOS 15.0, macCatalyst 15.0, tvOS 15.0, macOS 12.0, watchOS 8.0, *) { + if #available(iOS 15, macCatalyst 15, tvOS 15, macOS 12, watchOS 8, *) { return .teal } else { return .purple diff --git a/Sources/Core/CloudStatus.swift b/Sources/Core/CloudStatus.swift index efd4766..8cafa6c 100644 --- a/Sources/Core/CloudStatus.swift +++ b/Sources/Core/CloudStatus.swift @@ -24,7 +24,7 @@ public enum CloudStatus: CustomStringConvertible, Sendable, CaseIterable, Symbol } #if compiler(>=5.9) -@available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public extension CloudStatus { /// Shared enum behavior tests available to both the in-app test UI and Swift Testing bridge. @MainActor diff --git a/Sources/Core/Debug.swift b/Sources/Core/Debug.swift index 51e0e90..2d7a780 100644 --- a/Sources/Core/Debug.swift +++ b/Sources/Core/Debug.swift @@ -458,7 +458,7 @@ public extension TestFailure { // Testing and main-actor isolation are supported on current full-runtime WASM builds. #if compiler(>=5.9) -@available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public extension DebugLevel { @MainActor internal static let testDebugConfig: TestClosure = { diff --git a/Sources/Core/FileManager.swift b/Sources/Core/FileManager.swift index 5b66710..88ec6c4 100644 --- a/Sources/Core/FileManager.swift +++ b/Sources/Core/FileManager.swift @@ -42,7 +42,7 @@ public extension FileManager { } #if compiler(>=5.9) -@available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension FileManager { /// Shared file-manager tests used by both the in-app runner and Swift Testing. @MainActor diff --git a/Sources/Core/Module.swift b/Sources/Core/Module.swift index 790844c..72f4347 100644 --- a/Sources/Core/Module.swift +++ b/Sources/Core/Module.swift @@ -273,7 +273,7 @@ private enum DependentModuleTestFixture: Module { } /// Shared Module tests used by both the in-app All Tests UI and the Swift Testing bridge. -@available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) @MainActor private func testModuleMetadataAndDefaults() async throws { // Verify the default name remains derived from the conforming type so modules do not need boilerplate. @@ -324,13 +324,13 @@ private func testModuleMetadataAndDefaults() async throws { } /// Preserve the module test's actor boundary on every concurrency-capable target, including WebAssembly. -@available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) private let moduleMetadataTest: TestClosure = { @MainActor in try await testModuleMetadataAndDefaults() } /// The collection remains main-actor isolated on every supported platform, including WebAssembly. -@available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) @MainActor internal let moduleTests: [TestCase] = [ TestCase("Module metadata and defaults", moduleMetadataTest), diff --git a/Sources/Core/Test.swift b/Sources/Core/Test.swift index aee2ca1..6304cd3 100644 --- a/Sources/Core/Test.swift +++ b/Sources/Core/Test.swift @@ -430,7 +430,7 @@ public extension TestCase { } } -@available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public extension TestCase { /// Every reusable Compatibility test, grouped in deterministic display and execution order. /// @@ -480,7 +480,7 @@ public extension TestCase { }() } -@available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public extension Compatibility { /// Compatibility's global test catalog. @MainActor diff --git a/Sources/Foundation/CodingMixedTypes.swift b/Sources/Foundation/CodingMixedTypes.swift index b054b6a..9cc89c2 100644 --- a/Sources/Foundation/CodingMixedTypes.swift +++ b/Sources/Foundation/CodingMixedTypes.swift @@ -194,7 +194,7 @@ public enum MixedTypeField: Equatable, Sendable, Hashable { } #if compiler(>=5.9) -@available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public extension MixedTypeField { /// Shared value, formatting, and `Field` integration tests available to the in-app and Swift Testing runners. @MainActor diff --git a/Sources/Foundation/Date.swift b/Sources/Foundation/Date.swift index 201a540..b174781 100644 --- a/Sources/Foundation/Date.swift +++ b/Sources/Foundation/Date.swift @@ -209,7 +209,7 @@ public extension Date { // Testing is only supported with Swift 5.9+ #if compiler(>=5.9) && canImport(Foundation) -@available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public extension Date { @MainActor static let tests = [ @@ -224,7 +224,7 @@ public extension Date { #if canImport(SwiftUI) import SwiftUI -@available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) #Preview { VStack { Text("\(String(describing: Date(from: "2023-01-02 17:12:00", format: "yyyy-MM-dd HH:mm:ss")))") @@ -233,7 +233,7 @@ import SwiftUI Text("\(String(describing: Date(from: "2023-01-02 17:12:00", format: "yyyy-MM-dd HH:mm:ss")?.pretty))") } } -@available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) #Preview("Tests") { TestsListView(tests: Date.tests) } diff --git a/Sources/Foundation/DateString.swift b/Sources/Foundation/DateString.swift index 0c92446..f3e4e45 100644 --- a/Sources/Foundation/DateString.swift +++ b/Sources/Foundation/DateString.swift @@ -180,7 +180,7 @@ public extension Date { try expect(Date(parse: "Jan 2, 2023")?.mysqlDate == "2023-01-02") try expect(Date(parse: "not a date") == nil) } - @available(macOS 12, *) + @available(macOS 10.15, *) @MainActor internal static let testFormatted: TestClosure = { let date = Date(from: "2023-01-02 17:12:00", format: .mysqlDateTimeFormat) diff --git a/Sources/Foundation/Double.swift b/Sources/Foundation/Double.swift index 6c3cfb3..8c161c4 100644 --- a/Sources/Foundation/Double.swift +++ b/Sources/Foundation/Double.swift @@ -293,7 +293,7 @@ public extension Double { // Testing is only supported with Swift 5.9+ #if compiler(>=5.9) -@available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public extension Double { @MainActor static let tests = [ diff --git a/Sources/UI/Backport.swift b/Sources/UI/Backport.swift index 96c63e1..f4e47ae 100644 --- a/Sources/UI/Backport.swift +++ b/Sources/UI/Backport.swift @@ -35,7 +35,7 @@ extension Backport where Content == Any { } } -@available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Backport where Content == Any { @ViewBuilder public static func LabeledContent(_ titleKey: String, value: some StringProtocol) -> some View { if titleKey.count > 35 { diff --git a/Sources/UI/OverlappingStack.swift b/Sources/UI/OverlappingStack.swift index 875eadf..cd4a158 100644 --- a/Sources/UI/OverlappingStack.swift +++ b/Sources/UI/OverlappingStack.swift @@ -219,7 +219,7 @@ private struct OverlappingStack: Layout { } } -@available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) #Preview("OverlappingHStack") { VStack { Text("All of these should be the same height.") diff --git a/Sources/UI/Pasteboard.swift b/Sources/UI/Pasteboard.swift index 46048db..5e078c8 100644 --- a/Sources/UI/Pasteboard.swift +++ b/Sources/UI/Pasteboard.swift @@ -204,7 +204,7 @@ public extension Compatibility { } #if compiler(>=5.9) -@available(iOS 13, macOS 12, tvOS 13, watchOS 6, *) +@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Pasteboard { /// Deterministic pasteboard tests shared by the in-app runner and Swift Testing. @MainActor