react-native-minimal-webview 1.2.0 → 1.3.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 (98) hide show
  1. package/README.md +35 -31
  2. package/android/build.gradle +1 -1
  3. package/android/src/main/java/expo/modules/minimalwebview/Asks.kt +5 -11
  4. package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +17 -11
  5. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +83 -125
  6. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +16 -31
  7. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +18 -19
  8. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +24 -38
  9. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +24 -36
  10. package/android/src/main/java/expo/modules/minimalwebview/NavigationRules.kt +19 -20
  11. package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +41 -37
  12. package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +14 -18
  13. package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +12 -23
  14. package/android/src/main/java/expo/modules/minimalwebview/requests/FileUpload.kt +0 -1
  15. package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +1 -4
  16. package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +34 -24
  17. package/build/WebView.d.ts +11 -2
  18. package/build/WebView.d.ts.map +1 -1
  19. package/build/WebView.js +45 -71
  20. package/build/WebView.js.map +1 -1
  21. package/build/bridge/createBridge.d.ts +1 -5
  22. package/build/bridge/createBridge.d.ts.map +1 -1
  23. package/build/bridge/createBridge.js +3 -15
  24. package/build/bridge/createBridge.js.map +1 -1
  25. package/build/bridge/endpoint.d.ts +1 -2
  26. package/build/bridge/endpoint.d.ts.map +1 -1
  27. package/build/bridge/endpoint.js +5 -6
  28. package/build/bridge/endpoint.js.map +1 -1
  29. package/build/bridge/matchesOrigin.d.ts +11 -0
  30. package/build/bridge/matchesOrigin.d.ts.map +1 -0
  31. package/build/bridge/matchesOrigin.js +26 -0
  32. package/build/bridge/matchesOrigin.js.map +1 -0
  33. package/build/bridge/origins.d.ts +2 -13
  34. package/build/bridge/origins.d.ts.map +1 -1
  35. package/build/bridge/origins.js +1 -30
  36. package/build/bridge/origins.js.map +1 -1
  37. package/build/bridge/pageClient.generated.d.ts +1 -1
  38. package/build/bridge/pageClient.generated.d.ts.map +1 -1
  39. package/build/bridge/pageClient.generated.js +2 -2
  40. package/build/bridge/pageClient.generated.js.map +1 -1
  41. package/build/bridge/protocol.d.ts +3 -5
  42. package/build/bridge/protocol.d.ts.map +1 -1
  43. package/build/bridge/protocol.js +12 -14
  44. package/build/bridge/protocol.js.map +1 -1
  45. package/build/index.d.ts +1 -1
  46. package/build/index.js +1 -1
  47. package/build/navigationRules.d.ts +0 -5
  48. package/build/navigationRules.d.ts.map +1 -1
  49. package/build/navigationRules.js +3 -12
  50. package/build/navigationRules.js.map +1 -1
  51. package/build/reactNativeWebViewDefaults.d.ts +0 -4
  52. package/build/reactNativeWebViewDefaults.d.ts.map +1 -1
  53. package/build/reactNativeWebViewDefaults.js +0 -4
  54. package/build/reactNativeWebViewDefaults.js.map +1 -1
  55. package/build/reactNativeWebViewMessages.d.ts.map +1 -1
  56. package/build/reactNativeWebViewMessages.js +0 -1
  57. package/build/reactNativeWebViewMessages.js.map +1 -1
  58. package/build/refStore.d.ts +0 -2
  59. package/build/refStore.d.ts.map +1 -1
  60. package/build/refStore.js +0 -6
  61. package/build/refStore.js.map +1 -1
  62. package/build/types.d.ts +55 -39
  63. package/build/types.d.ts.map +1 -1
  64. package/ios/Asks.swift +6 -9
  65. package/ios/DelegateProxy.swift +4 -18
  66. package/ios/DownloadName.swift +0 -2
  67. package/ios/Downloads.swift +0 -2
  68. package/ios/Hooks.swift +4 -6
  69. package/ios/Loads.swift +37 -19
  70. package/ios/MinimalWebView+Dialogs.swift +5 -7
  71. package/ios/MinimalWebView+Navigation.swift +23 -49
  72. package/ios/MinimalWebView+Scripts.swift +10 -17
  73. package/ios/MinimalWebView.podspec +1 -2
  74. package/ios/MinimalWebView.swift +63 -128
  75. package/ios/MinimalWebViewModule.swift +1 -18
  76. package/ios/NavigationRules.swift +2 -9
  77. package/ios/OriginRules.swift +4 -13
  78. package/ios/PlatformSettings.swift +9 -30
  79. package/ios/ReadAccess.swift +0 -2
  80. package/ios/Records.swift +18 -0
  81. package/ios/Recovery.swift +2 -8
  82. package/ios/SharedCookies.swift +10 -25
  83. package/mocks/MinimalWebView.ts +5 -0
  84. package/package.json +11 -10
  85. package/src/WebView.tsx +58 -80
  86. package/src/bridge/createBridge.ts +5 -20
  87. package/src/bridge/endpoint.ts +6 -9
  88. package/src/bridge/matchesOrigin.ts +27 -0
  89. package/src/bridge/origins.ts +2 -30
  90. package/src/bridge/pageClient.generated.ts +2 -2
  91. package/src/bridge/pageClient.ts +1 -7
  92. package/src/bridge/protocol.ts +16 -18
  93. package/src/index.ts +1 -1
  94. package/src/navigationRules.ts +6 -12
  95. package/src/reactNativeWebViewDefaults.ts +0 -4
  96. package/src/reactNativeWebViewMessages.ts +0 -1
  97. package/src/refStore.ts +0 -7
  98. package/src/types.ts +55 -39
@@ -1,8 +1,8 @@
1
1
  import ExpoModulesCore
2
2
  import WebKit
3
3
 
4
- // swiftlint:disable file_length - because the view is the aggregate root: it holds what has one owner (the Expo surface, the platform WebView's life, crash recovery, the Document scope, the navigation state, the hook plumbing), and a feature with state of its own gets its own class
5
- // swiftlint:disable:next type_body_length - because the view is the aggregate root, see the file_length reason above
4
+ // swiftlint:disable file_length - because the view is the aggregate root
5
+ // swiftlint:disable:next type_body_length - because the view is the aggregate root
6
6
  class MinimalWebView: ExpoView, WKNavigationDelegate {
7
7
  let onNavigationState = EventDispatcher()
8
8
  let onBridge = EventDispatcher()
@@ -11,16 +11,12 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
11
11
  let onProcessGone = EventDispatcher()
12
12
  let onNavigation = EventDispatcher()
13
13
 
14
- // Props, applied together in applyProps(). The bridge, the hooks with a configure step and the `configuration`
15
- // settings are fixed at mount (see `webView`).
16
14
  var source: WebViewSource?
17
15
  var bridgeScript: String?
18
16
  var bridgeOrigins: [String] = []
19
- /// The `hookOptions` prop, made from the `extensions` prop's options: each hook's value by key. A change reaches the attached hooks (onOptions).
20
17
  var hookOptions: [String: Any] = [:] {
21
18
  didSet { if webView != nil { optionsChanged(from: oldValue) } }
22
19
  }
23
- /// The `ios` prop: WebKit properties by name, applied by PlatformSettings.
24
20
  var settings: [String: Any] = [:]
25
21
  let platformSettings = PlatformSettings()
26
22
  var pullToRefresh = false
@@ -35,66 +31,43 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
35
31
  var injectedScripts: [InjectedScript] = [] {
36
32
  didSet { if let webView { installScripts(webView.configuration.userContentController) } }
37
33
  }
38
- /// The user scripts installScripts added: the others in the content controller are a hook's.
39
34
  var ownScripts: [WKUserScript] = []
40
- /// The page requests JS has a prop for, by prop name (`onDownload`, `onNavigationRequest`, ...), and `onNavigation`, read when a
41
- /// request comes or a decision is reported.
42
35
  var requestHandlers: Set<String> = []
43
36
  private var loadedSource: NSDictionary?
44
37
 
45
- // Created once, from the first props: WebKit reads some WKWebViewConfiguration settings only at creation.
46
38
  private(set) var webView: WKWebView?
47
39
  private var observations: [NSKeyValueObservation] = []
48
40
  private lazy var downloads = Downloads(view: self)
49
41
  private lazy var proxy = DelegateProxy(core: self)
50
- /// When the user last tapped the WKWebView: a link activation counts as user-initiated only right after a tap.
51
42
  let taps = Taps(target: nil, action: nil)
52
43
 
53
- // Navigation state, derived from WebKit in refreshUrls(). Native owns the committed URL; JS is told.
54
44
  private(set) var url = ""
55
- /// `url` as the hooks see it (`WebViewContext.url`): it follows `url` while no load is in flight and WebKit's own URL
56
- /// agrees, and takes the new page at each commit, after `onDocumentEnd`. WebKit moves the back-forward list to the
57
- /// next page before didCommit, and `url` can follow it early.
45
+ /// `WebViewContext.url`: WebKit moves the back-forward list to the next page before didCommit, and `url` can follow it early.
58
46
  private(set) var hookUrl = ""
59
47
  private var pendingUrl: String?
60
- /// An html source never reaches the back-forward list (WebKit hides substitute-data loads from session history):
61
- /// while the item that was current at its commit stays current, the html page is what is on screen.
48
+ /// WebKit hides substitute-data loads (an html source) from the back-forward list.
62
49
  private var htmlNavigation: WKNavigation?
63
50
  private var htmlCommit: (url: String, item: WKBackForwardListItem?)?
64
- /// The loads this view starts itself (source, `load`, reload after an error, an allowed new window), each until its
65
- /// main-frame policy check, which skips the rules, with `mainFrameChecks` at its start. A list: a load can start
66
- /// before the previous one's check, and the page being left can commit after it. A commit drops the loads a later
67
- /// check passed (cut off before their own), so a page can't later skip the rules by navigating to one.
68
- var ownLoads: [(url: URL, checks: Int)] = []
69
- var mainFrameChecks = 0
70
- private(set) lazy var asks = Asks { [weak self] in self?.onHookEvent($0) }
71
- /// The attached hooks' contexts in attach order, for the life of the WKWebView: a hook may keep its own.
51
+ var ownLoads = OwnLoads()
52
+ // No weak self: forming a weak reference to an object in deinit aborts, and deinit's tearDown can be the first use.
53
+ private(set) lazy var asks = Asks { [onHookEvent] in onHookEvent($0) }
72
54
  var hookContexts: [HookContext] = []
73
- /// URLs an `ask` allowed in this Document, keyed by mainFrame: a subframe's answer doesn't decide the main frame's.
74
55
  var askedAndAllowed: [Bool: Set<String>] = [:]
75
- /// A `source` or `load` load is being prepared (shared cookies): loads wait until it is done.
76
56
  private var preparing = false
77
- /// The ref's `load` while it is prepared: it loads instead of the `source` being prepared, if any.
78
57
  private var queuedUrl: URL?
79
- /// After a failed main-frame load `url` is the failed URL (as on Android, which commits an error page);
80
- /// WKWebView itself keeps the previous page, so `url` and reload() use this.
81
- private(set) var failedUrl: String?
82
- /// How the last load ended, "finished", "failed" or "cancelled"; JS sees it only while nothing loads.
83
- private var outcome: String?
58
+ private var directoryOnlyNavigation: WKNavigation?
59
+ /// WKWebView keeps the previous page after a failed main-frame load.
60
+ private var failedLoad: (url: String, inSourceRoot: Bool)?
61
+ private var outcome: Loads.Outcome?
84
62
  private var lastEmitted: NSDictionary?
85
63
  private var updateScheduled = false
86
64
  private var crashTimes: [TimeInterval] = []
87
- /// A web-process death whose reload waits until the view can be seen; a `load`, reload or new `source` replaces it.
88
65
  private var recoveryPending = false
89
- /// `evaluate` calls waiting for their result, by id, until a new document or a dead web process rejects them.
90
66
  var evaluations: [Int: Promise] = [:]
91
67
  var nextEvaluation = 0
92
68
 
93
- // The origin of the document whose page client last posted, as `location.origin` writes it (`*` when every origin is
94
- // allowed). JS's messages are delivered only while the page still has it.
95
69
  var bridgeOrigin: String?
96
- // The JS dialog on screen, and how to complete it if it has to go away.
97
- // While one is up the page is blocked, and an accessibility query into it (XCTest's) hangs: hide it.
70
+ // While a JS dialog is up the page is blocked, and an accessibility query into it (XCTest's) hangs.
98
71
  var dialog: (controller: UIAlertController, cancel: () -> Void)? {
99
72
  didSet { webView?.accessibilityElementsHidden = dialog != nil }
100
73
  }
@@ -102,8 +75,6 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
102
75
  required init(appContext: AppContext? = nil) {
103
76
  super.init(appContext: appContext)
104
77
  clipsToBounds = true
105
- // Made here, not lazily in the deinit fallback's endDocument(.closing), where its closure can't form a weak self.
106
- _ = asks
107
78
  NotificationCenter.default.addObserver(
108
79
  self, selector: #selector(recoverIfVisible), name: UIApplication.didBecomeActiveNotification, object: nil)
109
80
  }
@@ -113,8 +84,6 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
113
84
  recoverIfVisible()
114
85
  }
115
86
 
116
- /// Crash recovery reloads only in a window of an app not in the background, as on Android: there the reload
117
- /// could die the same way, unseen.
118
87
  @objc private func recoverIfVisible() {
119
88
  guard recoveryPending, window != nil, UIApplication.shared.applicationState != .background else { return }
120
89
  recoveryPending = false
@@ -129,34 +98,30 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
129
98
  if !opening { asks.documentEnded(reason) }
130
99
  failEvaluations()
131
100
  bridgeOrigin = nil
132
- // JS queues bridge messages until the next page is ready; at unmount it rejects what is in flight itself.
133
101
  if reason == .committed, bridgeScript != nil { onBridge(["navigated": true]) }
134
102
  if reason == .crashed, bridgeScript != nil { onBridge(["crashed": true]) }
135
103
  askedAndAllowed.removeAll()
136
104
  dismissDialog()
137
- // The spinner belongs to a load, and a crash ends the load without a delegate callback.
105
+ // A crash ends the load without a delegate callback.
138
106
  if reason == .crashed { refreshControl.endRefreshing() }
139
107
  if !opening { hookContexts.forEach { $0.documentEnded(reason) } }
140
108
  }
141
109
 
142
- /// Called once per prop batch. `source` loads last so everything else is ready first.
143
110
  func applyProps() {
144
111
  if webView == nil { createWebView() }
145
112
  guard let webView, !preparing else { return }
146
113
  report(platformSettings.apply(settings, webView: webView))
147
114
  let refresh = pullToRefresh ? refreshControl : nil
148
115
  if webView.scrollView.refreshControl !== refresh { webView.scrollView.refreshControl = refresh }
149
- cookies.set(sharedCookies)
116
+ cookies.set(sharedCookies, for: webView.configuration.websiteDataStore.httpCookieStore)
150
117
  // Records aren't Equatable: compare their dictionaries.
151
118
  guard let next = source, loadedSource != next.toDictionary() as NSDictionary else { return }
152
119
  loadedSource = next.toDictionary() as NSDictionary
153
- // New content from the app: the crash-loop guard starts over (recovery reloads don't come through here).
154
120
  crashTimes = []
155
121
  recoveryPending = false
156
122
  prepare(next)
157
123
  }
158
124
 
159
- /// The ref's `load`. It is prepared as a `source` load is, and a later call replaces one still waiting.
160
125
  func load(url: String) {
161
126
  guard let target = URL(string: url) else { return warn("load: \(url) is not a URL") }
162
127
  guard webView != nil else { return }
@@ -171,15 +136,12 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
171
136
  cookies.prepare { [weak self, weak webView] in
172
137
  guard let self, let webView, webView === self.webView else { return }
173
138
  preparing = false
174
- // A load asked for while the source was prepared replaces it: started first, the source's request (a POST
175
- // included) would be sent only to be cut off.
176
139
  if let queuedUrl {
177
140
  self.queuedUrl = nil
178
141
  loadProgrammatic(URLRequest(url: queuedUrl), inSourceRoot: false)
179
142
  } else if let source {
180
143
  load(source)
181
144
  }
182
- // Props that changed while preparing (a newer source) apply now.
183
145
  applyProps()
184
146
  }
185
147
  }
@@ -199,44 +161,37 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
199
161
  } else {
200
162
  let baseURL = source.baseUrl.flatMap(URL.init)
201
163
  // WebKit puts the html load through decidePolicyFor at its base URL, about:blank without one.
202
- if let own = baseURL ?? URL(string: "about:blank") { ownLoads.append((own, mainFrameChecks)) }
164
+ if let own = baseURL ?? URL(string: "about:blank") { ownLoads.started(own) }
203
165
  htmlNavigation = webView?.loadHTMLString(source.html ?? "", baseURL: baseURL)
204
166
  }
205
167
  }
206
168
 
207
- /// The page on screen (`url`) is the `source`: its URL, or an html source whose commit no other commit or failed load
208
- /// has followed.
209
169
  private var onSource: Bool {
210
170
  guard let source else { return false }
211
- guard let uri = source.uri.flatMap(URL.init) else { return htmlCommit != nil && failedUrl == nil }
171
+ guard let uri = source.uri.flatMap(URL.init) else { return htmlCommit != nil && failedLoad == nil }
212
172
  return Recovery.showsSource(uri.absoluteString, url)
213
173
  }
214
174
 
215
- /// The page on screen is the POST `source`: it can't be fetched again by URL, so reload loads the source instead.
216
175
  private var onPostSource: Bool { source?.body != nil && onSource }
217
176
 
218
- /// Settings keys that could not be applied, as warnings: JS logs them with console.warn.
219
177
  private func report(_ rejected: [[String: String]]) {
220
178
  for entry in rejected {
221
179
  warn("ios.\(entry["key"] ?? ""): \(entry["reason"] ?? "")")
222
180
  }
223
181
  }
224
182
 
225
- /// Loads a request the app started (see `ownLoads`). A file URL goes through loadFileURL, so the page's own assets
226
- /// load (load(_:) can't read local files), with the source's read root or, outside it, the file's directory.
227
183
  func loadProgrammatic(_ request: URLRequest, inSourceRoot: Bool = true) {
228
- if let url = request.url { ownLoads.append((url, mainFrameChecks)) }
184
+ if let url = request.url { ownLoads.started(url) }
229
185
  if let url = request.url, url.isFileURL {
230
186
  let access = ReadAccess.root(for: url, inSourceRoot ? source?.readAccessRoot : nil)
231
187
  if let warning = access.warning { warn(warning) }
232
- webView?.loadFileURL(url, allowingReadAccessTo: access.root)
188
+ let navigation = webView?.loadFileURL(url, allowingReadAccessTo: access.root)
189
+ if !inSourceRoot { directoryOnlyNavigation = navigation }
233
190
  } else {
234
191
  webView?.load(request)
235
192
  }
236
193
  }
237
194
 
238
- /// The ref's reload: an explicit retry starts the crash-loop guard over, like a new source. Pull-to-refresh uses
239
- /// reload().
240
195
  func retry() {
241
196
  crashTimes = []
242
197
  reload()
@@ -244,37 +199,27 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
244
199
 
245
200
  func reload() {
246
201
  recoveryPending = false
247
- // WebKit's reload redoes no failed load, POST or html source (it fetches the base URL), and loads nothing while `url`
248
- // is nil (no commit, a dead process).
202
+ // WebKit's reload redoes no failed load, POST or html source, and loads nothing while `url` is nil.
249
203
  let onHtmlSource = onSource && source?.uri == nil
250
- if let webView, webView.url != nil, failedUrl == nil, !onPostSource, !onHtmlSource { webView.reload() } else { loadAgain() }
204
+ if let webView, webView.url != nil, failedLoad == nil, !onPostSource, !onHtmlSource { webView.reload() } else { loadAgain() }
251
205
  }
252
206
 
253
- /// Loads the page on screen again, as crash recovery does. In order:
254
- /// - the `source`, when it is the page or nothing has committed (so its headers, POST body or html are used);
255
- /// - else the failed URL;
256
- /// - else the back-forward list's item (a dead web process relaunches with it, so history stays).
257
- /// A `source` being prepared loads once it is ready instead.
258
207
  private func loadAgain() {
259
208
  guard let webView, !preparing else { return }
260
- if let source, onSource || failedUrl == nil && webView.backForwardList.currentItem == nil {
209
+ if let source, onSource || failedLoad == nil && webView.backForwardList.currentItem == nil {
261
210
  load(source)
262
- } else if let failedUrl, let target = URL(string: failedUrl) {
263
- loadProgrammatic(URLRequest(url: target))
211
+ } else if let failedLoad, let target = URL(string: failedLoad.url) {
212
+ loadProgrammatic(URLRequest(url: target), inSourceRoot: failedLoad.inSourceRoot)
264
213
  } else {
265
214
  webView.reload()
266
215
  }
267
216
  }
268
217
 
269
- /// `source` loads from applyProps once the load is prepared.
270
218
  private func createWebView() {
271
219
  let configuration = WKWebViewConfiguration()
272
- // The creation-time settings (`ios.configuration`) and the configure hooks go first and the bridge after them,
273
- // so nothing they set displaces the content controller the bridge is installed in.
274
220
  report(platformSettings.apply(settings, webView: nil, configuration: configuration))
275
221
  hookContexts = MinimalWebViewHooks.hooks.filter { hookOptions[$0.key] != nil }.map { HookContext($0, self) }
276
222
  for context in hookContexts { context.hook.configure?(configuration, context) }
277
- // A typo, or a hook's module not linked or not rebuilt.
278
223
  for key in hookOptions.keys where !hookContexts.contains(where: { $0.key == key }) {
279
224
  warn("extension \(key): no hook is registered under this key")
280
225
  }
@@ -289,6 +234,7 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
289
234
  }
290
235
  let webView = webViewClass.init(frame: bounds, configuration: configuration)
291
236
  webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
237
+ proxy.hookDecides = { [weak self] in _ = self?.takeOwnLoad($0) }
292
238
  webView.navigationDelegate = proxy
293
239
  webView.uiDelegate = proxy
294
240
  webView.addGestureRecognizer(taps)
@@ -301,18 +247,14 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
301
247
  webView.observe(\.estimatedProgress) { _, _ in update() }
302
248
  ] + [\WKWebView.canGoBack, \.canGoForward].map { webView.observe($0) { _, _ in update() } }
303
249
  self.webView = webView
304
- cookies.didCreate(webView)
305
- // The live settings before the hooks, as on Android: what a hook sets wins over the package's defaults.
306
250
  report(platformSettings.apply(settings, webView: webView))
307
251
  hookContexts.forEach { $0.hook.attach(webView, $0) }
308
252
  }
309
253
 
310
- /// React Native calls `invalidate` on this view (the Fabric component view; Expo's are never recycled) at every
311
- /// unmount. Expo's Swift-visible header doesn't declare it, so Swift can't `override` it: declared here, it wins at
312
- /// runtime, and it calls the inherited one as `super` would.
254
+ /// React Native calls `invalidate` at every unmount (Expo's views are never recycled), and Expo's (React Native 0.82+) resets its size-update guard.
255
+ /// Expo's Swift-visible header doesn't declare it, so Swift can't `override` it: this one wins at runtime.
313
256
  @objc func invalidate() {
314
257
  tearDown()
315
- // Expo's (React Native 0.82+) resets its size-update guard; React Native's UIView default does nothing.
316
258
  let selector = #selector(invalidate)
317
259
  typealias Invalidate = @convention(c) (AnyObject, Selector) -> Void
318
260
  guard class_respondsToSelector(ExpoView.self, selector),
@@ -320,12 +262,10 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
320
262
  unsafeBitCast(inherited, to: Invalidate.self)(self, selector)
321
263
  }
322
264
 
323
- /// Once: from invalidate, or from deinit if that never ran (there weak self is nil, so in-flight evaluates can't be
324
- /// rejected).
325
265
  private func tearDown() {
326
266
  guard let webView else { return }
327
267
  endDocument(.closing)
328
- cookies.detach()
268
+ cookies.set(false, for: webView.configuration.websiteDataStore.httpCookieStore)
329
269
  let closed = hookContexts
330
270
  closed.forEach { $0.detach() }
331
271
  hookContexts = []
@@ -347,26 +287,21 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
347
287
  MainActor.assumeIsolated { tearDown() }
348
288
  }
349
289
 
350
- /// The page on screen: the back-forward list's current item, which a commit creates or moves to a moment before
351
- /// didCommit (a history step may move it earlier), and pushState/replaceState/hash update.
352
290
  private func refreshUrls() {
353
291
  guard let webView else { return }
354
292
  let item = webView.backForwardList.currentItem
355
- // Empty before the first commit: the URL being loaded is pendingUrl.
356
293
  let committed = htmlCommit.flatMap { $0.item === item ? $0.url : nil } ?? item?.url.absoluteString ?? ""
357
- url = failedUrl ?? committed
294
+ url = failedLoad?.url ?? committed
358
295
  // WebKit's `url` is the active URL: a pending or provisional load shows here first.
359
296
  let active = webView.url?.absoluteString
360
297
  pendingUrl = webView.isLoading && active != committed ? active : nil
361
- if !webView.isLoading, failedUrl != nil || active == committed { hookUrl = url }
298
+ if !webView.isLoading, failedLoad != nil || active == committed { hookUrl = url }
362
299
  }
363
300
 
364
- /// WebKit's KVO fires before the delegate callbacks: the state is read and emitted one main-queue turn later, once
365
- /// per turn, so changes within one pass are combined into one event. The start of a load goes out at once as well: a
366
- /// load that starts and fails within one pass must still reach JS as loading true -> false. The end of a load waits
367
- /// for the pass, because WebKit clears isLoading before it reports the failure (the error and outcome go first).
301
+ /// WebKit's KVO fires before the delegate callbacks, and clears isLoading before it reports a failure: the state is
302
+ /// read a main-queue turn later.
368
303
  private func scheduleUpdate() {
369
- if let webView, webView.isLoading, lastEmitted?["loading"] as? Bool != true { emitState() }
304
+ if loadStartUnsent { emitState() }
370
305
  guard !updateScheduled else { return }
371
306
  updateScheduled = true
372
307
  DispatchQueue.main.async { [weak self] in
@@ -377,6 +312,8 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
377
312
  }
378
313
  }
379
314
 
315
+ private var loadStartUnsent: Bool { webView?.isLoading == true && lastEmitted?["loading"] as? Bool != true }
316
+
380
317
  private func emitState() {
381
318
  guard let webView else { return }
382
319
  let state: NSDictionary = [
@@ -387,33 +324,17 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
387
324
  "progress": webView.estimatedProgress,
388
325
  "canGoBack": webView.canGoBack,
389
326
  "canGoForward": webView.canGoForward,
390
- "outcome": webView.isLoading ? NSNull() : outcome as Any? ?? NSNull()
327
+ "outcome": webView.isLoading ? NSNull() : outcome?.rawValue as Any? ?? NSNull()
391
328
  ]
392
329
  guard state != lastEmitted else { return }
393
330
  lastEmitted = state
394
331
  onNavigationState(state as? [String: Any] ?? [:])
395
332
  }
396
333
 
397
- /// An observation callback the core implements: every hook delegate that implements it gets it after the core.
398
334
  private func forward(_ callback: (WKNavigationDelegate) -> Void) {
399
335
  proxy.navigationDelegates.forEach(callback)
400
336
  }
401
337
 
402
- /// A main-frame load WebKit ended with `error`: reports it to onError when it failed (`Loads.ended`), and returns its
403
- /// outcome.
404
- private func ended(with error: Error) -> String {
405
- let nsError = error as NSError
406
- let end = Loads.ended(by: nsError)
407
- guard let kind = end.kind else { return end.outcome }
408
- let failing = (nsError.userInfo[NSURLErrorFailingURLErrorKey] as? URL)?.absoluteString
409
- ?? nsError.userInfo[NSURLErrorFailingURLStringErrorKey] as? String ?? pendingUrl ?? url
410
- failedUrl = failing
411
- onError(["kind": kind, "url": failing, "code": nsError.code, "description": nsError.localizedDescription])
412
- return end.outcome
413
- }
414
-
415
- // MARK: WKNavigationDelegate
416
-
417
338
  func webView(
418
339
  _ webView: WKWebView,
419
340
  decidePolicyFor navigationAction: WKNavigationAction,
@@ -455,8 +376,8 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
455
376
 
456
377
  func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
457
378
  endDocument(.committed)
458
- ownLoads.removeAll { $0.checks < mainFrameChecks }
459
- failedUrl = nil
379
+ ownLoads.committed()
380
+ failedLoad = nil
460
381
  htmlCommit = navigation === htmlNavigation
461
382
  ? (webView.url?.absoluteString ?? "about:blank", webView.backForwardList.currentItem) : nil
462
383
  refreshUrls()
@@ -466,30 +387,48 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
466
387
  }
467
388
 
468
389
  func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
469
- loadEnded { $0.webView?(webView, didFinish: navigation) }
390
+ loadEnded(.finished) { $0.webView?(webView, didFinish: navigation) }
470
391
  }
471
392
 
472
393
  func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
473
- loadEnded(error) { $0.webView?(webView, didFail: navigation, withError: error) }
394
+ loadFailed(webView, navigation, error, provisional: false)
474
395
  }
475
396
 
476
397
  func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
477
- loadEnded(error) { $0.webView?(webView, didFailProvisionalNavigation: navigation, withError: error) }
398
+ loadFailed(webView, navigation, error, provisional: true)
399
+ }
400
+
401
+ private func loadFailed(_ webView: WKWebView, _ navigation: WKNavigation?, _ error: Error, provisional: Bool) {
402
+ let nsError = error as NSError
403
+ let end = Loads.ended(by: nsError)
404
+ if let kind = end.kind {
405
+ let failing = (nsError.userInfo[NSURLErrorFailingURLErrorKey] as? URL)?.absoluteString
406
+ ?? nsError.userInfo[NSURLErrorFailingURLStringErrorKey] as? String ?? pendingUrl ?? url
407
+ failedLoad = (failing, inSourceRoot: navigation == nil || navigation !== directoryOnlyNavigation)
408
+ onError(["kind": kind, "url": failing, "code": nsError.code, "description": nsError.localizedDescription])
409
+ }
410
+ loadEnded(end.outcome) {
411
+ if provisional {
412
+ $0.webView?(webView, didFailProvisionalNavigation: navigation, withError: error)
413
+ } else {
414
+ $0.webView?(webView, didFail: navigation, withError: error)
415
+ }
416
+ }
478
417
  }
479
418
 
480
- private func loadEnded(_ error: Error? = nil, _ callback: (WKNavigationDelegate) -> Void) {
481
- outcome = error.map { ended(with: $0) } ?? "finished"
419
+ private func loadEnded(_ outcome: Loads.Outcome, _ callback: (WKNavigationDelegate) -> Void) {
420
+ self.outcome = outcome
482
421
  // The spinner stops, or it would ignore the next pull.
483
422
  refreshControl.endRefreshing()
484
423
  scheduleUpdate()
485
424
  forward(callback)
486
425
  }
487
426
 
488
- /// The web content process died. The WKWebView survives it, so reload, unless it keeps crashing.
427
+ /// The WKWebView survives its web content process's death.
489
428
  func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
490
429
  let recovered = Recovery.crashAllowsReload(&crashTimes, now: ProcessInfo.processInfo.systemUptime) && !onPostSource
491
430
  endDocument(.crashed)
492
- if lastEmitted?["loading"] as? Bool == true { outcome = "failed" } // the load the crash cut off
431
+ if lastEmitted?["loading"] as? Bool == true { outcome = .failed }
493
432
  if recovered {
494
433
  recoveryPending = true
495
434
  recoverIfVisible()
@@ -499,9 +438,7 @@ class MinimalWebView: ExpoView, WKNavigationDelegate {
499
438
  }
500
439
  }
501
440
 
502
- /// What the hooks see of this view, through a HookContext per attached hook.
503
441
  extension MinimalWebView {
504
- /// Tells each attached hook whose value changed, and attaches a hook without `configure` or `webViewClass` whose key turns on.
505
442
  private func optionsChanged(from old: [String: Any]) {
506
443
  for key in inRegistrationOrder(Set(old.keys).union(hookOptions.keys), MinimalWebViewHooks.hooks.map(\.key)) {
507
444
  let (was, value) = (old[key], hookOptions[key])
@@ -518,7 +455,6 @@ extension MinimalWebView {
518
455
  guard let webView, let hook = MinimalWebViewHooks.hooks.first(where: { $0.key == key }) else {
519
456
  return warn("extension \(key): no hook is registered under this key")
520
457
  }
521
- // configure edits the configuration the WKWebView was created from, and webViewClass makes it: too late for this one.
522
458
  guard hook.configure == nil, hook.webViewClass == nil else {
523
459
  let why = hook.configure != nil ? "configure" : "a webViewClass"
524
460
  return warn("extension \(key): its hook has \(why), so it attaches only when the WebView is created")
@@ -532,7 +468,6 @@ extension MinimalWebView {
532
468
  hookContexts.first { $0.key == key && $0.isOn }?.handlers[method]
533
469
  }
534
470
 
535
- /// Gives the proxy the delegates of the hooks that are on, in attach order, then each hook's own order.
536
471
  func routeDelegates() {
537
472
  let on = hookContexts.filter(\.isOn)
538
473
  proxy.navigationDelegates = on.flatMap(\.navigationDelegates)
@@ -41,7 +41,7 @@ public class MinimalWebViewModule: Module {
41
41
  AsyncFunction("bridgePost") { (view: MinimalWebView, message: String) in view.bridgePost(message) }
42
42
  AsyncFunction("answer") { (view: MinimalWebView, askId: Int, json: String) in
43
43
  let value = try? JSONSerialization.jsonObject(with: Data(json.utf8), options: .fragmentsAllowed)
44
- view.asks.answer(askId, value is NSNull ? nil : value)
44
+ MainActor.assumeIsolated { view.asks.answer(askId, value is NSNull ? nil : value) }
45
45
  }
46
46
  AsyncFunction("hook") { (view: MinimalWebView, name: String, method: String, args: String, promise: Promise) in
47
47
  hook(view, name, method, args, promise)
@@ -92,20 +92,3 @@ private func reject(_ promise: Promise, _ error: Error) {
92
92
  let platform = error as? PlatformError
93
93
  promise.reject(platform?.code ?? "native_error", platform?.message ?? error.localizedDescription)
94
94
  }
95
-
96
- // A prop that fails to convert is dropped whole (ExpoFabricView's try?), so every field is optional.
97
-
98
- struct WebViewSource: Record {
99
- @Field var uri: String? = nil
100
- @Field var headers: [String: String]? = nil
101
- @Field var body: String? = nil
102
- @Field var readAccessRoot: String? = nil
103
- @Field var html: String? = nil
104
- @Field var baseUrl: String? = nil
105
- }
106
-
107
- struct InjectedScript: Record {
108
- @Field var code: String? = nil
109
- @Field var allFrames: Bool? = nil
110
- }
111
-
@@ -1,6 +1,5 @@
1
1
  import Foundation
2
2
 
3
- /// The structured navigation rules. Semantics and cases: src/__tests__/vectors/navigation-rules.json (shared with Kotlin).
4
3
  enum NavigationRules {
5
4
  struct Request {
6
5
  let url: String
@@ -8,7 +7,6 @@ enum NavigationRules {
8
7
  let newWindow: Bool
9
8
  let userInitiated: Bool
10
9
 
11
- /// The fields JS events carry.
12
10
  var payload: [String: Any] {
13
11
  ["url": url, "mainFrame": mainFrame, "newWindow": newWindow, "userInitiated": userInitiated]
14
12
  }
@@ -22,7 +20,6 @@ enum NavigationRules {
22
20
  let rule: Int?
23
21
  }
24
22
 
25
- /// What rules match; `params` are the query's `&`-separated parameters.
26
23
  private struct Parts {
27
24
  let scheme: String
28
25
  let host: String?
@@ -30,10 +27,8 @@ enum NavigationRules {
30
27
  let params: [String]
31
28
  }
32
29
 
33
- /// Load in place without the rules.
34
30
  private static let internalSchemes: Set<String> = ["about", "data", "javascript"]
35
- /// Never open as a new window, whatever the rules say: the core loads an allowed new window in the main frame itself,
36
- /// past the engine's limits on what a page may navigate the top frame to.
31
+ /// The core loads an allowed new window itself, past WebKit's limits on what a page may navigate the top frame to.
37
32
  private static let noNewWindowSchemes = internalSchemes.union(["blob", "file"])
38
33
 
39
34
  /// The rules' decision, gated for `ask`: blocked when nothing can answer it (`canAsk` false), allowed when its URL is
@@ -55,7 +50,6 @@ enum NavigationRules {
55
50
  let scheme = request.url.firstIndex(of: ":").map { request.url[..<$0].lowercased() } ?? ""
56
51
  if request.newWindow, noNewWindowSchemes.contains(scheme) { return Decision(action: .block, rule: nil) }
57
52
  if internalSchemes.contains(scheme) { return Decision(action: .allow, rule: nil) }
58
- // JS sends defaultNavigationRules when the prop is unset; no rules, nil or empty, match nothing.
59
53
  guard let rules, !rules.isEmpty,
60
54
  let parts = scheme == "blob" ? blobOrigin(request.url) : urlParts(scheme, request.url)
61
55
  else { return Decision(action: .block, rule: nil) }
@@ -66,10 +60,9 @@ enum NavigationRules {
66
60
  }
67
61
 
68
62
  private static func urlParts(_ scheme: String, _ url: String) -> Parts {
69
- // shortcut: an unparseable URL has no host and path "/", so only host-less rules match; parse it by hand when a rule must match such URLs
70
63
  let components = URLComponents(string: url)
71
64
  let rawPath = components?.percentEncodedPath ?? ""
72
- // No authority (`myapp:/abs`, `myapp:open`): the path is "/", as in Kotlin. `file:///x` has an empty one, not none.
65
+ // URLComponents gives `file:///x` an empty host, not none.
73
66
  let path = rawPath.isEmpty || components?.host == nil ? "/" : rawPath
74
67
  let params = components?.percentEncodedQuery?.split(separator: "&").map(String.init) ?? []
75
68
  return Parts(scheme: scheme, host: host(components), path: path, params: params)
@@ -1,14 +1,8 @@
1
1
  import Foundation
2
2
  import WebKit
3
3
 
4
- /// Origin rules in Android's format (the bridge's `allowedOrigins`):
5
- /// `*`, an exact http(s) origin such as `https://example.com:8443`, or `https://*.example.com` for subdomains.
6
- /// Compared case-insensitively, a missing port is the scheme's default, and a malformed rule matches nothing.
7
- /// createBridge validates the rules on the JS side. Cases: src/__tests__/vectors/origin-rules.json.
8
4
  enum OriginRules {
9
- /// The origin string of a frame, `scheme://host[:port]`, or `null` for an opaque origin (no scheme: an html source
10
- /// without `baseUrl`, a sandboxed page). The default port is left out (WebKit reports it as 0) and an IPv6 host is
11
- /// bracketed.
5
+ /// The origin as `location.origin` writes it: `null` for an opaque one (no scheme). WebKit reports a default port as 0.
12
6
  static func origin(_ scheme: String, _ host: String, _ port: Int) -> String {
13
7
  guard !scheme.isEmpty else { return "null" }
14
8
  let defaultPort = scheme == "https" ? 443 : scheme == "http" ? 80 : nil
@@ -16,12 +10,11 @@ enum OriginRules {
16
10
  return "\(scheme)://\(host)" + (port == 0 || port == defaultPort ? "" : ":\(port)")
17
11
  }
18
12
 
19
- /// The origin as `location.origin` writes it, so the bridge can compare the two exactly.
20
13
  static func origin(of security: WKSecurityOrigin) -> String {
21
14
  origin(security.protocol, security.host, security.port)
22
15
  }
23
16
 
24
- static func allows(_ rules: [String], _ origin: String) -> Bool {
17
+ @MainActor static func allows(_ rules: [String], _ origin: String) -> Bool {
25
18
  let value = parse(origin)
26
19
  return rules.contains { rule in
27
20
  guard let r = parse(rule), let o = value, !o.wildcard else { return rule == "*" }
@@ -29,13 +22,11 @@ enum OriginRules {
29
22
  }
30
23
  }
31
24
 
32
- // Built once: a regex literal in the function body is compiled again on every call. Regex isn't Sendable; every
33
- // caller is a WebKit delegate callback on the main thread.
34
- nonisolated(unsafe) private static let pattern = #/(https?):\/\/(\*\.(?!\[))?([a-z0-9_-]+(?:\.[a-z0-9_-]+)*|\[[0-9a-f:.]+\])(?::(\d{1,5}))?/#
25
+ @MainActor private static let pattern = #/(https?):\/\/(\*\.(?!\[))?([a-z0-9_-]+(?:\.[a-z0-9_-]+)*|\[[0-9a-f:.]+\])(?::(\d{1,5}))?/#
35
26
 
36
27
  private struct Parsed { let scheme: Substring, wildcard: Bool, host: Substring, port: Int }
37
28
 
38
- private static func parse(_ text: String) -> Parsed? {
29
+ @MainActor private static func parse(_ text: String) -> Parsed? {
39
30
  guard let m = try? pattern.wholeMatch(in: text.lowercased()) else { return nil }
40
31
  return Parsed(scheme: m.1, wildcard: m.2 != nil, host: m.3, port: m.4.flatMap { Int($0) } ?? (m.1 == "https" ? 443 : 80))
41
32
  }