react-native-minimal-webview 0.0.0-stage → 1.0.0

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.
Files changed (118) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +130 -2
  3. package/android/build.gradle +26 -0
  4. package/android/consumer-rules.pro +4 -0
  5. package/android/src/main/AndroidManifest.xml +2 -0
  6. package/android/src/main/java/expo/modules/minimalwebview/Asks.kt +44 -0
  7. package/android/src/main/java/expo/modules/minimalwebview/DocumentEnd.kt +31 -0
  8. package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +496 -0
  9. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +510 -0
  10. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +359 -0
  11. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +245 -0
  12. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +199 -0
  13. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +191 -0
  14. package/android/src/main/java/expo/modules/minimalwebview/NavigationRules.kt +113 -0
  15. package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +306 -0
  16. package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +76 -0
  17. package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +258 -0
  18. package/android/src/main/java/expo/modules/minimalwebview/requests/FileUpload.kt +44 -0
  19. package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +87 -0
  20. package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +77 -0
  21. package/build/WebView.d.ts +99 -0
  22. package/build/WebView.d.ts.map +1 -0
  23. package/build/WebView.js +448 -0
  24. package/build/WebView.js.map +1 -0
  25. package/build/bridge/createBridge.d.ts +32 -0
  26. package/build/bridge/createBridge.d.ts.map +1 -0
  27. package/build/bridge/createBridge.js +135 -0
  28. package/build/bridge/createBridge.js.map +1 -0
  29. package/build/bridge/endpoint.d.ts +35 -0
  30. package/build/bridge/endpoint.d.ts.map +1 -0
  31. package/build/bridge/endpoint.js +100 -0
  32. package/build/bridge/endpoint.js.map +1 -0
  33. package/build/bridge/origins.d.ts +25 -0
  34. package/build/bridge/origins.d.ts.map +1 -0
  35. package/build/bridge/origins.js +60 -0
  36. package/build/bridge/origins.js.map +1 -0
  37. package/build/bridge/pageClient.generated.d.ts +3 -0
  38. package/build/bridge/pageClient.generated.d.ts.map +1 -0
  39. package/build/bridge/pageClient.generated.js +4 -0
  40. package/build/bridge/pageClient.generated.js.map +1 -0
  41. package/build/bridge/protocol.d.ts +50 -0
  42. package/build/bridge/protocol.d.ts.map +1 -0
  43. package/build/bridge/protocol.js +52 -0
  44. package/build/bridge/protocol.js.map +1 -0
  45. package/build/defaultNavigationRules.d.ts +16 -0
  46. package/build/defaultNavigationRules.d.ts.map +1 -0
  47. package/build/defaultNavigationRules.js +23 -0
  48. package/build/defaultNavigationRules.js.map +1 -0
  49. package/build/index.d.ts +31 -0
  50. package/build/index.d.ts.map +1 -0
  51. package/build/index.js +30 -0
  52. package/build/index.js.map +1 -0
  53. package/build/platform.generated.d.ts +702 -0
  54. package/build/platform.generated.d.ts.map +1 -0
  55. package/build/platform.generated.js +199 -0
  56. package/build/platform.generated.js.map +1 -0
  57. package/build/reactNativeWebViewDefaults.d.ts +21 -0
  58. package/build/reactNativeWebViewDefaults.d.ts.map +1 -0
  59. package/build/reactNativeWebViewDefaults.js +12 -0
  60. package/build/reactNativeWebViewDefaults.js.map +1 -0
  61. package/build/reactNativeWebViewMessages.d.ts +22 -0
  62. package/build/reactNativeWebViewMessages.d.ts.map +1 -0
  63. package/build/reactNativeWebViewMessages.js +30 -0
  64. package/build/reactNativeWebViewMessages.js.map +1 -0
  65. package/build/refStore.d.ts +31 -0
  66. package/build/refStore.d.ts.map +1 -0
  67. package/build/refStore.js +113 -0
  68. package/build/refStore.js.map +1 -0
  69. package/build/types.d.ts +1127 -0
  70. package/build/types.d.ts.map +1 -0
  71. package/build/types.defaults.d.ts +8 -0
  72. package/build/types.defaults.d.ts.map +1 -0
  73. package/build/types.defaults.js +17 -0
  74. package/build/types.defaults.js.map +1 -0
  75. package/build/types.js +2 -0
  76. package/build/types.js.map +1 -0
  77. package/expo-module.config.json +9 -0
  78. package/ios/Asks.swift +45 -0
  79. package/ios/DelegateProxy.swift +162 -0
  80. package/ios/DocumentEnd.swift +23 -0
  81. package/ios/DownloadName.swift +12 -0
  82. package/ios/Downloads.swift +51 -0
  83. package/ios/Hooks.swift +308 -0
  84. package/ios/Loads.swift +44 -0
  85. package/ios/MRWExceptions.h +9 -0
  86. package/ios/MRWExceptions.m +10 -0
  87. package/ios/MRWInvoke.h +23 -0
  88. package/ios/MRWInvoke.m +187 -0
  89. package/ios/MinimalWebView+Dialogs.swift +99 -0
  90. package/ios/MinimalWebView+Navigation.swift +244 -0
  91. package/ios/MinimalWebView+Scripts.swift +92 -0
  92. package/ios/MinimalWebView.docc/MinimalWebView.md +13 -0
  93. package/ios/MinimalWebView.podspec +32 -0
  94. package/ios/MinimalWebView.swift +512 -0
  95. package/ios/MinimalWebViewModule.swift +110 -0
  96. package/ios/NavigationRules.swift +123 -0
  97. package/ios/OriginRules.swift +35 -0
  98. package/ios/PlatformCompletions.generated.swift +39 -0
  99. package/ios/PlatformSettings.swift +247 -0
  100. package/ios/ReadAccess.swift +19 -0
  101. package/ios/Recovery.swift +25 -0
  102. package/ios/SharedCookies.swift +59 -0
  103. package/package.json +94 -4
  104. package/src/WebView.tsx +623 -0
  105. package/src/bridge/createBridge.ts +176 -0
  106. package/src/bridge/endpoint.ts +119 -0
  107. package/src/bridge/origins.ts +62 -0
  108. package/src/bridge/pageClient.generated.ts +5 -0
  109. package/src/bridge/pageClient.ts +68 -0
  110. package/src/bridge/protocol.ts +78 -0
  111. package/src/defaultNavigationRules.ts +25 -0
  112. package/src/index.ts +37 -0
  113. package/src/platform.generated.ts +694 -0
  114. package/src/reactNativeWebViewDefaults.ts +13 -0
  115. package/src/reactNativeWebViewMessages.ts +32 -0
  116. package/src/refStore.ts +164 -0
  117. package/src/types.defaults.ts +24 -0
  118. package/src/types.ts +1194 -0
@@ -0,0 +1,308 @@
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
+ /// The [native hooks guide](https://rasmuskard.github.io/react-native-minimal-webview/guides/native-hooks/)
7
+ /// walks through one.
8
+ ///
9
+ /// A hook attaches to each WebView whose `extensions` prop has an extension with its key that is on;
10
+ /// [`HookExtension.options`](https://rasmuskard.github.io/react-native-minimal-webview/typescript/react-native-minimal-webview/type-aliases/HookExtension/#options)
11
+ /// says when.
12
+ ///
13
+ /// - Important: Leave alone what the core owns: the WKWebView's own `navigationDelegate` and `uiDelegate` (add to the
14
+ /// context's lists instead), and the bridge's script message handler and user scripts.
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 web content process 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`, null as nil
94
+ /// (`NSNull` inside an array).
95
+ public protocol WebViewContext: AnyObject {
96
+ /// This hook's extension's `options`, the new ones after a change; nil while the hook is off.
97
+ var options: Any? { get }
98
+ /// The committed URL, the one `useWebViewState` reports; empty before the first commit.
99
+ ///
100
+ /// Inside ``onDocumentEnd(_:)`` it is still the page that ended.
101
+ var url: String { get }
102
+ /// Your navigation delegates, in order. While the hook is off, none of them gets a callback.
103
+ ///
104
+ /// WebKit reads which callbacks a delegate implements when it is assigned, so a delegate must implement what it
105
+ /// handles by the time you add it. The core assigns itself again after each change to the list.
106
+ ///
107
+ /// Each callback reaches the delegates by one of these rules:
108
+ /// - A decision, the action or the response policy, goes to the first delegate that implements it, instead of the
109
+ /// core. Either action policy variant, with or without `preferences`, counts, and that delegate's own variant is
110
+ /// called.
111
+ /// - The authentication challenge goes to each delegate that implements it, in order, until one answers other than
112
+ /// `.performDefaultHandling`; when none does, WebKit's default handling. Each must call its completion handler
113
+ /// exactly once, and the next delegate gets the challenge only after that.
114
+ /// - Every other callback the core implements reaches the core, then each delegate that implements it. So do
115
+ /// `didStartProvisionalNavigation` and `didReceiveServerRedirectForProvisionalNavigation`.
116
+ /// - Any other callback goes only to the first delegate that implements it.
117
+ ///
118
+ /// Taking a decision switches off what the core decides from the app's props or their defaults, the default
119
+ /// navigation rules' security checks included, and a warning names the callback and what stops applying. A
120
+ /// delegate that takes the action policy decides navigations instead of the navigation rules, which still decide new
121
+ /// windows unless a UI delegate takes `createWebViewWith`.
122
+ ///
123
+ /// A decision more than one delegate implements still goes only to the first, and a warning names it. Each
124
+ /// warning comes once per WebView, when the delegate is added.
125
+ ///
126
+ /// While `onDownload` is set, a delegate whose `didBecome` sets `download.delegate` takes the download, and
127
+ /// `onDownload` gets nothing for it.
128
+ var navigationDelegates: [WKNavigationDelegate] { get set }
129
+ /// Your UI delegates, in order, by the rules of ``navigationDelegates``.
130
+ ///
131
+ /// Their decisions are `createWebViewWith`, the alert, confirm and prompt panels and the media capture permission.
132
+ /// `webViewDidClose` reaches every delegate.
133
+ ///
134
+ /// A callback goes only to the list of the protocol that declares it: a navigation delegate's alert panel, or a UI
135
+ /// delegate's action policy, is never called.
136
+ ///
137
+ /// A delegate that holds a panel's completion handler should set `webView.accessibilityElementsHidden` until it
138
+ /// answers, as the core does for its own panels: an accessibility query (XCTest's) into the blocked page hangs.
139
+ var uiDelegates: [WKUIDelegate] { get set }
140
+ /// The control `pullToRefresh` shows: the same one for the view's life, shown or not; nil once the view has closed.
141
+ ///
142
+ /// Style it (`tintColor`), but leave its actions and where it is shown to the core.
143
+ var refreshControl: UIRefreshControl? { get }
144
+ /// Sends an event to JS: the extension with the hook's key gets `{ name, payload }` in its `onEvent`. It is dropped
145
+ /// while the hook is off, and after the view closed.
146
+ func emit(_ name: String, _ payload: [String: Any])
147
+ /// Sends the event as ``emit(_:_:)`` does, and calls `onAnswer` with the extension's `onEvent` return value, a
148
+ /// promise awaited.
149
+ ///
150
+ /// It answers nil when the handler throws or there is none, or when the Document ends first; there is no timeout. It
151
+ /// answers nil at once while the hook is off, and after the view closed.
152
+ /// An ask made before the first commit (in `attach`, or after a crash) belongs to the Document that commit opens.
153
+ func ask(_ name: String, _ payload: [String: Any], _ onAnswer: @escaping (Any?) -> Void)
154
+ /// Runs `handler` at once with this hook's extension's `options`, then with the new ones each time they change,
155
+ /// live; nil while the hook is off.
156
+ ///
157
+ /// The hook turns off when the extension is removed, or its `options` become null or false. A change from one off
158
+ /// value to another doesn't run it, and a context kept after the view closed never does.
159
+ func onOptions(_ handler: @escaping (_ options: Any?) -> Void)
160
+ /// Runs `handler` at each end of the Document (see ``DocumentEnd``), after the core's own resets: per-page
161
+ /// state belongs here.
162
+ func onDocumentEnd(_ handler: @escaping (DocumentEnd) -> Void)
163
+ /// Runs `handler` once this view closes, with ``DocumentEnd/closing``, the only reason it gets on iOS.
164
+ ///
165
+ /// It comes after the ``onDocumentEnd(_:)`` handlers that get `closing`. The WKWebView has stopped loading, paused
166
+ /// its media and left the view by then, but is still alive, and the context does nothing.
167
+ ///
168
+ /// Clean up here: what `attach` set up on the WKWebView, such as an observation or a swapped class.
169
+ func onDestroyed(_ handler: @escaping (DocumentEnd) -> Void)
170
+ /// Answers JS's `ref.hook("<key>", method, args)`: `handler` gets the arguments, which cross as JSON, and a
171
+ /// ``HookReply``, which it calls with the reply or fails, then or later.
172
+ ///
173
+ /// One handler per method: the last one wins. A handler that never replies leaves the call waiting until the view
174
+ /// unmounts: a navigation or a crash doesn't settle it.
175
+ func handle(_ method: String, _ handler: @escaping (_ args: [Any], _ reply: HookReply) -> Void)
176
+ }
177
+
178
+ /// The answer to one JS `ref.hook` call, which a ``WebViewContext/handle(_:_:)`` handler gets: call it with the value
179
+ /// the call resolves with, or ``fail(_:)`` it.
180
+ ///
181
+ /// Only the first reply or fail counts: any after it does nothing. Call it from any thread.
182
+ public final class HookReply {
183
+ private let resolve: (Any?) -> Void
184
+ private let reject: (String) -> Void
185
+ private let lock = NSLock()
186
+ private var settled = false
187
+
188
+ init(resolve: @escaping (Any?) -> Void, reject: @escaping (String) -> Void) {
189
+ self.resolve = resolve
190
+ self.reject = reject
191
+ }
192
+
193
+ /// Resolves the JS call with `value`, which crosses as JSON: a value JSON can't encode rejects it with
194
+ /// `native_error` instead.
195
+ public func callAsFunction(_ value: Any?) {
196
+ if first() { resolve(value) }
197
+ }
198
+
199
+ /// Rejects the JS call with `handler_error` and `message`.
200
+ public func fail(_ message: String) {
201
+ if first() { reject(message) }
202
+ }
203
+
204
+ private func first() -> Bool {
205
+ lock.lock()
206
+ defer { lock.unlock() }
207
+ let first = !settled
208
+ settled = true
209
+ return first
210
+ }
211
+ }
212
+
213
+ /// A hook's view of the WebView: the core's context with the hook's key on its events. The view owns it. A hook can
214
+ /// outlive the view (an async callback): then the context is detached and does nothing.
215
+ /// The view routes the delegates of the contexts that are on.
216
+ final class HookContext: WebViewContext {
217
+ let hook: MinimalWebViewHooks.Hook
218
+ private weak var view: MinimalWebView?
219
+ /// The `hookOptions` value while the hook is on, nil while it is off.
220
+ private(set) var options: Any?
221
+ private var optionsHandlers: [(Any?) -> Void] = []
222
+ private var documentEndHandlers: [(DocumentEnd) -> Void] = []
223
+ private var destroyedHandlers: [(DocumentEnd) -> Void] = []
224
+ private(set) var handlers: [String: ([Any], HookReply) -> Void] = [:]
225
+
226
+ init(_ hook: MinimalWebViewHooks.Hook, _ view: MinimalWebView) {
227
+ self.hook = hook
228
+ self.view = view
229
+ options = view.hookOptions[hook.key]
230
+ }
231
+
232
+ /// The view closed: the context keeps nothing of it and nothing the hook gave it, and nothing routes it.
233
+ func detach() {
234
+ view = nil
235
+ navigationDelegates = []
236
+ uiDelegates = []
237
+ optionsHandlers = []
238
+ documentEndHandlers = []
239
+ handlers = [:]
240
+ }
241
+
242
+ var key: String { hook.key }
243
+
244
+ var url: String { view?.hookUrl ?? "" }
245
+
246
+ var isOn: Bool { options != nil }
247
+
248
+ var navigationDelegates: [WKNavigationDelegate] = [] {
249
+ didSet { view?.routeDelegates() }
250
+ }
251
+
252
+ var uiDelegates: [WKUIDelegate] = [] {
253
+ didSet { view?.routeDelegates() }
254
+ }
255
+
256
+ var refreshControl: UIRefreshControl? { view?.refreshControl }
257
+
258
+ func emit(_ event: String, _ payload: [String: Any]) {
259
+ onMain { [self] in if isOn { view?.emit(key, event, payload) } }
260
+ }
261
+
262
+ func ask(_ event: String, _ payload: [String: Any], _ onAnswer: @escaping (Any?) -> Void) {
263
+ onMain { [self] in
264
+ guard let view, isOn else { return onAnswer(nil) }
265
+ view.asks.ask(key, event, payload, onAnswer)
266
+ }
267
+ }
268
+
269
+ func onOptions(_ handler: @escaping (_ options: Any?) -> Void) {
270
+ guard view != nil else { return }
271
+ optionsHandlers.append(handler)
272
+ handler(options)
273
+ }
274
+
275
+ func onDocumentEnd(_ handler: @escaping (DocumentEnd) -> Void) {
276
+ documentEndHandlers.append(handler)
277
+ }
278
+
279
+ func onDestroyed(_ handler: @escaping (DocumentEnd) -> Void) {
280
+ destroyedHandlers.append(handler)
281
+ }
282
+
283
+ func handle(_ method: String, _ handler: @escaping (_ args: [Any], _ reply: HookReply) -> Void) {
284
+ handlers[method] = handler
285
+ }
286
+
287
+ func optionsChanged(_ value: Any?) {
288
+ options = value
289
+ view?.routeDelegates()
290
+ optionsHandlers.forEach { $0(options) }
291
+ }
292
+
293
+ func documentEnded(_ reason: DocumentEnd) {
294
+ documentEndHandlers.forEach { $0(reason) }
295
+ }
296
+
297
+ /// The view closed, and its WKWebView is torn down: the handlers run once, and the context drops them.
298
+ func destroyed() {
299
+ let handlers = destroyedHandlers
300
+ destroyedHandlers = []
301
+ handlers.forEach { $0(.closing) }
302
+ }
303
+
304
+ // A hook's own background work (a URLSession completion) may emit or ask; the view's asks are main-thread state.
305
+ private func onMain(_ block: @escaping () -> Void) {
306
+ if Thread.isMainThread { block() } else { DispatchQueue.main.async(execute: block) }
307
+ }
308
+ }
@@ -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 reason of the Objective-C exception it raised, 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
+ }
@@ -0,0 +1,23 @@
1
+ #import <Foundation/Foundation.h>
2
+
3
+ NS_ASSUME_NONNULL_BEGIN
4
+
5
+ /// Calls `selector` on `target` with the JSON `args` set by the method signature's type encodings (booleans, numbers,
6
+ /// strings, the four structs from objects, nil from null; `{ set: [] }`, `{ date: seconds }`, `{ data: base64 }` and
7
+ /// `{ cookie: properties }` for an NSSet, NSDate, NSData or NSHTTPCookie, any other object as is), and resolves with
8
+ /// the result as `MRWJsonable` makes it, or with why it couldn't. A selector whose last argument is a block gets one of
9
+ /// the shape `completion` names: `void` `(void)`, `value` `(id)`, `valueError` `(id, NSError *)`, `error`
10
+ /// `(NSError *)` or `number` `(NSInteger)`; the block resolves, with the error's description as the error. Rejects,
11
+ /// never raises, for an unknown selector, a block selector without a `completion`, a wrong argument count, an argument
12
+ /// that doesn't fit (a tagged object that can't be made, such as invalid base64 or a cookie without a name, value,
13
+ /// domain and path) or an exception the method, or making its result JSON, raises. A wrong block shape or an object
14
+ /// argument of the wrong class is undefined behaviour.
15
+ FOUNDATION_EXPORT void MRWInvoke(id target, SEL selector, NSArray *args, NSString *_Nullable completion,
16
+ void (^resolve)(id _Nullable result, NSString *_Nullable error)) NS_REFINED_FOR_SWIFT;
17
+
18
+ /// `value` as JSON: numbers, strings, URLs as strings, dates as seconds since 1970, NSData and UIImage (PNG) as
19
+ /// base64, the four struct NSValues (UIEdgeInsets, CGPoint, CGSize, CGRect) as objects, an NSHTTPCookie as its
20
+ /// `properties`, lists, sets and dictionaries of them; anything else, and nil, is null.
21
+ FOUNDATION_EXPORT id MRWJsonable(id _Nullable value) NS_REFINED_FOR_SWIFT;
22
+
23
+ NS_ASSUME_NONNULL_END
@@ -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
+ }