react-native-minimal-webview 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +150 -2
- package/android/build.gradle +26 -0
- package/android/consumer-rules.pro +4 -0
- package/android/src/main/AndroidManifest.xml +2 -0
- package/android/src/main/java/expo/modules/minimalwebview/Asks.kt +44 -0
- package/android/src/main/java/expo/modules/minimalwebview/DocumentEnd.kt +31 -0
- package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +487 -0
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +507 -0
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +358 -0
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +245 -0
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +199 -0
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +197 -0
- package/android/src/main/java/expo/modules/minimalwebview/NavigationRules.kt +113 -0
- package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +303 -0
- package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +76 -0
- package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +259 -0
- package/android/src/main/java/expo/modules/minimalwebview/requests/FileUpload.kt +44 -0
- package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +87 -0
- package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +77 -0
- package/build/WebView.d.ts +96 -0
- package/build/WebView.d.ts.map +1 -0
- package/build/WebView.js +453 -0
- package/build/WebView.js.map +1 -0
- package/build/bridge/createBridge.d.ts +32 -0
- package/build/bridge/createBridge.d.ts.map +1 -0
- package/build/bridge/createBridge.js +137 -0
- package/build/bridge/createBridge.js.map +1 -0
- package/build/bridge/endpoint.d.ts +33 -0
- package/build/bridge/endpoint.d.ts.map +1 -0
- package/build/bridge/endpoint.js +105 -0
- package/build/bridge/endpoint.js.map +1 -0
- package/build/bridge/origins.d.ts +25 -0
- package/build/bridge/origins.d.ts.map +1 -0
- package/build/bridge/origins.js +59 -0
- package/build/bridge/origins.js.map +1 -0
- package/build/bridge/pageClient.generated.d.ts +3 -0
- package/build/bridge/pageClient.generated.d.ts.map +1 -0
- package/build/bridge/pageClient.generated.js +4 -0
- package/build/bridge/pageClient.generated.js.map +1 -0
- package/build/bridge/protocol.d.ts +50 -0
- package/build/bridge/protocol.d.ts.map +1 -0
- package/build/bridge/protocol.js +52 -0
- package/build/bridge/protocol.js.map +1 -0
- package/build/defaultNavigationRules.d.ts +15 -0
- package/build/defaultNavigationRules.d.ts.map +1 -0
- package/build/defaultNavigationRules.js +22 -0
- package/build/defaultNavigationRules.js.map +1 -0
- package/build/index.d.ts +31 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +30 -0
- package/build/index.js.map +1 -0
- package/build/platform.generated.d.ts +701 -0
- package/build/platform.generated.d.ts.map +1 -0
- package/build/platform.generated.js +201 -0
- package/build/platform.generated.js.map +1 -0
- package/build/reactNativeWebViewDefaults.d.ts +21 -0
- package/build/reactNativeWebViewDefaults.d.ts.map +1 -0
- package/build/reactNativeWebViewDefaults.js +12 -0
- package/build/reactNativeWebViewDefaults.js.map +1 -0
- package/build/reactNativeWebViewMessages.d.ts +16 -0
- package/build/reactNativeWebViewMessages.d.ts.map +1 -0
- package/build/reactNativeWebViewMessages.js +24 -0
- package/build/reactNativeWebViewMessages.js.map +1 -0
- package/build/refStore.d.ts +32 -0
- package/build/refStore.d.ts.map +1 -0
- package/build/refStore.js +115 -0
- package/build/refStore.js.map +1 -0
- package/build/types.d.ts +1173 -0
- package/build/types.d.ts.map +1 -0
- package/build/types.defaults.d.ts +8 -0
- package/build/types.defaults.d.ts.map +1 -0
- package/build/types.defaults.js +17 -0
- package/build/types.defaults.js.map +1 -0
- package/build/types.js +2 -0
- package/build/types.js.map +1 -0
- package/expo-module.config.json +9 -0
- package/ios/Asks.swift +45 -0
- package/ios/DelegateProxy.swift +158 -0
- package/ios/DocumentEnd.swift +22 -0
- package/ios/DownloadName.swift +10 -0
- package/ios/Downloads.swift +51 -0
- package/ios/Hooks.swift +310 -0
- package/ios/Loads.swift +44 -0
- package/ios/MRWExceptions.h +9 -0
- package/ios/MRWExceptions.m +10 -0
- package/ios/MRWInvoke.h +38 -0
- package/ios/MRWInvoke.m +187 -0
- package/ios/MinimalWebView+Dialogs.swift +96 -0
- package/ios/MinimalWebView+Navigation.swift +243 -0
- package/ios/MinimalWebView+Scripts.swift +92 -0
- package/ios/MinimalWebView.docc/MinimalWebView.md +13 -0
- package/ios/MinimalWebView.podspec +32 -0
- package/ios/MinimalWebView.swift +513 -0
- package/ios/MinimalWebViewModule.swift +110 -0
- package/ios/NavigationRules.swift +123 -0
- package/ios/OriginRules.swift +36 -0
- package/ios/PlatformCompletions.generated.swift +39 -0
- package/ios/PlatformSettings.swift +252 -0
- package/ios/ReadAccess.swift +19 -0
- package/ios/Recovery.swift +25 -0
- package/ios/SharedCookies.swift +59 -0
- package/package.json +99 -4
- package/src/WebView.tsx +626 -0
- package/src/bridge/createBridge.ts +178 -0
- package/src/bridge/endpoint.ts +123 -0
- package/src/bridge/origins.ts +61 -0
- package/src/bridge/pageClient.generated.ts +5 -0
- package/src/bridge/pageClient.ts +67 -0
- package/src/bridge/protocol.ts +78 -0
- package/src/defaultNavigationRules.ts +24 -0
- package/src/index.ts +37 -0
- package/src/platform.generated.ts +693 -0
- package/src/reactNativeWebViewDefaults.ts +13 -0
- package/src/reactNativeWebViewMessages.ts +26 -0
- package/src/refStore.ts +165 -0
- package/src/types.defaults.ts +24 -0
- package/src/types.ts +1240 -0
package/ios/Hooks.swift
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
import WebKit
|
|
2
|
+
|
|
3
|
+
/// Native hooks: Swift in your own Expo module that gets the real WKWebView behind each WebView, its creation-time
|
|
4
|
+
/// configuration and a ``WebViewContext``, with no protocol to implement.
|
|
5
|
+
///
|
|
6
|
+
/// A hook attaches to each WebView whose `extensions` prop has an extension with its key that is on;
|
|
7
|
+
/// [`HookExtension.options`](https://rasmuskard.github.io/react-native-minimal-webview/typescript/react-native-minimal-webview/type-aliases/HookExtension/#options)
|
|
8
|
+
/// says when.
|
|
9
|
+
///
|
|
10
|
+
/// - Important: Leave alone what the core owns: the WKWebView's own `navigationDelegate` and `uiDelegate` (add to the
|
|
11
|
+
/// context's lists instead), and the bridge's script message handler and user scripts.
|
|
12
|
+
///
|
|
13
|
+
/// ## See Also
|
|
14
|
+
/// - [Native hooks guide](https://rasmuskard.github.io/react-native-minimal-webview/guides/native-hooks/)
|
|
15
|
+
public enum MinimalWebViewHooks {
|
|
16
|
+
struct Hook {
|
|
17
|
+
let key: String
|
|
18
|
+
/// Where it was registered, `#fileID:#line`: the same place again is a JS reload, not a second hook.
|
|
19
|
+
let site: String
|
|
20
|
+
let webViewClass: WKWebView.Type?
|
|
21
|
+
let configure: ((WKWebViewConfiguration, WebViewContext) -> Void)?
|
|
22
|
+
let attach: (WKWebView, WebViewContext) -> Void
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
private(set) static var hooks: [Hook] = []
|
|
26
|
+
|
|
27
|
+
/// Registers the hook for `key`.
|
|
28
|
+
///
|
|
29
|
+
/// Call it from your module's `OnCreate`, before the first WebView.
|
|
30
|
+
///
|
|
31
|
+
/// A second hook under a key stops the app with `fatalError`, naming the key and both call sites. A hook under `core`
|
|
32
|
+
/// is logged and not registered.
|
|
33
|
+
///
|
|
34
|
+
/// The same call running again replaces its hook: a JS reload creates the modules anew and runs their `OnCreate`
|
|
35
|
+
/// again. A helper that calls `register` for other code is one call site, so a second hook through it replaces the
|
|
36
|
+
/// first silently, unless the helper passes its caller's `file` and `line` on.
|
|
37
|
+
///
|
|
38
|
+
/// Hooks are configured and attached in registration order, which across packages is autolinking's: packages sorted
|
|
39
|
+
/// by name. A hook whose key turns on after the WebView was created attaches after the hooks attached already.
|
|
40
|
+
///
|
|
41
|
+
/// - Parameters:
|
|
42
|
+
/// - key: The key of the app's extension that turns on the hook. Keys are global, so prefix yours with your
|
|
43
|
+
/// package's name.
|
|
44
|
+
/// - webViewClass: The WKWebView subclass that each WebView enabling this hook is made from, to override what
|
|
45
|
+
/// WKWebView lets a subclass override; nil leaves the class to the other hooks. When the enabled hooks name
|
|
46
|
+
/// different classes, the first one's in registration order makes the view, and a warning names the
|
|
47
|
+
/// others. Those still attach, so check the class `attach` gets. The hidden view that `window.open('')` gets is
|
|
48
|
+
/// always a plain WKWebView.
|
|
49
|
+
/// - configure: Runs before the WKWebView exists, with the configuration it is created from: after the
|
|
50
|
+
/// `ios.configuration` settings and before the bridge, so replacing the user content controller is fine. User
|
|
51
|
+
/// scripts you add stay, and run after the package's. It gets the same context that `attach` gets next, so state
|
|
52
|
+
/// it makes can be keyed by the context. `window.open('')` opens a hidden WKWebView from this configuration: your
|
|
53
|
+
/// user scripts run in it and your script message handlers get its messages, so compare `message.webView` with
|
|
54
|
+
/// the WKWebView `attach` gets.
|
|
55
|
+
/// - attach: Runs once the WKWebView exists and its settings are applied, so what it sets wins over them. Register
|
|
56
|
+
/// what to run when the view goes away with ``WebViewContext/onDestroyed(_:)``. A renderer crash
|
|
57
|
+
/// reloads the same WKWebView, so nothing attaches again (see ``DocumentEnd/crashed``).
|
|
58
|
+
/// - file: With `line`, the call site that tells a reload from a second hook; leave both to their defaults.
|
|
59
|
+
/// - line: The call site's line, with `file`.
|
|
60
|
+
public static func register(
|
|
61
|
+
_ key: String,
|
|
62
|
+
webViewClass: WKWebView.Type? = nil,
|
|
63
|
+
configure: ((WKWebViewConfiguration, WebViewContext) -> Void)? = nil,
|
|
64
|
+
attach: @escaping (WKWebView, WebViewContext) -> Void,
|
|
65
|
+
file: String = #fileID,
|
|
66
|
+
line: Int = #line
|
|
67
|
+
) {
|
|
68
|
+
guard key != "core" else { return NSLog("[react-native-minimal-webview] the hook key `core` is reserved: the hook is not registered") }
|
|
69
|
+
let hook = Hook(key: key, site: "\(file):\(line)", webViewClass: webViewClass, configure: configure, attach: attach)
|
|
70
|
+
guard let index = hooks.firstIndex(where: { $0.key == key }) else { return hooks.append(hook) }
|
|
71
|
+
guard hooks[index].site == hook.site else {
|
|
72
|
+
fatalError(
|
|
73
|
+
"[react-native-minimal-webview] two hooks are registered under `\(key)`, at \(hooks[index].site) and \(hook.site): "
|
|
74
|
+
+ "prefix yours with your package's name"
|
|
75
|
+
)
|
|
76
|
+
}
|
|
77
|
+
hooks[index] = hook
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/// One WebView as one hook sees it, for the life of the WKWebView.
|
|
82
|
+
///
|
|
83
|
+
/// Call ``emit(_:_:)`` and ``ask(_:_:_:)`` from any thread, and the rest on the main thread, where `configure`,
|
|
84
|
+
/// `attach`, the handlers and the answers run.
|
|
85
|
+
///
|
|
86
|
+
/// A context kept after the view closed does nothing.
|
|
87
|
+
///
|
|
88
|
+
/// A hook is on while its extension's `options` are not null or false;
|
|
89
|
+
/// [`HookExtension.options`](https://rasmuskard.github.io/react-native-minimal-webview/typescript/react-native-minimal-webview/type-aliases/HookExtension/#options)
|
|
90
|
+
/// says what off means. ``onOptions(_:)`` runs when the hook turns off, so it can undo what it set up, and again when
|
|
91
|
+
/// it turns on.
|
|
92
|
+
///
|
|
93
|
+
/// Values from JS arrive as Foundation's JSON types: a number as `NSNumber`, an object as `NSDictionary`, an array as
|
|
94
|
+
/// `NSArray`. In an ask's answer and a ``handle(_:_:)`` handler's arguments, null is nil at the top level and `NSNull`
|
|
95
|
+
/// inside an array or object.
|
|
96
|
+
///
|
|
97
|
+
/// ## See Also
|
|
98
|
+
/// - [Native hooks guide](https://rasmuskard.github.io/react-native-minimal-webview/guides/native-hooks/)
|
|
99
|
+
public protocol WebViewContext: AnyObject {
|
|
100
|
+
/// This hook's extension's `options`, the new ones after a change; nil while the hook is off.
|
|
101
|
+
var options: Any? { get }
|
|
102
|
+
/// The committed URL, the one `useWebViewState` reports; empty before the first commit.
|
|
103
|
+
///
|
|
104
|
+
/// Inside ``onDocumentEnd(_:)`` it is still the page that ended.
|
|
105
|
+
var url: String { get }
|
|
106
|
+
/// Your navigation delegates, in order. While the hook is off, none of them gets a callback.
|
|
107
|
+
///
|
|
108
|
+
/// WebKit reads which callbacks a delegate implements when it is assigned, so a delegate must implement what it
|
|
109
|
+
/// handles by the time you add it.
|
|
110
|
+
///
|
|
111
|
+
/// Each callback reaches the delegates by one of these rules:
|
|
112
|
+
/// - A decision, the action or the response policy, goes to the first delegate that implements it, instead of the
|
|
113
|
+
/// core. Either action policy variant, with or without `preferences`, counts, and that delegate's own variant is
|
|
114
|
+
/// called.
|
|
115
|
+
/// - The authentication challenge goes to each delegate that implements it, in order, until one answers other than
|
|
116
|
+
/// `.performDefaultHandling`; when none does, WebKit's default handling. Each must call its completion handler
|
|
117
|
+
/// exactly once, and the next delegate gets the challenge only after that.
|
|
118
|
+
/// - Every other callback the core implements reaches the core, then each delegate that implements it.
|
|
119
|
+
/// - `didStartProvisionalNavigation` and `didReceiveServerRedirectForProvisionalNavigation` reach each delegate that
|
|
120
|
+
/// implements them.
|
|
121
|
+
/// - Any other callback goes only to the first delegate that implements it.
|
|
122
|
+
///
|
|
123
|
+
/// Taking a decision switches off what the core decides from the app's props or their defaults, the default
|
|
124
|
+
/// navigation rules' security checks included, and a warning names the callback and what stops applying. A
|
|
125
|
+
/// delegate that takes the action policy decides navigations instead of the navigation rules, which still decide new
|
|
126
|
+
/// windows unless a UI delegate takes `createWebViewWith`. A new window the rules allow loads in place, and that load
|
|
127
|
+
/// reaches the delegate that takes the action policy.
|
|
128
|
+
///
|
|
129
|
+
/// A decision more than one delegate implements still goes only to the first, and a warning names it. Each
|
|
130
|
+
/// warning comes once per WebView, when the delegate is added.
|
|
131
|
+
///
|
|
132
|
+
/// While `onDownload` is set, a delegate whose `didBecome` sets `download.delegate` takes the download, and
|
|
133
|
+
/// `onDownload` gets nothing for it.
|
|
134
|
+
var navigationDelegates: [WKNavigationDelegate] { get set }
|
|
135
|
+
/// Your UI delegates, in order, by the rules of ``navigationDelegates``.
|
|
136
|
+
///
|
|
137
|
+
/// Their decisions are `createWebViewWith`, the alert, confirm and prompt panels and the media capture permission.
|
|
138
|
+
/// `webViewDidClose` reaches every delegate.
|
|
139
|
+
///
|
|
140
|
+
/// A callback goes only to the list of the protocol that declares it: a navigation delegate's alert panel, or a UI
|
|
141
|
+
/// delegate's action policy, is never called.
|
|
142
|
+
///
|
|
143
|
+
/// A delegate that holds a panel's completion handler should set `webView.accessibilityElementsHidden` until it
|
|
144
|
+
/// answers, as the core does for its own panels: an accessibility query (XCTest's) into the blocked page hangs.
|
|
145
|
+
var uiDelegates: [WKUIDelegate] { get set }
|
|
146
|
+
/// The control `pullToRefresh` shows: the same one for the view's life, shown or not; nil once the view has closed.
|
|
147
|
+
///
|
|
148
|
+
/// Style it (`tintColor`), but leave its actions and where it is shown to the core.
|
|
149
|
+
var refreshControl: UIRefreshControl? { get }
|
|
150
|
+
/// Sends an event to JS: the extension with the hook's key gets `{ name, payload }` in its `onEvent`. It is dropped
|
|
151
|
+
/// while the hook is off, and after the view closed.
|
|
152
|
+
func emit(_ name: String, _ payload: [String: Any])
|
|
153
|
+
/// Sends the event as ``emit(_:_:)`` does, and calls `onAnswer` with the extension's `onEvent` return value, a
|
|
154
|
+
/// promise awaited.
|
|
155
|
+
///
|
|
156
|
+
/// It answers nil when the handler throws or there is none, or when the Document ends first; there is no timeout. It
|
|
157
|
+
/// answers nil at once while the hook is off, and after the view closed.
|
|
158
|
+
/// An ask made before the first commit (in `attach`, or after a crash) belongs to the Document that commit opens.
|
|
159
|
+
func ask(_ name: String, _ payload: [String: Any], _ onAnswer: @escaping (Any?) -> Void)
|
|
160
|
+
/// Runs `handler` at once with this hook's extension's `options`, then with the new ones each time they change,
|
|
161
|
+
/// live; nil while the hook is off.
|
|
162
|
+
///
|
|
163
|
+
/// A change from one off value to another doesn't run it, and a context kept after the view closed never does.
|
|
164
|
+
func onOptions(_ handler: @escaping (_ options: Any?) -> Void)
|
|
165
|
+
/// Runs `handler` at each end of the Document (see ``DocumentEnd``), after the core's own resets: per-page
|
|
166
|
+
/// state belongs here.
|
|
167
|
+
func onDocumentEnd(_ handler: @escaping (DocumentEnd) -> Void)
|
|
168
|
+
/// Runs `handler` once this view closes, with ``DocumentEnd/closing``, the only reason it gets on iOS.
|
|
169
|
+
///
|
|
170
|
+
/// It comes after the ``onDocumentEnd(_:)`` handlers that get `closing`. The WKWebView has stopped loading, paused
|
|
171
|
+
/// its media, lost every script message handler (yours too) and left the view by then, but is still alive, and the
|
|
172
|
+
/// context does nothing.
|
|
173
|
+
///
|
|
174
|
+
/// Clean up here: what `attach` set up on the WKWebView, such as an observation or a swapped class.
|
|
175
|
+
func onDestroyed(_ handler: @escaping (DocumentEnd) -> Void)
|
|
176
|
+
/// Answers JS's `ref.hook("<key>", method, args)`: `handler` gets the arguments, which cross as JSON, and a
|
|
177
|
+
/// ``HookReply``, which it calls with the reply or fails, then or later.
|
|
178
|
+
///
|
|
179
|
+
/// One handler per method: the last one wins. A handler that never replies leaves the call waiting until the view
|
|
180
|
+
/// unmounts: a navigation or a crash doesn't settle it.
|
|
181
|
+
func handle(_ method: String, _ handler: @escaping (_ args: [Any], _ reply: HookReply) -> Void)
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/// The answer to one JS `ref.hook` call, which a ``WebViewContext/handle(_:_:)`` handler gets: call it with the value
|
|
185
|
+
/// the call resolves with, or ``fail(_:)`` it.
|
|
186
|
+
///
|
|
187
|
+
/// Only the first reply or fail counts: any after it does nothing. Call it from any thread.
|
|
188
|
+
public final class HookReply {
|
|
189
|
+
private let resolve: (Any?) -> Void
|
|
190
|
+
private let reject: (String) -> Void
|
|
191
|
+
private let lock = NSLock()
|
|
192
|
+
private var settled = false
|
|
193
|
+
|
|
194
|
+
init(resolve: @escaping (Any?) -> Void, reject: @escaping (String) -> Void) {
|
|
195
|
+
self.resolve = resolve
|
|
196
|
+
self.reject = reject
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/// Resolves the JS call with `value`, converted as `ref.call`'s results are: JSON types, and also an `NSURL`, `NSDate`,
|
|
200
|
+
/// `NSData`, `UIImage`, `NSHTTPCookie`, `NSSet` or geometry struct; any other object arrives as null, and a non-finite
|
|
201
|
+
/// number rejects the call with `native_error` instead.
|
|
202
|
+
public func callAsFunction(_ value: Any?) {
|
|
203
|
+
if first() { resolve(value) }
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/// Rejects the JS call with `handler_error` and `message`.
|
|
207
|
+
public func fail(_ message: String) {
|
|
208
|
+
if first() { reject(message) }
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
private func first() -> Bool {
|
|
212
|
+
lock.lock()
|
|
213
|
+
defer { lock.unlock() }
|
|
214
|
+
let first = !settled
|
|
215
|
+
settled = true
|
|
216
|
+
return first
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/// A hook's view of the WebView: the core's context with the hook's key on its events. The view owns it and routes the delegates of the contexts that are on.
|
|
221
|
+
final class HookContext: WebViewContext {
|
|
222
|
+
let hook: MinimalWebViewHooks.Hook
|
|
223
|
+
private weak var view: MinimalWebView?
|
|
224
|
+
private(set) var options: Any?
|
|
225
|
+
private var optionsHandlers: [(Any?) -> Void] = []
|
|
226
|
+
private var documentEndHandlers: [(DocumentEnd) -> Void] = []
|
|
227
|
+
private var destroyedHandlers: [(DocumentEnd) -> Void] = []
|
|
228
|
+
private(set) var handlers: [String: ([Any], HookReply) -> Void] = [:]
|
|
229
|
+
|
|
230
|
+
init(_ hook: MinimalWebViewHooks.Hook, _ view: MinimalWebView) {
|
|
231
|
+
self.hook = hook
|
|
232
|
+
self.view = view
|
|
233
|
+
options = view.hookOptions[hook.key]
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
func detach() {
|
|
237
|
+
view = nil
|
|
238
|
+
navigationDelegates = []
|
|
239
|
+
uiDelegates = []
|
|
240
|
+
optionsHandlers = []
|
|
241
|
+
documentEndHandlers = []
|
|
242
|
+
handlers = [:]
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
var key: String { hook.key }
|
|
246
|
+
|
|
247
|
+
var url: String { view?.hookUrl ?? "" }
|
|
248
|
+
|
|
249
|
+
var isOn: Bool { options != nil }
|
|
250
|
+
|
|
251
|
+
var navigationDelegates: [WKNavigationDelegate] = [] {
|
|
252
|
+
didSet { view?.routeDelegates() }
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
var uiDelegates: [WKUIDelegate] = [] {
|
|
256
|
+
didSet { view?.routeDelegates() }
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
var refreshControl: UIRefreshControl? { view?.refreshControl }
|
|
260
|
+
|
|
261
|
+
func emit(_ event: String, _ payload: [String: Any]) {
|
|
262
|
+
onMain { [self] in if isOn { view?.emit(key, event, payload) } }
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
func ask(_ event: String, _ payload: [String: Any], _ onAnswer: @escaping (Any?) -> Void) {
|
|
266
|
+
onMain { [self] in
|
|
267
|
+
guard let view, isOn else { return onAnswer(nil) }
|
|
268
|
+
view.asks.ask(key, event, payload, onAnswer)
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
func onOptions(_ handler: @escaping (_ options: Any?) -> Void) {
|
|
273
|
+
guard view != nil else { return }
|
|
274
|
+
optionsHandlers.append(handler)
|
|
275
|
+
handler(options)
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
func onDocumentEnd(_ handler: @escaping (DocumentEnd) -> Void) {
|
|
279
|
+
documentEndHandlers.append(handler)
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
func onDestroyed(_ handler: @escaping (DocumentEnd) -> Void) {
|
|
283
|
+
destroyedHandlers.append(handler)
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
func handle(_ method: String, _ handler: @escaping (_ args: [Any], _ reply: HookReply) -> Void) {
|
|
287
|
+
handlers[method] = handler
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
func optionsChanged(_ value: Any?) {
|
|
291
|
+
options = value
|
|
292
|
+
view?.routeDelegates()
|
|
293
|
+
optionsHandlers.forEach { $0(options) }
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
func documentEnded(_ reason: DocumentEnd) {
|
|
297
|
+
documentEndHandlers.forEach { $0(reason) }
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
func destroyed() {
|
|
301
|
+
let handlers = destroyedHandlers
|
|
302
|
+
destroyedHandlers = []
|
|
303
|
+
handlers.forEach { $0(.closing) }
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// A hook's own background work (a URLSession completion) may emit or ask; the view's asks are main-thread state.
|
|
307
|
+
private func onMain(_ block: @escaping () -> Void) {
|
|
308
|
+
if Thread.isMainThread { block() } else { DispatchQueue.main.async(execute: block) }
|
|
309
|
+
}
|
|
310
|
+
}
|
package/ios/Loads.swift
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// The main-frame loads' choices that need no WebView.
|
|
4
|
+
enum Loads {
|
|
5
|
+
/// Whether `a` and `b` are the same URL as WebKit reports one: with the scheme and host lowercase, the scheme's
|
|
6
|
+
/// default port dropped and an empty path `/`. The rest (userinfo, path, query, fragment) compares exactly. It picks
|
|
7
|
+
/// out our own loads (`programmaticUrl`), which skip the navigation rules: WebKit reports the load of a `source.uri`
|
|
8
|
+
/// of `https://Example.com:443` as `https://example.com/`.
|
|
9
|
+
static func sameURL(_ a: URL, _ b: URL) -> Bool {
|
|
10
|
+
canonical(a) == canonical(b)
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
private static func canonical(_ url: URL) -> String {
|
|
14
|
+
guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return url.absoluteString }
|
|
15
|
+
components.scheme = components.scheme?.lowercased()
|
|
16
|
+
if let host = components.encodedHost, host != host.lowercased() { components.encodedHost = host.lowercased() }
|
|
17
|
+
if let port = components.port, port == defaultPorts[components.scheme ?? ""] { components.port = nil }
|
|
18
|
+
if components.percentEncodedPath.isEmpty { components.percentEncodedPath = "/" }
|
|
19
|
+
return components.string ?? url.absoluteString
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/// How a main-frame load WebKit ended with `error` went: its outcome, and the `onError` kind when it failed.
|
|
23
|
+
static func ended(by error: NSError) -> (outcome: String, kind: String?) {
|
|
24
|
+
switch (error.domain, error.code) {
|
|
25
|
+
// Superseded or stopped (NSURLErrorCancelled), or a policy cancel (WebKitErrorFrameLoadInterruptedByPolicyChange:
|
|
26
|
+
// a download, a 204, a blocked redirect): not an error.
|
|
27
|
+
case (NSURLErrorDomain, NSURLErrorCancelled), ("WebKitErrorDomain", 102):
|
|
28
|
+
return (outcome: "cancelled", kind: nil)
|
|
29
|
+
// WebKitErrorPlugInWillHandleLoad: a media file. WebKit ends the load once its media document has committed, and
|
|
30
|
+
// the document's video loads the file itself (WebLocalFrameLoaderClient::committedLoad): the page shows, as on
|
|
31
|
+
// Android.
|
|
32
|
+
case ("WebKitErrorDomain", 204):
|
|
33
|
+
return (outcome: "finished", kind: nil)
|
|
34
|
+
// The TLS handshake and certificate errors.
|
|
35
|
+
case (NSURLErrorDomain, NSURLErrorClientCertificateRequired...NSURLErrorSecureConnectionFailed):
|
|
36
|
+
return (outcome: "failed", kind: "ssl")
|
|
37
|
+
default:
|
|
38
|
+
return (outcome: "failed", kind: "network")
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/// The special schemes' default ports, which WebKit drops from a URL (the WHATWG URL Standard's).
|
|
44
|
+
private let defaultPorts = ["http": 80, "https": 443, "ws": 80, "wss": 443, "ftp": 21]
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
#import <Foundation/Foundation.h>
|
|
2
|
+
|
|
3
|
+
NS_ASSUME_NONNULL_BEGIN
|
|
4
|
+
|
|
5
|
+
/// Runs `block` and returns the Objective-C exception it raised as `name: reason`, or nil. Swift can't catch those;
|
|
6
|
+
/// Key-Value Coding raises one for an unknown key or a value a setter rejects.
|
|
7
|
+
FOUNDATION_EXPORT NSString *_Nullable MRWCatchException(void (NS_NOESCAPE ^block)(void)) NS_REFINED_FOR_SWIFT;
|
|
8
|
+
|
|
9
|
+
NS_ASSUME_NONNULL_END
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#import "MRWExceptions.h"
|
|
2
|
+
|
|
3
|
+
NSString *MRWCatchException(void (NS_NOESCAPE ^block)(void)) {
|
|
4
|
+
@try {
|
|
5
|
+
block();
|
|
6
|
+
return nil;
|
|
7
|
+
} @catch (NSException *exception) {
|
|
8
|
+
return [NSString stringWithFormat:@"%@: %@", exception.name, exception.reason ?: @""];
|
|
9
|
+
}
|
|
10
|
+
}
|
package/ios/MRWInvoke.h
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
#import <Foundation/Foundation.h>
|
|
2
|
+
|
|
3
|
+
NS_ASSUME_NONNULL_BEGIN
|
|
4
|
+
|
|
5
|
+
/// Calls `selector` on `target` with the JSON `args` and resolves with the result as `MRWJsonable` makes it, or with
|
|
6
|
+
/// why it couldn't.
|
|
7
|
+
///
|
|
8
|
+
/// `args` are set by the method signature's type encodings:
|
|
9
|
+
/// - booleans, numbers and strings as themselves, and nil from null;
|
|
10
|
+
/// - the four structs (UIEdgeInsets, CGPoint, CGSize, CGRect) from objects;
|
|
11
|
+
/// - `{ set: [] }`, `{ date: seconds }`, `{ data: base64 }` and `{ cookie: properties }` for an NSSet, NSDate, NSData
|
|
12
|
+
/// or NSHTTPCookie;
|
|
13
|
+
/// - any other object as is.
|
|
14
|
+
///
|
|
15
|
+
/// A selector whose last argument is a block gets the shape `completion` names, and the block resolves, with the
|
|
16
|
+
/// error's description as the error:
|
|
17
|
+
/// - `void`: `(void)`
|
|
18
|
+
/// - `value`: `(id)`
|
|
19
|
+
/// - `valueError`: `(id, NSError *)`
|
|
20
|
+
/// - `error`: `(NSError *)`
|
|
21
|
+
/// - `number`: `(NSInteger)`
|
|
22
|
+
///
|
|
23
|
+
/// Rejects, never raises, for:
|
|
24
|
+
/// - an unknown selector, a block selector without a `completion`, or a wrong argument count;
|
|
25
|
+
/// - an argument that doesn't fit, such as a tagged object that can't be made (invalid base64, a cookie without a name,
|
|
26
|
+
/// value, path, and domain or origin URL);
|
|
27
|
+
/// - an exception the method, or making its result JSON, raises.
|
|
28
|
+
///
|
|
29
|
+
/// A wrong block shape or an object argument of the wrong class is undefined behavior.
|
|
30
|
+
FOUNDATION_EXPORT void MRWInvoke(id target, SEL selector, NSArray *args, NSString *_Nullable completion,
|
|
31
|
+
void (^resolve)(id _Nullable result, NSString *_Nullable error)) NS_REFINED_FOR_SWIFT;
|
|
32
|
+
|
|
33
|
+
/// `value` as JSON: numbers, strings, URLs as strings, dates as seconds since 1970, NSData and UIImage (PNG) as
|
|
34
|
+
/// base64, the four struct NSValues (UIEdgeInsets, CGPoint, CGSize, CGRect) as objects, an NSHTTPCookie as its
|
|
35
|
+
/// `properties`, lists, sets and dictionaries of them; anything else, and nil, is null.
|
|
36
|
+
FOUNDATION_EXPORT id MRWJsonable(id _Nullable value) NS_REFINED_FOR_SWIFT;
|
|
37
|
+
|
|
38
|
+
NS_ASSUME_NONNULL_END
|
package/ios/MRWInvoke.m
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
#import "MRWInvoke.h"
|
|
2
|
+
#import "MRWExceptions.h"
|
|
3
|
+
#import <UIKit/UIKit.h>
|
|
4
|
+
|
|
5
|
+
static NSDictionary *MRWStruct(NSValue *value) {
|
|
6
|
+
const char *type = value.objCType;
|
|
7
|
+
if (strcmp(type, @encode(UIEdgeInsets)) == 0) {
|
|
8
|
+
UIEdgeInsets i = value.UIEdgeInsetsValue;
|
|
9
|
+
return @{@"top": @(i.top), @"left": @(i.left), @"bottom": @(i.bottom), @"right": @(i.right)};
|
|
10
|
+
}
|
|
11
|
+
if (strcmp(type, @encode(CGPoint)) == 0) return @{@"x": @(value.CGPointValue.x), @"y": @(value.CGPointValue.y)};
|
|
12
|
+
if (strcmp(type, @encode(CGSize)) == 0) return @{@"width": @(value.CGSizeValue.width), @"height": @(value.CGSizeValue.height)};
|
|
13
|
+
if (strcmp(type, @encode(CGRect)) == 0) {
|
|
14
|
+
CGRect r = value.CGRectValue;
|
|
15
|
+
return @{@"x": @(r.origin.x), @"y": @(r.origin.y), @"width": @(r.size.width), @"height": @(r.size.height)};
|
|
16
|
+
}
|
|
17
|
+
return nil;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
id MRWJsonable(id value) {
|
|
21
|
+
if ([value isKindOfClass:NSNumber.class] || [value isKindOfClass:NSString.class]) return value;
|
|
22
|
+
if ([value isKindOfClass:NSURL.class]) return [value absoluteString];
|
|
23
|
+
if ([value isKindOfClass:NSDate.class]) return @([value timeIntervalSince1970]);
|
|
24
|
+
if ([value isKindOfClass:NSData.class]) return [value base64EncodedStringWithOptions:0];
|
|
25
|
+
if ([value isKindOfClass:UIImage.class]) return MRWJsonable(UIImagePNGRepresentation(value));
|
|
26
|
+
if ([value isKindOfClass:NSHTTPCookie.class]) return MRWJsonable([value properties]);
|
|
27
|
+
if ([value isKindOfClass:NSArray.class] || [value isKindOfClass:NSSet.class]) {
|
|
28
|
+
NSMutableArray *list = [NSMutableArray new];
|
|
29
|
+
for (id item in value) [list addObject:MRWJsonable(item)];
|
|
30
|
+
return list;
|
|
31
|
+
}
|
|
32
|
+
if ([value isKindOfClass:NSDictionary.class]) {
|
|
33
|
+
NSMutableDictionary *object = [NSMutableDictionary new];
|
|
34
|
+
for (id key in value) object[[key description]] = MRWJsonable(value[key]);
|
|
35
|
+
return object;
|
|
36
|
+
}
|
|
37
|
+
if ([value isKindOfClass:NSValue.class]) return MRWStruct(value) ?: NSNull.null;
|
|
38
|
+
return NSNull.null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/// A JSON argument for an `@` parameter: nil for null, the tagged objects as their class (nil for one that can't be
|
|
42
|
+
/// made), the rest as is.
|
|
43
|
+
static id MRWObject(id json) {
|
|
44
|
+
if (json == NSNull.null) return nil;
|
|
45
|
+
if (![json isKindOfClass:NSDictionary.class] || [json count] != 1) return json;
|
|
46
|
+
id set = json[@"set"], date = json[@"date"], data = json[@"data"], cookie = json[@"cookie"];
|
|
47
|
+
if ([set isKindOfClass:NSArray.class]) return [NSSet setWithArray:set];
|
|
48
|
+
if ([date isKindOfClass:NSNumber.class]) return [NSDate dateWithTimeIntervalSince1970:[date doubleValue]];
|
|
49
|
+
if ([data isKindOfClass:NSString.class]) return [[NSData alloc] initWithBase64EncodedString:data options:0];
|
|
50
|
+
if ([cookie isKindOfClass:NSDictionary.class]) {
|
|
51
|
+
// A `Path` that isn't a string raises instead of returning nil.
|
|
52
|
+
__block NSHTTPCookie *made = nil;
|
|
53
|
+
MRWCatchException(^{ made = [NSHTTPCookie cookieWithProperties:cookie]; });
|
|
54
|
+
return made;
|
|
55
|
+
}
|
|
56
|
+
return json;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/// Reads `keys` of `object` as numbers into `out`; NO when one is missing or not a number.
|
|
60
|
+
static BOOL MRWNumbers(id object, NSArray<NSString *> *keys, double *out) {
|
|
61
|
+
if (![object isKindOfClass:NSDictionary.class]) return NO;
|
|
62
|
+
for (NSUInteger i = 0; i < keys.count; i++) {
|
|
63
|
+
id number = object[keys[i]];
|
|
64
|
+
if (![number isKindOfClass:NSNumber.class]) return NO;
|
|
65
|
+
out[i] = [number doubleValue];
|
|
66
|
+
}
|
|
67
|
+
return YES;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
#define MRW_SET(ctype, expr) { ctype v = (expr); [invocation setArgument:&v atIndex:index]; return YES; }
|
|
71
|
+
|
|
72
|
+
/// Sets argument `index` from the JSON `value` as the type encoding `type` wants it, or returns NO when it doesn't fit.
|
|
73
|
+
/// An object made here goes into `keep`: the invocation holds it unretained until `retainArguments`.
|
|
74
|
+
static BOOL MRWSetArgument(NSInvocation *invocation, NSUInteger index, const char *type, id value, NSMutableArray *keep) {
|
|
75
|
+
NSNumber *number = [value isKindOfClass:NSNumber.class] ? value : nil;
|
|
76
|
+
BOOL isBool = number && CFGetTypeID((__bridge CFTypeRef)number) == CFBooleanGetTypeID();
|
|
77
|
+
double n[4];
|
|
78
|
+
switch (type[0]) {
|
|
79
|
+
case 'B': if (isBool) MRW_SET(bool, number.boolValue) break;
|
|
80
|
+
case 'c': if (isBool) MRW_SET(signed char, number.boolValue) break;
|
|
81
|
+
case 's': if (number && !isBool) MRW_SET(short, number.shortValue) break;
|
|
82
|
+
case 'S': if (number && !isBool) MRW_SET(unsigned short, number.unsignedShortValue) break;
|
|
83
|
+
case 'i': if (number && !isBool) MRW_SET(int, number.intValue) break;
|
|
84
|
+
case 'I': if (number && !isBool) MRW_SET(unsigned int, number.unsignedIntValue) break;
|
|
85
|
+
case 'l': if (number && !isBool) MRW_SET(long, number.longValue) break;
|
|
86
|
+
case 'L': if (number && !isBool) MRW_SET(unsigned long, number.unsignedLongValue) break;
|
|
87
|
+
case 'q': if (number && !isBool) MRW_SET(long long, number.longLongValue) break;
|
|
88
|
+
case 'Q': if (number && !isBool) MRW_SET(unsigned long long, number.unsignedLongLongValue) break;
|
|
89
|
+
case 'f': if (number && !isBool) MRW_SET(float, number.floatValue) break;
|
|
90
|
+
case 'd': if (number && !isBool) MRW_SET(double, number.doubleValue) break;
|
|
91
|
+
case '@': {
|
|
92
|
+
if (type[1] == '?') break;
|
|
93
|
+
id object = MRWObject(value);
|
|
94
|
+
if (!object && value != NSNull.null) break;
|
|
95
|
+
if (object) [keep addObject:object];
|
|
96
|
+
MRW_SET(id, object)
|
|
97
|
+
}
|
|
98
|
+
case '{':
|
|
99
|
+
if (strcmp(type, @encode(UIEdgeInsets)) == 0 && MRWNumbers(value, @[@"top", @"left", @"bottom", @"right"], n)) MRW_SET(UIEdgeInsets, UIEdgeInsetsMake(n[0], n[1], n[2], n[3]))
|
|
100
|
+
if (strcmp(type, @encode(CGPoint)) == 0 && MRWNumbers(value, @[@"x", @"y"], n)) MRW_SET(CGPoint, CGPointMake(n[0], n[1]))
|
|
101
|
+
if (strcmp(type, @encode(CGSize)) == 0 && MRWNumbers(value, @[@"width", @"height"], n)) MRW_SET(CGSize, CGSizeMake(n[0], n[1]))
|
|
102
|
+
if (strcmp(type, @encode(CGRect)) == 0 && MRWNumbers(value, @[@"x", @"y", @"width", @"height"], n)) MRW_SET(CGRect, CGRectMake(n[0], n[1], n[2], n[3]))
|
|
103
|
+
break;
|
|
104
|
+
default: break;
|
|
105
|
+
}
|
|
106
|
+
return NO;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
#define MRW_GET(ctype, box) { ctype v; [invocation getReturnValue:&v]; return (box); }
|
|
110
|
+
|
|
111
|
+
/// The invocation's return value as an object for `MRWJsonable`; null for void and for what JSON can't carry.
|
|
112
|
+
static id MRWReturnValue(NSInvocation *invocation) {
|
|
113
|
+
const char *type = invocation.methodSignature.methodReturnType;
|
|
114
|
+
switch (type[0]) {
|
|
115
|
+
case 'B': MRW_GET(bool, @(v))
|
|
116
|
+
case 'c': MRW_GET(signed char, @((BOOL)v))
|
|
117
|
+
case 's': MRW_GET(short, @(v))
|
|
118
|
+
case 'S': MRW_GET(unsigned short, @(v))
|
|
119
|
+
case 'i': MRW_GET(int, @(v))
|
|
120
|
+
case 'I': MRW_GET(unsigned int, @(v))
|
|
121
|
+
case 'l': MRW_GET(long, @(v))
|
|
122
|
+
case 'L': MRW_GET(unsigned long, @(v))
|
|
123
|
+
case 'q': MRW_GET(long long, @(v))
|
|
124
|
+
case 'Q': MRW_GET(unsigned long long, @(v))
|
|
125
|
+
case 'f': MRW_GET(float, @(v))
|
|
126
|
+
case 'd': MRW_GET(double, @(v))
|
|
127
|
+
case '@': { __unsafe_unretained id v = nil; [invocation getReturnValue:&v]; return v; }
|
|
128
|
+
case '{':
|
|
129
|
+
if (strcmp(type, @encode(UIEdgeInsets)) == 0) MRW_GET(UIEdgeInsets, [NSValue valueWithUIEdgeInsets:v])
|
|
130
|
+
if (strcmp(type, @encode(CGPoint)) == 0) MRW_GET(CGPoint, [NSValue valueWithCGPoint:v])
|
|
131
|
+
if (strcmp(type, @encode(CGSize)) == 0) MRW_GET(CGSize, [NSValue valueWithCGSize:v])
|
|
132
|
+
if (strcmp(type, @encode(CGRect)) == 0) MRW_GET(CGRect, [NSValue valueWithCGRect:v])
|
|
133
|
+
return NSNull.null;
|
|
134
|
+
default: return NSNull.null;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/// A completion block of the shape `completion` names, resolving `resolve`; nil for an unknown shape.
|
|
139
|
+
static id MRWBlock(NSString *completion, void (^resolve)(id, NSString *)) {
|
|
140
|
+
if ([completion isEqualToString:@"void"]) return [^{ resolve(NSNull.null, nil); } copy];
|
|
141
|
+
if ([completion isEqualToString:@"value"]) return [^(id value) { resolve(value, nil); } copy];
|
|
142
|
+
if ([completion isEqualToString:@"valueError"]) {
|
|
143
|
+
return [^(id value, NSError *error) { resolve(value, error.localizedDescription); } copy];
|
|
144
|
+
}
|
|
145
|
+
if ([completion isEqualToString:@"error"]) return [^(NSError *error) { resolve(NSNull.null, error.localizedDescription); } copy];
|
|
146
|
+
if ([completion isEqualToString:@"number"]) return [^(NSInteger value) { resolve(@(value), nil); } copy];
|
|
147
|
+
return nil;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
void MRWInvoke(id target, SEL selector, NSArray *args, NSString *completion, void (^resolve)(id, NSString *)) {
|
|
151
|
+
NSString *name = NSStringFromSelector(selector);
|
|
152
|
+
NSMethodSignature *signature = [target methodSignatureForSelector:selector];
|
|
153
|
+
if (!signature) return resolve(nil, [NSString stringWithFormat:@"%@ has no method %@", [target class], name]);
|
|
154
|
+
NSUInteger count = signature.numberOfArguments - 2;
|
|
155
|
+
BOOL takesBlock = count > 0 && strcmp([signature getArgumentTypeAtIndex:count + 1], "@?") == 0;
|
|
156
|
+
NSUInteger expected = takesBlock ? count - 1 : count;
|
|
157
|
+
if (args.count != expected) {
|
|
158
|
+
return resolve(nil, [NSString stringWithFormat:@"%@ takes %lu arguments, got %lu", name, (unsigned long)expected, (unsigned long)args.count]);
|
|
159
|
+
}
|
|
160
|
+
// The method may call its block before returning, or raise after calling it: the first settlement counts.
|
|
161
|
+
// The result is made JSON here, inside the catch: walking a KVC proxy or a raising getter rejects.
|
|
162
|
+
__block BOOL settled = NO;
|
|
163
|
+
void (^once)(id, NSString *) = ^(id result, NSString *error) {
|
|
164
|
+
if (settled) return;
|
|
165
|
+
settled = YES;
|
|
166
|
+
__block id json = nil;
|
|
167
|
+
NSString *raised = MRWCatchException(^{ json = MRWJsonable(result); });
|
|
168
|
+
resolve(raised ? nil : json, error ?: raised);
|
|
169
|
+
};
|
|
170
|
+
id block = takesBlock ? MRWBlock(completion, once) : nil;
|
|
171
|
+
if (takesBlock && !block) return once(nil, @"the method takes a completion handler this package's SDK headers don't list: write a native hook");
|
|
172
|
+
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
|
|
173
|
+
NSMutableArray *keep = [NSMutableArray new];
|
|
174
|
+
invocation.target = target;
|
|
175
|
+
invocation.selector = selector;
|
|
176
|
+
for (NSUInteger i = 0; i < expected; i++) {
|
|
177
|
+
const char *type = [signature getArgumentTypeAtIndex:i + 2];
|
|
178
|
+
if (!MRWSetArgument(invocation, i + 2, type, args[i], keep)) {
|
|
179
|
+
return once(nil, [NSString stringWithFormat:@"argument %lu of %@ (%s) can't take %@", (unsigned long)i + 1, name, type, args[i]]);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
if (block) [invocation setArgument:&block atIndex:count + 1];
|
|
183
|
+
[invocation retainArguments];
|
|
184
|
+
NSString *raised = MRWCatchException(^{ [invocation invoke]; });
|
|
185
|
+
if (raised) return once(nil, raised);
|
|
186
|
+
if (!block) once(MRWReturnValue(invocation), nil);
|
|
187
|
+
}
|