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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +130 -2
  3. package/android/build.gradle +26 -0
  4. package/android/consumer-rules.pro +4 -0
  5. package/android/src/main/AndroidManifest.xml +2 -0
  6. package/android/src/main/java/expo/modules/minimalwebview/Asks.kt +44 -0
  7. package/android/src/main/java/expo/modules/minimalwebview/DocumentEnd.kt +31 -0
  8. package/android/src/main/java/expo/modules/minimalwebview/Hooks.kt +496 -0
  9. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebView.kt +510 -0
  10. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewClients.kt +359 -0
  11. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewModule.kt +245 -0
  12. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewNavigation.kt +199 -0
  13. package/android/src/main/java/expo/modules/minimalwebview/MinimalWebViewScripts.kt +191 -0
  14. package/android/src/main/java/expo/modules/minimalwebview/NavigationRules.kt +113 -0
  15. package/android/src/main/java/expo/modules/minimalwebview/PlatformSettings.kt +306 -0
  16. package/android/src/main/java/expo/modules/minimalwebview/PullToRefresh.kt +76 -0
  17. package/android/src/main/java/expo/modules/minimalwebview/requests/Downloads.kt +258 -0
  18. package/android/src/main/java/expo/modules/minimalwebview/requests/FileUpload.kt +44 -0
  19. package/android/src/main/java/expo/modules/minimalwebview/requests/FullscreenVideo.kt +87 -0
  20. package/android/src/main/java/expo/modules/minimalwebview/requests/Permissions.kt +77 -0
  21. package/build/WebView.d.ts +99 -0
  22. package/build/WebView.d.ts.map +1 -0
  23. package/build/WebView.js +448 -0
  24. package/build/WebView.js.map +1 -0
  25. package/build/bridge/createBridge.d.ts +32 -0
  26. package/build/bridge/createBridge.d.ts.map +1 -0
  27. package/build/bridge/createBridge.js +135 -0
  28. package/build/bridge/createBridge.js.map +1 -0
  29. package/build/bridge/endpoint.d.ts +35 -0
  30. package/build/bridge/endpoint.d.ts.map +1 -0
  31. package/build/bridge/endpoint.js +100 -0
  32. package/build/bridge/endpoint.js.map +1 -0
  33. package/build/bridge/origins.d.ts +25 -0
  34. package/build/bridge/origins.d.ts.map +1 -0
  35. package/build/bridge/origins.js +60 -0
  36. package/build/bridge/origins.js.map +1 -0
  37. package/build/bridge/pageClient.generated.d.ts +3 -0
  38. package/build/bridge/pageClient.generated.d.ts.map +1 -0
  39. package/build/bridge/pageClient.generated.js +4 -0
  40. package/build/bridge/pageClient.generated.js.map +1 -0
  41. package/build/bridge/protocol.d.ts +50 -0
  42. package/build/bridge/protocol.d.ts.map +1 -0
  43. package/build/bridge/protocol.js +52 -0
  44. package/build/bridge/protocol.js.map +1 -0
  45. package/build/defaultNavigationRules.d.ts +16 -0
  46. package/build/defaultNavigationRules.d.ts.map +1 -0
  47. package/build/defaultNavigationRules.js +23 -0
  48. package/build/defaultNavigationRules.js.map +1 -0
  49. package/build/index.d.ts +31 -0
  50. package/build/index.d.ts.map +1 -0
  51. package/build/index.js +30 -0
  52. package/build/index.js.map +1 -0
  53. package/build/platform.generated.d.ts +702 -0
  54. package/build/platform.generated.d.ts.map +1 -0
  55. package/build/platform.generated.js +199 -0
  56. package/build/platform.generated.js.map +1 -0
  57. package/build/reactNativeWebViewDefaults.d.ts +21 -0
  58. package/build/reactNativeWebViewDefaults.d.ts.map +1 -0
  59. package/build/reactNativeWebViewDefaults.js +12 -0
  60. package/build/reactNativeWebViewDefaults.js.map +1 -0
  61. package/build/reactNativeWebViewMessages.d.ts +22 -0
  62. package/build/reactNativeWebViewMessages.d.ts.map +1 -0
  63. package/build/reactNativeWebViewMessages.js +30 -0
  64. package/build/reactNativeWebViewMessages.js.map +1 -0
  65. package/build/refStore.d.ts +31 -0
  66. package/build/refStore.d.ts.map +1 -0
  67. package/build/refStore.js +113 -0
  68. package/build/refStore.js.map +1 -0
  69. package/build/types.d.ts +1127 -0
  70. package/build/types.d.ts.map +1 -0
  71. package/build/types.defaults.d.ts +8 -0
  72. package/build/types.defaults.d.ts.map +1 -0
  73. package/build/types.defaults.js +17 -0
  74. package/build/types.defaults.js.map +1 -0
  75. package/build/types.js +2 -0
  76. package/build/types.js.map +1 -0
  77. package/expo-module.config.json +9 -0
  78. package/ios/Asks.swift +45 -0
  79. package/ios/DelegateProxy.swift +162 -0
  80. package/ios/DocumentEnd.swift +23 -0
  81. package/ios/DownloadName.swift +12 -0
  82. package/ios/Downloads.swift +51 -0
  83. package/ios/Hooks.swift +308 -0
  84. package/ios/Loads.swift +44 -0
  85. package/ios/MRWExceptions.h +9 -0
  86. package/ios/MRWExceptions.m +10 -0
  87. package/ios/MRWInvoke.h +23 -0
  88. package/ios/MRWInvoke.m +187 -0
  89. package/ios/MinimalWebView+Dialogs.swift +99 -0
  90. package/ios/MinimalWebView+Navigation.swift +244 -0
  91. package/ios/MinimalWebView+Scripts.swift +92 -0
  92. package/ios/MinimalWebView.docc/MinimalWebView.md +13 -0
  93. package/ios/MinimalWebView.podspec +32 -0
  94. package/ios/MinimalWebView.swift +512 -0
  95. package/ios/MinimalWebViewModule.swift +110 -0
  96. package/ios/NavigationRules.swift +123 -0
  97. package/ios/OriginRules.swift +35 -0
  98. package/ios/PlatformCompletions.generated.swift +39 -0
  99. package/ios/PlatformSettings.swift +247 -0
  100. package/ios/ReadAccess.swift +19 -0
  101. package/ios/Recovery.swift +25 -0
  102. package/ios/SharedCookies.swift +59 -0
  103. package/package.json +94 -4
  104. package/src/WebView.tsx +623 -0
  105. package/src/bridge/createBridge.ts +176 -0
  106. package/src/bridge/endpoint.ts +119 -0
  107. package/src/bridge/origins.ts +62 -0
  108. package/src/bridge/pageClient.generated.ts +5 -0
  109. package/src/bridge/pageClient.ts +68 -0
  110. package/src/bridge/protocol.ts +78 -0
  111. package/src/defaultNavigationRules.ts +25 -0
  112. package/src/index.ts +37 -0
  113. package/src/platform.generated.ts +694 -0
  114. package/src/reactNativeWebViewDefaults.ts +13 -0
  115. package/src/reactNativeWebViewMessages.ts +32 -0
  116. package/src/refStore.ts +164 -0
  117. package/src/types.defaults.ts +24 -0
  118. package/src/types.ts +1194 -0
@@ -0,0 +1,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 if one must
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,35 @@
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 default port left out (WebKit reports it as 0), an IPv6 host in brackets, and an opaque origin (no scheme: an
9
+ /// html source without `baseUrl`, a sandboxed page) as `null`.
10
+ static func origin(_ scheme: String, _ host: String, _ port: Int) -> String {
11
+ guard !scheme.isEmpty else { return "null" }
12
+ let defaultPort = scheme == "https" ? 443 : scheme == "http" ? 80 : nil
13
+ let host = host.contains(":") && !host.hasPrefix("[") ? "[\(host)]" : host
14
+ return "\(scheme)://\(host)" + (port == 0 || port == defaultPort ? "" : ":\(port)")
15
+ }
16
+
17
+ static func allows(_ rules: [String], _ origin: String) -> Bool {
18
+ let value = parse(origin)
19
+ return rules.contains { rule in
20
+ guard let r = parse(rule), let o = value, !o.wildcard else { return rule == "*" }
21
+ return (r.wildcard ? o.host.hasSuffix("." + r.host) : o.host == r.host) && r.scheme == o.scheme && r.port == o.port
22
+ }
23
+ }
24
+
25
+ // Built once: a regex literal in the function body is compiled again on every call. Regex isn't Sendable; every
26
+ // caller is a WebKit delegate callback on the main thread.
27
+ nonisolated(unsafe) private static let pattern = #/(https?):\/\/(\*\.(?!\[))?([a-z0-9_-]+(?:\.[a-z0-9_-]+)*|\[[0-9a-f:.]+\])(?::(\d{1,5}))?/#
28
+
29
+ private struct Parsed { let scheme: Substring, wildcard: Bool, host: Substring, port: Int }
30
+
31
+ private static func parse(_ text: String) -> Parsed? {
32
+ guard let m = try? pattern.wholeMatch(in: text.lowercased()) else { return nil }
33
+ return Parsed(scheme: m.1, wildcard: m.2 != nil, host: m.3, port: m.4.flatMap { Int($0) } ?? (m.1 == "https" ? 443 : 80))
34
+ }
35
+ }
@@ -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,247 @@
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: BOOL; integers, enums and option sets by raw value; floats; NSString; NSURL
12
+ /// from a string; UIColor from `#rrggbb` or `#rrggbbaa`; UIEdgeInsets, CGPoint, CGSize and CGRect from an object; and
13
+ /// `websiteDataStore` from `"default"` or `"nonPersistent"`. Anything else is rejected before KVC runs: a wrong value
14
+ /// in an object-typed property can take the process down (WebKit asserts), and an unknown key raises an Objective-C
15
+ /// exception Swift can't catch. Underscore (private) properties are refused, and the only private keys accepted are the
16
+ /// two react-native-webview sets by KVC (`privateBools`).
17
+ ///
18
+ /// `get` reads a property of a root and `call` invokes a method on one by selector, through MRWInvoke (MRWInvoke.h),
19
+ /// which sets the arguments by the method's signature. For those two, `websiteDataStore` and `httpCookieStore` are
20
+ /// roots as well.
21
+ final class PlatformSettings {
22
+ /// "root.key" -> the last value applied or rejected, so an unchanged value is neither applied nor reported again.
23
+ private var applied: [String: NSObject] = [:]
24
+ /// "root.key" of a live root -> its value before the first write (NSNull for nil), set back when the key is removed.
25
+ private var originals: [String: Any] = [:]
26
+
27
+ /// Applies `settings`. While creating (`configuration` given, no WebView yet) only the `configuration` root applies;
28
+ /// live, every other root does (JS remounts the view for a new `configuration`), and a key applied before and missing
29
+ /// now goes back to its value before the first write. Returns the rejected keys.
30
+ func apply(_ settings: [String: Any], webView: WKWebView?, configuration: WKWebViewConfiguration? = nil) -> [[String: String]] {
31
+ var rejected: [[String: String]] = []
32
+ let creating = configuration != nil
33
+ // Before the new values, so restoring one (a scroll view's inset) can't undo another (its offset).
34
+ if !creating { rejected += restore(removedFrom: settings, webView: webView) }
35
+ for (rootName, entries) in settings {
36
+ guard let entries = entries as? [String: Any] else {
37
+ rejected.append(["key": rootName, "reason": "not an object"])
38
+ continue
39
+ }
40
+ let isConfiguration = rootName == "configuration"
41
+ guard isConfiguration == creating else { continue }
42
+ for (key, value) in entries {
43
+ let id = "\(rootName).\(key)"
44
+ let boxed = value as? NSObject ?? NSNull()
45
+ if applied[id] == boxed { continue }
46
+ applied[id] = boxed
47
+ guard let object = root(rootName, webView: webView, configuration: configuration) else {
48
+ rejected.append(["key": id, "reason": "unknown root: use \(Self.roots)"])
49
+ continue
50
+ }
51
+ if let reason = set(object, key, value, original: isConfiguration ? nil : id) {
52
+ rejected.append(["key": id, "reason": reason])
53
+ }
54
+ }
55
+ }
56
+ return rejected
57
+ }
58
+
59
+ /// Forgets each applied key `settings` no longer has and sets its original value back; returns those that failed.
60
+ private func restore(removedFrom settings: [String: Any], webView: WKWebView?) -> [[String: String]] {
61
+ var present = Set<String>()
62
+ for (rootName, entries) in settings {
63
+ guard let entries = entries as? [String: Any] else { continue }
64
+ present.formUnion(entries.keys.map { "\(rootName).\($0)" })
65
+ }
66
+ var failed: [[String: String]] = []
67
+ for id in applied.keys where !present.contains(id) {
68
+ applied[id] = nil
69
+ guard let original = originals.removeValue(forKey: id), let dot = id.firstIndex(of: "."),
70
+ let object = root(String(id[..<dot]), webView: webView, configuration: nil) else { continue }
71
+ let key = String(id[id.index(after: dot)...])
72
+ // shortcut: a null_resettable property (underPageBackgroundColor) comes back as the value read, not as "follow the
73
+ // default"; set nil for those if one matters.
74
+ if let reason = __MRWCatchException({ object.setValue(original is NSNull ? nil : original, forKey: key) }) {
75
+ failed.append(["key": id, "reason": "removed, but restoring it failed: \(reason)"])
76
+ }
77
+ }
78
+ return failed
79
+ }
80
+
81
+ /// `root.key` through KVC, as JSON. Throws a `PlatformError` with the reason when it can't.
82
+ func get(_ path: String, webView: WKWebView) throws -> String {
83
+ guard let dot = path.firstIndex(of: ".") else { throw PlatformError("use root.key", code: "not_found") }
84
+ let rootName = String(path[..<dot])
85
+ let key = String(path[path.index(after: dot)...])
86
+ guard let object = root(rootName, webView: webView, configuration: webView.configuration) else {
87
+ throw PlatformError("unknown root: use \(Self.roots)", code: "not_found")
88
+ }
89
+ guard !key.hasPrefix("_"), !key.contains("."), Self.attributes(object, key) != nil else {
90
+ throw PlatformError("no such property \(path)", code: "not_found")
91
+ }
92
+ return try Self.json { __MRWJsonable(object.value(forKey: key)) }
93
+ }
94
+
95
+ /// `root.selector:` with the JSON `args`, resolved with the result as JSON, or with why it couldn't be called.
96
+ func call(_ path: String, args: [Any], webView: WKWebView, resolve: @escaping (String?, String?) -> Void) throws {
97
+ guard let dot = path.lastIndex(of: ".") else { throw PlatformError("use root.selector:", code: "not_found") }
98
+ let selector = String(path[path.index(after: dot)...])
99
+ guard let object = root(String(path[..<dot]), webView: webView, configuration: webView.configuration) else {
100
+ throw PlatformError("unknown root: use \(Self.roots)", code: "not_found")
101
+ }
102
+ guard !Self.refused.contains(where: selector.hasPrefix) else {
103
+ throw PlatformError("\(selector) is owned by the core, or private")
104
+ }
105
+ guard object.responds(to: NSSelectorFromString(selector)) else {
106
+ throw PlatformError("\(type(of: object)) has no method \(selector)", code: "not_found")
107
+ }
108
+ __MRWInvoke(object, NSSelectorFromString(selector), args, platformCompletions[path]) { result, error in
109
+ guard error == nil, let result else { return resolve(nil, error ?? "the result is not JSON") }
110
+ do {
111
+ let json = try Self.json { result }
112
+ resolve(json, nil)
113
+ } catch let failure {
114
+ resolve(nil, (failure as? PlatformError)?.message ?? failure.localizedDescription)
115
+ }
116
+ }
117
+ }
118
+
119
+ /// `value()` as JSON text. It runs inside MRWCatchException: a getter that raises, or a NaN that JSONSerialization
120
+ /// raises for, throws here instead of crashing the app.
121
+ static func json(_ value: () -> Any) throws -> String {
122
+ var data: Data?
123
+ let raised = __MRWCatchException {
124
+ data = try? JSONSerialization.data(withJSONObject: value(), options: .fragmentsAllowed)
125
+ }
126
+ if let raised { throw PlatformError(raised) }
127
+ guard let data else { throw PlatformError("the result is not JSON") }
128
+ return String(decoding: data, as: UTF8.self)
129
+ }
130
+
131
+ /// Selector prefixes `call` refuses: what the ref and the core own (every load, navigation, script, download and
132
+ /// delegate selector), private API, the plumbing that would reach either (KVC, KVO's willChange/didChange,
133
+ /// performSelector), object lifecycle (init, copy, new: a re-initialized live object, or a +1 result MRWInvoke would
134
+ /// leak) and reference counting. `mutable` covers `mutableCopy` and KVC's `mutableArrayValueForKey:` and its kin.
135
+ private static let refused = [
136
+ "_", "load", "go", "reload", "stop", "evaluateJavaScript", "callAsyncJavaScript", "startDownload", "resumeDownload",
137
+ "setInteractionState", "setNavigationDelegate", "setUIDelegate", "setDelegate", "setValue", "setValuesForKeys", "valueForKey",
138
+ "dictionaryWithValuesForKeys", "mutable", "willChange", "didChange", "performSelector", "init", "copy", "new",
139
+ "retain", "release", "autorelease", "dealloc",
140
+ ]
141
+ static let roots = "configuration, preferences, webpagePreferences, webView, scrollView, websiteDataStore or httpCookieStore"
142
+
143
+ private func root(_ name: String, webView: WKWebView?, configuration: WKWebViewConfiguration?) -> NSObject? {
144
+ switch name {
145
+ case "configuration": return configuration
146
+ case "preferences": return webView?.configuration.preferences
147
+ case "webpagePreferences": return webView?.configuration.defaultWebpagePreferences
148
+ case "webView": return webView
149
+ case "scrollView": return webView?.scrollView
150
+ case "websiteDataStore": return webView?.configuration.websiteDataStore
151
+ case "httpCookieStore": return webView?.configuration.websiteDataStore.httpCookieStore
152
+ default: return nil
153
+ }
154
+ }
155
+
156
+ /// Sets one property, or returns why not; with `original`, first keeps the value it replaces under that id unless one
157
+ /// is kept already. The property's type encoding (`TB`, `TQ`, `T@"NSString"`, `T{UIEdgeInsets=dddd}`, …) decides what
158
+ /// the value may be.
159
+ private func set(_ object: NSObject, _ key: String, _ value: Any, original id: String?) -> String? {
160
+ guard !key.hasPrefix("_"), !key.contains(".") else { return "private and nested keys are not allowed" }
161
+ guard let attributes = Self.attributes(object, key) else { return "no such property" }
162
+ guard let first = attributes.first, first.hasPrefix("T") else { return "no type" }
163
+ if attributes.contains("R") { return "read-only" }
164
+ let type = String(first.dropFirst())
165
+ guard let coerced = Self.coerce(value, type) else { return "a \(type) property can't take \(value)" }
166
+ return __MRWCatchException {
167
+ if let id, originals[id] == nil { originals[id] = object.value(forKey: key) ?? NSNull() }
168
+ object.setValue(coerced is NSNull ? nil : coerced, forKey: key)
169
+ }
170
+ }
171
+
172
+ /// The attributes of `object`'s property `key` (`TB`, `R`, …), or nil when it has none.
173
+ private static func attributes(_ object: NSObject, _ key: String) -> [Substring]? {
174
+ if privateBools[key].map({ object.isKind(of: $0) }) == true { return ["TB"] }
175
+ guard let property = class_getProperty(type(of: object), key) else { return nil }
176
+ return String(cString: property_getAttributes(property)!).split(separator: ",")
177
+ }
178
+
179
+ /// The private BOOLs react-native-webview sets by KVC, which reaches WebKit's `_set…` accessors: they declare no
180
+ /// property by these names. They widen what `file:` pages read: other `file:` URLs, and any URL.
181
+ private static let privateBools: [String: AnyClass] = [
182
+ "allowFileAccessFromFileURLs": WKPreferences.self,
183
+ "allowUniversalAccessFromFileURLs": WKWebViewConfiguration.self,
184
+ ]
185
+
186
+ /// `value` as KVC must get it for a property of type encoding `type`; NSNull stands for nil. Nil: doesn't fit.
187
+ private static func coerce(_ value: Any, _ type: String) -> Any? {
188
+ let isBool = CFGetTypeID(value as CFTypeRef) == CFBooleanGetTypeID()
189
+ let number = isBool ? nil : value as? NSNumber
190
+ let string = value as? String
191
+ let object = value as? [String: Any]
192
+ let isNull = value is NSNull
193
+ switch type {
194
+ case "B", "c":
195
+ return isBool ? value : nil
196
+ case "s", "S", "i", "I", "l", "L", "q", "Q", "f", "d":
197
+ return number
198
+ case "@\"NSString\"":
199
+ return string ?? (isNull ? NSNull() : nil)
200
+ case "@\"NSURL\"":
201
+ return string.flatMap { URL(string: $0) as NSURL? } ?? (isNull ? NSNull() : nil)
202
+ case "@\"NSNumber\"":
203
+ return number ?? (isNull ? NSNull() : nil)
204
+ case "@\"UIColor\"":
205
+ return string.flatMap(color) ?? (isNull ? NSNull() : nil)
206
+ case "@\"WKWebsiteDataStore\"":
207
+ switch string {
208
+ case "default": return WKWebsiteDataStore.default()
209
+ case "nonPersistent": return WKWebsiteDataStore.nonPersistent()
210
+ default: return nil
211
+ }
212
+ case "{UIEdgeInsets=dddd}":
213
+ 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 }
214
+ return NSValue(uiEdgeInsets: UIEdgeInsets(top: t, left: l, bottom: b, right: r))
215
+ case "{CGPoint=dd}":
216
+ guard let o = object, let x = o["x"] as? Double, let y = o["y"] as? Double else { return nil }
217
+ return NSValue(cgPoint: CGPoint(x: x, y: y))
218
+ case "{CGSize=dd}":
219
+ guard let o = object, let w = o["width"] as? Double, let h = o["height"] as? Double else { return nil }
220
+ return NSValue(cgSize: CGSize(width: w, height: h))
221
+ case "{CGRect={CGPoint=dd}{CGSize=dd}}":
222
+ 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 }
223
+ return NSValue(cgRect: CGRect(x: x, y: y, width: w, height: h))
224
+ default:
225
+ return nil
226
+ }
227
+ }
228
+
229
+ /// `#rrggbb` or `#rrggbbaa`.
230
+ private static func color(_ text: String) -> UIColor? {
231
+ let hex = text.hasPrefix("#") ? String(text.dropFirst()) : text
232
+ guard hex.count == 6 || hex.count == 8, let bits = UInt32(hex, radix: 16) else { return nil }
233
+ let rgba = hex.count == 8 ? bits : bits << 8 | 0xFF
234
+ let part = { (offset: UInt32) in CGFloat((rgba >> offset) & 0xFF) / 255 }
235
+ return UIColor(red: part(24), green: part(16), blue: part(8), alpha: part(0))
236
+ }
237
+ }
238
+
239
+ /// Why `get` or `call` failed; `code` is the JS error code (`not_found` or `native_error`).
240
+ struct PlatformError: Error {
241
+ let message: String
242
+ let code: String
243
+ init(_ message: String, code: String = "native_error") {
244
+ self.message = message
245
+ self.code = code
246
+ }
247
+ }
@@ -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 seconds of a clock the device time doesn't move
15
+ /// (`ProcessInfo.systemUptime`), in `times` and says whether to reload after it: not after more than 3 in 60 s, a
16
+ /// crash exactly 60 s back included.
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
+ }
package/package.json CHANGED
@@ -1,6 +1,96 @@
1
1
  {
2
2
  "name": "react-native-minimal-webview",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "A minimal, extensible WebView for React Native (Expo Modules)",
5
+ "main": "build/index.js",
6
+ "types": "build/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./build/index.d.ts",
10
+ "react-native": "./src/index.ts",
11
+ "default": "./build/index.js"
12
+ },
13
+ "./package.json": "./package.json"
14
+ },
15
+ "files": [
16
+ "build",
17
+ "src",
18
+ "!src/**/__tests__",
19
+ "ios",
20
+ "!ios/Tests",
21
+ "android/build.gradle",
22
+ "android/consumer-rules.pro",
23
+ "android/src/main",
24
+ "expo-module.config.json"
25
+ ],
26
+ "scripts": {
27
+ "build": "tsc && tsc -p extensions",
28
+ "clean": "rm -rf build extensions/build",
29
+ "pretest": "npm run build:page-client -- --check && npm run gen:platform-types -- --check && npm run gen:defaults -- --check",
30
+ "test": "jest",
31
+ "lint": "eslint --max-warnings 0 src extensions example .github && prettier --check .",
32
+ "prepare": "npm run clean && npm run build",
33
+ "check": "npm test && npm run lint && knip --config .config/knip.json && tsc --noEmit -p src/__tests__/tsconfig.json && tsc --noEmit -p extensions/src/__tests__/tsconfig.json && (cd example && npx tsc --noEmit) && node .github/scripts/check-doc-samples.mts && npm run prepare && npm run docs:check",
34
+ "mutation": "stryker run .config/stryker.config.json",
35
+ "build:page-client": "node .github/scripts/build-page-client.mts",
36
+ "gen:platform-types": "node .github/scripts/gen-platform-types.mts",
37
+ "gen:defaults": "tsdoc-defaults",
38
+ "docs": "rn-cross-platform-docs generate --out build/docs/reference && rn-cross-platform-docs-zensical build --reference build/docs/reference --out build/docs/site --site-url https://rasmuskard.github.io/react-native-minimal-webview/",
39
+ "docs:check": "typedoc --emit none"
40
+ },
41
+ "keywords": [
42
+ "react-native",
43
+ "expo",
44
+ "react-native-minimal-webview",
45
+ "MinimalWebView"
46
+ ],
47
+ "repository": "https://github.com/RasmusKard/react-native-minimal-webview",
48
+ "bugs": {
49
+ "url": "https://github.com/RasmusKard/react-native-minimal-webview/issues"
50
+ },
51
+ "author": "Rasmus Kard <rasmuskard@gmail.com> (https://github.com/RasmusKard)",
52
+ "license": "MIT",
53
+ "homepage": "https://github.com/RasmusKard/react-native-minimal-webview#readme",
54
+ "devDependencies": {
55
+ "@babel/core": "^7.29.13",
56
+ "@rn-cross-platform-docs/cli": "1.3.0",
57
+ "@rn-cross-platform-docs/zensical": "1.3.0",
58
+ "@stryker-mutator/core": "10.1.1",
59
+ "@stryker-mutator/jest-runner": "10.1.1",
60
+ "@types/jest": "^30.0.0",
61
+ "@types/node": "22.20.5",
62
+ "@types/react": "~19.3.0",
63
+ "eslint": "~9.39.4",
64
+ "eslint-config-universe": "^16.1.2",
65
+ "eslint-plugin-sonarjs": "4.2.2",
66
+ "expo": "~58.0.25",
67
+ "globals": "^17.14.0",
68
+ "jest": "^30.0.0",
69
+ "jest-expo": "~58.0.14",
70
+ "knip": "6.45.1",
71
+ "prettier": "^3.10.1",
72
+ "react": "19.3.0",
73
+ "react-native": "0.88.1",
74
+ "test-renderer": "1.3.1",
75
+ "tsdoc-defaults": "^1.0.2",
76
+ "typedoc": "0.28.20",
77
+ "typedoc-plugin-markdown": "4.14.1",
78
+ "typescript": "~6.0.3"
79
+ },
80
+ "jest": {
81
+ "preset": "jest-expo",
82
+ "roots": [
83
+ "<rootDir>/src",
84
+ "<rootDir>/extensions/src"
85
+ ]
86
+ },
87
+ "peerDependencies": {
88
+ "expo": ">=53",
89
+ "react": ">=19",
90
+ "react-native": ">=0.79"
91
+ },
92
+ "react-native": "src/index.ts",
93
+ "workspaces": [
94
+ "extensions"
95
+ ]
96
+ }