react-native-minimal-webview 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +150 -2
- package/android/build.gradle +26 -0
- package/android/consumer-rules.pro +4 -0
- package/android/src/main/AndroidManifest.xml +2 -0
- package/android/src/main/java/expo/modules/minimalwebview/Asks.kt +44 -0
- package/android/src/main/java/expo/modules/minimalwebview/DocumentEnd.kt +31 -0
- package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +487 -0
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +507 -0
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +358 -0
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +245 -0
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +199 -0
- package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +197 -0
- package/android/src/main/java/expo/modules/minimalwebview/NavigationRules.kt +113 -0
- package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +303 -0
- package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +76 -0
- package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +259 -0
- package/android/src/main/java/expo/modules/minimalwebview/requests/FileUpload.kt +44 -0
- package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +87 -0
- package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +77 -0
- package/build/WebView.d.ts +96 -0
- package/build/WebView.d.ts.map +1 -0
- package/build/WebView.js +453 -0
- package/build/WebView.js.map +1 -0
- package/build/bridge/createBridge.d.ts +32 -0
- package/build/bridge/createBridge.d.ts.map +1 -0
- package/build/bridge/createBridge.js +137 -0
- package/build/bridge/createBridge.js.map +1 -0
- package/build/bridge/endpoint.d.ts +33 -0
- package/build/bridge/endpoint.d.ts.map +1 -0
- package/build/bridge/endpoint.js +105 -0
- package/build/bridge/endpoint.js.map +1 -0
- package/build/bridge/origins.d.ts +25 -0
- package/build/bridge/origins.d.ts.map +1 -0
- package/build/bridge/origins.js +59 -0
- package/build/bridge/origins.js.map +1 -0
- package/build/bridge/pageClient.generated.d.ts +3 -0
- package/build/bridge/pageClient.generated.d.ts.map +1 -0
- package/build/bridge/pageClient.generated.js +4 -0
- package/build/bridge/pageClient.generated.js.map +1 -0
- package/build/bridge/protocol.d.ts +50 -0
- package/build/bridge/protocol.d.ts.map +1 -0
- package/build/bridge/protocol.js +52 -0
- package/build/bridge/protocol.js.map +1 -0
- package/build/defaultNavigationRules.d.ts +15 -0
- package/build/defaultNavigationRules.d.ts.map +1 -0
- package/build/defaultNavigationRules.js +22 -0
- package/build/defaultNavigationRules.js.map +1 -0
- package/build/index.d.ts +31 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +30 -0
- package/build/index.js.map +1 -0
- package/build/platform.generated.d.ts +701 -0
- package/build/platform.generated.d.ts.map +1 -0
- package/build/platform.generated.js +201 -0
- package/build/platform.generated.js.map +1 -0
- package/build/reactNativeWebViewDefaults.d.ts +21 -0
- package/build/reactNativeWebViewDefaults.d.ts.map +1 -0
- package/build/reactNativeWebViewDefaults.js +12 -0
- package/build/reactNativeWebViewDefaults.js.map +1 -0
- package/build/reactNativeWebViewMessages.d.ts +16 -0
- package/build/reactNativeWebViewMessages.d.ts.map +1 -0
- package/build/reactNativeWebViewMessages.js +24 -0
- package/build/reactNativeWebViewMessages.js.map +1 -0
- package/build/refStore.d.ts +32 -0
- package/build/refStore.d.ts.map +1 -0
- package/build/refStore.js +115 -0
- package/build/refStore.js.map +1 -0
- package/build/types.d.ts +1173 -0
- package/build/types.d.ts.map +1 -0
- package/build/types.defaults.d.ts +8 -0
- package/build/types.defaults.d.ts.map +1 -0
- package/build/types.defaults.js +17 -0
- package/build/types.defaults.js.map +1 -0
- package/build/types.js +2 -0
- package/build/types.js.map +1 -0
- package/expo-module.config.json +9 -0
- package/ios/Asks.swift +45 -0
- package/ios/DelegateProxy.swift +158 -0
- package/ios/DocumentEnd.swift +22 -0
- package/ios/DownloadName.swift +10 -0
- package/ios/Downloads.swift +51 -0
- package/ios/Hooks.swift +310 -0
- package/ios/Loads.swift +44 -0
- package/ios/MRWExceptions.h +9 -0
- package/ios/MRWExceptions.m +10 -0
- package/ios/MRWInvoke.h +38 -0
- package/ios/MRWInvoke.m +187 -0
- package/ios/MinimalWebView+Dialogs.swift +96 -0
- package/ios/MinimalWebView+Navigation.swift +243 -0
- package/ios/MinimalWebView+Scripts.swift +92 -0
- package/ios/MinimalWebView.docc/MinimalWebView.md +13 -0
- package/ios/MinimalWebView.podspec +32 -0
- package/ios/MinimalWebView.swift +513 -0
- package/ios/MinimalWebViewModule.swift +110 -0
- package/ios/NavigationRules.swift +123 -0
- package/ios/OriginRules.swift +36 -0
- package/ios/PlatformCompletions.generated.swift +39 -0
- package/ios/PlatformSettings.swift +252 -0
- package/ios/ReadAccess.swift +19 -0
- package/ios/Recovery.swift +25 -0
- package/ios/SharedCookies.swift +59 -0
- package/package.json +99 -4
- package/src/WebView.tsx +626 -0
- package/src/bridge/createBridge.ts +178 -0
- package/src/bridge/endpoint.ts +123 -0
- package/src/bridge/origins.ts +61 -0
- package/src/bridge/pageClient.generated.ts +5 -0
- package/src/bridge/pageClient.ts +67 -0
- package/src/bridge/protocol.ts +78 -0
- package/src/defaultNavigationRules.ts +24 -0
- package/src/index.ts +37 -0
- package/src/platform.generated.ts +693 -0
- package/src/reactNativeWebViewDefaults.ts +13 -0
- package/src/reactNativeWebViewMessages.ts +26 -0
- package/src/refStore.ts +165 -0
- package/src/types.defaults.ts +24 -0
- package/src/types.ts +1240 -0
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// The structured navigation rules. Semantics and cases: src/__tests__/vectors/navigation-rules.json (shared with Kotlin).
|
|
4
|
+
enum NavigationRules {
|
|
5
|
+
struct Request {
|
|
6
|
+
let url: String
|
|
7
|
+
let mainFrame: Bool
|
|
8
|
+
let newWindow: Bool
|
|
9
|
+
let userInitiated: Bool
|
|
10
|
+
|
|
11
|
+
/// The fields JS events carry.
|
|
12
|
+
var payload: [String: Any] {
|
|
13
|
+
["url": url, "mainFrame": mainFrame, "newWindow": newWindow, "userInitiated": userInitiated]
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/// `action` is allow, block, external or ask; `rule` is the matching rule's index, nil when a default decided.
|
|
18
|
+
struct Decision: Equatable {
|
|
19
|
+
let action: String
|
|
20
|
+
let rule: Int?
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/// What rules match; `params` are the query's `&`-separated parameters.
|
|
24
|
+
private struct Parts {
|
|
25
|
+
let scheme: String
|
|
26
|
+
let host: String?
|
|
27
|
+
let path: String
|
|
28
|
+
let params: [String]
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/// Load in place without the rules.
|
|
32
|
+
private static let internalSchemes: Set<String> = ["about", "data", "javascript"]
|
|
33
|
+
/// Never open as a new window, whatever the rules say: the core loads an allowed new window in the main frame itself,
|
|
34
|
+
/// past the engine's limits on what a page may navigate the top frame to.
|
|
35
|
+
private static let noNewWindowSchemes = internalSchemes.union(["blob", "file"])
|
|
36
|
+
private static let actions: Set<String> = ["allow", "block", "external", "ask"]
|
|
37
|
+
private static let answers: Set<String> = ["allow", "block", "external"]
|
|
38
|
+
|
|
39
|
+
/// The rules' decision, gated for `ask`: blocked when nothing can answer it (`canAsk` false), allowed when its URL is
|
|
40
|
+
/// in `asked` (URLs an `ask` already allowed). An unknown rule action blocks.
|
|
41
|
+
static func decide(_ rules: [[String: Any]]?, _ request: Request, asked: Set<String>, canAsk: Bool) -> Decision {
|
|
42
|
+
let decision = match(rules, request)
|
|
43
|
+
guard decision.action == "ask" else { return decision }
|
|
44
|
+
if !canAsk { return Decision(action: "block", rule: decision.rule) }
|
|
45
|
+
return asked.contains(request.url) ? Decision(action: "allow", rule: decision.rule) : decision
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/// An `ask` answer: allow, block or external; anything else (nil on a timeout) blocks.
|
|
49
|
+
static func answer(_ value: Any?) -> String {
|
|
50
|
+
(value as? String).flatMap { answers.contains($0) ? $0 : nil } ?? "block"
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
private static func match(_ rules: [[String: Any]]?, _ request: Request) -> Decision {
|
|
54
|
+
let scheme = request.url.firstIndex(of: ":").map { request.url[..<$0].lowercased() } ?? ""
|
|
55
|
+
if request.newWindow, noNewWindowSchemes.contains(scheme) { return Decision(action: "block", rule: nil) }
|
|
56
|
+
if internalSchemes.contains(scheme) { return Decision(action: "allow", rule: nil) }
|
|
57
|
+
// JS sends defaultNavigationRules when the prop is unset; no rules, nil or empty, match nothing.
|
|
58
|
+
guard let rules, !rules.isEmpty,
|
|
59
|
+
let parts = scheme == "blob" ? blobOrigin(request.url) : urlParts(scheme, request.url)
|
|
60
|
+
else { return Decision(action: "block", rule: nil) }
|
|
61
|
+
guard let index = rules.firstIndex(where: { matches($0, parts, request) }) else {
|
|
62
|
+
return Decision(action: "block", rule: nil)
|
|
63
|
+
}
|
|
64
|
+
let action = rules[index]["action"] as? String
|
|
65
|
+
return Decision(action: action.flatMap { actions.contains($0) ? $0 : nil } ?? "block", rule: index)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
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
|
+
let components = URLComponents(string: url)
|
|
71
|
+
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.
|
|
73
|
+
let path = rawPath.isEmpty || components?.host == nil ? "/" : rawPath
|
|
74
|
+
let params = components?.percentEncodedQuery?.split(separator: "&").map(String.init) ?? []
|
|
75
|
+
return Parts(scheme: scheme, host: host(components), path: path, params: params)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/// A blob: document has the origin its URL carries (`blob:https://a.test/…`), so the rules see that origin, with
|
|
79
|
+
/// path "/"; nil for an opaque one (`blob:null/…`), which no rule describes.
|
|
80
|
+
private static func blobOrigin(_ url: String) -> Parts? {
|
|
81
|
+
let components = URLComponents(string: String(url.dropFirst("blob:".count)))
|
|
82
|
+
guard let scheme = components?.scheme?.lowercased() else { return nil }
|
|
83
|
+
return Parts(scheme: scheme, host: host(components), path: "/", params: [])
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/// Lowercased, without a trailing dot; nil when there is none.
|
|
87
|
+
private static func host(_ components: URLComponents?) -> String? {
|
|
88
|
+
// encodedHost keeps an IDNA host in its xn-- form; `host` would decode it.
|
|
89
|
+
var host = (components?.encodedHost ?? components?.host)?.lowercased()
|
|
90
|
+
if host?.hasSuffix(".") == true { host?.removeLast() }
|
|
91
|
+
return host?.isEmpty == true ? nil : host
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/// nil when the field is unset; a value that isn't a list (a string from untyped JS) matches nothing.
|
|
95
|
+
private static func list(_ value: Any?) -> [String]? {
|
|
96
|
+
value.map { ($0 as? [Any])?.map { "\($0)" } ?? [] }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
private static func matches(_ rule: [String: Any], _ parts: Parts, _ request: Request) -> Bool {
|
|
100
|
+
if let schemes = list(rule["scheme"]), !schemes.contains(where: { $0.lowercased() == parts.scheme }) { return false }
|
|
101
|
+
if let hosts = list(rule["host"]) {
|
|
102
|
+
guard let host = parts.host, hosts.contains(where: { hostMatches($0.lowercased(), host) }) else { return false }
|
|
103
|
+
}
|
|
104
|
+
if let paths = list(rule["path"]), !paths.contains(where: { parts.path.hasPrefix($0) }) { return false }
|
|
105
|
+
if let queries = list(rule["query"]), !queries.contains(where: { paramMatches($0, parts.params) }) { return false }
|
|
106
|
+
return flag(rule["mainFrame"], request.mainFrame) && flag(rule["newWindow"], request.newWindow)
|
|
107
|
+
&& flag(rule["userInitiated"], request.userInitiated)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/// `name=value` matches that exact parameter; `name` matches a parameter with that name, whatever its value.
|
|
111
|
+
private static func paramMatches(_ entry: String, _ params: [String]) -> Bool {
|
|
112
|
+
params.contains { param in entry.contains("=") ? param == entry : param.prefix(while: { $0 != "=" }) == entry }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
private static func flag(_ value: Any?, _ actual: Bool) -> Bool {
|
|
116
|
+
guard let expected = value as? Bool else { return true }
|
|
117
|
+
return expected == actual
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
private static func hostMatches(_ pattern: String, _ host: String) -> Bool {
|
|
121
|
+
pattern.hasPrefix("*.") ? host.hasSuffix(String(pattern.dropFirst())) : host == pattern
|
|
122
|
+
}
|
|
123
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Origin rules in Android's format (the bridge's `allowedOrigins`):
|
|
4
|
+
/// `*`, an exact http(s) origin such as `https://example.com:8443`, or `https://*.example.com` for subdomains.
|
|
5
|
+
/// Compared case-insensitively, a missing port is the scheme's default, and a malformed rule matches nothing.
|
|
6
|
+
/// createBridge validates the rules on the JS side. Cases: src/__tests__/vectors/origin-rules.json.
|
|
7
|
+
enum OriginRules {
|
|
8
|
+
/// The origin string of a frame, `scheme://host[:port]`, or `null` for an opaque origin (no scheme: an html source
|
|
9
|
+
/// without `baseUrl`, a sandboxed page). The default port is left out (WebKit reports it as 0) and an IPv6 host is
|
|
10
|
+
/// bracketed.
|
|
11
|
+
static func origin(_ scheme: String, _ host: String, _ port: Int) -> String {
|
|
12
|
+
guard !scheme.isEmpty else { return "null" }
|
|
13
|
+
let defaultPort = scheme == "https" ? 443 : scheme == "http" ? 80 : nil
|
|
14
|
+
let host = host.contains(":") && !host.hasPrefix("[") ? "[\(host)]" : host
|
|
15
|
+
return "\(scheme)://\(host)" + (port == 0 || port == defaultPort ? "" : ":\(port)")
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
static func allows(_ rules: [String], _ origin: String) -> Bool {
|
|
19
|
+
let value = parse(origin)
|
|
20
|
+
return rules.contains { rule in
|
|
21
|
+
guard let r = parse(rule), let o = value, !o.wildcard else { return rule == "*" }
|
|
22
|
+
return (r.wildcard ? o.host.hasSuffix("." + r.host) : o.host == r.host) && r.scheme == o.scheme && r.port == o.port
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Built once: a regex literal in the function body is compiled again on every call. Regex isn't Sendable; every
|
|
27
|
+
// caller is a WebKit delegate callback on the main thread.
|
|
28
|
+
nonisolated(unsafe) private static let pattern = #/(https?):\/\/(\*\.(?!\[))?([a-z0-9_-]+(?:\.[a-z0-9_-]+)*|\[[0-9a-f:.]+\])(?::(\d{1,5}))?/#
|
|
29
|
+
|
|
30
|
+
private struct Parsed { let scheme: Substring, wildcard: Bool, host: Substring, port: Int }
|
|
31
|
+
|
|
32
|
+
private static func parse(_ text: String) -> Parsed? {
|
|
33
|
+
guard let m = try? pattern.wholeMatch(in: text.lowercased()) else { return nil }
|
|
34
|
+
return Parsed(scheme: m.1, wildcard: m.2 != nil, host: m.3, port: m.4.flatMap { Int($0) } ?? (m.1 == "https" ? 443 : 80))
|
|
35
|
+
}
|
|
36
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Generated by .github/scripts/gen-platform-types.mts from .github/scripts/platform-headers/. Do not edit.
|
|
2
|
+
// Regenerate with `npm run gen:platform-types`.
|
|
3
|
+
|
|
4
|
+
/// The completion-handler shape of each WebKit method `PlatformSettings.call` reaches, by `root.selector`, for MRWInvoke.
|
|
5
|
+
let platformCompletions: [String: String] = [
|
|
6
|
+
"webView.evaluateJavaScript:completionHandler:": "valueError",
|
|
7
|
+
"webView.evaluateJavaScript:inFrame:inContentWorld:completionHandler:": "valueError",
|
|
8
|
+
"webView.callAsyncJavaScript:arguments:inFrame:inContentWorld:completionHandler:": "valueError",
|
|
9
|
+
"webView.closeAllMediaPresentationsWithCompletionHandler:": "void",
|
|
10
|
+
"webView.pauseAllMediaPlaybackWithCompletionHandler:": "void",
|
|
11
|
+
"webView.pauseAllMediaPlayback:": "void",
|
|
12
|
+
"webView.setAllMediaPlaybackSuspended:completionHandler:": "void",
|
|
13
|
+
"webView.resumeAllMediaPlayback:": "void",
|
|
14
|
+
"webView.suspendAllMediaPlayback:": "void",
|
|
15
|
+
"webView.requestMediaPlaybackStateWithCompletionHandler:": "number",
|
|
16
|
+
"webView.requestMediaPlaybackState:": "number",
|
|
17
|
+
"webView.setCameraCaptureState:completionHandler:": "void",
|
|
18
|
+
"webView.setMicrophoneCaptureState:completionHandler:": "void",
|
|
19
|
+
"webView.takeSnapshotWithConfiguration:completionHandler:": "valueError",
|
|
20
|
+
"webView.createPDFWithConfiguration:completionHandler:": "valueError",
|
|
21
|
+
"webView.createWebArchiveDataWithCompletionHandler:": "valueError",
|
|
22
|
+
"webView.findString:withConfiguration:completionHandler:": "value",
|
|
23
|
+
"webView.startDownloadUsingRequest:completionHandler:": "value",
|
|
24
|
+
"webView.resumeDownloadFromResumeData:completionHandler:": "value",
|
|
25
|
+
"webView.fetchDataOfTypes:completionHandler:": "valueError",
|
|
26
|
+
"webView.restoreData:completionHandler:": "error",
|
|
27
|
+
"websiteDataStore.fetchDataRecordsOfTypes:completionHandler:": "value",
|
|
28
|
+
"websiteDataStore.removeDataOfTypes:forDataRecords:completionHandler:": "void",
|
|
29
|
+
"websiteDataStore.removeDataOfTypes:modifiedSince:completionHandler:": "void",
|
|
30
|
+
"websiteDataStore.fetchDataOfTypes:completionHandler:": "valueError",
|
|
31
|
+
"websiteDataStore.restoreData:completionHandler:": "error",
|
|
32
|
+
"httpCookieStore.getAllCookies:": "value",
|
|
33
|
+
"httpCookieStore.getCookiesForURL:completionHandler:": "value",
|
|
34
|
+
"httpCookieStore.setCookie:completionHandler:": "void",
|
|
35
|
+
"httpCookieStore.setCookies:completionHandler:": "void",
|
|
36
|
+
"httpCookieStore.deleteCookie:completionHandler:": "void",
|
|
37
|
+
"httpCookieStore.setCookiePolicy:completionHandler:": "void",
|
|
38
|
+
"httpCookieStore.getCookiePolicy:": "number",
|
|
39
|
+
]
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import ObjectiveC
|
|
2
|
+
import UIKit
|
|
3
|
+
import WebKit
|
|
4
|
+
|
|
5
|
+
/// The `ios` settings prop, `{ configuration: {…}, preferences: {…}, webpagePreferences: {…}, webView: {…},
|
|
6
|
+
/// scrollView: {…} }`, applied by Objective-C property name through Key-Value Coding, so a public property this
|
|
7
|
+
/// package doesn't know (one a newer WebKit adds) needs no code here. `configuration` is read once, when the WKWebView
|
|
8
|
+
/// is created; the other roots apply live, to `webView.configuration.preferences`,
|
|
9
|
+
/// `webView.configuration.defaultWebpagePreferences`, the WKWebView and its scroll view.
|
|
10
|
+
///
|
|
11
|
+
/// A value must fit the property's type:
|
|
12
|
+
/// - BOOL, floats and NSString as themselves
|
|
13
|
+
/// - integers, enums and option sets by raw value
|
|
14
|
+
/// - NSURL from a string
|
|
15
|
+
/// - UIColor from `#rrggbb` or `#rrggbbaa`
|
|
16
|
+
/// - UIEdgeInsets, CGPoint, CGSize and CGRect from an object
|
|
17
|
+
/// - `websiteDataStore` from `"default"` or `"nonPersistent"`
|
|
18
|
+
///
|
|
19
|
+
/// Anything else is rejected before KVC runs: a wrong value in an object-typed property can take the process down
|
|
20
|
+
/// (WebKit asserts), and an unknown key raises an Objective-C exception Swift can't catch. Underscore (private)
|
|
21
|
+
/// properties are refused, and the only private keys accepted are the two react-native-webview sets by KVC
|
|
22
|
+
/// (`privateBools`).
|
|
23
|
+
///
|
|
24
|
+
/// `get` reads a property of a root and `call` invokes a method on one by selector, through MRWInvoke (MRWInvoke.h),
|
|
25
|
+
/// which sets the arguments by the method's signature. For those two, `websiteDataStore` and `httpCookieStore` are
|
|
26
|
+
/// roots as well.
|
|
27
|
+
final class PlatformSettings {
|
|
28
|
+
/// "root.key" -> the last value applied or rejected, so an unchanged value is neither applied nor reported again.
|
|
29
|
+
private var applied: [String: NSObject] = [:]
|
|
30
|
+
/// "root.key" of a live root -> its value before the first write (NSNull for nil), set back when the key is removed.
|
|
31
|
+
private var originals: [String: Any] = [:]
|
|
32
|
+
|
|
33
|
+
/// Applies `settings`. While creating (`configuration` given, no WebView yet) only the `configuration` root applies;
|
|
34
|
+
/// live, every other root does (JS remounts the view for a new `configuration`), and a key applied before and missing
|
|
35
|
+
/// now goes back to its value before the first write. Returns the rejected keys.
|
|
36
|
+
func apply(_ settings: [String: Any], webView: WKWebView?, configuration: WKWebViewConfiguration? = nil) -> [[String: String]] {
|
|
37
|
+
var rejected: [[String: String]] = []
|
|
38
|
+
let creating = configuration != nil
|
|
39
|
+
// Before the new values, so restoring one (a scroll view's inset) can't undo another (its offset).
|
|
40
|
+
if !creating { rejected += restore(removedFrom: settings, webView: webView) }
|
|
41
|
+
for (rootName, entries) in settings {
|
|
42
|
+
guard let entries = entries as? [String: Any] else {
|
|
43
|
+
rejected.append(["key": rootName, "reason": "not an object"])
|
|
44
|
+
continue
|
|
45
|
+
}
|
|
46
|
+
let isConfiguration = rootName == "configuration"
|
|
47
|
+
guard isConfiguration == creating else { continue }
|
|
48
|
+
for (key, value) in entries {
|
|
49
|
+
let id = "\(rootName).\(key)"
|
|
50
|
+
let boxed = value as? NSObject ?? NSNull()
|
|
51
|
+
if applied[id] == boxed { continue }
|
|
52
|
+
applied[id] = boxed
|
|
53
|
+
guard let object = root(rootName, webView: webView, configuration: configuration) else {
|
|
54
|
+
rejected.append(["key": id, "reason": "unknown root: use \(Self.roots)"])
|
|
55
|
+
continue
|
|
56
|
+
}
|
|
57
|
+
if let reason = set(object, key, value, original: isConfiguration ? nil : id) {
|
|
58
|
+
rejected.append(["key": id, "reason": reason])
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return rejected
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/// Forgets each applied key `settings` no longer has and sets its original value back; returns those that failed.
|
|
66
|
+
private func restore(removedFrom settings: [String: Any], webView: WKWebView?) -> [[String: String]] {
|
|
67
|
+
var present = Set<String>()
|
|
68
|
+
for (rootName, entries) in settings {
|
|
69
|
+
guard let entries = entries as? [String: Any] else { continue }
|
|
70
|
+
present.formUnion(entries.keys.map { "\(rootName).\($0)" })
|
|
71
|
+
}
|
|
72
|
+
var failed: [[String: String]] = []
|
|
73
|
+
for id in applied.keys where !present.contains(id) {
|
|
74
|
+
applied[id] = nil
|
|
75
|
+
guard let original = originals.removeValue(forKey: id), let dot = id.firstIndex(of: "."),
|
|
76
|
+
let object = root(String(id[..<dot]), webView: webView, configuration: nil) else { continue }
|
|
77
|
+
let key = String(id[id.index(after: dot)...])
|
|
78
|
+
// shortcut: a null_resettable property (underPageBackgroundColor) comes back as the value read, not as "follow the
|
|
79
|
+
// default"; set nil for those if one matters.
|
|
80
|
+
if let reason = __MRWCatchException({ object.setValue(original is NSNull ? nil : original, forKey: key) }) {
|
|
81
|
+
failed.append(["key": id, "reason": "removed, but restoring it failed: \(reason)"])
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return failed
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/// `root.key` through KVC, as JSON. Throws a `PlatformError` with the reason when it can't.
|
|
88
|
+
func get(_ path: String, webView: WKWebView) throws -> String {
|
|
89
|
+
guard let dot = path.firstIndex(of: ".") else { throw PlatformError("use root.key", code: "not_found") }
|
|
90
|
+
let rootName = String(path[..<dot])
|
|
91
|
+
let key = String(path[path.index(after: dot)...])
|
|
92
|
+
guard let object = root(rootName, webView: webView, configuration: webView.configuration) else {
|
|
93
|
+
throw PlatformError("unknown root: use \(Self.roots)", code: "not_found")
|
|
94
|
+
}
|
|
95
|
+
guard !key.hasPrefix("_"), !key.contains("."), Self.attributes(object, key) != nil else {
|
|
96
|
+
throw PlatformError("no such property \(path)", code: "not_found")
|
|
97
|
+
}
|
|
98
|
+
return try Self.json { __MRWJsonable(object.value(forKey: key)) }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/// `root.selector:` with the JSON `args`, resolved with the result as JSON, or with why it couldn't be called.
|
|
102
|
+
func call(_ path: String, args: [Any], webView: WKWebView, resolve: @escaping (String?, String?) -> Void) throws {
|
|
103
|
+
guard let dot = path.lastIndex(of: ".") else { throw PlatformError("use root.selector:", code: "not_found") }
|
|
104
|
+
let selector = String(path[path.index(after: dot)...])
|
|
105
|
+
guard let object = root(String(path[..<dot]), webView: webView, configuration: webView.configuration) else {
|
|
106
|
+
throw PlatformError("unknown root: use \(Self.roots)", code: "not_found")
|
|
107
|
+
}
|
|
108
|
+
guard !Self.refused.contains(where: selector.hasPrefix) else {
|
|
109
|
+
throw PlatformError("\(selector) is owned by the core, or private")
|
|
110
|
+
}
|
|
111
|
+
guard object.responds(to: NSSelectorFromString(selector)) else {
|
|
112
|
+
throw PlatformError("\(type(of: object)) has no method \(selector)", code: "not_found")
|
|
113
|
+
}
|
|
114
|
+
__MRWInvoke(object, NSSelectorFromString(selector), args, platformCompletions[path]) { result, error in
|
|
115
|
+
guard error == nil, let result else { return resolve(nil, error ?? "the result is not JSON") }
|
|
116
|
+
do {
|
|
117
|
+
let json = try Self.json { result }
|
|
118
|
+
resolve(json, nil)
|
|
119
|
+
} catch let failure {
|
|
120
|
+
resolve(nil, (failure as? PlatformError)?.message ?? failure.localizedDescription)
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/// `value()` as JSON text. It runs inside MRWCatchException: a getter that raises, or a NaN that JSONSerialization
|
|
126
|
+
/// raises for, throws here instead of crashing the app.
|
|
127
|
+
static func json(_ value: () -> Any) throws -> String {
|
|
128
|
+
var data: Data?
|
|
129
|
+
let raised = __MRWCatchException {
|
|
130
|
+
data = try? JSONSerialization.data(withJSONObject: value(), options: .fragmentsAllowed)
|
|
131
|
+
}
|
|
132
|
+
if let raised { throw PlatformError(raised) }
|
|
133
|
+
guard let data else { throw PlatformError("the result is not JSON") }
|
|
134
|
+
return String(decoding: data, as: UTF8.self)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/// Selector prefixes `call` refuses: what the ref and the core own (every load, navigation, script, download and
|
|
138
|
+
/// delegate selector), private API, the plumbing that would reach either (KVC, KVO's willChange/didChange,
|
|
139
|
+
/// performSelector), object lifecycle (init, copy, new: a re-initialized live object, or a +1 result MRWInvoke would
|
|
140
|
+
/// leak) and reference counting. `mutable` covers `mutableCopy` and KVC's `mutableArrayValueForKey:` and its kin.
|
|
141
|
+
private static let refused = [
|
|
142
|
+
"_", "load", "go", "reload", "stop", "evaluateJavaScript", "callAsyncJavaScript", "startDownload", "resumeDownload",
|
|
143
|
+
"setInteractionState", "setNavigationDelegate", "setUIDelegate", "setDelegate", "setValue", "setValuesForKeys", "valueForKey",
|
|
144
|
+
"dictionaryWithValuesForKeys", "mutable", "willChange", "didChange", "performSelector", "init", "copy", "new",
|
|
145
|
+
"retain", "release", "autorelease", "dealloc",
|
|
146
|
+
]
|
|
147
|
+
static let roots = "configuration, preferences, webpagePreferences, webView, scrollView, websiteDataStore or httpCookieStore"
|
|
148
|
+
|
|
149
|
+
private func root(_ name: String, webView: WKWebView?, configuration: WKWebViewConfiguration?) -> NSObject? {
|
|
150
|
+
switch name {
|
|
151
|
+
case "configuration": return configuration
|
|
152
|
+
case "preferences": return webView?.configuration.preferences
|
|
153
|
+
case "webpagePreferences": return webView?.configuration.defaultWebpagePreferences
|
|
154
|
+
case "webView": return webView
|
|
155
|
+
case "scrollView": return webView?.scrollView
|
|
156
|
+
case "websiteDataStore": return webView?.configuration.websiteDataStore
|
|
157
|
+
case "httpCookieStore": return webView?.configuration.websiteDataStore.httpCookieStore
|
|
158
|
+
default: return nil
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/// Sets one property, or returns why not; with `original`, first keeps the value it replaces under that id unless one
|
|
163
|
+
/// is kept already. The property's type encoding (`TB`, `TQ`, `T@"NSString"`, `T{UIEdgeInsets=dddd}`, …) decides what
|
|
164
|
+
/// the value may be.
|
|
165
|
+
private func set(_ object: NSObject, _ key: String, _ value: Any, original id: String?) -> String? {
|
|
166
|
+
guard !key.hasPrefix("_"), !key.contains(".") else { return "private and nested keys are not allowed" }
|
|
167
|
+
guard let attributes = Self.attributes(object, key) else { return "no such property" }
|
|
168
|
+
guard let first = attributes.first, first.hasPrefix("T") else { return "no type" }
|
|
169
|
+
if attributes.contains("R") { return "read-only" }
|
|
170
|
+
let type = String(first.dropFirst())
|
|
171
|
+
guard let coerced = Self.coerce(value, type) else { return "a \(type) property can't take \(value)" }
|
|
172
|
+
return __MRWCatchException {
|
|
173
|
+
if let id, originals[id] == nil { originals[id] = object.value(forKey: key) ?? NSNull() }
|
|
174
|
+
object.setValue(coerced is NSNull ? nil : coerced, forKey: key)
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/// The attributes of `object`'s property `key` (`TB`, `R`, …), or nil when it has none.
|
|
179
|
+
private static func attributes(_ object: NSObject, _ key: String) -> [Substring]? {
|
|
180
|
+
if privateBools[key].map({ object.isKind(of: $0) }) == true { return ["TB"] }
|
|
181
|
+
guard let property = class_getProperty(type(of: object), key) else { return nil }
|
|
182
|
+
return String(cString: property_getAttributes(property)!).split(separator: ",")
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/// KVC reaches these through WebKit's `_set…` accessors: WebKit declares no property by these names. They widen what
|
|
186
|
+
/// `file:` pages read: other `file:` URLs, and any URL.
|
|
187
|
+
private static let privateBools: [String: AnyClass] = [
|
|
188
|
+
"allowFileAccessFromFileURLs": WKPreferences.self,
|
|
189
|
+
"allowUniversalAccessFromFileURLs": WKWebViewConfiguration.self,
|
|
190
|
+
]
|
|
191
|
+
|
|
192
|
+
/// `value` as KVC must get it for a property of type encoding `type`; NSNull stands for nil. Nil: doesn't fit.
|
|
193
|
+
private static func coerce(_ value: Any, _ type: String) -> Any? {
|
|
194
|
+
let isBool = CFGetTypeID(value as CFTypeRef) == CFBooleanGetTypeID()
|
|
195
|
+
let number = isBool ? nil : value as? NSNumber
|
|
196
|
+
let string = value as? String
|
|
197
|
+
let object = value as? [String: Any]
|
|
198
|
+
let isNull = value is NSNull
|
|
199
|
+
switch type {
|
|
200
|
+
case "B", "c":
|
|
201
|
+
return isBool ? value : nil
|
|
202
|
+
case "s", "S", "i", "I", "l", "L", "q", "Q", "f", "d":
|
|
203
|
+
return number
|
|
204
|
+
case "@\"NSString\"":
|
|
205
|
+
return string ?? (isNull ? NSNull() : nil)
|
|
206
|
+
case "@\"NSURL\"":
|
|
207
|
+
return string.flatMap { URL(string: $0) as NSURL? } ?? (isNull ? NSNull() : nil)
|
|
208
|
+
case "@\"NSNumber\"":
|
|
209
|
+
return number ?? (isNull ? NSNull() : nil)
|
|
210
|
+
case "@\"UIColor\"":
|
|
211
|
+
return string.flatMap(color) ?? (isNull ? NSNull() : nil)
|
|
212
|
+
case "@\"WKWebsiteDataStore\"":
|
|
213
|
+
switch string {
|
|
214
|
+
case "default": return WKWebsiteDataStore.default()
|
|
215
|
+
case "nonPersistent": return WKWebsiteDataStore.nonPersistent()
|
|
216
|
+
default: return nil
|
|
217
|
+
}
|
|
218
|
+
case "{UIEdgeInsets=dddd}":
|
|
219
|
+
guard let o = object, let t = o["top"] as? Double, let l = o["left"] as? Double, let b = o["bottom"] as? Double, let r = o["right"] as? Double else { return nil }
|
|
220
|
+
return NSValue(uiEdgeInsets: UIEdgeInsets(top: t, left: l, bottom: b, right: r))
|
|
221
|
+
case "{CGPoint=dd}":
|
|
222
|
+
guard let o = object, let x = o["x"] as? Double, let y = o["y"] as? Double else { return nil }
|
|
223
|
+
return NSValue(cgPoint: CGPoint(x: x, y: y))
|
|
224
|
+
case "{CGSize=dd}":
|
|
225
|
+
guard let o = object, let w = o["width"] as? Double, let h = o["height"] as? Double else { return nil }
|
|
226
|
+
return NSValue(cgSize: CGSize(width: w, height: h))
|
|
227
|
+
case "{CGRect={CGPoint=dd}{CGSize=dd}}":
|
|
228
|
+
guard let o = object, let x = o["x"] as? Double, let y = o["y"] as? Double, let w = o["width"] as? Double, let h = o["height"] as? Double else { return nil }
|
|
229
|
+
return NSValue(cgRect: CGRect(x: x, y: y, width: w, height: h))
|
|
230
|
+
default:
|
|
231
|
+
return nil
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
private static func color(_ text: String) -> UIColor? {
|
|
236
|
+
let hex = text.hasPrefix("#") ? String(text.dropFirst()) : text
|
|
237
|
+
guard hex.count == 6 || hex.count == 8, let bits = UInt32(hex, radix: 16) else { return nil }
|
|
238
|
+
let rgba = hex.count == 8 ? bits : bits << 8 | 0xFF
|
|
239
|
+
let part = { (offset: UInt32) in CGFloat((rgba >> offset) & 0xFF) / 255 }
|
|
240
|
+
return UIColor(red: part(24), green: part(16), blue: part(8), alpha: part(0))
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/// Why `get` or `call` failed; `code` is the JS error code (`not_found` or `native_error`).
|
|
245
|
+
struct PlatformError: Error {
|
|
246
|
+
let message: String
|
|
247
|
+
let code: String
|
|
248
|
+
init(_ message: String, code: String = "native_error") {
|
|
249
|
+
self.message = message
|
|
250
|
+
self.code = code
|
|
251
|
+
}
|
|
252
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// The read root of a `file:` load the app starts, from `source.readAccessRoot`.
|
|
4
|
+
enum ReadAccess {
|
|
5
|
+
/// `root` when it is a `file:` URL that contains `file`, else `file`'s directory and a warning that says why `root`
|
|
6
|
+
/// didn't apply. Always a file URL: loadFileURL raises an exception (a crash) for any other.
|
|
7
|
+
static func root(for file: URL, _ root: String?) -> (root: URL, warning: String?) {
|
|
8
|
+
let directory = file.deletingLastPathComponent()
|
|
9
|
+
guard let root else { return (directory, nil) }
|
|
10
|
+
guard let url = URL(string: root), url.isFileURL else {
|
|
11
|
+
return (directory, "source.readAccessRoot \(root) is not a file: URL, so the file's directory applies")
|
|
12
|
+
}
|
|
13
|
+
// Components, not a string prefix: `..` is resolved, and /a/site2 isn't inside /a/site.
|
|
14
|
+
guard file.standardizedFileURL.pathComponents.starts(with: url.standardizedFileURL.pathComponents) else {
|
|
15
|
+
return (directory, "source.readAccessRoot \(root) doesn't contain \(file.absoluteString), so the file's directory applies")
|
|
16
|
+
}
|
|
17
|
+
return (url, nil)
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Crash recovery's choices that need no WebView, as on Android (`showsSource` and `crashAllowsReload` in
|
|
4
|
+
/// MinimalWebView.kt). Cases: src/__tests__/vectors/recovery.json.
|
|
5
|
+
enum Recovery {
|
|
6
|
+
/// Whether the committed `url` is the page of the `source` with this `uri`: equal up to trailing slashes (WebKit
|
|
7
|
+
/// commits `https://example.com` as `https://example.com/`). Not `Loads.sameURL`'s rule: that one picks out our own
|
|
8
|
+
/// loads, which skip the navigation rules.
|
|
9
|
+
static func showsSource(_ uri: String, _ url: String) -> Bool {
|
|
10
|
+
func trimmed(_ url: String) -> String { url.replacingOccurrences(of: "/+$", with: "", options: .regularExpression) }
|
|
11
|
+
return trimmed(uri) == trimmed(url)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/// Records a web content process death at `now` in `times`, and says whether to reload after it: not after more than
|
|
15
|
+
/// `maxCrashesPerWindow` in `crashWindow`, a death exactly `crashWindow` back included. `now` is in seconds of
|
|
16
|
+
/// `ProcessInfo.systemUptime`, which a change of device time doesn't move.
|
|
17
|
+
static func crashAllowsReload(_ times: inout [TimeInterval], now: TimeInterval) -> Bool {
|
|
18
|
+
times = times.filter { now - $0 <= crashWindow } + [now]
|
|
19
|
+
return times.count <= maxCrashesPerWindow
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// shortcut: a fixed crash-loop guard, make it a prop if an app needs a different policy
|
|
24
|
+
private let maxCrashesPerWindow = 3
|
|
25
|
+
private let crashWindow: TimeInterval = 60
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import WebKit
|
|
2
|
+
|
|
3
|
+
/// The `sharedCookies` prop. In the core, not a hook: the copy before the first `source` load is something nothing
|
|
4
|
+
/// outside the core can hold.
|
|
5
|
+
final class SharedCookies: NSObject, WKHTTPCookieStoreObserver {
|
|
6
|
+
private weak var store: WKHTTPCookieStore?
|
|
7
|
+
private var enabled = false
|
|
8
|
+
private var copyScheduled = false
|
|
9
|
+
/// The WebView's cookies at the last copy: one gone from it since is deleted from native too.
|
|
10
|
+
private var copied: [HTTPCookie] = []
|
|
11
|
+
|
|
12
|
+
/// Once: the view's one WKWebView, which a crash keeps.
|
|
13
|
+
func didCreate(_ webView: WKWebView) {
|
|
14
|
+
store = webView.configuration.websiteDataStore.httpCookieStore
|
|
15
|
+
if enabled { store?.add(self) }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
func set(_ enabled: Bool) {
|
|
19
|
+
guard enabled != self.enabled else { return }
|
|
20
|
+
self.enabled = enabled
|
|
21
|
+
if enabled { store?.add(self) } else { store?.remove(self) }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/// Work that must finish before a `source` load: calls `done` once the native cookies are in the WebView.
|
|
25
|
+
func prepare(done: @escaping () -> Void) {
|
|
26
|
+
guard enabled, let store else { return done() }
|
|
27
|
+
let group = DispatchGroup()
|
|
28
|
+
// shortcut: one setCookie per cookie, use iOS 26's batch setCookies once the minimum allows
|
|
29
|
+
for cookie in HTTPCookieStorage.shared.cookies ?? [] {
|
|
30
|
+
group.enter()
|
|
31
|
+
store.setCookie(cookie) { group.leave() }
|
|
32
|
+
}
|
|
33
|
+
group.notify(queue: .main, execute: done)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/// One copy per main-queue turn: `prepare`'s setCookie calls, or a page setting many cookies, each fire this.
|
|
37
|
+
func cookiesDidChange(in cookieStore: WKHTTPCookieStore) {
|
|
38
|
+
guard !copyScheduled else { return }
|
|
39
|
+
copyScheduled = true
|
|
40
|
+
DispatchQueue.main.async { [weak self] in
|
|
41
|
+
guard let self else { return }
|
|
42
|
+
// Cleared before the read: a change after it schedules the next copy.
|
|
43
|
+
self.copyScheduled = false
|
|
44
|
+
self.store?.getAllCookies { [weak self] cookies in
|
|
45
|
+
guard let self else { return }
|
|
46
|
+
let key = { (cookie: HTTPCookie) in [cookie.name, cookie.domain, cookie.path] }
|
|
47
|
+
let present = Set(cookies.map(key))
|
|
48
|
+
// Deleted or expired in the WebView (a logout): native drops it too. Cookies only native set stay.
|
|
49
|
+
self.copied.filter { !present.contains(key($0)) }.forEach(HTTPCookieStorage.shared.deleteCookie)
|
|
50
|
+
cookies.forEach(HTTPCookieStorage.shared.setCookie)
|
|
51
|
+
self.copied = cookies
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
func detach() {
|
|
57
|
+
store?.remove(self)
|
|
58
|
+
}
|
|
59
|
+
}
|