-
Notifications
You must be signed in to change notification settings - Fork 343
/
Copy pathchromium.js
341 lines (281 loc) · 9.46 KB
/
chromium.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
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
/* @flow */
/**
* This module provide an ExtensionRunner subclass that manage an extension executed
* in a Chromium-based browser instance.
*/
import path from 'path';
import {fs} from 'mz';
import asyncMkdirp from 'mkdirp';
import {
LaunchedChrome,
launch as defaultChromiumLaunch,
default as ChromeLauncher,
} from 'chrome-launcher';
import WebSocket from 'ws';
import {createLogger} from '../util/logger';
import {TempDir} from '../util/temp-dir';
import type {
ExtensionRunnerParams,
ExtensionRunnerReloadResult,
} from './base';
type ChromiumSpecificRunnerParams = {|
chromiumBinary?: string,
chromiumProfile?: string,
chromiumLaunch?: typeof defaultChromiumLaunch,
|};
export type ChromiumExtensionRunnerParams = {|
...ExtensionRunnerParams,
// Chromium desktop CLI params.
...ChromiumSpecificRunnerParams,
|};
const log = createLogger(__filename);
const EXCLUDED_CHROME_FLAGS = [
'--disable-extensions',
'--mute-audio',
];
export const DEFAULT_CHROME_FLAGS = ChromeLauncher.defaultFlags()
.filter((flag) => !EXCLUDED_CHROME_FLAGS.includes(flag));
/**
* Implements an IExtensionRunner which manages a Chromium instance.
*/
export class ChromiumExtensionRunner {
cleanupCallbacks: Set<Function>;
params: ChromiumExtensionRunnerParams;
chromiumInstance: LaunchedChrome;
chromiumLaunch: typeof defaultChromiumLaunch;
reloadManagerExtension: string;
wss: WebSocket.Server;
exiting: boolean;
_promiseSetupDone: ?Promise<void>;
constructor(params: ChromiumExtensionRunnerParams) {
const {
chromiumLaunch = defaultChromiumLaunch,
} = params;
this.params = params;
this.chromiumLaunch = chromiumLaunch;
this.cleanupCallbacks = new Set();
}
// Method exported from the IExtensionRunner interface.
/**
* Returns the runner name.
*/
getName() {
return 'Chromium';
}
async run(): Promise<void> {
// Run should never be called more than once.
this._promiseSetupDone = this.setupInstance();
await this._promiseSetupDone;
}
/**
* Setup the Chromium Profile and run a Chromium instance.
*/
async setupInstance(): Promise<void> {
// Start a websocket server on a free localhost TCP port.
this.wss = await new Promise((resolve) => {
const server = new WebSocket.Server(
{port: 0, host: 'localhost'},
// Wait the server to be listening (so that the extension
// runner can successfully retrieve server address and port).
() => resolve(server));
});
// Prevent unhandled socket error (e.g. when chrome
// is exiting, See https://github.com/websockets/ws/issues/1256).
this.wss.on('connection', function(socket) {
socket.on('error', (err) => {
log.debug(`websocket connection error: ${err}`);
});
});
// Create the extension that will manage the addon reloads
this.reloadManagerExtension = await this.createReloadManagerExtension();
// Start chrome pointing it to a given profile dir
const extensions = [this.reloadManagerExtension].concat(
this.params.extensions.map(({sourceDir}) => sourceDir)
).join(',');
const {chromiumBinary} = this.params;
log.debug('Starting Chromium instance...');
if (chromiumBinary) {
log.debug(`(chromiumBinary: ${chromiumBinary})`);
}
const chromeFlags = [...DEFAULT_CHROME_FLAGS];
chromeFlags.push(`--load-extension=${extensions}`);
if (this.params.args) {
chromeFlags.push(...this.params.args);
}
if (this.params.chromiumProfile) {
chromeFlags.push(`--user-data-dir=${this.params.chromiumProfile}`);
}
let startingUrl;
if (this.params.startUrl) {
const startingUrls = Array.isArray(this.params.startUrl) ?
this.params.startUrl : [this.params.startUrl];
startingUrl = startingUrls.shift();
chromeFlags.push(...startingUrls);
}
this.chromiumInstance = await this.chromiumLaunch({
enableExtensions: true,
chromePath: chromiumBinary,
chromeFlags,
startingUrl,
// Ignore default flags to keep the extension enabled.
ignoreDefaultFlags: true,
});
this.chromiumInstance.process.once('close', () => {
this.chromiumInstance = null;
if (!this.exiting) {
log.info('Exiting on Chromium instance disconnected.');
this.exit();
}
});
}
async wssBroadcast(data: Object) {
return new Promise((resolve) => {
const clients = this.wss ? new Set(this.wss.clients) : new Set();
function cleanWebExtReloadComplete() {
const client = this;
client.removeEventListener('message', webExtReloadComplete);
client.removeEventListener('close', cleanWebExtReloadComplete);
clients.delete(client);
}
const webExtReloadComplete = async (message) => {
const msg = JSON.parse(message.data);
if (msg.type === 'webExtReloadExtensionComplete') {
for (const client of clients) {
cleanWebExtReloadComplete.call(client);
}
resolve();
}
};
for (const client of clients) {
if (client.readyState === WebSocket.OPEN) {
client.addEventListener('message', webExtReloadComplete);
client.addEventListener('close', cleanWebExtReloadComplete);
client.send(JSON.stringify(data));
} else {
clients.delete(client);
}
}
if (clients.size === 0) {
resolve();
}
});
}
async createReloadManagerExtension() {
const tmpDir = new TempDir();
await tmpDir.create();
this.registerCleanup(() => tmpDir.remove());
const extPath = path.join(
tmpDir.path(),
`reload-manager-extension-${Date.now()}`
);
log.debug(`Creating reload-manager-extension in ${extPath}`);
await asyncMkdirp(extPath);
await fs.writeFile(
path.join(extPath, 'manifest.json'),
JSON.stringify({
manifest_version: 2,
name: 'web-ext Reload Manager Extension',
version: '1.0',
permissions: ['management', 'tabs'],
background: {
scripts: ['bg.js'],
},
})
);
const wssInfo = this.wss.address();
const bgPage = `(function bgPage() {
async function getAllDevExtensions() {
const allExtensions = await new Promise(
r => chrome.management.getAll(r));
return allExtensions.filter((extension) => {
return extension.installType === "development" &&
extension.id !== chrome.runtime.id;
});
}
const setEnabled = (extensionId, value) =>
chrome.runtime.id == extensionId ?
new Promise.resolve() :
new Promise(r => chrome.management.setEnabled(extensionId, value, r));
async function reloadExtension(extensionId) {
await setEnabled(extensionId, false);
await setEnabled(extensionId, true);
}
const ws = new window.WebSocket(
"ws://${wssInfo.address}:${wssInfo.port}");
ws.onmessage = async (evt) => {
const msg = JSON.parse(evt.data);
if (msg.type === 'webExtReloadAllExtensions') {
const devExtensions = await getAllDevExtensions();
await Promise.all(devExtensions.map(ext => reloadExtension(ext.id)));
ws.send(JSON.stringify({ type: 'webExtReloadExtensionComplete' }));
}
};
})()`;
await fs.writeFile(path.join(extPath, 'bg.js'), bgPage);
return extPath;
}
/**
* Reloads all the extensions, collect any reload error and resolves to
* an array composed by a single ExtensionRunnerReloadResult object.
*/
async reloadAllExtensions(): Promise<Array<ExtensionRunnerReloadResult>> {
const runnerName = this.getName();
await this.wssBroadcast({
type: 'webExtReloadAllExtensions',
});
process.stdout.write(
`\rLast extension reload: ${(new Date()).toTimeString()}`);
log.debug('\n');
return [{runnerName}];
}
/**
* Reloads a single extension, collect any reload error and resolves to
* an array composed by a single ExtensionRunnerReloadResult object.
*/
async reloadExtensionBySourceDir(
extensionSourceDir: string // eslint-disable-line no-unused-vars
): Promise<Array<ExtensionRunnerReloadResult>> {
// TODO(rpl): detect the extension ids assigned to the
// target extensions and map it to the extensions source dir
// (https://github.com/mozilla/web-ext/issues/1687).
return this.reloadAllExtensions();
}
/**
* Register a callback to be called when the runner has been exited
* (e.g. the Chromium instance exits or the user has requested web-ext
* to exit).
*/
registerCleanup(fn: Function): void {
this.cleanupCallbacks.add(fn);
}
/**
* Exits the runner, by closing the managed Chromium instance.
*/
async exit(): Promise<void> {
this.exiting = true;
// Wait for the setup to complete if the extension runner is already
// being started.
if (this._promiseSetupDone) {
// Ignore initialization errors if any.
await this._promiseSetupDone.catch((err) => {
log.debug(`ignored setup error on chromium runner shutdown: ${err}`);
});
}
if (this.chromiumInstance) {
await this.chromiumInstance.kill();
this.chromiumInstance = null;
}
if (this.wss) {
await new Promise((resolve) => this.wss.close(resolve));
this.wss = null;
}
// Call all the registered cleanup callbacks.
for (const fn of this.cleanupCallbacks) {
try {
fn();
} catch (error) {
log.error(error);
}
}
}
}