-
Notifications
You must be signed in to change notification settings - Fork 9.3k
/
driver.js
77 lines (67 loc) · 2.69 KB
/
driver.js
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
/**
* @license Copyright 2020 The Lighthouse Authors. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';
const ProtocolSession = require('./session.js');
const ExecutionContext = require('../../gather/driver/execution-context.js');
const Fetcher = require('../../gather/fetcher.js');
/** @return {*} */
const throwNotConnectedFn = () => {
throw new Error('Session not connected');
};
/** @type {LH.Gatherer.FRProtocolSession} */
const defaultSession = {
setTargetInfo: throwNotConnectedFn,
hasNextProtocolTimeout: throwNotConnectedFn,
getNextProtocolTimeout: throwNotConnectedFn,
setNextProtocolTimeout: throwNotConnectedFn,
on: throwNotConnectedFn,
once: throwNotConnectedFn,
off: throwNotConnectedFn,
addProtocolMessageListener: throwNotConnectedFn,
removeProtocolMessageListener: throwNotConnectedFn,
addSessionAttachedListener: throwNotConnectedFn,
removeSessionAttachedListener: throwNotConnectedFn,
sendCommand: throwNotConnectedFn,
};
/** @implements {LH.Gatherer.FRTransitionalDriver} */
class Driver {
/**
* @param {import('puppeteer').Page} page
*/
constructor(page) {
this._page = page;
/** @type {LH.Gatherer.FRProtocolSession|undefined} */
this._session = undefined;
/** @type {ExecutionContext|undefined} */
this._executionContext = undefined;
/** @type {Fetcher|undefined} */
this._fetcher = undefined;
this.defaultSession = defaultSession;
}
/** @return {LH.Gatherer.FRTransitionalDriver['executionContext']} */
get executionContext() {
if (!this._executionContext) return throwNotConnectedFn();
return this._executionContext;
}
/** @return {Fetcher} */
get fetcher() {
if (!this._fetcher) return throwNotConnectedFn();
return this._fetcher;
}
/** @return {Promise<string>} */
async url() {
return this._page.url();
}
/** @return {Promise<void>} */
async connect() {
if (this._session) return;
const session = await this._page.target().createCDPSession();
this._session = this.defaultSession = new ProtocolSession(session);
this._executionContext = new ExecutionContext(this._session);
this._fetcher = new Fetcher(this._session, this._executionContext);
}
}
module.exports = Driver;