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.
Files changed (118) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +150 -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 +487 -0
  9. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +507 -0
  10. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +358 -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 +197 -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 +303 -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 +259 -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 +96 -0
  22. package/build/WebView.d.ts.map +1 -0
  23. package/build/WebView.js +453 -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 +137 -0
  28. package/build/bridge/createBridge.js.map +1 -0
  29. package/build/bridge/endpoint.d.ts +33 -0
  30. package/build/bridge/endpoint.d.ts.map +1 -0
  31. package/build/bridge/endpoint.js +105 -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 +59 -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 +15 -0
  46. package/build/defaultNavigationRules.d.ts.map +1 -0
  47. package/build/defaultNavigationRules.js +22 -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 +701 -0
  54. package/build/platform.generated.d.ts.map +1 -0
  55. package/build/platform.generated.js +201 -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 +16 -0
  62. package/build/reactNativeWebViewMessages.d.ts.map +1 -0
  63. package/build/reactNativeWebViewMessages.js +24 -0
  64. package/build/reactNativeWebViewMessages.js.map +1 -0
  65. package/build/refStore.d.ts +32 -0
  66. package/build/refStore.d.ts.map +1 -0
  67. package/build/refStore.js +115 -0
  68. package/build/refStore.js.map +1 -0
  69. package/build/types.d.ts +1173 -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 +158 -0
  80. package/ios/DocumentEnd.swift +22 -0
  81. package/ios/DownloadName.swift +10 -0
  82. package/ios/Downloads.swift +51 -0
  83. package/ios/Hooks.swift +310 -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 +38 -0
  88. package/ios/MRWInvoke.m +187 -0
  89. package/ios/MinimalWebView+Dialogs.swift +96 -0
  90. package/ios/MinimalWebView+Navigation.swift +243 -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 +513 -0
  95. package/ios/MinimalWebViewModule.swift +110 -0
  96. package/ios/NavigationRules.swift +123 -0
  97. package/ios/OriginRules.swift +36 -0
  98. package/ios/PlatformCompletions.generated.swift +39 -0
  99. package/ios/PlatformSettings.swift +252 -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 +99 -4
  104. package/src/WebView.tsx +626 -0
  105. package/src/bridge/createBridge.ts +178 -0
  106. package/src/bridge/endpoint.ts +123 -0
  107. package/src/bridge/origins.ts +61 -0
  108. package/src/bridge/pageClient.generated.ts +5 -0
  109. package/src/bridge/pageClient.ts +67 -0
  110. package/src/bridge/protocol.ts +78 -0
  111. package/src/defaultNavigationRules.ts +24 -0
  112. package/src/index.ts +37 -0
  113. package/src/platform.generated.ts +693 -0
  114. package/src/reactNativeWebViewDefaults.ts +13 -0
  115. package/src/reactNativeWebViewMessages.ts +26 -0
  116. package/src/refStore.ts +165 -0
  117. package/src/types.defaults.ts +24 -0
  118. package/src/types.ts +1240 -0
@@ -0,0 +1,487 @@
1
+ package expo.modules.minimalwebview
2
+
3
+ import android.content.Context
4
+ import android.os.Handler
5
+ import android.os.Looper
6
+ import android.util.Log
7
+ import android.view.View
8
+ import android.webkit.ConsoleMessage
9
+ import android.webkit.SafeBrowsingResponse
10
+ import android.webkit.WebChromeClient
11
+ import android.webkit.WebResourceError
12
+ import android.webkit.WebResourceRequest
13
+ import android.webkit.WebView
14
+ import android.webkit.WebViewClient
15
+ import androidx.webkit.SafeBrowsingResponseCompat
16
+ import androidx.webkit.WebResourceErrorCompat
17
+ import androidx.webkit.WebViewClientCompat
18
+ import java.util.concurrent.ConcurrentHashMap
19
+ import java.util.concurrent.CopyOnWriteArrayList
20
+ import java.util.concurrent.atomic.AtomicBoolean
21
+
22
+ /**
23
+ * Native hooks: Kotlin in an app's or a package's own Expo module that gets the real [WebView] behind this package's
24
+ * WebViews and chains its own clients to it, with no protocol to implement.
25
+ *
26
+ * **Important:** leave alone what the core owns: the WebView's own client slots (add to [WebViewContext.clients] and
27
+ * [WebViewContext.chromeClients] instead), its touch and scroll-change listeners ([WebViewContext.touchListeners] and
28
+ * [WebViewContext.scrollListeners]), the bridge's web message listener and document-start scripts, and the download
29
+ * listener ([WebViewContext.onDownloadStart]).
30
+ * @see [Native hooks guide](https://rasmuskard.github.io/react-native-minimal-webview/guides/native-hooks/)
31
+ */
32
+ object MinimalWebViewHooks {
33
+ internal class Hook(
34
+ val key: String,
35
+ val webViewFactory: ((Context) -> WebView)?,
36
+ val configure: ((WebView, WebViewContext) -> Unit)?,
37
+ val attach: (WebView, WebViewContext) -> Unit
38
+ )
39
+
40
+ internal val hooks = mutableListOf<Hook>()
41
+
42
+ /**
43
+ * Registers the hook for [key].
44
+ *
45
+ * Call it from your module's `OnCreate`, before the first WebView.
46
+ *
47
+ * The same `register` call running again replaces its hook: a JS reload creates the modules anew and runs their
48
+ * `OnCreate` again. The call is told apart by where its [attach] lambda is written, so a helper that wraps its
49
+ * caller's `attach` in a lambda of its own is one call, and a second hook through it replaces the first silently; a
50
+ * helper that passes the caller's lambda on keeps them apart.
51
+ *
52
+ * The hook attaches to each WebView whose `extensions` prop has an extension with [key] that is on;
53
+ * [HookExtension.options](https://rasmuskard.github.io/react-native-minimal-webview/typescript/react-native-minimal-webview/type-aliases/HookExtension/#options)
54
+ * says when. After a renderer crash it attaches again, to the WebView that replaces the dead one.
55
+ *
56
+ * Hooks attach in registration order, which across packages is autolinking's (packages sorted by name), so an
57
+ * earlier hook's clients come first. A hook whose key turns on after the WebView was created attaches after the
58
+ * hooks attached already; after a crash it takes its place in registration order again.
59
+ *
60
+ * @param key the key of the app's extension that turns on the hook. Keys are global, so prefix yours with your
61
+ * package's name. `core` is reserved for the package's own events: a hook under it is logged and not registered.
62
+ * @param webViewFactory makes each WebView this hook is attached to, on or off: the first one and each after a
63
+ * renderer crash, as a subclass that overrides what WebView lets a subclass override. Null leaves it to the other
64
+ * hooks. When the attached hooks name different factories (the same object is one), the first one's in
65
+ * registration order makes the WebView, and a warning names the others. Those still attach, so check the
66
+ * class `attach` gets.
67
+ * @param configure runs on the main thread as soon as each WebView this hook is attached to, on or off, is made,
68
+ * before the package sets it up ([WebViewCompat.setProfile][androidx.webkit.WebViewCompat.setProfile] goes here).
69
+ * It gets the same context that [attach] gets next for that WebView, so state it makes can be keyed by the context.
70
+ * @param attach runs on the main thread once the WebView has its settings and is in the view hierarchy, so what it
71
+ * sets wins over those settings. Register what to run when that WebView goes away with
72
+ * [WebViewContext.onDestroyed]. Document-start scripts you add here run before the package's, so
73
+ * `window.nativeBridge` and `injectedScripts` aren't there yet (on iOS yours run after them).
74
+ * @throws IllegalStateException when a different hook is registered under [key] already. Don't rely on it: a minified
75
+ * build can't tell the two apart and may replace the first hook instead, so give each hook its own key.
76
+ */
77
+ fun register(
78
+ key: String,
79
+ webViewFactory: ((Context) -> WebView)? = null,
80
+ configure: ((WebView, WebViewContext) -> Unit)? = null,
81
+ attach: (WebView, WebViewContext) -> Unit
82
+ ) {
83
+ if (key == "core") {
84
+ Log.e(TAG, "the hook key `core` is reserved: the hook is not registered")
85
+ return
86
+ }
87
+ val hook = Hook(key, webViewFactory, configure, attach)
88
+ val index = hooks.indexOfFirst { it.key == key }
89
+ if (index < 0) {
90
+ hooks += hook
91
+ return
92
+ }
93
+ // Each lambda in the source compiles to a class of its own: the same class is the same call running again.
94
+ // shortcut: R8 can merge two lambdas' classes in a minified build; upgrade if a duplicate must throw there too.
95
+ val first = hooks[index].attach.javaClass
96
+ check(first == attach.javaClass) {
97
+ "two hooks are registered under `$key` (${first.name} and ${attach.javaClass.name}): " +
98
+ "prefix yours with your package's name"
99
+ }
100
+ hooks[index] = hook
101
+ }
102
+ }
103
+
104
+ /** Splits [keys] into the [hooks] registered under them, in registration order, and the keys no hook is registered under. */
105
+ internal fun selectHooks(
106
+ hooks: List<MinimalWebViewHooks.Hook>,
107
+ keys: Set<String>
108
+ ): Pair<List<MinimalWebViewHooks.Hook>, Set<String>> {
109
+ val attaching = hooks.filter { it.key in keys }
110
+ return attaching to keys - attaching.map { it.key }.toSet()
111
+ }
112
+
113
+ /** Hooks whose keys turn on together attach in registration order, which orders their clients. */
114
+ internal fun inRegistrationOrder(keys: Set<String>, registered: List<String>) =
115
+ registered.filter { it in keys } + (keys - registered.toSet()).sorted()
116
+
117
+ /** Picks the hook that makes the WebView from [attaching] (the first with a factory, null for a plain WebView), and the keys of the others whose factory is a different object. */
118
+ internal fun pickFactory(attaching: List<MinimalWebViewHooks.Hook>): Pair<MinimalWebViewHooks.Hook?, List<String>> {
119
+ val named = attaching.filter { it.webViewFactory != null }
120
+ val maker = named.firstOrNull()
121
+ return maker to named.filter { it.webViewFactory !== maker?.webViewFactory }.map { it.key }
122
+ }
123
+
124
+ /**
125
+ * Picks the first of the clients that override a decision callback, or null. Calls [warn] once per callback and reason:
126
+ * - more than one client overrides the callback;
127
+ * - a client takes it, when the caller passes `lost`: what stops applying, the app's props or their defaults that would decide it otherwise.
128
+ */
129
+ internal class Deciders(private val warn: (String) -> Unit) {
130
+ // Concurrent: shouldInterceptRequest decides on Chromium's IO thread.
131
+ private val warned = ConcurrentHashMap.newKeySet<String>()
132
+
133
+ fun <T> first(callback: String, clients: List<T>, lost: String? = null, overrides: (T) -> Boolean): T? {
134
+ val overriding = clients.filter(overrides)
135
+ if (overriding.size > 1 && warned.add(callback)) {
136
+ warn("$callback: more than one hook client overrides it; only the first one gets it")
137
+ }
138
+ if (lost != null && overriding.isNotEmpty() && warned.add("$callback taken")) {
139
+ warn("$callback: a hook client takes it, so $lost")
140
+ }
141
+ return overriding.firstOrNull()
142
+ }
143
+ }
144
+
145
+ /**
146
+ * One WebView as one hook sees it, for one attach.
147
+ *
148
+ * Each attach gets a new context, and the handlers registered on it belong to that attach: after a renderer crash, the
149
+ * new WebView's `attach` registers them again.
150
+ *
151
+ * Call [emit] and [ask] from any thread, and the rest on the main thread, where the handlers and the answers run.
152
+ *
153
+ * Values from JS, the [options], an [ask]'s answer and a [handle] handler's arguments, come in JSON types: a number as
154
+ * a `Double`, an object as a `Map<String, Any?>`, an array as a `List<Any?>`, and a string, a boolean and null as
155
+ * themselves.
156
+ *
157
+ * The hook is on while its extension's `options` are not null or false;
158
+ * [HookExtension.options](https://rasmuskard.github.io/react-native-minimal-webview/typescript/react-native-minimal-webview/type-aliases/HookExtension/#options)
159
+ * says what off means. [onOptions] runs when the hook turns off, so it can release what it holds, and again when it
160
+ * turns on.
161
+ *
162
+ * A context kept after its attach ended (the view closed, or a renderer crash replaced the WebView) does nothing and
163
+ * holds nothing of the WebView.
164
+ * @see [Native hooks guide](https://rasmuskard.github.io/react-native-minimal-webview/guides/native-hooks/)
165
+ */
166
+ interface WebViewContext {
167
+ /**
168
+ * This hook's extension's `options`, the new ones after a change; null while the hook is off.
169
+ *
170
+ * After a change they are the new value already when the [onOptions] handlers run.
171
+ */
172
+ val options: Any?
173
+
174
+ /**
175
+ * The committed URL, the one `useWebViewState` reports; empty before the first commit and after the attach ended.
176
+ *
177
+ * Inside [onDocumentEnd] it is still the page that ended. With WebView 146 and later, `onPageStarted` comes after the
178
+ * commit that ends the Document, so `url` is already the new page there.
179
+ */
180
+ val url: String
181
+
182
+ /**
183
+ * Your clients, in order; add them in `attach`. While the hook is off, none of them gets a callback.
184
+ *
185
+ * Each callback reaches the clients by one of these rules:
186
+ * - A callback that decides something, by its return value or through the handler, request or callback it gets
187
+ * (`onReceivedSslError`, `onReceivedHttpAuthRequest`, `onReceivedClientCertRequest`), goes to the first client
188
+ * that overrides it, instead of the core and the app's props.
189
+ * - Every other callback reaches the core first, then each client that overrides it.
190
+ * - `onRenderProcessGone` is the exception: it reaches every client that overrides it, and the core returns true and
191
+ * replaces the WebView, so a client's return value is ignored.
192
+ *
193
+ * Taking a decision the core makes from the app's props or their defaults switches them off, the default navigation
194
+ * rules' security checks included, and a warning names the callback and what stops applying.
195
+ *
196
+ * A client that overrides `shouldOverrideUrlLoading` decides navigations instead of the navigation rules, which still
197
+ * decide new windows unless a chrome client overrides `onCreateWindow`. A new window the rules allow loads in place
198
+ * with `loadUrl`, which doesn't reach `shouldOverrideUrlLoading` (on iOS that load reaches the deciding delegate).
199
+ *
200
+ * A decision more than one client overrides still goes only to the first, and a warning names it. Each warning
201
+ * comes once per WebView, when its decision first comes.
202
+ *
203
+ * Overriding a variant the base class forwards to counts as overriding the callback. The variants are:
204
+ * - [WebViewClientCompat]'s `onReceivedError`, `onSafeBrowsingHit` and `shouldOverrideUrlLoading(WebView, String)`.
205
+ * - The platform's deprecated `shouldOverrideUrlLoading(WebView, String)`, `shouldInterceptRequest(WebView, String)` and 4-argument `onReceivedError`.
206
+ *
207
+ * `shouldInterceptRequest` runs on a background thread.
208
+ */
209
+ val clients: MutableList<WebViewClient>
210
+
211
+ /**
212
+ * Your chrome clients, routed as [clients] are.
213
+ *
214
+ * Overriding the deprecated `onConsoleMessage(String, Int, String)` counts as overriding `onConsoleMessage`.
215
+ * Favicon downloads are off, so `onReceivedIcon` gets no icon until the hook's `attach` turns `downloadFaviconsEnabled`
216
+ * on.
217
+ */
218
+ val chromeClients: MutableList<WebChromeClient>
219
+
220
+ /**
221
+ * Your touch listeners, in order, called until one returns true: that one consumes the touch, which neither the
222
+ * later listeners nor the WebView get.
223
+ */
224
+ val touchListeners: MutableList<View.OnTouchListener>
225
+
226
+ /** Your scroll listeners: each one gets every scroll change, in order. */
227
+ val scrollListeners: MutableList<View.OnScrollChangeListener>
228
+
229
+ /**
230
+ * Sends an event to JS: the extension with the hook's key gets `{ name, payload }` in its `onEvent`. It is dropped
231
+ * while the hook is off, and after the context's attach ended.
232
+ */
233
+ fun emit(name: String, payload: Map<String, Any?>)
234
+
235
+ /**
236
+ * Sends the event as [emit] does, and calls [onAnswer] with JS's answer: the extension's `onEvent` return value, a
237
+ * promise awaited, in JSON types as [handle]'s arguments are.
238
+ *
239
+ * It answers null when the handler throws or there is none, or when the Document ends first; there is no timeout. It
240
+ * answers null at once while the hook is off, and after the context's attach ended. An ask made before the WebView's
241
+ * first commit (in `attach`) belongs to the Document that commit opens.
242
+ */
243
+ fun ask(name: String, payload: Map<String, Any?>, onAnswer: (Any?) -> Unit)
244
+
245
+ /**
246
+ * Runs [handler] at once with this hook's extension's `options`, then with the new ones each time they change, live
247
+ * on the same WebView; null while the hook is off.
248
+ *
249
+ * A change from one off value to another doesn't run it, and a context kept after its attach ended never does.
250
+ */
251
+ fun onOptions(handler: (options: Any?) -> Unit)
252
+
253
+ /**
254
+ * Runs [handler] at each end of the Document (see [DocumentEnd]), after the core's own resets: per-page state
255
+ * belongs here.
256
+ */
257
+ fun onDocumentEnd(handler: (DocumentEnd) -> Unit)
258
+
259
+ /**
260
+ * Runs [handler] once this attach's WebView is destroyed: with [DocumentEnd.CLOSING] at unmount, or with
261
+ * [DocumentEnd.CRASHED] after a renderer crash. It comes after the [onDocumentEnd] handlers that get the same
262
+ * reason, and the context does nothing by then.
263
+ *
264
+ * Clean up here, and release what must outlive the WebView, such as a [ProfileStore][androidx.webkit.ProfileStore]
265
+ * profile.
266
+ */
267
+ fun onDestroyed(handler: (DocumentEnd) -> Unit)
268
+
269
+ /**
270
+ * Offers [handler] each download the page starts, with [DownloadListener][android.webkit.DownloadListener]'s
271
+ * arguments (an unknown disposition or MIME type is empty), before the `onDownload` prop and the core's opening it
272
+ * externally.
273
+ *
274
+ * Return true to take it: neither of those gets it then. The hooks that are on are offered it in the order they
275
+ * attached (registration order, then those attached later), and the first that takes it ends the round.
276
+ */
277
+ fun onDownloadStart(
278
+ handler: (url: String, userAgent: String, contentDisposition: String, mimeType: String, contentLength: Long) -> Boolean
279
+ )
280
+
281
+ /**
282
+ * Answers JS's `ref.hook("<key>", method, args)`: [handler] gets the arguments and a [HookReply], which it calls with
283
+ * the reply or [fails][HookReply.fail], then or later.
284
+ *
285
+ * One handler per method: the last one wins.
286
+ *
287
+ * A handler that throws before it replies rejects the JS call with `handler_error` and the exception's message. A
288
+ * handler that never replies leaves the call waiting until the WebView unmounts: a navigation or a crash doesn't
289
+ * settle it.
290
+ */
291
+ fun handle(method: String, handler: (args: List<Any?>, reply: HookReply) -> Unit)
292
+ }
293
+
294
+ /**
295
+ * The answer to one JS `ref.hook` call, which a [WebViewContext.handle] handler gets: call it with the value the call
296
+ * resolves with, or [fail] it.
297
+ *
298
+ * Only the first reply or fail counts: any after it does nothing. Call it from any thread.
299
+ */
300
+ class HookReply internal constructor(
301
+ private val resolve: (Any?) -> Unit,
302
+ private val reject: (String) -> Unit
303
+ ) : (Any?) -> Unit {
304
+ private val settled = AtomicBoolean()
305
+
306
+ /** Resolves the JS call with [value]: strings, booleans, numbers, and `Map`s, `Collection`s and `Array`s of them cross as JSON; any other object, a primitive array such as `IntArray` included, arrives as null, and a non-finite number rejects the call with `native_error` instead. */
307
+ override fun invoke(value: Any?) {
308
+ if (settled.compareAndSet(false, true)) resolve(value)
309
+ }
310
+
311
+ /** Rejects the JS call with `handler_error` and [message]. */
312
+ fun fail(message: String) {
313
+ if (settled.compareAndSet(false, true)) reject(message)
314
+ }
315
+ }
316
+
317
+ /**
318
+ * [HookContext]'s base: the hook's `hookOptions` value (null while its key is absent), its lists, and whether the core
319
+ * routes them. Chromium's IO thread reads [routed] and [clients] (shouldInterceptRequest), so [options] and the detach
320
+ * are volatile; the rest is main thread only.
321
+ */
322
+ internal open class Attachment(value: Any?) {
323
+ @Volatile var options: Any? = value
324
+ private set
325
+ @Volatile private var detached = false
326
+ private val optionsHandlers = mutableListOf<(Any?) -> Unit>()
327
+ private val downloadHandlers = mutableListOf<(String, String, String, String, Long) -> Boolean>()
328
+
329
+ // Copy-on-write: Chromium reads the clients on its IO thread (shouldInterceptRequest) while attach and the hook's
330
+ // own changes write them.
331
+ val clients: MutableList<WebViewClient> = CopyOnWriteArrayList()
332
+ val chromeClients = mutableListOf<WebChromeClient>()
333
+ // Copy-on-write too: the core iterates them live, and a listener may remove itself while it runs.
334
+ val touchListeners: MutableList<View.OnTouchListener> = CopyOnWriteArrayList()
335
+ val scrollListeners: MutableList<View.OnScrollChangeListener> = CopyOnWriteArrayList()
336
+
337
+ /** Whether the hook is on and the attach is still there: the core routes the lists and passes events and asks. */
338
+ val routed get() = options != null && !detached
339
+
340
+ fun onOptions(handler: (Any?) -> Unit) {
341
+ if (detached) return
342
+ optionsHandlers += handler
343
+ handler(options)
344
+ }
345
+
346
+ /** The hook's new `hookOptions` [value], null when its key is gone; the view calls it only for a changed value. */
347
+ fun optionsChanged(value: Any?) {
348
+ options = value
349
+ optionsHandlers.forEach { it(value) }
350
+ }
351
+
352
+ /** The attach ended: the core routes nothing of it, and the emits and asks that follow reach nothing. */
353
+ open fun detach() {
354
+ detached = true
355
+ optionsHandlers.clear()
356
+ downloadHandlers.clear()
357
+ clients.clear()
358
+ chromeClients.clear()
359
+ touchListeners.clear()
360
+ scrollListeners.clear()
361
+ }
362
+
363
+ fun onDownloadStart(handler: (String, String, String, String, Long) -> Boolean) {
364
+ downloadHandlers += handler
365
+ }
366
+
367
+ fun downloadStarted(url: String, userAgent: String, contentDisposition: String, mimeType: String, contentLength: Long) =
368
+ routed && downloadHandlers.any { it(url, userAgent, contentDisposition, mimeType, contentLength) }
369
+
370
+ fun ifRouted(send: () -> Unit) {
371
+ if (routed) send()
372
+ }
373
+
374
+ fun askIfRouted(onAnswer: (Any?) -> Unit, send: () -> Unit) {
375
+ if (routed) send() else onAnswer(null)
376
+ }
377
+ }
378
+
379
+ internal fun <T> routed(attachments: List<Attachment>, pick: (Attachment) -> List<T>) =
380
+ attachments.filter { it.routed }.flatMap(pick)
381
+
382
+ /**
383
+ * A hook's view of the WebView, one per hook and WebView: the core's context with the hook's key on its events. The
384
+ * handlers live here, so the WebView after a crash gets the ones its `attach` registers again. A hook can keep the
385
+ * context past its attach (an async callback): [detach] then leaves it holding nothing of the view.
386
+ */
387
+ internal class HookContext(val hook: MinimalWebViewHooks.Hook, view: MinimalWebView) :
388
+ Attachment(view.hookOptions[hook.key]), WebViewContext {
389
+ /** Null once the attach ended. Main thread only. */
390
+ private var view: MinimalWebView? = view
391
+ val key get() = hook.key
392
+ override val url get() = view?.url.orEmpty()
393
+ private val documentEndHandlers = mutableListOf<(DocumentEnd) -> Unit>()
394
+ private val destroyedHandlers = mutableListOf<(DocumentEnd) -> Unit>()
395
+ val handlers = mutableMapOf<String, (List<Any?>, HookReply) -> Unit>()
396
+
397
+ /** The attach ended: also drops the view and what the hook gave it, bar the [onDestroyed] handlers [destroyed] runs next. */
398
+ override fun detach() {
399
+ super.detach()
400
+ view = null
401
+ handlers.clear()
402
+ documentEndHandlers.clear()
403
+ }
404
+
405
+ override fun emit(name: String, payload: Map<String, Any?>) =
406
+ onMain { ifRouted { view?.emit(key, name, payload) } }
407
+
408
+ override fun ask(name: String, payload: Map<String, Any?>, onAnswer: (Any?) -> Unit) =
409
+ onMain { askIfRouted(onAnswer) { view?.asks?.ask(key, name, payload, onAnswer) } }
410
+
411
+ override fun onDocumentEnd(handler: (DocumentEnd) -> Unit) {
412
+ documentEndHandlers += handler
413
+ }
414
+
415
+ override fun onDestroyed(handler: (DocumentEnd) -> Unit) {
416
+ destroyedHandlers += handler
417
+ }
418
+
419
+ override fun handle(method: String, handler: (args: List<Any?>, reply: HookReply) -> Unit) {
420
+ handlers[method] = handler
421
+ }
422
+
423
+ fun documentEnded(reason: DocumentEnd) = documentEndHandlers.forEach { it(reason) }
424
+
425
+ fun destroyed(reason: DocumentEnd) {
426
+ val handlers = destroyedHandlers.toList()
427
+ destroyedHandlers.clear()
428
+ handlers.forEach { it(reason) }
429
+ }
430
+
431
+ // A hook's shouldInterceptRequest runs on Chromium's IO thread; the view's events and asks are main-thread state.
432
+ private fun onMain(block: () -> Unit) {
433
+ if (Looper.myLooper() == Looper.getMainLooper()) block() else main.post { block() }
434
+ }
435
+
436
+ private companion object {
437
+ val main = Handler(Looper.getMainLooper())
438
+ }
439
+ }
440
+
441
+ // Concurrent: shouldInterceptRequest asks on Chromium's IO thread while the main thread fills it.
442
+ private val overrideCache = ConcurrentHashMap<String, Boolean>()
443
+ private val BASES = setOf<Class<*>>(WebViewClient::class.java, WebChromeClient::class.java, WebViewClientCompat::class.java)
444
+
445
+ /**
446
+ * The base classes' own methods that only forward to a variant of the callback: the variant's parameter types, by the
447
+ * declaring class and the callback's signature. WebViewClient's and WebChromeClient's forward to a deprecated variant;
448
+ * WebViewClientCompat's first two are final.
449
+ */
450
+ private val VARIANTS: Map<Class<*>, Map<String, Array<Class<*>>>> = mapOf(
451
+ WebViewClient::class.java to mapOf(
452
+ signature("shouldOverrideUrlLoading", WebView::class.java, WebResourceRequest::class.java) to
453
+ arrayOf(WebView::class.java, String::class.java),
454
+ signature("shouldInterceptRequest", WebView::class.java, WebResourceRequest::class.java) to
455
+ arrayOf(WebView::class.java, String::class.java),
456
+ signature("onReceivedError", WebView::class.java, WebResourceRequest::class.java, WebResourceError::class.java) to
457
+ arrayOf(WebView::class.java, Integer.TYPE, String::class.java, String::class.java)
458
+ ),
459
+ WebChromeClient::class.java to mapOf(
460
+ signature("onConsoleMessage", ConsoleMessage::class.java) to arrayOf(String::class.java, Integer.TYPE, String::class.java)
461
+ ),
462
+ WebViewClientCompat::class.java to mapOf(
463
+ signature("onReceivedError", WebView::class.java, WebResourceRequest::class.java, WebResourceError::class.java) to
464
+ arrayOf(WebView::class.java, WebResourceRequest::class.java, WebResourceErrorCompat::class.java),
465
+ signature("onSafeBrowsingHit", WebView::class.java, WebResourceRequest::class.java, Integer.TYPE, SafeBrowsingResponse::class.java) to
466
+ arrayOf(WebView::class.java, WebResourceRequest::class.java, Integer.TYPE, SafeBrowsingResponseCompat::class.java),
467
+ signature("shouldOverrideUrlLoading", WebView::class.java, WebResourceRequest::class.java) to
468
+ arrayOf(WebView::class.java, String::class.java)
469
+ )
470
+ )
471
+
472
+ private fun signature(callback: String, vararg types: Class<*>) = "$callback(${types.joinToString { it.name }})"
473
+
474
+ /** Whether this client's class overrides the callback [callback] taking [types]; the base classes' own methods don't count. */
475
+ internal fun Any.overrides(callback: String, vararg types: Class<*>): Boolean = javaClass.overrides(callback, *types)
476
+
477
+ /**
478
+ * [Any.overrides] for the class. A subclass that leaves one of the base classes' forwarding methods in place
479
+ * (VARIANTS) overrides the callback only through the variant the forwarder calls.
480
+ */
481
+ internal fun Class<*>.overrides(callback: String, vararg types: Class<*>): Boolean =
482
+ overrideCache.getOrPut("$name#${signature(callback, *types)}") {
483
+ val declared = getMethod(callback, *types).declaringClass
484
+ if (declared !in BASES) return@getOrPut true
485
+ val variant = VARIANTS[declared]?.get(signature(callback, *types)) ?: return@getOrPut false
486
+ getMethod(callback, *variant).declaringClass !in BASES
487
+ }