-
Notifications
You must be signed in to change notification settings - Fork 28
/
SeleniumTunnel.ts
650 lines (556 loc) · 16.1 KB
/
SeleniumTunnel.ts
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
import Tunnel, {
TunnelProperties,
DownloadOptions,
ChildExecutor
} from './Tunnel';
import { format } from 'util';
import { join } from 'path';
import { Handle, Task, CancellablePromise } from '@theintern/common';
import { fileExists, kill, on, writeFile } from './lib/util';
import { satisfies } from 'semver';
import { sync as commandExistsSync } from 'command-exists';
const driverInfo = {
SeleniumVersion: '3.141.59',
ChromeVersion: '74.0.3729.6',
FirefoxVersion: '0.24.0',
IEVersion: '3.141.59',
EdgeVersion: '17134',
EdgeUrls: {
'15063':
'https://download.microsoft.com/download/3/4/2/342316D7-EBE0-4F10-ABA2-AE8E0CDF36DD/MicrosoftWebDriver.exe',
'16299':
'https://download.microsoft.com/download/D/4/1/D417998A-58EE-4EFE-A7CC-39EF9E020768/MicrosoftWebDriver.exe',
'17134':
'https://download.microsoft.com/download/F/8/A/F8AF50AB-3C3A-4BC4-8773-DC27B32988DD/MicrosoftWebDriver.exe',
'75.0.137.0': {
x86:
'https://az813057.vo.msecnd.net/webdriver/msedgedriver_x86/msedgedriver.exe',
x64:
'https://az813057.vo.msecnd.net/webdriver/msedgedriver_x64/msedgedriver.exe'
}
}
};
/**
* A Selenium tunnel. This tunnel downloads the
* [[http://www.seleniumhq.org/download/|Selenium-standalone server]] and any
* necessary WebDriver executables, and handles starting and stopping Selenium.
*
* The primary configuration option is [[SeleniumTunnel.drivers|drivers]], which
* determines which browsers the Selenium tunnel will support.
*
* Note that Java must be installed and in the system path to use this tunnel.
*
* The standard browser names (for the `browserName` WebDriver capability) are:
*
* - `MicrosoftEdge`
* - `chrome`
* - `firefox`
* - `internet explorer`
* - `safari`
*/
export default class SeleniumTunnel extends Tunnel
implements SeleniumProperties {
/** Additional arguments to send to the Selenium server at startup */
seleniumArgs!: string[];
/**
* The desired Selenium drivers to download. Each entry may be a string or an
* object. Strings must be the names of existing drivers in SeleniumTunnel
* (see below). An object with a 'name' property is a configuration object --
* the name must be the name of an existing driver in SeleniumTunnel, and the
* remaining properties will be used to configure that driver. An object
* without a 'name' property is a driver definition. It must contain three
* properties:
*
* - `executable` - the name of the driver executable, one of:
* - `url` - the URL where the driver can be downloaded from
* - `seleniumProperty` - the name of the Java property used to tell
* Selenium where the driver is
*
* ```js
* [
* 'chrome',
* {
* name: 'firefox',
* version: '0.8.0'
* },
* {
* url: 'https://github.com/operasoftware/operachromiumdriver/releases/.../operadriver_mac64.zip',
* executable: 'operadriver',
* seleniumProperty: 'webdriver.opera.driver'
* }
* ]
* ```
*
* The built-in SeleniumTunnel drivers are:
*
* - 'chrome'
* - 'firefox'
* - 'internet explorer'
* - 'ie' (alias for 'internet explorer')
* - 'MicrosoftEdge'
* - 'edge' (alias for 'MicrosoftEdge')
*
* @default [ 'chrome' ]
*/
drivers!: DriverDescriptor[];
/**
* The base address where Selenium artifacts may be found.
*
* @default https://selenium-release.storage.googleapis.com
*/
baseUrl!: string;
/**
* The desired version of selenium to install.
*
* @default 3.3.1
*/
version!: string;
/**
* Timeout in milliseconds for communicating with the Selenium server
*
* @default 5000
*/
seleniumTimeout!: number;
constructor(options?: SeleniumOptions) {
super(
Object.assign(
{
seleniumArgs: [],
drivers: ['chrome'],
baseUrl: 'https://selenium-release.storage.googleapis.com',
version: driverInfo.SeleniumVersion,
seleniumTimeout: 5000
},
options || {}
)
);
// Emit a meaningful error if Java isn't available
if (!commandExistsSync('java')) {
throw new Error('Java must be installed to use SeleniumTunnel');
}
}
get artifact() {
return `selenium-server-standalone-${this.version}.jar`;
}
get directory() {
return join(__dirname, 'selenium-standalone');
}
get executable() {
return 'java';
}
get isDownloaded() {
const directory = this.directory;
return (
fileExists(join(directory, this.artifact)) &&
this._getDriverConfigs().every(config => {
return fileExists(join(directory, config.executable));
})
);
}
get url() {
const majorMinorVersion = this.version.slice(
0,
this.version.lastIndexOf('.')
);
return format('%s/%s/%s', this.baseUrl, majorMinorVersion, this.artifact);
}
download(forceDownload = false): CancellablePromise<void> {
if (!forceDownload && this.isDownloaded) {
return Task.resolve();
}
let tasks: CancellablePromise<void>[];
return new Task(
resolve => {
const configs: RemoteFile[] = [
{
url: this.url,
executable: this.artifact,
dontExtract: true
},
...this._getDriverConfigs()
];
tasks = configs.map(config => {
const executable = config.executable;
const dontExtract = Boolean(config.dontExtract);
const directory = config.directory;
if (fileExists(join(this.directory, executable))) {
return Task.resolve();
}
// TODO: progress events
return this._downloadFile(config.url, this.proxy, <
SeleniumDownloadOptions
>{
executable,
dontExtract,
directory
});
});
resolve(Task.all(tasks).then(() => {}));
},
() => {
tasks &&
tasks.forEach(task => {
task.cancel();
});
}
);
}
sendJobState(): CancellablePromise<void> {
// This is a noop for Selenium
return Task.resolve();
}
protected _getDriverConfigs(): DriverFile[] {
function getDriverConfig(name: string, options?: any) {
const Constructor = driverNameMap[name];
if (!Constructor) {
throw new Error('Invalid driver name "' + name + '"');
}
return new Constructor(options);
}
return this.drivers.map(function(data) {
if (typeof data === 'string') {
return getDriverConfig(data);
}
if (typeof data === 'object' && (<any>data).name) {
return getDriverConfig((<any>data).name, data);
}
// data is a driver definition
return <DriverFile>data;
});
}
protected _makeArgs(): string[] {
const directory = this.directory;
const driverConfigs = this._getDriverConfigs();
const args: string[] = [];
driverConfigs.reduce(function(args: string[], config) {
const file = join(directory, config.executable);
args.push('-D' + config.seleniumProperty + '=' + file);
return args;
}, args);
if (this.seleniumArgs) {
args.push(...this.seleniumArgs);
}
args.push('-jar', join(this.directory, this.artifact), '-port', this.port);
if (this.verbose) {
args.push('-debug');
if (satisfies(this.version, '>=3.1.0 <3.5.0')) {
args.push('true');
}
console.log('Starting with arguments: ', args.join(' '));
}
return args;
}
protected _postDownloadFile(data: Buffer, options: SeleniumDownloadOptions) {
const executable = options.executable!;
if (options.dontExtract) {
return writeFile(data, join(this.directory, executable));
}
return super._postDownloadFile(data, options);
}
protected _start(executor: ChildExecutor) {
let handle: Handle;
const task = this._makeChild((child, resolve, reject) => {
handle = on(child.stderr!, 'data', (data: string) => {
// Selenium recommends that we poll the hub looking for a status
// response
// https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/7957
// We're going against the recommendation here for a few reasons
// 1. There's no default pid or log to look for errors to
// provide a specific failure
// 2. Polling on a failed server start could leave us with an
// unpleasant wait
// 3. Just polling a selenium server doesn't guarantee it's the
// server we started
// 4. This works pretty well
data = String(data);
if (data.indexOf('Selenium Server is up and running') > -1) {
resolve();
} else if (
/Address already in use/.test(data) ||
/Port \d+ is busy/.test(data)
) {
reject(new Error('Address is already in use'));
// Kill the child since we're reporting that startup failed
kill(child.pid);
}
});
if (this.verbose) {
on(child.stderr!, 'data', (data: string) => {
process.stderr.write(data);
});
}
executor(child, resolve, reject);
});
task.then(() => handle.destroy(), () => handle.destroy());
return task;
}
}
export interface DriverFile extends RemoteFile {
seleniumProperty: string;
}
export interface RemoteFile {
dontExtract?: boolean;
directory?: string;
executable: string;
url: string;
}
export type DriverDescriptor =
| 'chrome'
| 'ie'
| 'firefox'
| DriverFile
| { name: string; version?: string };
/**
* Options specific to SeleniumTunnel
*/
export interface SeleniumProperties extends TunnelProperties {
/** [[SeleniumTunnel.SeleniumTunnel.seleniumArgs|More info]] */
seleniumArgs: string[];
/** [[SeleniumTunnel.SeleniumTunnel.drivers|More info]] */
drivers: DriverDescriptor[];
/** [[SeleniumTunnel.SeleniumTunnel.baseUrl|More info]] */
baseUrl: string;
/** [[SeleniumTunnel.SeleniumTunnel.version|More info]] */
version: string;
/** [[SeleniumTunnel.SeleniumTunnel.seleniumTimeout|More info]] */
seleniumTimeout: number;
}
export type SeleniumOptions = Partial<SeleniumProperties>;
export interface SeleniumDownloadOptions extends DownloadOptions {
executable?: string;
dontExtract?: boolean;
}
type DriverConstructor = { new (config?: any): DriverFile };
abstract class Config<T extends object> {
constructor(config: T) {
Object.assign(this, config);
}
abstract readonly executable: string;
abstract readonly url: string;
abstract readonly seleniumProperty?: string;
}
interface ChromeProperties {
arch: string;
baseUrl: string;
platform: string;
version: string;
}
type ChromeOptions = Partial<ChromeProperties>;
class ChromeConfig extends Config<ChromeOptions>
implements ChromeProperties, DriverFile {
arch!: string;
baseUrl!: string;
platform!: string;
version!: string;
constructor(options: ChromeOptions) {
super(
Object.assign(
{
arch: process.arch,
baseUrl: 'https://chromedriver.storage.googleapis.com',
platform: process.platform,
version: driverInfo.ChromeVersion
},
options
)
);
}
get artifact() {
let platform = this.platform;
if (platform === 'linux') {
platform = 'linux' + (this.arch === 'x86' ? '32' : '64');
} else if (platform === 'darwin') {
const parts = String(this.version)
.split('.')
.map(Number);
const isGreater = [2, 22].some(function(part, i) {
return parts[i] > part;
});
platform = isGreater ? 'mac64' : 'mac32';
}
return format('chromedriver_%s.zip', platform);
}
get directory() {
return join(this.version, this.arch);
}
get url() {
return format('%s/%s/%s', this.baseUrl, this.version, this.artifact);
}
get executable() {
return join(
this.directory,
this.platform === 'win32' ? 'chromedriver.exe' : 'chromedriver'
);
}
get seleniumProperty() {
return 'webdriver.chrome.driver';
}
}
interface FirefoxProperties {
arch: string;
baseUrl: string;
platform: string;
version: string;
}
type FirefoxOptions = Partial<FirefoxProperties>;
class FirefoxConfig extends Config<FirefoxOptions>
implements FirefoxProperties, DriverFile {
arch!: string;
baseUrl!: string;
platform!: string;
version!: string;
constructor(options: FirefoxOptions) {
super(
Object.assign(
{
arch: process.arch,
baseUrl: 'https://github.com/mozilla/geckodriver/releases/download',
platform: process.platform,
version: driverInfo.FirefoxVersion
},
options
)
);
}
get artifact() {
let platform = this.platform;
if (platform === 'linux') {
platform = 'linux' + (this.arch === 'x64' ? '64' : '32');
} else if (platform === 'win32') {
platform = 'win' + (this.arch === 'x64' ? '64' : '32');
} else if (platform === 'darwin') {
platform = 'macos';
}
const extension = /^win/.test(platform) ? '.zip' : '.tar.gz';
return format('geckodriver-v%s-%s%s', this.version, platform, extension);
}
get url() {
return format('%s/v%s/%s', this.baseUrl, this.version, this.artifact);
}
get directory() {
return join(this.version, this.arch);
}
get executable() {
return join(
this.directory,
this.platform === 'win32' ? 'geckodriver.exe' : 'geckodriver'
);
}
get seleniumProperty() {
return 'webdriver.gecko.driver';
}
}
// tslint:disable-next-line:interface-name
interface IEProperties {
arch: string;
baseUrl: string;
version: string;
}
type IEOptions = Partial<IEProperties>;
class IEConfig extends Config<IEOptions> implements IEProperties, DriverFile {
arch!: string;
baseUrl!: string;
version!: string;
constructor(options: IEOptions) {
super(
Object.assign(
{
arch: process.arch,
baseUrl: 'https://selenium-release.storage.googleapis.com',
version: driverInfo.IEVersion
},
options
)
);
}
get artifact() {
const architecture = this.arch === 'x64' ? 'x64' : 'Win32';
return format('IEDriverServer_%s_%s.zip', architecture, this.version);
}
get url() {
const majorMinorVersion = this.version.slice(
0,
this.version.lastIndexOf('.')
);
return format('%s/%s/%s', this.baseUrl, majorMinorVersion, this.artifact);
}
get directory() {
return join(this.version, this.arch);
}
get executable() {
return join(this.directory, 'IEDriverServer.exe');
}
get seleniumProperty() {
return 'webdriver.ie.driver';
}
}
interface EdgeProperties {
baseUrl: string;
uuid: string | undefined;
version: string;
}
type EdgeOptions = Partial<EdgeProperties>;
class EdgeConfig extends Config<EdgeOptions>
implements EdgeProperties, DriverFile {
arch!: string;
baseUrl!: string;
uuid: string | undefined;
version!: keyof typeof driverInfo.EdgeUrls;
constructor(options: EdgeOptions) {
super(
Object.assign(
{
arch: process.arch,
baseUrl: 'https://download.microsoft.com/download',
version: driverInfo.EdgeVersion
},
options
)
);
}
get dontExtract() {
return true;
}
get url() {
const { uuid } = this;
if (uuid) {
const a = uuid[0];
const b = uuid[1];
const c = uuid[2];
return format(
'%s/%s/%s/%s/%s/%s',
this.baseUrl,
a,
b,
c,
uuid,
this.artifact
);
}
const urlOrObj = driverInfo.EdgeUrls[this.version];
if (typeof urlOrObj === 'string') {
return urlOrObj;
}
return urlOrObj[this.arch as keyof typeof urlOrObj];
}
get artifact() {
return 'MicrosoftWebDriver.exe';
}
get directory() {
return this.version;
}
get executable() {
return join(this.version, 'MicrosoftWebDriver.exe');
}
get seleniumProperty() {
return 'webdriver.edge.driver';
}
}
const driverNameMap: { [key: string]: DriverConstructor } = {
chrome: ChromeConfig,
firefox: FirefoxConfig,
ie: IEConfig,
'internet explorer': IEConfig,
edge: EdgeConfig,
MicrosoftEdge: EdgeConfig
};