SPB Git

Repository Public License

UserScripts.swift 6.7 KB 149 lines swift

1import Foundation2import os3import WebKit45/// The scripts shipped in `Resources/`.6public enum BundledScript: String, Sendable, CaseIterable {7    case activation = "activation"8    case pageMetadata = "page-metadata"9    case scrollReporter = "scroll-reporter"10    case mediaState = "media-state"11    case contextElement = "context-element"12    case lens = "lens"13    case devErrors = "dev-errors"14    case devConsole = "dev-console"15    case morph = "morph"16    case reader = "reader"1718    /// The JavaScript source. A missing resource is a packaging error, reported loudly in debug builds.19    ///20    /// Sources are cached for the life of the process. Call `preload()` once at launch so that the files are21    /// read off the main actor; a script requested before that is read on the spot (a few kilobytes, once).22    public var source: String {23        if let cached = Self.cache.withLock({ $0[self] }) { return cached }24        let text = Self.read(self)25        Self.cache.withLock { $0[self] = text }26        return text27    }2829    /// Reads every bundled script on a background task.30    public static func preload() async {31        await Task.detached(priority: .utility) {32            for script in BundledScript.allCases { _ = script.source }33        }.value34    }3536    private static func read(_ script: BundledScript) -> String {37        guard let url = Bundle.module.url(forResource: script.rawValue, withExtension: "js"),38              let text = try? String(contentsOf: url, encoding: .utf8) else {39            assertionFailure("Missing bundled script \(script.rawValue).js")40            return ""41        }42        return text43    }4445    private static let cache = OSAllocatedUnfairLock<[BundledScript: String]>(initialState: [:])46}4748/// A user script to install. `id` identifies it for replacement and removal.49public struct UserScriptDescriptor: Sendable, Hashable, Identifiable {50    public enum InjectionTime: Sendable, Hashable { case documentStart, documentEnd }5152    /// Where the script runs. The page world is available only to this module (console mirror).53    enum Target: Sendable, Hashable { case isolated(ScriptWorld), pageWorld }5455    public var id: String56    public var source: String57    public var injectionTime: InjectionTime58    public var mainFrameOnly: Bool59    var target: Target6061    /// A script in one of the browser's isolated worlds. There is no public way to target the page world.62    public init(id: String, source: String, world: ScriptWorld, injectionTime: InjectionTime = .documentEnd,63                mainFrameOnly: Bool = true) {64        self.id = id; self.source = source; self.injectionTime = injectionTime65        self.mainFrameOnly = mainFrameOnly; self.target = .isolated(world)66    }6768    init(pageWorldID id: String, source: String, injectionTime: InjectionTime, mainFrameOnly: Bool) {69        self.id = id; self.source = source; self.injectionTime = injectionTime70        self.mainFrameOnly = mainFrameOnly; self.target = .pageWorld71    }7273    public var world: ScriptWorld? { if case .isolated(let world) = target { world } else { nil } }74}7576extension ScriptWorld {77    /// The `WKContentWorld` of this world. The objects are kept for the life of the process: WebKit tears a78    /// named world down in the web process when its `WKContentWorld` is deallocated, which would silently drop79    /// every global a previous evaluation defined there.80    @MainActor var contentWorld: WKContentWorld {81        if let world = Self.worlds[self] { return world }82        let world = WKContentWorld.world(name: rawValue)83        Self.worlds[self] = world84        return world85    }8687    @MainActor private static var worlds: [ScriptWorld: WKContentWorld] = [:]88}8990/// Adds and removes user scripts on one `WKUserContentController` without disturbing scripts it does not own.91///92/// WebKit can only remove *all* user scripts at once. Removal therefore snapshots every script of the93/// controller — including those installed by other code directly on the controller — clears, and re-adds all94/// but the removed one, in the original order.95@MainActor96public final class UserScriptRegistry {97    public let controller: WKUserContentController98    private var owned: [(descriptor: UserScriptDescriptor, script: WKUserScript)] = []99100    public init(controller: WKUserContentController) { self.controller = controller }101102    public var installed: [UserScriptDescriptor] { owned.map(\.descriptor) }103104    public func isInstalled(_ id: String) -> Bool { owned.contains { $0.descriptor.id == id } }105106    /// Installs `descriptor`, replacing a script with the same id. Takes effect at the next document load.107    public func install(_ descriptor: UserScriptDescriptor) {108        if let existing = owned.first(where: { $0.descriptor.id == descriptor.id }) {109            if existing.descriptor == descriptor { return }110            remove(id: descriptor.id)111        }112        let world: WKContentWorld = switch descriptor.target {113        case .isolated(let world): world.contentWorld114        case .pageWorld: .page115        }116        let script = WKUserScript(source: descriptor.source,117                                  injectionTime: descriptor.injectionTime == .documentStart ? .atDocumentStart : .atDocumentEnd,118                                  forMainFrameOnly: descriptor.mainFrameOnly, in: world)119        controller.addUserScript(script)120        owned.append((descriptor, script))121    }122123    /// Removes the script with `id`. Returns false when it was not installed by this registry.124    @discardableResult125    public func remove(id: String) -> Bool {126        guard let index = owned.firstIndex(where: { $0.descriptor.id == id }) else { return false }127        let removed = owned.remove(at: index).script128        // `userScripts` is bridged lazily from WebKit's own mutable array: without an eager copy the snapshot129        // empties itself when the controller is cleared.130        let all = controller.userScripts.map { $0 }131        controller.removeAllUserScripts()132        var dropped = false133        for script in all {134            // Identity when WebKit hands back the same wrapper; otherwise the first script with identical content.135            let matches = script === removed136                || (!all.contains(where: { $0 === removed }) && script.source == removed.source137                    && script.injectionTime == removed.injectionTime && script.isForMainFrameOnly == removed.isForMainFrameOnly)138            if matches && !dropped { dropped = true; continue }139            controller.addUserScript(script)140        }141        return true142    }143144    /// Removes every script this registry installed whose id starts with `prefix`; foreign scripts stay.145    public func removeAll(idPrefix prefix: String) {146        for id in owned.map(\.descriptor.id) where id.hasPrefix(prefix) { remove(id: id) }147    }148}149
Files main
Menu

Theme