Skip to content

Commit f3d8af7

Browse files
Merge pull request #4 from Compiler-Inc/chore/formatter-run-2
feat: swiftformat run
2 parents cd84518 + e88924f commit f3d8af7

29 files changed

+327
-322
lines changed

.swiftformat

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
--disable preferForLoop

Package.swift

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,10 @@ let package = Package(
88
products: [.library(name: "CompilerSwiftAI", targets: ["CompilerSwiftAI"])],
99
dependencies: [
1010
.package(url: "https://github.com/gonzalezreal/swift-markdown-ui", from: "2.4.1"),
11-
.package(url: "https://github.com/Compiler-Inc/Transcriber", branch: "main")
11+
.package(url: "https://github.com/Compiler-Inc/Transcriber", branch: "main"),
1212
],
1313
targets: [
14-
.target(name: "CompilerSwiftAI", dependencies: ["Transcriber", .product(name: "MarkdownUI", package: "swift-markdown-ui")] ),
14+
.target(name: "CompilerSwiftAI", dependencies: ["Transcriber", .product(name: "MarkdownUI", package: "swift-markdown-ui")]),
1515
.testTarget(name: "CompilerSwiftAITests", dependencies: ["CompilerSwiftAI"]),
1616
]
1717
)
18-

Sources/CompilerSwiftAI/Auth/CompilerCient+AppleAuth.swift

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,30 +2,31 @@
22

33
import AuthenticationServices
44

5-
extension CompilerClient {
6-
public func handleSignInWithApple(_ result: Result<ASAuthorization, Error>, nonce: String?) async throws -> Bool {
5+
public extension CompilerClient {
6+
func handleSignInWithApple(_ result: Result<ASAuthorization, Error>, nonce: String?) async throws -> Bool {
77
switch result {
8-
case .success(let auth):
8+
case let .success(auth):
99
guard let appleIDCredential = auth.credential as? ASAuthorizationAppleIDCredential,
1010
let idTokenData = appleIDCredential.identityToken,
11-
let idToken = String(data: idTokenData, encoding: .utf8) else {
11+
let idToken = String(data: idTokenData, encoding: .utf8)
12+
else {
1213
throw AuthError.invalidToken
1314
}
14-
15+
1516
// Store Apple ID token
1617
await keychain.save(idToken, service: "apple-id-token", account: "user")
17-
18+
1819
// Store the nonce for verification
1920
if let nonce = nonce {
2021
await keychain.save(nonce, service: "apple-nonce", account: "user")
2122
}
22-
23+
2324
let accessToken = try await authenticateWithServer(idToken: idToken, nonce: nonce)
2425
await keychain.save(accessToken, service: "access-token", account: "user")
25-
26+
2627
return true
27-
28-
case .failure(let error):
28+
29+
case let .failure(error):
2930
throw AuthError.networkError(error)
3031
}
3132
}

Sources/CompilerSwiftAI/Auth/CompilerClient+Auth.swift

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ extension CompilerClient {
1515
/// - Returns: Token string
1616
func getValidToken() async throws -> String {
1717
// First try to get the stored apple id token
18-
if let token = await keychain.read(service: "apple-id-token", account: "user") {
18+
if let token = await keychain.read(service: "apple-id-token", account: "user") {
1919
do {
2020
// Try to refresh the token
2121
let newToken = try await authenticateWithServer(idToken: token)
@@ -27,42 +27,42 @@ extension CompilerClient {
2727
}
2828
throw AuthError.invalidToken
2929
}
30-
30+
3131
func authenticateWithServer(idToken: String, nonce: String? = nil) async throws -> String {
3232
let lowercasedAppID = appID.uuidString.lowercased()
3333
let endpoint = "\(baseURL)/v1/apps/\(lowercasedAppID)/end-users/apple"
3434
guard let url = URL(string: endpoint) else {
3535
authLogger.error("Invalid URL: \(self.baseURL)")
3636
throw AuthError.invalidResponse
3737
}
38-
38+
3939
var body: [String: String] = ["id_token": idToken]
4040
if let nonce {
4141
body["nonce"] = nonce
4242
}
4343
authLogger.debug("Making auth request to: \(endpoint)")
44-
44+
4545
var request = URLRequest(url: url)
4646
request.httpMethod = "POST"
4747
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
4848
request.httpBody = try JSONEncoder().encode(body)
49-
49+
5050
authLogger.debug("Request body: \(body)")
51-
51+
5252
let (data, response) = try await URLSession.shared.data(for: request)
53-
53+
5454
guard let httpResponse = response as? HTTPURLResponse else {
5555
authLogger.error("Invalid response type received")
5656
throw AuthError.invalidResponse
5757
}
58-
58+
5959
authLogger.debug("Response status: \(httpResponse.statusCode)")
6060
if let responseString = String(data: data, encoding: .utf8) {
6161
authLogger.debug("Response body: \(responseString)")
6262
}
6363

6464
switch httpResponse.statusCode {
65-
case 200...299:
65+
case 200 ... 299:
6666
struct AuthResponse: Codable { let access_token: String }
6767
let authResponse = try JSONDecoder().decode(AuthResponse.self, from: data)
6868
authLogger.debug("Successfully got access token")
@@ -81,7 +81,7 @@ extension CompilerClient {
8181
throw AuthError.serverError("Server returned status code \(httpResponse.statusCode)")
8282
}
8383
}
84-
84+
8585
/// Try to login, taking advantage of any still-valid access tokens
8686
/// - Returns: Success state of the login
8787
public func attemptAutoLogin() async throws -> Bool {
Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
import CryptoKit
21
import AuthenticationServices
2+
import CryptoKit
33

4-
extension CompilerClient {
4+
public extension CompilerClient {
55
// Generate a random nonce for authentication
6-
public static func randomNonceString(length: Int = 32) -> String {
6+
static func randomNonceString(length: Int = 32) -> String {
77
precondition(length > 0)
88
let charset: [Character] = Array("0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._")
99
var result = ""
1010
var remainingLength = length
11-
11+
1212
while remainingLength > 0 {
1313
let randoms: [UInt8] = (0 ..< 16).map { _ in
1414
var random: UInt8 = 0
@@ -18,30 +18,30 @@ extension CompilerClient {
1818
}
1919
return random
2020
}
21-
21+
2222
randoms.forEach { random in
2323
if remainingLength == 0 {
2424
return
2525
}
26-
26+
2727
if random < charset.count {
2828
result.append(charset[Int(random)])
2929
remainingLength -= 1
3030
}
3131
}
3232
}
33-
33+
3434
return result
3535
}
36-
36+
3737
// Compute the SHA256 hash of a string
38-
public static func sha256(_ input: String) -> String {
38+
static func sha256(_ input: String) -> String {
3939
let inputData = Data(input.utf8)
4040
let hashedData = SHA256.hash(data: inputData)
4141
let hashString = hashedData.compactMap {
4242
String(format: "%02x", $0)
4343
}.joined()
44-
44+
4545
return hashString
4646
}
4747
}

Sources/CompilerSwiftAI/Auth/KeychainHelper.swift

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,45 +6,46 @@ import SwiftUI
66
/// Helper for Keychain operations
77
actor KeychainHelper {
88
static let standard = KeychainHelper()
9-
9+
1010
func save(_ data: String, service: String, account: String) async {
1111
guard let data = data.data(using: .utf8) else { return }
12-
12+
1313
let query = [
1414
kSecValueData: data,
1515
kSecClass: kSecClassGenericPassword,
1616
kSecAttrService: service,
1717
kSecAttrAccount: account,
1818
] as CFDictionary
19-
19+
2020
// First remove any existing item
2121
SecItemDelete(query)
22-
22+
2323
// Add the new item
2424
let status = SecItemAdd(query, nil)
2525
guard status == errSecSuccess else {
2626
print("Error saving to Keychain: \(status)")
2727
return
2828
}
2929
}
30-
30+
3131
func read(service: String, account: String) async -> String? {
3232
let query = [
3333
kSecClass: kSecClassGenericPassword,
3434
kSecAttrService: service,
3535
kSecAttrAccount: account,
36-
kSecReturnData: true
36+
kSecReturnData: true,
3737
] as CFDictionary
38-
38+
3939
var result: AnyObject?
4040
let status = SecItemCopyMatching(query, &result)
41-
41+
4242
guard status == errSecSuccess,
4343
let data = result as? Data,
44-
let string = String(data: data, encoding: .utf8) else {
44+
let string = String(data: data, encoding: .utf8)
45+
else {
4546
return nil
4647
}
47-
48+
4849
return string
4950
}
5051
}

Sources/CompilerSwiftAI/CompilerClient.swift

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ public final actor CompilerClient {
99
public var streamingChat: StreamConfiguration
1010
/// Whether to enable debug logging
1111
public var enableDebugLogging: Bool
12-
12+
1313
/// Initialize a new Configuration instance
1414
/// - Parameters:
1515
/// - streamingChat: The streaming configuration to use for chat interactions, defaults to OpenAI GPT-4
@@ -22,41 +22,41 @@ public final actor CompilerClient {
2222
self.enableDebugLogging = enableDebugLogging
2323
}
2424
}
25-
25+
2626
/// Application ID (retrievable from the Comiler Developer Dashboard)
2727
let appID: UUID
28-
28+
2929
private(set) var configuration: Configuration
3030

31-
internal let baseURL: String = "https://backend.compiler.inc"
32-
internal let keychain: KeychainHelper = KeychainHelper.standard
33-
internal let functionLogger: DebugLogger
34-
internal let modelLogger: DebugLogger
35-
internal let authLogger: DebugLogger
36-
31+
let baseURL: String = "https://backend.compiler.inc"
32+
let keychain: KeychainHelper = .standard
33+
let functionLogger: DebugLogger
34+
let modelLogger: DebugLogger
35+
let authLogger: DebugLogger
36+
3737
/// Initialize the Compiler Client
3838
/// - Parameters:
3939
/// - appID: Application ID (retrievable from the Comiler Developer Dashboard)
4040
/// - configuration: Client configuration including streaming chat settings and debug options
4141
public init(
42-
appID: UUID,
42+
appID: UUID,
4343
configuration: Configuration = Configuration()
4444
) {
4545
self.appID = appID
4646
self.configuration = configuration
47-
self.functionLogger = DebugLogger(Logger.functionCalls, isEnabled: configuration.enableDebugLogging)
48-
self.modelLogger = DebugLogger(Logger.modelCalls, isEnabled: configuration.enableDebugLogging)
49-
self.authLogger = DebugLogger(Logger.auth, isEnabled: configuration.enableDebugLogging)
47+
functionLogger = DebugLogger(Logger.functionCalls, isEnabled: configuration.enableDebugLogging)
48+
modelLogger = DebugLogger(Logger.modelCalls, isEnabled: configuration.enableDebugLogging)
49+
authLogger = DebugLogger(Logger.auth, isEnabled: configuration.enableDebugLogging)
5050
}
51-
51+
5252
/// Update streaming chat configuration
5353
/// - Parameter update: Closure that takes an inout StreamConfiguration parameter
5454
public func updateStreamingChat(
5555
_ update: (inout StreamConfiguration) -> Void
5656
) {
5757
update(&configuration.streamingChat)
5858
}
59-
59+
6060
/// Creates an immutable streaming session configuration
6161
/// This captures the current streaming configuration at a point in time
6262
public func makeStreamingSession() -> StreamConfiguration {

Sources/CompilerSwiftAI/Function Calling/CompilerClient+Functions.swift

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,24 +16,24 @@ extension CompilerClient {
1616
/// - state: Current state of your app (as defined by the developer, only needs to conform to Encodable and Sendable)
1717
/// - token: Authorization token
1818
/// - Returns: An array of functions with Parameters that are both Decodable and Sendable
19-
public func processFunction<State: Encodable & Sendable, Parameters: Decodable & Sendable>(_ prompt: String, for state: State, using token: String) async throws -> [Function<Parameters>] {
19+
public func processFunction<State: Encodable & Sendable, Parameters: Decodable & Sendable>(_ prompt: String, for state: State, using _: String) async throws -> [Function<Parameters>] {
2020
functionLogger.debug("Starting processFunction with prompt: \(prompt)")
2121

2222
let endpoint = "\(baseURL)/v1/function-call/\(appID.uuidString)"
23-
23+
2424
guard let url = URL(string: endpoint) else {
2525
functionLogger.error("Invalid URL: \(self.baseURL)")
2626
throw URLError(.badURL)
2727
}
28-
28+
2929
functionLogger.debug("URL created: \(url)")
3030

3131
let request = Request(id: appID.uuidString, prompt: prompt, state: state)
3232

3333
var urlRequest = URLRequest(url: url)
3434
urlRequest.httpMethod = "POST"
3535
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
36-
36+
3737
// Get a fresh token
3838
let token = try await getValidToken()
3939
urlRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
@@ -64,7 +64,4 @@ extension CompilerClient {
6464
throw error
6565
}
6666
}
67-
68-
69-
7067
}

Sources/CompilerSwiftAI/Logger.swift

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,13 @@ import OSLog
44

55
extension Logger {
66
private static let subsystem = "CompilerSwiftAI"
7-
7+
88
/// Logs related to function calling and processing
99
static let functionCalls = Logger(subsystem: subsystem, category: "functionCalls")
10-
10+
1111
/// Logs related to model calls, streaming, and responses
1212
static let modelCalls = Logger(subsystem: subsystem, category: "modelCalls")
13-
13+
1414
/// Logs related to authentication and token management
1515
static let auth = Logger(subsystem: subsystem, category: "auth")
1616
}
@@ -19,17 +19,17 @@ extension Logger {
1919
struct DebugLogger {
2020
private let logger: Logger
2121
private let isEnabled: Bool
22-
22+
2323
init(_ logger: Logger, isEnabled: Bool) {
2424
self.logger = logger
2525
self.isEnabled = isEnabled
2626
}
27-
27+
2828
func debug(_ message: @escaping @autoclosure () -> String) {
2929
guard isEnabled else { return }
3030
logger.debug("\(message())")
3131
}
32-
32+
3333
func error(_ message: @escaping @autoclosure () -> String) {
3434
// Always log errors, regardless of debug mode
3535
logger.error("\(message())")

0 commit comments

Comments
 (0)