Repository navigation
Expand file tree
/
Copy pathWebEngine.swift
More file actions
5956 lines (5362 loc) · 230 KB
/
Copy pathWebEngine.swift
File metadata and controls
5956 lines (5362 loc) · 230 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2024–2026 Skip
// SPDX-License-Identifier: MPL-2.0
#if !SKIP_BRIDGE
import Foundation
import SwiftUI
#if !SKIP
import WebKit
import UniformTypeIdentifiers
import CryptoKit
#else
import android.graphics.Bitmap
import android.graphics.Canvas
import androidx.webkit.WebResourceRequestCompat
import androidx.webkit.ScriptHandler
import androidx.webkit.ProfileStore
import androidx.webkit.WebStorageCompat
import androidx.webkit.WebViewCompat
import androidx.webkit.WebViewFeature
import java.lang.ref.WeakReference
import kotlin.coroutines.suspendCoroutine
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.asExecutor
import kotlinx.coroutines.withContext
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
#endif
#if SKIP
/// Completes one visual-state request without exposing Android callback types across the bridge.
private struct WebEngineVisualStateCallback: android.webkit.WebView.VisualStateCallback {
let completion: () -> Void
override func onComplete(requestId: Int64) {
completion()
}
}
#endif
public enum WebProfile: Equatable, Hashable, Sendable {
/// Uses the platform default persistent website data store.
case `default`
/// Uses a persistent website data store isolated by the supplied identifier.
///
/// On Android, identifiers beginning with `skipweb-internal-` are reserved for
/// SkipWeb-owned profiles and fail with ``WebProfileError/invalidProfileName``.
case named(String)
/// Uses an in-memory website data store when the platform supports one.
///
/// On iOS this maps to `WKWebsiteDataStore.nonPersistent()`. On Android this maps to
/// a generated named WebView profile when `MULTI_PROFILE` is supported.
case ephemeral
/// Uses one explicitly owned ephemeral browsing session shared by multiple web views.
///
/// Engines created with the same nonempty identifier share cookies and website data without
/// using the default persistent store. Release those engines, then call
/// ``WebEngine/clearEphemeralSessionProfile(identifier:)`` when the session ends.
/// On iOS the shared nonpersistent data store is released. On Android the corresponding
/// isolated WebView profile is kept, but its browsing data is deleted.
case ephemeralSession(String)
fileprivate var normalizedNamedIdentifier: String? {
guard case .named(let rawIdentifier) = self else {
return nil
}
let identifier = rawIdentifier.trimmingCharacters(in: .whitespacesAndNewlines)
guard !identifier.isEmpty else {
return nil
}
if identifier.lowercased() == "default" {
return nil
}
return identifier
}
fileprivate var normalizedEphemeralSessionIdentifier: String? {
guard case .ephemeralSession(let rawIdentifier) = self else {
return nil
}
let identifier = rawIdentifier.trimmingCharacters(in: .whitespacesAndNewlines)
guard !identifier.isEmpty else {
return nil
}
return identifier
}
}
public enum WebProfileError: Error, Equatable {
case unsupportedOnAndroid
case invalidProfileName
case profileSetupFailed
}
enum AndroidWebProfileNamespace {
static let internalPrefix = "skipweb-internal-"
static func ephemeralSessionProfileName(identifier: String) -> String {
"\(internalPrefix)ephemeral-session-\(identifier)"
}
static func isReservedNamedProfileIdentifier(_ identifier: String) -> Bool {
identifier.hasPrefix(internalPrefix)
}
}
enum WebProfilePolicy {
static func validationError(for profile: WebProfile) -> WebProfileError? {
switch profile {
case .default, .ephemeral:
return nil
case .ephemeralSession:
return profile.normalizedEphemeralSessionIdentifier == nil ? .invalidProfileName : nil
case .named:
return profile.normalizedNamedIdentifier == nil ? .invalidProfileName : nil
}
}
static func androidSupportError(
for profile: WebProfile,
isMultiProfileFeatureSupported: Bool
) -> WebProfileError? {
if let validationError = validationError(for: profile) {
return validationError
}
switch profile {
case .default:
return nil
case .ephemeral, .ephemeralSession:
return isMultiProfileFeatureSupported ? nil : .unsupportedOnAndroid
case .named:
if let identifier = profile.normalizedNamedIdentifier,
AndroidWebProfileNamespace.isReservedNamedProfileIdentifier(identifier) {
return .invalidProfileName
}
return isMultiProfileFeatureSupported ? nil : .unsupportedOnAndroid
}
}
}
#if !SKIP
@MainActor
private enum EphemeralSessionWebsiteDataStores {
private static var stores: [String: WKWebsiteDataStore] = [:]
static func store(for identifier: String) -> WKWebsiteDataStore {
if let existing = stores[identifier] {
return existing
}
let store = WKWebsiteDataStore.nonPersistent()
stores[identifier] = store
return store
}
static func release(identifier: String) -> Bool {
stores.removeValue(forKey: identifier) != nil
}
}
#endif
#if SKIP || os(iOS)
/// A bridge-safe message sent from JavaScript to the host app.
///
/// `bodyJSON` is the canonical payload. JavaScript values posted through
/// `window.webkit.messageHandlers.<name>.postMessage(...)` are encoded with
/// `JSON.stringify` before crossing the platform bridge.
public struct WebViewScriptMessage: Equatable, Sendable {
/// The configured message handler name.
public let name: String
/// The JSON-encoded JavaScript message body.
public let bodyJSON: String
/// The URL of the frame that sent the message, when available.
public let sourceURL: String?
/// Whether the sending frame is the main frame, when available.
public let isMainFrame: Bool?
/// Creates a script message envelope.
public init(name: String, bodyJSON: String, sourceURL: String? = nil, isMainFrame: Bool? = nil) {
self.name = name
self.bodyJSON = bodyJSON
self.sourceURL = sourceURL
self.isMainFrame = isMainFrame
}
}
/// Delegate for bridge-safe JavaScript messages sent from a web view.
@MainActor
public protocol WebViewScriptMessageDelegate: AnyObject {
/// Called when JavaScript posts a message to a configured handler name.
func webEngine(_ webEngine: WebEngine, didReceiveScriptMessage message: WebViewScriptMessage)
}
#if !SKIP
private func webViewScriptMessageBodyJSON(from body: Any) -> String {
if body is NSNull {
return "null"
}
if JSONSerialization.isValidJSONObject(body),
let data = try? JSONSerialization.data(withJSONObject: body, options: []),
let json = String(data: data, encoding: .utf8) {
return json
}
let wrappedBody: [Any] = [body]
if JSONSerialization.isValidJSONObject(wrappedBody),
let data = try? JSONSerialization.data(withJSONObject: wrappedBody, options: []),
let wrappedJSON = String(data: data, encoding: .utf8),
wrappedJSON.hasPrefix("["),
wrappedJSON.hasSuffix("]") {
let start = wrappedJSON.index(after: wrappedJSON.startIndex)
let end = wrappedJSON.index(before: wrappedJSON.endIndex)
return String(wrappedJSON[start..<end])
}
if let data = try? JSONEncoder().encode(String(describing: body)),
let json = String(data: data, encoding: .utf8) {
return json
}
return "null"
}
#endif
public struct SkipWebSnapshotRect: Equatable, Sendable {
public static let null = SkipWebSnapshotRect(x: 0.0, y: 0.0, width: -1.0, height: -1.0)
public var x: Double
public var y: Double
public var width: Double
public var height: Double
public init(x: Double, y: Double, width: Double, height: Double) {
self.x = x
self.y = y
self.width = width
self.height = height
}
public var isNull: Bool {
width < 0.0 || height < 0.0
}
fileprivate var asCGRect: CGRect {
isNull ? .null : CGRect(x: x, y: y, width: width, height: height)
}
}
/// Bridge-safe encoded image format for a web-view snapshot.
public struct SkipWebSnapshotImageFormat: Equatable, Sendable {
/// PNG snapshot encoding.
public static let png = SkipWebSnapshotImageFormat(mimeType: "image/png", quality: 1.0)
/// JPEG snapshot encoding with a clamped quality in the `0.0...1.0` range.
public static func jpeg(quality: Double = 0.85) -> SkipWebSnapshotImageFormat {
SkipWebSnapshotImageFormat(mimeType: "image/jpeg", quality: quality)
}
/// MIME type for the encoded snapshot image data.
public let mimeType: String
/// Encoding quality clamped to the `0.0...1.0` range.
public let quality: Double
/// Creates an image format from bridge-safe stored values.
///
/// Only JPEG and PNG are currently supported. Unknown MIME types are normalized to JPEG.
public init(mimeType: String, quality: Double = 0.85) {
if mimeType == "image/png" {
self.mimeType = "image/png"
self.quality = 1.0
} else {
self.mimeType = "image/jpeg"
self.quality = min(max(quality, 0.0), 1.0)
}
}
fileprivate var isPNG: Bool {
mimeType == "image/png"
}
}
/// Selects the Android rendering source used to capture a web-view snapshot.
public enum AndroidSnapshotCaptureMode: Hashable, Sendable {
/// Draws the WebView content directly into a bitmap-backed canvas.
///
/// This excludes other window content, including overlays and blur effects, and compensates
/// for the WebView's current scroll offset so the visible portion of the page is captured.
case webViewContent
/// Copies the pixels currently composited in the WebView's window rectangle.
///
/// This includes anything drawn over the WebView, including overlays and blur effects.
case visibleWindowPixels
}
/// Snapshot configuration for `WebEngine.takeSnapshot(configuration:)`.
///
/// This mirrors the key behavior of `WKSnapshotConfiguration`:
/// - `rect`: view-coordinate capture region (`.null` means full visible bounds)
/// - `snapshotWidth`: optional output width while preserving aspect ratio
/// - `afterScreenUpdates`: capture after pending updates when possible
/// - `imageFormat`: encoded output format for the returned image bytes
///
/// On Android, `androidCaptureMode` selects whether the WebView content or its composited window
/// pixels are captured. It has no effect on iOS.
public struct SkipWebSnapshotConfiguration: Sendable {
/// View-coordinate capture region (`.null` means full visible bounds).
public var rect: SkipWebSnapshotRect
/// Optional output width while preserving aspect ratio.
public var snapshotWidth: Double?
/// Capture after pending updates when possible.
public var afterScreenUpdates: Bool
/// Rendering source used for Android snapshots. This value has no effect on iOS.
public var androidCaptureMode: AndroidSnapshotCaptureMode
/// Encoded output format for the returned image bytes.
public var imageFormat: SkipWebSnapshotImageFormat
public init(
rect: SkipWebSnapshotRect = .null,
snapshotWidth: Double? = nil,
afterScreenUpdates: Bool = true,
androidCaptureMode: AndroidSnapshotCaptureMode = .webViewContent,
imageFormat: SkipWebSnapshotImageFormat = .jpeg(quality: 0.85)
) {
self.rect = rect
self.snapshotWidth = snapshotWidth
self.afterScreenUpdates = afterScreenUpdates
self.androidCaptureMode = androidCaptureMode
self.imageFormat = imageFormat
}
}
/// A captured web-view snapshot stored as encoded image bytes plus metadata.
public struct SkipWebSnapshot: Sendable {
/// Encoded image bytes for this snapshot.
public let imageData: Data
/// Format used to encode `imageData`.
public let imageFormat: SkipWebSnapshotImageFormat
/// Encoded image width in pixels.
public let pixelWidth: Int
/// Encoded image height in pixels.
public let pixelHeight: Int
public init(imageData: Data, imageFormat: SkipWebSnapshotImageFormat, pixelWidth: Int, pixelHeight: Int) {
self.imageData = imageData
self.imageFormat = imageFormat
self.pixelWidth = pixelWidth
self.pixelHeight = pixelHeight
}
}
public enum WebSnapshotError: Error {
case viewNotLaidOut
case afterScreenUpdatesUnavailable
case invalidRect
case emptySnapshot
case imageEncodingFailed
/// PixelCopy could not capture the requested visible window pixels on Android.
case visibleWindowPixelsCaptureFailed
}
/// Portable cookie representation shared by iOS and Android implementations.
public struct WebCookie: Equatable, Hashable, Sendable {
public var name: String
public var value: String
public var domain: String?
public var path: String?
public var expires: Date?
public var isSecure: Bool
public var isHTTPOnly: Bool
public init(
name: String,
value: String,
domain: String? = nil,
path: String? = nil,
expires: Date? = nil,
isSecure: Bool = false,
isHTTPOnly: Bool = false
) {
self.name = name
self.value = value
self.domain = domain
self.path = path
self.expires = expires
self.isSecure = isSecure
self.isHTTPOnly = isHTTPOnly
}
}
public enum WebCookieError: Error {
case invalidCookieName
case missingCookieDomain
case invalidCookie
}
/// Cross-platform content-blocker configuration for a `WebEngine`.
///
/// Think of it as the single place where apps describe:
/// - iOS rule-list files to compile and install
/// - domains that should bypass blocking entirely
/// - popup source domains that should bypass popup blocking only
/// - Android request and cosmetic blocking behavior
public struct WebContentBlockerConfiguration {
/// Paths to iOS WebKit content-blocker JSON files.
///
/// SkipWeb compiles these files into `WKContentRuleList` values and installs them
/// into the web view configuration on Apple platforms.
public var iOSRuleListPaths: [String]
/// Domain allowlist entries that bypass SkipWeb-managed blocking on matching pages.
///
/// Entries use WebKit-style host matching such as `example.com` and `*.example.com`.
public var whitelistedDomains: [String]
/// Popup source-site allowlist entries that bypass popup blocking only.
///
/// Bare domains such as `example.com` cover both the exact host and common
/// subdomains. Wildcard entries such as `*.example.com` cover subdomains only.
public var popupWhitelistedSourceDomains: [String]
/// Primary Android content-blocking entry point.
///
/// Use `.custom(...)` to supply request and cosmetic blocking behavior from one provider.
public var androidMode: AndroidContentBlockingMode
/// Creates a content-blocker configuration.
///
/// - Parameters:
/// - iOSRuleListPaths: iOS WebKit content-blocker JSON files to compile.
/// - whitelistedDomains: Host patterns that should bypass blocking.
/// - popupWhitelistedSourceDomains: Popup source-site host patterns that should bypass popup blocking only.
/// - androidMode: Primary Android blocking configuration.
public init(
iOSRuleListPaths: [String] = [],
whitelistedDomains: [String] = [],
popupWhitelistedSourceDomains: [String] = [],
androidMode: AndroidContentBlockingMode = .disabled
) {
self.iOSRuleListPaths = iOSRuleListPaths
self.whitelistedDomains = whitelistedDomains
self.popupWhitelistedSourceDomains = popupWhitelistedSourceDomains
self.androidMode = androidMode
}
}
/// Android request and cosmetic blocking provider used by `AndroidContentBlockingMode.custom`.
public protocol AndroidContentBlockingProvider {
/// Long-lived cosmetic rules that SkipWeb can reuse across navigations.
///
/// Put CSS here when it acts like a baseline for the whole browsing session rather than
/// a rule that depends on the current page URL. The runtime captures this array once per
/// revision; call ``WebContentBlockerRuntime/reapply(configuration:reloadLiveWebViews:)``
/// after changing the baseline.
var persistentCosmeticRules: [AndroidCosmeticRule] { get }
/// Returns the request-blocking decision for an Android resource load.
func requestDecision(for request: AndroidBlockableRequest) -> AndroidRequestBlockDecision
/// Returns page-specific cosmetic rules for the current main-frame navigation.
///
/// Think of this as the per-page delta that sits on top of `persistentCosmeticRules`.
func navigationCosmeticRules(for page: AndroidPageContext) -> [AndroidCosmeticRule]
}
public extension AndroidContentBlockingProvider {
/// Default request-blocking implementation that allows every request.
func requestDecision(for request: AndroidBlockableRequest) -> AndroidRequestBlockDecision {
.allow
}
}
/// Android content-blocking mode used by `WebContentBlockerConfiguration`.
public enum AndroidContentBlockingMode {
/// Disable SkipWeb-managed Android content blocking.
case disabled
/// Use a custom provider for Android request and cosmetic blocking.
case custom(any AndroidContentBlockingProvider)
}
/// Request-blocking decision returned by Android blocker providers.
public enum AndroidRequestBlockDecision: Equatable, Sendable {
/// Allow the request to continue.
case allow
/// Block the request and return an empty response.
case block
}
/// Best-effort Android resource classification exposed to request blockers.
public enum AndroidResourceTypeHint: String, CaseIterable, Hashable, Sendable {
case document
case subdocument
case stylesheet
case script
case image
case font
case media
case xhr
case fetch
case websocket
case other
}
/// Android request details passed to request blockers.
public struct AndroidBlockableRequest: Equatable, Sendable {
/// The URL being requested.
public var url: URL
/// The current main document URL when known.
public var mainDocumentURL: URL?
/// The HTTP method used for the request.
public var method: String
/// HTTP headers captured from the Android request when available.
public var headers: [String: String]
/// Whether Android marked this as a main-frame navigation.
public var isForMainFrame: Bool
/// Whether the request was triggered by a user gesture.
public var hasGesture: Bool
/// Whether Android marked this request as a redirect, when known.
public var isRedirect: Bool?
/// Best-effort Android resource classification for the request.
public var resourceTypeHint: AndroidResourceTypeHint?
/// Creates an Android request description for blocker evaluation.
public init(
url: URL,
mainDocumentURL: URL? = nil,
method: String,
headers: [String: String] = [:],
isForMainFrame: Bool,
hasGesture: Bool,
isRedirect: Bool? = nil,
resourceTypeHint: AndroidResourceTypeHint? = nil
) {
self.url = url
self.mainDocumentURL = mainDocumentURL
self.method = method
self.headers = headers
self.isForMainFrame = isForMainFrame
self.hasGesture = hasGesture
self.isRedirect = isRedirect
self.resourceTypeHint = resourceTypeHint
}
}
/// Page details passed to Android cosmetic blockers.
public struct AndroidPageContext: Equatable, Sendable {
/// The current page URL.
public var url: URL
/// The page host, defaulting to `url.host`.
public var host: String?
/// Creates a page context for Android cosmetic rule evaluation.
public init(url: URL, host: String? = nil) {
self.url = url
self.host = host ?? url.host
}
}
/// Frame scope for an Android cosmetic rule.
public enum AndroidCosmeticFrameScope: String, CaseIterable, Hashable, Sendable {
/// Apply only in the top-level document.
case mainFrameOnly
/// Apply only in subframes.
case subframesOnly
/// Apply in both the top-level document and subframes.
case allFrames
}
/// Preferred injection timing for an Android cosmetic rule.
public enum AndroidCosmeticInjectionTiming: String, CaseIterable, Hashable, Sendable {
/// Install at document start when supported.
case documentStart
/// Inject later during the page lifecycle.
case pageLifecycle
}
/// Android cosmetic rule describing CSS to hide or scope.
public struct AndroidCosmeticRule: Equatable, Sendable {
/// Selector or selector-list entries to hide with `display: none !important`.
public var hiddenSelectors: [String]
/// Optional regex-style URL filter that must match the current frame URL before the rule applies.
///
/// Think of it as a runtime frame guard: SkipWeb evaluates it before returning CSS to a
/// document, so one fixed document-start hook can serve matching subframes and redirected pages.
public var urlFilterPattern: String?
/// Origin patterns that must match the current frame before the rule applies.
///
/// When Android document-start scripts are supported, SkipWeb installs one fixed hook for all
/// origins and evaluates these patterns in the shared runtime before returning CSS. Use `"*"`
/// to allow every origin.
public var allowedOriginRules: [String]
/// Host patterns that must match the current frame host before the rule applies.
public var ifDomainList: [String]
/// Host patterns that must not match the current frame host before the rule applies.
public var unlessDomainList: [String]
/// Frame scope for the injected CSS.
public var frameScope: AndroidCosmeticFrameScope
/// Preferred injection timing for the CSS.
public var preferredTiming: AndroidCosmeticInjectionTiming
/// Creates an Android cosmetic rule.
///
/// `hiddenSelectors` is the public API shape; SkipWeb turns each selector into
/// `display: none !important` CSS internally.
public init(
hiddenSelectors: [String] = [],
urlFilterPattern: String? = nil,
allowedOriginRules: [String] = ["*"],
ifDomainList: [String] = [],
unlessDomainList: [String] = [],
frameScope: AndroidCosmeticFrameScope = .mainFrameOnly,
preferredTiming: AndroidCosmeticInjectionTiming = .documentStart
) {
self.hiddenSelectors = Self.normalizedHiddenSelectors(hiddenSelectors)
self.urlFilterPattern = urlFilterPattern
self.allowedOriginRules = allowedOriginRules
self.ifDomainList = ifDomainList
self.unlessDomainList = unlessDomainList
self.frameScope = frameScope
self.preferredTiming = preferredTiming
}
fileprivate static func normalizedHiddenSelectors(_ selectors: [String]) -> [String] {
selectors
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
.filter { !$0.isEmpty }
}
fileprivate static func hideCSS(for selectors: [String]) -> [String] {
normalizedHiddenSelectors(selectors)
.map { "\($0) { display: none !important; }" }
}
}
@MainActor
public protocol SkipWebNavigationDelegate {
/// Asks whether a main-frame navigation should be cancelled.
///
/// Return `true` after handling a URL in native code. Return `false` to let the web view load it.
func webEngine(_ engine: WebEngine, shouldOverrideURLLoading url: URL) -> Bool
/// Called when the main frame starts provisional navigation.
///
/// At this point ``WebEngine/url`` exposes the concrete URL, including the first URL of a
/// detached popup engine before that engine is mounted in a ``WebView``.
func webEngineDidStartProvisionalNavigation(_ engine: WebEngine)
/// Called after the main-frame navigation commits its first content.
func webEngineDidCommitNavigation(_ engine: WebEngine)
/// Called after the main-frame navigation finishes loading.
func webEngineDidFinishNavigation(_ engine: WebEngine)
/// Called when a main-frame provisional or committed navigation fails.
func webEngine(_ engine: WebEngine, didFailNavigation error: Error)
}
public extension SkipWebNavigationDelegate {
func webEngine(_ engine: WebEngine, shouldOverrideURLLoading url: URL) -> Bool {
false
}
func webEngineDidStartProvisionalNavigation(_ engine: WebEngine) {
}
func webEngineDidCommitNavigation(_ engine: WebEngine) {
}
func webEngineDidFinishNavigation(_ engine: WebEngine) {
}
func webEngine(_ engine: WebEngine, didFailNavigation error: Error) {
}
}
#if !SKIP
/// Forwards navigation events while an engine is not mounted in a `WebView` coordinator.
///
/// Popup children need this immediately after creation so their first URL and redirects can be
/// classified while the engine remains detached from the visible browser hierarchy.
@MainActor
private final class WebEngineConfigurationNavigationDelegate: NSObject, WKNavigationDelegate {
weak var engine: WebEngine?
let navigationDelegate: any SkipWebNavigationDelegate
init(engine: WebEngine, navigationDelegate: any SkipWebNavigationDelegate) {
self.engine = engine
self.navigationDelegate = navigationDelegate
}
func webView(
_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
preferences: WKWebpagePreferences
) async -> (WKNavigationActionPolicy, WKWebpagePreferences) {
guard navigationAction.targetFrame?.isMainFrame != false,
let engine,
let url = navigationAction.request.url else {
return (.allow, preferences)
}
let shouldCancel = navigationDelegate.webEngine(engine, shouldOverrideURLLoading: url)
return (shouldCancel ? .cancel : .allow, preferences)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
guard let engine else { return }
navigationDelegate.webEngineDidStartProvisionalNavigation(engine)
}
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
guard let engine else { return }
navigationDelegate.webEngineDidCommitNavigation(engine)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
guard let engine else { return }
navigationDelegate.webEngineDidFinishNavigation(engine)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
guard let engine else { return }
navigationDelegate.webEngine(engine, didFailNavigation: error)
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
guard let engine else { return }
navigationDelegate.webEngine(engine, didFailNavigation: error)
}
}
#endif
struct AndroidCosmeticInjectionPlan {
var documentStartRules: [AndroidCosmeticRule] = []
var lifecycleCSS: [String] = []
}
struct AndroidCosmeticNavigationSnapshot {
let mainPageURL: URL
let isWhitelisted: Bool
let rules: [AndroidCosmeticRule]
}
struct AndroidDocumentStartRuleBatchKey: Hashable {
let frameScope: AndroidCosmeticFrameScope
let preferredTiming: AndroidCosmeticInjectionTiming
let urlFilterPattern: String?
let allowedOriginRules: [String]
let ifDomainList: [String]
let unlessDomainList: [String]
}
fileprivate struct WhitelistedAndroidContentBlockingProvider: AndroidContentBlockingProvider {
let provider: any AndroidContentBlockingProvider
let whitelistedDomains: [String]
func requestDecision(for request: AndroidBlockableRequest) -> AndroidRequestBlockDecision {
if isWhitelisted(request: request) {
return .allow
}
return provider.requestDecision(for: request)
}
var persistentCosmeticRules: [AndroidCosmeticRule] {
provider.persistentCosmeticRules
}
func navigationCosmeticRules(for page: AndroidPageContext) -> [AndroidCosmeticRule] {
provider.navigationCosmeticRules(for: page)
}
private func isWhitelisted(request: AndroidBlockableRequest) -> Bool {
if WebContentBlockerConfiguration.matchesWhitelistedURL(request.mainDocumentURL, in: whitelistedDomains) {
return true
}
if request.isForMainFrame {
return WebContentBlockerConfiguration.matchesWhitelistedURL(request.url, in: whitelistedDomains)
}
return false
}
}
extension WebContentBlockerConfiguration {
var normalizedWhitelistedDomains: [String] {
Self.normalizedWhitelistedDomains(from: whitelistedDomains)
}
var normalizedPopupWhitelistedSourceDomains: [String] {
Self.normalizedWhitelistedDomains(from: popupWhitelistedSourceDomains)
}
var effectiveAndroidMode: AndroidContentBlockingMode {
switch androidMode {
case .disabled:
return .disabled
case .custom(let provider):
guard !normalizedWhitelistedDomains.isEmpty else {
return .custom(provider)
}
return .custom(
WhitelistedAndroidContentBlockingProvider(
provider: provider,
whitelistedDomains: normalizedWhitelistedDomains
)
)
}
}
var effectiveAndroidProvider: (any AndroidContentBlockingProvider)? {
switch effectiveAndroidMode {
case .disabled:
return nil
case .custom(let provider):
return provider
}
}
static func normalizedWhitelistedDomains(from domains: [String]) -> [String] {
Array(
Set(
domains.compactMap { domain in
let trimmed = domain.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
return trimmed.isEmpty ? nil : trimmed
}
)
).sorted()
}
static func matchesWhitelistedURL(_ url: URL?, in domains: [String]) -> Bool {
matchesWhitelistedDomain(url?.host, in: domains)
}
static func matchesWhitelistedDomain(_ host: String?, in domains: [String]) -> Bool {
guard let normalizedHost = host?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased(),
!normalizedHost.isEmpty else {
return false
}
for domain in domains {
if domain.hasPrefix("*.") {
let suffix = String(domain.dropFirst(2))
guard !suffix.isEmpty else {
continue
}
if normalizedHost.count > suffix.count && normalizedHost.hasSuffix(".\(suffix)") {
return true
}
} else if normalizedHost == domain {
return true
}
}
return false
}
#if !SKIP
func augmentedIOSRuleListContent(_ content: String) -> String {
Self.augmentedIOSRuleListContent(
content,
whitelistedDomains: normalizedWhitelistedDomains,
popupWhitelistedSourceDomains: normalizedPopupWhitelistedSourceDomains
)
}
static func augmentedIOSRuleListContent(
_ content: String,
whitelistedDomains: [String],
popupWhitelistedSourceDomains: [String] = []
) -> String {
guard !whitelistedDomains.isEmpty || !popupWhitelistedSourceDomains.isEmpty,
let data = content.data(using: .utf8),
let jsonObject = try? JSONSerialization.jsonObject(with: data),
var rules = jsonObject as? [[String: Any]] else {
return content
}
if !whitelistedDomains.isEmpty {
rules.append([
"comment": "user-injected domain exemptions (whitelisted domains)",
"trigger": [
"url-filter": ".*",
"if-domain": whitelistedDomains
],
"action": [
"type": "ignore-previous-rules"
]
])
}
let popupTopURLs = popupWhitelistTopURLs(from: popupWhitelistedSourceDomains)
if !popupTopURLs.isEmpty {
rules.append([
"comment": "user-injected popup exemptions (allowed source domains)",
"trigger": [
"url-filter": ".*",
"resource-type": ["popup"],
"if-top-url": popupTopURLs
],
"action": [
"type": "ignore-previous-rules"
]
])
}
guard JSONSerialization.isValidJSONObject(rules),
let augmentedData = try? JSONSerialization.data(withJSONObject: rules, options: [.sortedKeys]),
let augmentedContent = String(data: augmentedData, encoding: .utf8) else {
return content
}
return augmentedContent
}
static func popupWhitelistTopURLs(from domains: [String]) -> [String] {
Array(
Set(
domains.flatMap { domain in
if domain.hasPrefix("*.") {
return ["http://\(domain)/*", "https://\(domain)/*"]
} else {
return [
"http://\(domain)/*",
"http://*.\(domain)/*",
"https://\(domain)/*",
"https://*.\(domain)/*",
]
}
}
)
).sorted()
}
#endif
}
/// Errors surfaced while preparing, caching, or installing content blockers.
public enum WebContentBlockerError: Error, Equatable, LocalizedError {
/// SkipWeb could not create or access the persistent content-blocker store.
case storeUnavailable(String)
/// SkipWeb could not read a configured content-blocker file.
case fileReadFailed(path: String, description: String)
/// A configured content-blocker file was not valid UTF-8 text.
case fileEncodingFailed(path: String)
/// SkipWeb could not look up a previously compiled rule list in the cache.
case cacheLookupFailed(identifier: String, description: String)
/// WebKit failed to compile a rule-list file.
case compilationFailed(path: String, description: String)
/// SkipWeb could not read the persistent metadata it uses to track compiled rule lists.
case metadataReadFailed(String)
/// SkipWeb could not write the persistent metadata it uses to track compiled rule lists.
case metadataWriteFailed(String)
/// SkipWeb could not prune a stale compiled rule list from the cache.
case staleRuleRemovalFailed(identifier: String, description: String)
/// A content-blocker store operation did not finish before the timeout.
case operationTimedOut(String)
public var errorDescription: String? {
switch self {
case .storeUnavailable(let description):
return "Content blocker store unavailable: \(description)"
case .fileReadFailed(let path, let description):
return "Failed to read content blocker file at \(path): \(description)"
case .fileEncodingFailed(let path):
return "Content blocker file is not valid UTF-8: \(path)"
case .cacheLookupFailed(let identifier, let description):
return "Failed to look up compiled content blocker \(identifier): \(description)"
case .compilationFailed(let path, let description):
return "Failed to compile content blocker file at \(path): \(description)"
case .metadataReadFailed(let description):
return "Failed to read content blocker metadata: \(description)"
case .metadataWriteFailed(let description):
return "Failed to write content blocker metadata: \(description)"
case .staleRuleRemovalFailed(let identifier, let description):
return "Failed to remove stale compiled content blocker \(identifier): \(description)"
case .operationTimedOut(let description):
return "Timed out while preparing content blockers: \(description)"
}
}
}
/// Prepared content-blocking state that can be shared by multiple web engines.
///
/// Think of a runtime as one registration lifetime: the first engine prepares the rule snapshot,
/// popup children inherit it, and independently created engines can opt into the same snapshot.
/// Call ``reapply(configuration:reloadLiveWebViews:)`` only when the app has changed its rules.
///
/// The runtime tracks attached engines weakly. Sharing a runtime does not by itself keep a
/// `WebEngine` or native web view alive.
@MainActor public final class WebContentBlockerRuntime {
/// The configuration represented by the current prepared revision.
public private(set) var configuration: WebContentBlockerConfiguration
/// Monotonically increasing revision updated after every explicit reapplication.
public private(set) var revision: Int = 0
private var attachedEngines: [WeakContentBlockerEngine] = []
#if SKIP
private var androidPersistentRules: [AndroidCosmeticRule] = []
private var androidIsPrepared = false
#else
private var preparedIOSRuleLists: [WKContentRuleList] = []
private var preparedIOSErrors: [WebContentBlockerError] = []
private var preparedIOSRevision: Int?
private var iosPreparationTask: (
revision: Int,
task: Task<PreparedContentBlockerRuleLists, Never>
)?
private let iosRuleListPreparer: @MainActor (
_ sourcePaths: [String],
_ whitelistedDomains: [String],
_ popupWhitelistedSourceDomains: [String]