| 20 | const { AddInterceptParameters } = require('../bidi/addInterceptParameters') |
| 21 | |
| 22 | class Network { |
| 23 | #callbackId = 0 |
| 24 | #driver |
| 25 | #network |
| 26 | #authHandlers = new Map() |
| 27 | |
| 28 | constructor(driver) { |
| 29 | this.#driver = driver |
| 30 | } |
| 31 | |
| 32 | // This should be done in the constructor. |
| 33 | // But since it needs to call async methods we cannot do that in the constructor. |
| 34 | // We can have a separate async method that initialises the Network instance. |
| 35 | // However, that pattern does not allow chaining the methods as we would like the user to use it. |
| 36 | // Since it involves awaiting to get the instance and then another await to call the method. |
| 37 | // Using this allows the user to do this "await driver.network.addAuthenticationHandler(callback)" |
| 38 | async #init() { |
| 39 | if (this.#network !== undefined) { |
| 40 | return |
| 41 | } |
| 42 | this.#network = await getNetwork(this.#driver) |
| 43 | |
| 44 | await this.#network.addIntercept(new AddInterceptParameters(InterceptPhase.AUTH_REQUIRED)) |
| 45 | |
| 46 | await this.#network.authRequired(async (event) => { |
| 47 | const requestId = event.request.request |
| 48 | const uri = event.request.url |
| 49 | const credentials = this.getAuthCredentials(uri) |
| 50 | if (credentials !== null) { |
| 51 | await this.#network.continueWithAuth(requestId, credentials.username, credentials.password) |
| 52 | return |
| 53 | } |
| 54 | |
| 55 | await this.#network.continueWithAuthNoCredentials(requestId) |
| 56 | }) |
| 57 | } |
| 58 | |
| 59 | getAuthCredentials(uri) { |
| 60 | for (let [, value] of this.#authHandlers) { |
| 61 | if (uri.match(value.uri)) { |
| 62 | return value |
| 63 | } |
| 64 | } |
| 65 | return null |
| 66 | } |
| 67 | async addAuthenticationHandler(username, password, uri = '//') { |
| 68 | await this.#init() |
| 69 | |
| 70 | const id = this.#callbackId++ |
| 71 | |
| 72 | this.#authHandlers.set(id, { username, password, uri }) |
| 73 | return id |
| 74 | } |
| 75 | |
| 76 | async removeAuthenticationHandler(id) { |
| 77 | await this.#init() |
| 78 | |
| 79 | if (this.#authHandlers.has(id)) { |
no outgoing calls