-
Notifications
You must be signed in to change notification settings - Fork 0
Add invoke() bridge for source/remote/updater #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,190 @@ | ||
| import Foundation | ||
|
|
||
| #if canImport(WebKit) | ||
| import WebKit | ||
|
|
||
| /// The native bridge for communicate with WKWebView. | ||
| @MainActor | ||
| public final class Bridge: NSObject, WKScriptMessageHandler { | ||
| public typealias Handler = @MainActor (_ params: Any?) async throws -> Any? | ||
|
|
||
| /// The `window.webkit.messageHandlers` name the web side posts to. | ||
| static let messageHandlerName = "wvbIos" | ||
|
|
||
| private(set) var handlers: [String: Handler] = [:] | ||
|
|
||
| public override init() { | ||
| super.init() | ||
| } | ||
|
|
||
| @discardableResult | ||
| public func handler(_ name: String, _ handler: @escaping Handler) -> Bridge { | ||
| handlers[name] = handler | ||
| return self | ||
| } | ||
|
|
||
| @discardableResult | ||
| public func add(_ handlers: any BridgeHandlers) -> Bridge { | ||
| handlers.register(on: self) | ||
| return self | ||
| } | ||
|
|
||
| /// Registers this bridge on `configuration` as the `wvbIos` message handler. | ||
| func install(on configuration: WKWebViewConfiguration) { | ||
| configuration.userContentController.add(self, name: Self.messageHandlerName) | ||
| } | ||
|
|
||
| public func userContentController( | ||
| _ userContentController: WKUserContentController, | ||
| didReceive message: WKScriptMessage | ||
| ) { | ||
| // WebKit exposes the message handler to every frame, so an embedded | ||
| // (possibly third-party) iframe could invoke privileged native commands. | ||
| // Only the main frame is allowed; subframe messages are dropped. | ||
| guard message.frameInfo.isMainFrame else { | ||
| Log.bridge.error("invoke message dropped: not from the main frame") | ||
| return | ||
| } | ||
| guard let body = message.body as? [String: Any], | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
|
||
| let successExpr = body["success"] as? String, | ||
| let errorExpr = body["error"] as? String | ||
| else { | ||
| // No callback to reply through: the message is dropped and the web | ||
| // `Promise` hangs with no other signal, so log it loudly. | ||
| let name = (message.body as? [String: Any])?["name"] as? String ?? "<unknown>" | ||
| Log.bridge.error( | ||
| "invoke message dropped: missing success/error callback (command: \(name, privacy: .public))" | ||
| ) | ||
| return | ||
| } | ||
| let name = body["name"] as? String ?? "" | ||
| let params = body["params"] is NSNull ? nil : body["params"] | ||
| let webView = message.webView | ||
| let handler = handlers[name] | ||
|
|
||
| // Inherits the main actor; `await` lets an async handler suspend without | ||
| // blocking the main thread, then resumes here to evaluate the reply. | ||
| Task { [weak webView] in | ||
| let js: String | ||
| do { | ||
| guard let handler else { | ||
| throw InvokeError.handlerNotFound(name) | ||
| } | ||
| let result = try await handler(params) | ||
| js = "\(successExpr)(\(try Self.encode(result)))" | ||
| } catch { | ||
| let payload = | ||
| (try? Self.encode(Self.errorJSON(error))) ?? "{\"message\":\"unknown error\"}" | ||
| js = "\(errorExpr)(\(payload))" | ||
| } | ||
| // Usually benign (page navigated, or WebKit's "unsupported type" on an | ||
| // `undefined` return from a successful reply), so a warning, not an error. | ||
| do { | ||
| _ = try await webView?.evaluateJavaScript(js) | ||
| } catch { | ||
| Log.bridge.warning( | ||
| "invoke reply eval failed (command: \(name, privacy: .public)): \(error.localizedDescription, privacy: .public)" | ||
| ) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// Builds the `{ code?, message }` error payload delivered to the webview. | ||
| static func errorJSON(_ error: Swift.Error) -> [String: Any] { | ||
| let message: String | ||
| let code: String? | ||
| if let failure = error as? BridgeFailure { | ||
| message = failure.message | ||
| code = failure.code | ||
| } else { | ||
| message = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription | ||
| code = nil | ||
| } | ||
| var json: [String: Any] = ["message": message] | ||
| if let code { json["code"] = code } | ||
| return json | ||
| } | ||
|
|
||
| /// Serializes a handler result to a JSON literal for a callback argument. | ||
| static func encode(_ value: Any?) throws -> String { | ||
| guard let value, !(value is NSNull) else { return "null" } | ||
| guard isJSONEncodable(value), let json = jsonString(value) else { | ||
| throw InvokeError.unencodableResult | ||
| } | ||
| return json | ||
| } | ||
|
|
||
| /// Whether `value` (and, recursively, its contents) is a finite JSON value | ||
| /// that `JSONSerialization` can encode without raising. | ||
| private static func isJSONEncodable(_ value: Any) -> Bool { | ||
| switch value { | ||
| case let number as NSNumber: | ||
| // Bool/Int/Double/Float all bridge to NSNumber; reject NaN/±Infinity. | ||
| return number.doubleValue.isFinite | ||
| case is String, is NSNull: | ||
| // JSON `null` decodes to NSNull and serializes back to `null`. | ||
| return true | ||
| case let array as [Any]: | ||
| return array.allSatisfy(isJSONEncodable) | ||
| case let object as [String: Any]: | ||
| return object.values.allSatisfy(isJSONEncodable) | ||
| default: | ||
| return false | ||
| } | ||
| } | ||
|
|
||
| private static func jsonString(_ value: Any) -> String? { | ||
| guard | ||
| let data = try? JSONSerialization.data(withJSONObject: value, options: [.fragmentsAllowed]), | ||
| let json = String(data: data, encoding: .utf8) | ||
| else { | ||
| return nil | ||
| } | ||
| return escapeForJS(json) | ||
| } | ||
|
|
||
| // JSON permits the raw line separators U+2028/U+2029 inside strings, but they | ||
| // are line terminators in JavaScript source and would break the | ||
| // `callback(<json>)` we evaluate. Built from scalars to keep the source ASCII. | ||
| private static let lineSeparator = String(UnicodeScalar(0x2028)!) | ||
| private static let paragraphSeparator = String(UnicodeScalar(0x2029)!) | ||
|
|
||
| private static func escapeForJS(_ string: String) -> String { | ||
| string | ||
| .replacingOccurrences(of: lineSeparator, with: "\\u2028") | ||
| .replacingOccurrences(of: paragraphSeparator, with: "\\u2029") | ||
| } | ||
| } | ||
|
|
||
| @MainActor | ||
| public protocol BridgeHandlers { | ||
| func register(on bridge: Bridge) | ||
| } | ||
|
|
||
| /// Errors raised by the ``Bridge`` dispatch itself | ||
| public enum InvokeError: Swift.Error, LocalizedError, BridgeFailure, Equatable { | ||
| /// No handler was registered for the requested command name. | ||
| case handlerNotFound(String) | ||
| /// A handler returned a value that is not a JSON value (a custom type, or a | ||
| /// non-finite number), so it cannot be delivered to the web side. | ||
| case unencodableResult | ||
|
|
||
| public var errorDescription: String? { | ||
| switch self { | ||
| case .handlerNotFound(let name): | ||
| return "no invoke handler registered for \"\(name)\"" | ||
| case .unencodableResult: | ||
| return "invoke handler returned a value that is not JSON-encodable" | ||
| } | ||
| } | ||
|
|
||
| public var code: String? { | ||
| switch self { | ||
| case .handlerNotFound: return "handler_not_found" | ||
| case .unencodableResult: return "unencodable_result" | ||
| } | ||
| } | ||
|
|
||
| public var message: String { errorDescription ?? "" } | ||
| } | ||
| #endif | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| import Foundation | ||
|
|
||
| /// Bridges raw `invoke()` payloads to typed Swift values via `Codable`. | ||
| enum BridgeCodec { | ||
| /// Decodes the `invoke()` params object into a typed arguments value. | ||
| static func decode<T: Decodable>(_ params: Any?, as type: T.Type) throws -> T { | ||
| let object = params ?? [String: Any]() | ||
| guard JSONSerialization.isValidJSONObject(object) else { | ||
| throw BridgeError(code: "invalid_params", message: "invoke params must be an object") | ||
| } | ||
| let data = try JSONSerialization.data(withJSONObject: object) | ||
| do { | ||
| return try JSONDecoder().decode(T.self, from: data) | ||
| } catch let error as DecodingError { | ||
| throw BridgeError(code: "invalid_params", message: describe(error)) | ||
| } | ||
| } | ||
|
|
||
| /// Encodes an `Encodable` response payload to a JSON-native value | ||
| /// (`[String: Any]` / `[Any]` / scalar) for the bridge reply. | ||
| static func jsonObject<T: Encodable>(_ value: T) throws -> Any { | ||
| let data = try JSONEncoder().encode(value) | ||
| return try JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed]) | ||
| } | ||
|
|
||
| private static func describe(_ error: DecodingError) -> String { | ||
| switch error { | ||
| case .keyNotFound(let key, _): | ||
| return "missing required param \"\(key.stringValue)\"" | ||
| case .typeMismatch(_, let context), .valueNotFound(_, let context): | ||
| let path = context.codingPath.map(\.stringValue).joined(separator: ".") | ||
| return path.isEmpty ? context.debugDescription : "invalid param \"\(path)\"" | ||
| case .dataCorrupted(let context): | ||
| return context.debugDescription | ||
| @unknown default: | ||
| return "invalid invoke params" | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| import Foundation | ||
|
|
||
| /// A Swift error that maps to the web-facing `{ code?, message }` bridge error | ||
| /// shape. Conform a custom error to deliver a `code` alongside its `message` | ||
| public protocol BridgeFailure: Swift.Error { | ||
| /// Optional machine-readable code, omitted from the payload when `nil`. | ||
| var code: String? { get } | ||
| /// Human-readable message, always present in the payload. | ||
| var message: String { get } | ||
| } | ||
|
|
||
| /// The canonical `{ code?, message }` error thrown to reject an `invoke()` | ||
| /// command. Other thrown errors are encoded with their localized description as | ||
| /// `message` and no `code`. | ||
| public struct BridgeError: BridgeFailure, Equatable { | ||
| public var code: String? | ||
| public var message: String | ||
|
|
||
| public init(code: String? = nil, message: String) { | ||
| self.code = code | ||
| self.message = message | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,38 +1,38 @@ | ||
| import Foundation | ||
|
|
||
| extension HttpMethod { | ||
| /// Maps a `URLRequest.httpMethod` string to the FFI ``HttpMethod``. | ||
| /// Defaults to `.get` for unknown or missing methods. | ||
| static func from(_ method: String?) -> HttpMethod { | ||
| switch method?.uppercased() { | ||
| case "GET": return .get | ||
| case "HEAD": return .head | ||
| case "OPTIONS": return .options | ||
| case "POST": return .post | ||
| case "PUT": return .put | ||
| case "PATCH": return .patch | ||
| case "DELETE": return .delete | ||
| case "TRACE": return .trace | ||
| case "CONNECT": return .connect | ||
| default: return .get | ||
| } | ||
| /// Maps a `URLRequest.httpMethod` string to the FFI ``HttpMethod``. | ||
| /// Defaults to `.get` for unknown or missing methods. | ||
| static func from(_ method: String?) -> HttpMethod { | ||
| switch method?.uppercased() { | ||
| case "GET": return .get | ||
| case "HEAD": return .head | ||
| case "OPTIONS": return .options | ||
| case "POST": return .post | ||
| case "PUT": return .put | ||
| case "PATCH": return .patch | ||
| case "DELETE": return .delete | ||
| case "TRACE": return .trace | ||
| case "CONNECT": return .connect | ||
| default: return .get | ||
| } | ||
| } | ||
| } | ||
|
|
||
| extension HttpResponse { | ||
| /// Builds an `HTTPURLResponse` for `url` from this response's status and | ||
| /// headers. | ||
| func makeURLResponse(url: URL) -> HTTPURLResponse { | ||
| HTTPURLResponse( | ||
| url: url, | ||
| statusCode: Int(status), | ||
| httpVersion: "HTTP/1.1", | ||
| headerFields: headers | ||
| ) ?? HTTPURLResponse( | ||
| url: url, | ||
| statusCode: Int(status), | ||
| httpVersion: "HTTP/1.1", | ||
| headerFields: nil | ||
| )! | ||
| } | ||
| /// Builds an `HTTPURLResponse` for `url` from this response's status and | ||
| /// headers. | ||
| func makeURLResponse(url: URL) -> HTTPURLResponse { | ||
| HTTPURLResponse( | ||
| url: url, | ||
| statusCode: Int(status), | ||
| httpVersion: "HTTP/1.1", | ||
| headerFields: headers | ||
| ) ?? HTTPURLResponse( | ||
| url: url, | ||
| statusCode: Int(status), | ||
| httpVersion: "HTTP/1.1", | ||
| headerFields: nil | ||
| )! | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| import Foundation | ||
| import os | ||
|
|
||
| /// Severity of an SDK log event; mirrors Rust `tracing` levels so core events | ||
| /// can forward into the same pipeline (see ``CoreLog``). | ||
| enum LogLevel: Int, Sendable, Comparable { | ||
| case trace, debug, info, warning, error | ||
|
|
||
| static func < (lhs: LogLevel, rhs: LogLevel) -> Bool { lhs.rawValue < rhs.rawValue } | ||
|
|
||
| /// `os` has no `warning`, so it folds into `.default`. | ||
| var osLogType: OSLogType { | ||
| switch self { | ||
| case .trace, .debug: return .debug | ||
| case .info: return .info | ||
| case .warning: return .default | ||
| case .error: return .error | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// Unified `os.Logger` channels. Filter on `subsystem == "webview-bundle"` to | ||
| /// see Swift-side and (once enabled) Rust-core logs together. | ||
| enum Log { | ||
| static let subsystem = "webview-bundle" | ||
|
|
||
| static let bridge = Logger(subsystem: subsystem, category: "bridge") | ||
| static let core = Logger(subsystem: subsystem, category: "core") | ||
| } | ||
|
|
||
| /// Seam for forwarding the Rust core's `tracing` into the unified `core` | ||
| /// channel. The level/route mapping is implemented; wiring it to an FFI | ||
| /// log-subscriber callback is pending (the FFI exposes none yet). | ||
| enum CoreLog { | ||
| /// `message` is already formatted by the core; `target` is its module path. | ||
| /// Logged `.public` since tracing is an explicit opt-in, so the core must not | ||
| /// emit user PII into tracing messages. | ||
| static func forward(level: LogLevel, target: String, message: String) { | ||
| Log.core.log( | ||
| level: level.osLogType, | ||
| "[\(target, privacy: .public)] \(message, privacy: .public)") | ||
| } | ||
| } | ||
|
|
||
| extension WebViewBundle { | ||
| /// The unified-logging subsystem the SDK logs under. | ||
| public static let logSubsystem = Log.subsystem | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P2:
install(on:)is not idempotent and can crash when called more than once on the same configuration. Remove existing handler before re-addingwvbIos.Prompt for AI agents