summaryrefslogtreecommitdiff
path: root/node_modules/selenium-webdriver/lib/webdriver.js
blob: 081d77bda1bc0dd93ca6575d575103deb7922606 (plain)
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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you 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.

/**
 * @fileoverview The heart of the WebDriver JavaScript API.
 */

'use strict';

const actions = require('./actions');
const by = require('./by');
const Capabilities = require('./capabilities').Capabilities;
const command = require('./command');
const error = require('./error');
const input = require('./input');
const logging = require('./logging');
const {Session} = require('./session');
const Symbols = require('./symbols');
const promise = require('./promise');


/**
 * Defines a condition for use with WebDriver's {@linkplain WebDriver#wait wait
 * command}.
 *
 * @template OUT
 */
class Condition {
  /**
   * @param {string} message A descriptive error message. Should complete the
   *     sentence "Waiting [...]"
   * @param {function(!WebDriver): OUT} fn The condition function to
   *     evaluate on each iteration of the wait loop.
   */
  constructor(message, fn) {
    /** @private {string} */
    this.description_ = 'Waiting ' + message;

    /** @type {function(!WebDriver): OUT} */
    this.fn = fn;
  }

  /** @return {string} A description of this condition. */
  description() {
    return this.description_;
  }
}


/**
 * Defines a condition that will result in a {@link WebElement}.
 *
 * @extends {Condition<!(WebElement|IThenable<!WebElement>)>}
 */
class WebElementCondition extends Condition {
  /**
   * @param {string} message A descriptive error message. Should complete the
   *     sentence "Waiting [...]"
   * @param {function(!WebDriver): !(WebElement|IThenable<!WebElement>)}
   *     fn The condition function to evaluate on each iteration of the wait
   *     loop.
   */
  constructor(message, fn) {
    super(message, fn);
  }
}


//////////////////////////////////////////////////////////////////////////////
//
//  WebDriver
//
//////////////////////////////////////////////////////////////////////////////


/**
 * Translates a command to its wire-protocol representation before passing it
 * to the given `executor` for execution.
 * @param {!command.Executor} executor The executor to use.
 * @param {!command.Command} command The command to execute.
 * @return {!Promise} A promise that will resolve with the command response.
 */
function executeCommand(executor, command) {
  return toWireValue(command.getParameters()).
      then(function(parameters) {
        command.setParameters(parameters);
        return executor.execute(command);
      });
}


/**
 * Converts an object to its JSON representation in the WebDriver wire protocol.
 * When converting values of type object, the following steps will be taken:
 * <ol>
 * <li>if the object is a WebElement, the return value will be the element's
 *     server ID
 * <li>if the object defines a {@link Symbols.serialize} method, this algorithm
 *     will be recursively applied to the object's serialized representation
 * <li>if the object provides a "toJSON" function, this algorithm will
 *     recursively be applied to the result of that function
 * <li>otherwise, the value of each key will be recursively converted according
 *     to the rules above.
 * </ol>
 *
 * @param {*} obj The object to convert.
 * @return {!Promise<?>} A promise that will resolve to the input value's JSON
 *     representation.
 */
function toWireValue(obj) {
  if (promise.isPromise(obj)) {
    return Promise.resolve(obj).then(toWireValue);
  }
  return Promise.resolve(convertValue(obj));
}


function convertValue(value) {
  if (value === void 0 || value === null) {
    return value;
  }

  if (typeof value === 'boolean'
      || typeof value === 'number'
      || typeof value === 'string') {
    return value;
  }

  if (Array.isArray(value)) {
    return convertKeys(value);
  }

  if (typeof value === 'function') {
    return '' + value;
  }

  if (typeof value[Symbols.serialize] === 'function') {
    return toWireValue(value[Symbols.serialize]());
  } else if (typeof value.toJSON === 'function') {
    return toWireValue(value.toJSON());
  }
  return convertKeys(value);
}


function convertKeys(obj) {
  const isArray = Array.isArray(obj);
  const numKeys = isArray ? obj.length : Object.keys(obj).length;
  const ret = isArray ? new Array(numKeys) : {};
  if (!numKeys) {
    return Promise.resolve(ret);
  }

  let numResolved = 0;

  function forEachKey(obj, fn) {
    if (Array.isArray(obj)) {
      for (let i = 0, n = obj.length; i < n; i++) {
        fn(obj[i], i);
      }
    } else {
      for (let key in obj) {
        fn(obj[key], key);
      }
    }
  }

  return new Promise(function(done, reject) {
    forEachKey(obj, function(value, key) {
      if (promise.isPromise(value)) {
        value.then(toWireValue).then(setValue, reject);
      } else {
        value = convertValue(value);
        if (promise.isPromise(value)) {
          value.then(toWireValue).then(setValue, reject);
        } else {
          setValue(value);
        }
      }

      function setValue(value) {
        ret[key] = value;
        maybeFulfill();
      }
    });

    function maybeFulfill() {
      if (++numResolved === numKeys) {
        done(ret);
      }
    }
  });
}


/**
 * Converts a value from its JSON representation according to the WebDriver wire
 * protocol. Any JSON object that defines a WebElement ID will be decoded to a
 * {@link WebElement} object. All other values will be passed through as is.
 *
 * @param {!WebDriver} driver The driver to use as the parent of any unwrapped
 *     {@link WebElement} values.
 * @param {*} value The value to convert.
 * @return {*} The converted value.
 */
function fromWireValue(driver, value) {
  if (Array.isArray(value)) {
    value = value.map(v => fromWireValue(driver, v));
  } else if (WebElement.isId(value)) {
    let id = WebElement.extractId(value);
    value = new WebElement(driver, id);
  } else if (value && typeof value === 'object') {
    let result = {};
    for (let key in value) {
      if (value.hasOwnProperty(key)) {
        result[key] = fromWireValue(driver, value[key]);
      }
    }
    value = result;
  }
  return value;
}


/**
 * Structural interface for a WebDriver client.
 *
 * @record
 */
class IWebDriver {

  /** @return {!promise.ControlFlow} The control flow used by this instance. */
  controlFlow() {}

  /**
   * Schedules a {@link command.Command} to be executed by this driver's
   * {@link command.Executor}.
   *
   * @param {!command.Command} command The command to schedule.
   * @param {string} description A description of the command for debugging.
   * @return {!promise.Thenable<T>} A promise that will be resolved
   *     with the command result.
   * @template T
   */
  schedule(command, description) {}

  /**
   * Sets the {@linkplain input.FileDetector file detector} that should be
   * used with this instance.
   * @param {input.FileDetector} detector The detector to use or {@code null}.
   */
  setFileDetector(detector) {}

  /**
   * @return {!command.Executor} The command executor used by this instance.
   */
  getExecutor() {}

  /**
   * @return {!promise.Thenable<!Session>} A promise for this client's session.
   */
  getSession() {}

  /**
   * @return {!promise.Thenable<!Capabilities>} A promise that will resolve with
   *     the this instance's capabilities.
   */
  getCapabilities() {}

  /**
   * Terminates the browser session. After calling quit, this instance will be
   * invalidated and may no longer be used to issue commands against the
   * browser.
   *
   * @return {!promise.Thenable<void>} A promise that will be resolved when the
   *     command has completed.
   */
  quit() {}

  /**
   * Creates a new action sequence using this driver. The sequence will not be
   * scheduled for execution until {@link actions.ActionSequence#perform} is
   * called. Example:
   *
   *     driver.actions().
   *         mouseDown(element1).
   *         mouseMove(element2).
   *         mouseUp().
   *         perform();
   *
   * @return {!actions.ActionSequence} A new action sequence for this instance.
   */
  actions() {}

  /**
   * Creates a new touch sequence using this driver. The sequence will not be
   * scheduled for execution until {@link actions.TouchSequence#perform} is
   * called. Example:
   *
   *     driver.touchActions().
   *         tap(element1).
   *         doubleTap(element2).
   *         perform();
   *
   * @return {!actions.TouchSequence} A new touch sequence for this instance.
   */
  touchActions() {}

  /**
   * Schedules a command to execute JavaScript in the context of the currently
   * selected frame or window. The script fragment will be executed as the body
   * of an anonymous function. If the script is provided as a function object,
   * that function will be converted to a string for injection into the target
   * window.
   *
   * Any arguments provided in addition to the script will be included as script
   * arguments and may be referenced using the {@code arguments} object.
   * Arguments may be a boolean, number, string, or {@linkplain WebElement}.
   * Arrays and objects may also be used as script arguments as long as each item
   * adheres to the types previously mentioned.
   *
   * The script may refer to any variables accessible from the current window.
   * Furthermore, the script will execute in the window's context, thus
   * {@code document} may be used to refer to the current document. Any local
   * variables will not be available once the script has finished executing,
   * though global variables will persist.
   *
   * If the script has a return value (i.e. if the script contains a return
   * statement), then the following steps will be taken for resolving this
   * functions return value:
   *
   * - For a HTML element, the value will resolve to a {@linkplain WebElement}
   * - Null and undefined return values will resolve to null</li>
   * - Booleans, numbers, and strings will resolve as is</li>
   * - Functions will resolve to their string representation</li>
   * - For arrays and objects, each member item will be converted according to
   *     the rules above
   *
   * @param {!(string|Function)} script The script to execute.
   * @param {...*} var_args The arguments to pass to the script.
   * @return {!promise.Thenable<T>} A promise that will resolve to the
   *    scripts return value.
   * @template T
   */
  executeScript(script, var_args) {}

  /**
   * Schedules a command to execute asynchronous JavaScript in the context of the
   * currently selected frame or window. The script fragment will be executed as
   * the body of an anonymous function. If the script is provided as a function
   * object, that function will be converted to a string for injection into the
   * target window.
   *
   * Any arguments provided in addition to the script will be included as script
   * arguments and may be referenced using the {@code arguments} object.
   * Arguments may be a boolean, number, string, or {@code WebElement}.
   * Arrays and objects may also be used as script arguments as long as each item
   * adheres to the types previously mentioned.
   *
   * Unlike executing synchronous JavaScript with {@link #executeScript},
   * scripts executed with this function must explicitly signal they are finished
   * by invoking the provided callback. This callback will always be injected
   * into the executed function as the last argument, and thus may be referenced
   * with {@code arguments[arguments.length - 1]}. The following steps will be
   * taken for resolving this functions return value against the first argument
   * to the script's callback function:
   *
   * - For a HTML element, the value will resolve to a
   *     {@link WebElement}
   * - Null and undefined return values will resolve to null
   * - Booleans, numbers, and strings will resolve as is
   * - Functions will resolve to their string representation
   * - For arrays and objects, each member item will be converted according to
   *     the rules above
   *
   * __Example #1:__ Performing a sleep that is synchronized with the currently
   * selected window:
   *
   *     var start = new Date().getTime();
   *     driver.executeAsyncScript(
   *         'window.setTimeout(arguments[arguments.length - 1], 500);').
   *         then(function() {
   *           console.log(
   *               'Elapsed time: ' + (new Date().getTime() - start) + ' ms');
   *         });
   *
   * __Example #2:__ Synchronizing a test with an AJAX application:
   *
   *     var button = driver.findElement(By.id('compose-button'));
   *     button.click();
   *     driver.executeAsyncScript(
   *         'var callback = arguments[arguments.length - 1];' +
   *         'mailClient.getComposeWindowWidget().onload(callback);');
   *     driver.switchTo().frame('composeWidget');
   *     driver.findElement(By.id('to')).sendKeys('dog@example.com');
   *
   * __Example #3:__ Injecting a XMLHttpRequest and waiting for the result. In
   * this example, the inject script is specified with a function literal. When
   * using this format, the function is converted to a string for injection, so it
   * should not reference any symbols not defined in the scope of the page under
   * test.
   *
   *     driver.executeAsyncScript(function() {
   *       var callback = arguments[arguments.length - 1];
   *       var xhr = new XMLHttpRequest();
   *       xhr.open("GET", "/resource/data.json", true);
   *       xhr.onreadystatechange = function() {
   *         if (xhr.readyState == 4) {
   *           callback(xhr.responseText);
   *         }
   *       };
   *       xhr.send('');
   *     }).then(function(str) {
   *       console.log(JSON.parse(str)['food']);
   *     });
   *
   * @param {!(string|Function)} script The script to execute.
   * @param {...*} var_args The arguments to pass to the script.
   * @return {!promise.Thenable<T>} A promise that will resolve to the
   *    scripts return value.
   * @template T
   */
  executeAsyncScript(script, var_args) {}

  /**
   * Schedules a command to execute a custom function.
   * @param {function(...): (T|IThenable<T>)} fn The function to execute.
   * @param {Object=} opt_scope The object in whose scope to execute the function.
   * @param {...*} var_args Any arguments to pass to the function.
   * @return {!promise.Thenable<T>} A promise that will be resolved'
   *     with the function's result.
   * @template T
   */
  call(fn, opt_scope, var_args) {}

  /**
   * Schedules a command to wait for a condition to hold. The condition may be
   * specified by a {@link Condition}, as a custom function, or as any
   * promise-like thenable.
   *
   * For a {@link Condition} or function, the wait will repeatedly
   * evaluate the condition until it returns a truthy value. If any errors occur
   * while evaluating the condition, they will be allowed to propagate. In the
   * event a condition returns a {@link promise.Promise promise}, the polling
   * loop will wait for it to be resolved and use the resolved value for whether
   * the condition has been satisified. Note the resolution time for a promise
   * is factored into whether a wait has timed out.
   *
   * Note, if the provided condition is a {@link WebElementCondition}, then
   * the wait will return a {@link WebElementPromise} that will resolve to the
   * element that satisified the condition.
   *
   * _Example:_ waiting up to 10 seconds for an element to be present on the
   * page.
   *
   *     var button = driver.wait(until.elementLocated(By.id('foo')), 10000);
   *     button.click();
   *
   * This function may also be used to block the command flow on the resolution
   * of any thenable promise object. When given a promise, the command will
   * simply wait for its resolution before completing. A timeout may be provided
   * to fail the command if the promise does not resolve before the timeout
   * expires.
   *
   * _Example:_ Suppose you have a function, `startTestServer`, that returns a
   * promise for when a server is ready for requests. You can block a WebDriver
   * client on this promise with:
   *
   *     var started = startTestServer();
   *     driver.wait(started, 5 * 1000, 'Server should start within 5 seconds');
   *     driver.get(getServerUrl());
   *
   * @param {!(IThenable<T>|
   *           Condition<T>|
   *           function(!WebDriver): T)} condition The condition to
   *     wait on, defined as a promise, condition object, or  a function to
   *     evaluate as a condition.
   * @param {number=} opt_timeout How long to wait for the condition to be true.
   * @param {string=} opt_message An optional message to use if the wait times
   *     out.
   * @return {!(promise.Thenable<T>|WebElementPromise)} A promise that will be
   *     resolved with the first truthy value returned by the condition
   *     function, or rejected if the condition times out. If the input
   *     input condition is an instance of a {@link WebElementCondition},
   *     the returned value will be a {@link WebElementPromise}.
   * @throws {TypeError} if the provided `condition` is not a valid type.
   * @template T
   */
  wait(condition, opt_timeout, opt_message) {}

  /**
   * Schedules a command to make the driver sleep for the given amount of time.
   * @param {number} ms The amount of time, in milliseconds, to sleep.
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when the sleep has finished.
   */
  sleep(ms) {}

  /**
   * Schedules a command to retrieve the current window handle.
   * @return {!promise.Thenable<string>} A promise that will be
   *     resolved with the current window handle.
   */
  getWindowHandle() {}

  /**
   * Schedules a command to retrieve the current list of available window handles.
   * @return {!promise.Thenable<!Array<string>>} A promise that will
   *     be resolved with an array of window handles.
   */
  getAllWindowHandles() {}

  /**
   * Schedules a command to retrieve the current page's source. The page source
   * returned is a representation of the underlying DOM: do not expect it to be
   * formatted or escaped in the same way as the response sent from the web
   * server.
   * @return {!promise.Thenable<string>} A promise that will be
   *     resolved with the current page source.
   */
  getPageSource() {}

  /**
   * Schedules a command to close the current window.
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when this command has completed.
   */
  close() {}

  /**
   * Schedules a command to navigate to the given URL.
   * @param {string} url The fully qualified URL to open.
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when the document has finished loading.
   */
  get(url) {}

  /**
   * Schedules a command to retrieve the URL of the current page.
   * @return {!promise.Thenable<string>} A promise that will be
   *     resolved with the current URL.
   */
  getCurrentUrl() {}

  /**
   * Schedules a command to retrieve the current page's title.
   * @return {!promise.Thenable<string>} A promise that will be
   *     resolved with the current page's title.
   */
  getTitle() {}

  /**
   * Schedule a command to find an element on the page. If the element cannot be
   * found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned
   * by the driver. Unlike other commands, this error cannot be suppressed. In
   * other words, scheduling a command to find an element doubles as an assert
   * that the element is present on the page. To test whether an element is
   * present on the page, use {@link #findElements}:
   *
   *     driver.findElements(By.id('foo'))
   *         .then(found => console.log('Element found? %s', !!found.length));
   *
   * The search criteria for an element may be defined using one of the
   * factories in the {@link webdriver.By} namespace, or as a short-hand
   * {@link webdriver.By.Hash} object. For example, the following two statements
   * are equivalent:
   *
   *     var e1 = driver.findElement(By.id('foo'));
   *     var e2 = driver.findElement({id:'foo'});
   *
   * You may also provide a custom locator function, which takes as input this
   * instance and returns a {@link WebElement}, or a promise that will resolve
   * to a WebElement. If the returned promise resolves to an array of
   * WebElements, WebDriver will use the first element. For example, to find the
   * first visible link on a page, you could write:
   *
   *     var link = driver.findElement(firstVisibleLink);
   *
   *     function firstVisibleLink(driver) {
   *       var links = driver.findElements(By.tagName('a'));
   *       return promise.filter(links, function(link) {
   *         return link.isDisplayed();
   *       });
   *     }
   *
   * @param {!(by.By|Function)} locator The locator to use.
   * @return {!WebElementPromise} A WebElement that can be used to issue
   *     commands against the located element. If the element is not found, the
   *     element will be invalidated and all scheduled commands aborted.
   */
  findElement(locator) {}

  /**
   * Schedule a command to search for multiple elements on the page.
   *
   * @param {!(by.By|Function)} locator The locator to use.
   * @return {!promise.Thenable<!Array<!WebElement>>} A
   *     promise that will resolve to an array of WebElements.
   */
  findElements(locator) {}

  /**
   * Schedule a command to take a screenshot. The driver makes a best effort to
   * return a screenshot of the following, in order of preference:
   *
   * 1. Entire page
   * 2. Current window
   * 3. Visible portion of the current frame
   * 4. The entire display containing the browser
   *
   * @return {!promise.Thenable<string>} A promise that will be
   *     resolved to the screenshot as a base-64 encoded PNG.
   */
  takeScreenshot() {}

  /**
   * @return {!Options} The options interface for this instance.
   */
  manage() {}

  /**
   * @return {!Navigation} The navigation interface for this instance.
   */
  navigate() {}

  /**
   * @return {!TargetLocator} The target locator interface for this
   *     instance.
   */
  switchTo() {}
}


/**
 * Each WebDriver instance provides automated control over a browser session.
 *
 * @implements {IWebDriver}
 */
class WebDriver {
  /**
   * @param {!(Session|IThenable<!Session>)} session Either a known session or a
   *     promise that will be resolved to a session.
   * @param {!command.Executor} executor The executor to use when sending
   *     commands to the browser.
   * @param {promise.ControlFlow=} opt_flow The flow to
   *     schedule commands through. Defaults to the active flow object.
   * @param {(function(this: void): ?)=} opt_onQuit A function to call, if any,
   *     when the session is terminated.
   */
  constructor(session, executor, opt_flow, opt_onQuit) {
    /** @private {!promise.ControlFlow} */
    this.flow_ = opt_flow || promise.controlFlow();

    /** @private {!promise.Thenable<!Session>} */
    this.session_ = this.flow_.promise(resolve => resolve(session));

    /** @private {!command.Executor} */
    this.executor_ = executor;

    /** @private {input.FileDetector} */
    this.fileDetector_ = null;

    /** @private @const {(function(this: void): ?|undefined)} */
    this.onQuit_ = opt_onQuit;
  }

  /**
   * Creates a new WebDriver client for an existing session.
   * @param {!command.Executor} executor Command executor to use when querying
   *     for session details.
   * @param {string} sessionId ID of the session to attach to.
   * @param {promise.ControlFlow=} opt_flow The control flow all
   *     driver commands should execute under. Defaults to the
   *     {@link promise.controlFlow() currently active}  control flow.
   * @return {!WebDriver} A new client for the specified session.
   */
  static attachToSession(executor, sessionId, opt_flow) {
    let flow = opt_flow || promise.controlFlow();
    let cmd = new command.Command(command.Name.DESCRIBE_SESSION)
        .setParameter('sessionId', sessionId);
    let session = flow.execute(
        () => executeCommand(executor, cmd).catch(err => {
          // The DESCRIBE_SESSION command is not supported by the W3C spec, so
          // if we get back an unknown command, just return a session with
          // unknown capabilities.
          if (err instanceof error.UnknownCommandError) {
            return new Session(sessionId, new Capabilities);
          }
          throw err;
        }),
        'WebDriver.attachToSession()');
    return new WebDriver(session, executor, flow);
  }

  /**
   * Creates a new WebDriver session.
   *
   * By default, the requested session `capabilities` are merely "desired" and
   * the remote end will still create a new session even if it cannot satisfy
   * all of the requested capabilities. You can query which capabilities a
   * session actually has using the
   * {@linkplain #getCapabilities() getCapabilities()} method on the returned
   * WebDriver instance.
   *
   * To define _required capabilities_, provide the `capabilities` as an object
   * literal with `required` and `desired` keys. The `desired` key may be
   * omitted if all capabilities are required, and vice versa. If the server
   * cannot create a session with all of the required capabilities, it will
   * return an {@linkplain error.SessionNotCreatedError}.
   *
   *     let required = new Capabilities().set('browserName', 'firefox');
   *     let desired = new Capabilities().set('version', '45');
   *     let driver = WebDriver.createSession(executor, {required, desired});
   *
   * This function will always return a WebDriver instance. If there is an error
   * creating the session, such as the aforementioned SessionNotCreatedError,
   * the driver will have a rejected {@linkplain #getSession session} promise.
   * It is recommended that this promise is left _unhandled_ so it will
   * propagate through the {@linkplain promise.ControlFlow control flow} and
   * cause subsequent commands to fail.
   *
   *     let required = Capabilities.firefox();
   *     let driver = WebDriver.createSession(executor, {required});
   *
   *     // If the createSession operation failed, then this command will also
   *     // also fail, propagating the creation failure.
   *     driver.get('http://www.google.com').catch(e => console.log(e));
   *
   * @param {!command.Executor} executor The executor to create the new session
   *     with.
   * @param {(!Capabilities|
   *          {desired: (Capabilities|undefined),
   *           required: (Capabilities|undefined)})} capabilities The desired
   *     capabilities for the new session.
   * @param {promise.ControlFlow=} opt_flow The control flow all driver
   *     commands should execute under, including the initial session creation.
   *     Defaults to the {@link promise.controlFlow() currently active}
   *     control flow.
   * @param {(function(new: WebDriver,
   *                   !IThenable<!Session>,
   *                   !command.Executor,
   *                   promise.ControlFlow=))=} opt_ctor
   *    A reference to the constructor of the specific type of WebDriver client
   *    to instantiate. Will create a vanilla {@linkplain WebDriver} instance
   *    if a constructor is not provided.
   * @param {(function(this: void): ?)=} opt_onQuit A callback to invoke when
   *    the newly created session is terminated. This should be used to clean
   *    up any resources associated with the session.
   * @return {!WebDriver} The driver for the newly created session.
   */
  static createSession(
        executor, capabilities, opt_flow, opt_ctor, opt_onQuit) {
    let flow = opt_flow || promise.controlFlow();
    let cmd = new command.Command(command.Name.NEW_SESSION);

    if (capabilities && (capabilities.desired || capabilities.required)) {
      cmd.setParameter('desiredCapabilities', capabilities.desired);
      cmd.setParameter('requiredCapabilities', capabilities.required);
    } else {
      cmd.setParameter('desiredCapabilities', capabilities);
    }

    let session = flow.execute(
        () => executeCommand(executor, cmd),
        'WebDriver.createSession()');
    if (typeof opt_onQuit === 'function') {
      session = session.catch(err => {
        return Promise.resolve(opt_onQuit.call(void 0)).then(_ => {throw err});
      });
    }
    const ctor = opt_ctor || WebDriver;
    return new ctor(session, executor, flow, opt_onQuit);
  }

  /** @override */
  controlFlow() {
    return this.flow_;
  }

  /** @override */
  schedule(command, description) {
    command.setParameter('sessionId', this.session_);

    // If any of the command parameters are rejected promises, those
    // rejections may be reported as unhandled before the control flow
    // attempts to execute the command. To ensure parameters errors
    // propagate through the command itself, we resolve all of the
    // command parameters now, but suppress any errors until the ControlFlow
    // actually executes the command. This addresses scenarios like catching
    // an element not found error in:
    //
    //     driver.findElement(By.id('foo')).click().catch(function(e) {
    //       if (e instanceof NoSuchElementError) {
    //         // Do something.
    //       }
    //     });
    var prepCommand = toWireValue(command.getParameters());
    prepCommand.catch(function() {});

    var flow = this.flow_;
    var executor = this.executor_;
    return flow.execute(() => {
      // Retrieve resolved command parameters; any previously suppressed errors
      // will now propagate up through the control flow as part of the command
      // execution.
      return prepCommand.then(function(parameters) {
        command.setParameters(parameters);
        return executor.execute(command);
      }).then(value => fromWireValue(this, value));
    }, description);
  }

  /** @override */
  setFileDetector(detector) {
    this.fileDetector_ = detector;
  }

  /** @override */
  getExecutor() {
    return this.executor_;
  }

  /** @override */
  getSession() {
    return this.session_;
  }

  /** @override */
  getCapabilities() {
    return this.session_.then(s => s.getCapabilities());
  }

  /** @override */
  quit() {
    var result = this.schedule(
        new command.Command(command.Name.QUIT),
        'WebDriver.quit()');
    // Delete our session ID when the quit command finishes; this will allow us
    // to throw an error when attemnpting to use a driver post-quit.
    return /** @type {!promise.Thenable} */(promise.finally(result, () => {
      this.session_ = this.flow_.promise((_, reject) => {
        reject(new error.NoSuchSessionError(
            'This driver instance does not have a valid session ID ' +
            '(did you call WebDriver.quit()?) and may no longer be used.'));
      });

      // Only want the session rejection to bubble if accessed.
      this.session_.catch(function() {});

      if (this.onQuit_) {
        return this.onQuit_.call(void 0);
      }
    }));
  }

  /** @override */
  actions() {
    return new actions.ActionSequence(this);
  }

  /** @override */
  touchActions() {
    return new actions.TouchSequence(this);
  }

  /** @override */
  executeScript(script, var_args) {
    if (typeof script === 'function') {
      script = 'return (' + script + ').apply(null, arguments);';
    }
    let args =
        arguments.length > 1 ? Array.prototype.slice.call(arguments, 1) : [];
   return this.schedule(
        new command.Command(command.Name.EXECUTE_SCRIPT).
            setParameter('script', script).
            setParameter('args', args),
        'WebDriver.executeScript()');
  }

  /** @override */
  executeAsyncScript(script, var_args) {
    if (typeof script === 'function') {
      script = 'return (' + script + ').apply(null, arguments);';
    }
    let args = Array.prototype.slice.call(arguments, 1);
    return this.schedule(
        new command.Command(command.Name.EXECUTE_ASYNC_SCRIPT).
            setParameter('script', script).
            setParameter('args', args),
        'WebDriver.executeScript()');
  }

  /** @override */
  call(fn, opt_scope, var_args) {
    let args = Array.prototype.slice.call(arguments, 2);
    return this.flow_.execute(function() {
      return promise.fullyResolved(args).then(function(args) {
        if (promise.isGenerator(fn)) {
          args.unshift(fn, opt_scope);
          return promise.consume.apply(null, args);
        }
        return fn.apply(opt_scope, args);
      });
    }, 'WebDriver.call(' + (fn.name || 'function') + ')');
  }

  /** @override */
  wait(condition, opt_timeout, opt_message) {
    if (promise.isPromise(condition)) {
      return this.flow_.wait(
          /** @type {!IThenable} */(condition),
          opt_timeout, opt_message);
    }

    var message = opt_message;
    var fn = /** @type {!Function} */(condition);
    if (condition instanceof Condition) {
      message = message || condition.description();
      fn = condition.fn;
    }

    if (typeof fn !== 'function') {
      throw TypeError(
          'Wait condition must be a promise-like object, function, or a '
              + 'Condition object');
    }

    var driver = this;
    var result = this.flow_.wait(function() {
      if (promise.isGenerator(fn)) {
        return promise.consume(fn, null, [driver]);
      }
      return fn(driver);
    }, opt_timeout, message);

    if (condition instanceof WebElementCondition) {
      result = new WebElementPromise(this, result.then(function(value) {
        if (!(value instanceof WebElement)) {
          throw TypeError(
              'WebElementCondition did not resolve to a WebElement: '
                  + Object.prototype.toString.call(value));
        }
        return value;
      }));
    }
    return result;
  }

  /** @override */
  sleep(ms) {
    return this.flow_.timeout(ms, 'WebDriver.sleep(' + ms + ')');
  }

  /** @override */
  getWindowHandle() {
    return this.schedule(
        new command.Command(command.Name.GET_CURRENT_WINDOW_HANDLE),
        'WebDriver.getWindowHandle()');
  }

  /** @override */
  getAllWindowHandles() {
    return this.schedule(
        new command.Command(command.Name.GET_WINDOW_HANDLES),
        'WebDriver.getAllWindowHandles()');
  }

  /** @override */
  getPageSource() {
    return this.schedule(
        new command.Command(command.Name.GET_PAGE_SOURCE),
        'WebDriver.getPageSource()');
  }

  /** @override */
  close() {
    return this.schedule(new command.Command(command.Name.CLOSE),
                         'WebDriver.close()');
  }

  /** @override */
  get(url) {
    return this.navigate().to(url);
  }

  /** @override */
  getCurrentUrl() {
    return this.schedule(
        new command.Command(command.Name.GET_CURRENT_URL),
        'WebDriver.getCurrentUrl()');
  }

  /** @override */
  getTitle() {
    return this.schedule(new command.Command(command.Name.GET_TITLE),
                         'WebDriver.getTitle()');
  }

  /** @override */
  findElement(locator) {
    let id;
    locator = by.checkedLocator(locator);
    if (typeof locator === 'function') {
      id = this.findElementInternal_(locator, this);
    } else {
      let cmd = new command.Command(command.Name.FIND_ELEMENT).
          setParameter('using', locator.using).
          setParameter('value', locator.value);
      id = this.schedule(cmd, 'WebDriver.findElement(' + locator + ')');
    }
    return new WebElementPromise(this, id);
  }

  /**
   * @param {!Function} locatorFn The locator function to use.
   * @param {!(WebDriver|WebElement)} context The search
   *     context.
   * @return {!promise.Thenable<!WebElement>} A
   *     promise that will resolve to a list of WebElements.
   * @private
   */
  findElementInternal_(locatorFn, context) {
    return this.call(() => locatorFn(context)).then(function(result) {
      if (Array.isArray(result)) {
        result = result[0];
      }
      if (!(result instanceof WebElement)) {
        throw new TypeError('Custom locator did not return a WebElement');
      }
      return result;
    });
  }

  /** @override */
  findElements(locator) {
    locator = by.checkedLocator(locator);
    if (typeof locator === 'function') {
      return this.findElementsInternal_(locator, this);
    } else {
      let cmd = new command.Command(command.Name.FIND_ELEMENTS).
          setParameter('using', locator.using).
          setParameter('value', locator.value);
      let res = this.schedule(cmd, 'WebDriver.findElements(' + locator + ')');
      return res.catch(function(e) {
        if (e instanceof error.NoSuchElementError) {
          return [];
        }
        throw e;
      });
    }
  }

  /**
   * @param {!Function} locatorFn The locator function to use.
   * @param {!(WebDriver|WebElement)} context The search context.
   * @return {!promise.Thenable<!Array<!WebElement>>} A promise that
   *     will resolve to an array of WebElements.
   * @private
   */
  findElementsInternal_(locatorFn, context) {
    return this.call(() => locatorFn(context)).then(function(result) {
      if (result instanceof WebElement) {
        return [result];
      }

      if (!Array.isArray(result)) {
        return [];
      }

      return result.filter(function(item) {
        return item instanceof WebElement;
      });
    });
  }

  /** @override */
  takeScreenshot() {
    return this.schedule(new command.Command(command.Name.SCREENSHOT),
        'WebDriver.takeScreenshot()');
  }

  /** @override */
  manage() {
    return new Options(this);
  }

  /** @override */
  navigate() {
    return new Navigation(this);
  }

  /** @override */
  switchTo() {
    return new TargetLocator(this);
  }
}


/**
 * Interface for navigating back and forth in the browser history.
 *
 * This class should never be instantiated directly. Instead, obtain an instance
 * with
 *
 *    webdriver.navigate()
 *
 * @see WebDriver#navigate()
 */
class Navigation {
  /**
   * @param {!WebDriver} driver The parent driver.
   * @private
   */
  constructor(driver) {
    /** @private {!WebDriver} */
    this.driver_ = driver;
  }

  /**
   * Schedules a command to navigate to a new URL.
   * @param {string} url The URL to navigate to.
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when the URL has been loaded.
   */
  to(url) {
    return this.driver_.schedule(
        new command.Command(command.Name.GET).
            setParameter('url', url),
        'WebDriver.navigate().to(' + url + ')');
  }

  /**
   * Schedules a command to move backwards in the browser history.
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when the navigation event has completed.
   */
  back() {
    return this.driver_.schedule(
        new command.Command(command.Name.GO_BACK),
        'WebDriver.navigate().back()');
  }

  /**
   * Schedules a command to move forwards in the browser history.
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when the navigation event has completed.
   */
  forward() {
    return this.driver_.schedule(
        new command.Command(command.Name.GO_FORWARD),
        'WebDriver.navigate().forward()');
  }

  /**
   * Schedules a command to refresh the current page.
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when the navigation event has completed.
   */
  refresh() {
    return this.driver_.schedule(
        new command.Command(command.Name.REFRESH),
        'WebDriver.navigate().refresh()');
  }
}


/**
 * Provides methods for managing browser and driver state.
 *
 * This class should never be instantiated directly. Insead, obtain an instance
 * with {@linkplain WebDriver#manage() webdriver.manage()}.
 */
class Options {
  /**
   * @param {!WebDriver} driver The parent driver.
   * @private
   */
  constructor(driver) {
    /** @private {!WebDriver} */
    this.driver_ = driver;
  }

  /**
   * Schedules a command to add a cookie.
   *
   * __Sample Usage:__
   *
   *     // Set a basic cookie.
   *     driver.options().addCookie({name: 'foo', value: 'bar'});
   *
   *     // Set a cookie that expires in 10 minutes.
   *     let expiry = new Date(Date.now() + (10 * 60 * 1000));
   *     driver.options().addCookie({name: 'foo', value: 'bar', expiry});
   *
   *     // The cookie expiration may also be specified in seconds since epoch.
   *     driver.options().addCookie({
   *       name: 'foo',
   *       value: 'bar',
   *       expiry: Math.floor(Date.now() / 1000)
   *     });
   *
   * @param {!Options.Cookie} spec Defines the cookie to add.
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when the cookie has been added to the page.
   * @throws {error.InvalidArgumentError} if any of the cookie parameters are
   *     invalid.
   * @throws {TypeError} if `spec` is not a cookie object.
   */
  addCookie(spec) {
    if (!spec || typeof spec !== 'object') {
      throw TypeError('addCookie called with non-cookie parameter');
    }

    // We do not allow '=' or ';' in the name.
    let name = spec.name;
    if (/[;=]/.test(name)) {
      throw new error.InvalidArgumentError(
          'Invalid cookie name "' + name + '"');
    }

    // We do not allow ';' in value.
    let value = spec.value;
    if (/;/.test(value)) {
      throw new error.InvalidArgumentError(
          'Invalid cookie value "' + value + '"');
    }

    let cookieString = name + '=' + value +
        (spec.domain ? ';domain=' + spec.domain : '') +
        (spec.path ? ';path=' + spec.path : '') +
        (spec.secure ? ';secure' : '');

    let expiry;
    if (typeof spec.expiry === 'number') {
      expiry = Math.floor(spec.expiry);
      cookieString += ';expires=' + new Date(spec.expiry * 1000).toUTCString();
    } else if (spec.expiry instanceof Date) {
      let date = /** @type {!Date} */(spec.expiry);
      expiry = Math.floor(date.getTime() / 1000);
      cookieString += ';expires=' + date.toUTCString();
    }

    return this.driver_.schedule(
        new command.Command(command.Name.ADD_COOKIE).
            setParameter('cookie', {
              'name': name,
              'value': value,
              'path': spec.path,
              'domain': spec.domain,
              'secure': !!spec.secure,
              'expiry': expiry
            }),
        'WebDriver.manage().addCookie(' + cookieString + ')');
  }

  /**
   * Schedules a command to delete all cookies visible to the current page.
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when all cookies have been deleted.
   */
  deleteAllCookies() {
    return this.driver_.schedule(
        new command.Command(command.Name.DELETE_ALL_COOKIES),
        'WebDriver.manage().deleteAllCookies()');
  }

  /**
   * Schedules a command to delete the cookie with the given name. This command
   * is a no-op if there is no cookie with the given name visible to the current
   * page.
   * @param {string} name The name of the cookie to delete.
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when the cookie has been deleted.
   */
  deleteCookie(name) {
    return this.driver_.schedule(
        new command.Command(command.Name.DELETE_COOKIE).
            setParameter('name', name),
        'WebDriver.manage().deleteCookie(' + name + ')');
  }

  /**
   * Schedules a command to retrieve all cookies visible to the current page.
   * Each cookie will be returned as a JSON object as described by the WebDriver
   * wire protocol.
   * @return {!promise.Thenable<!Array<!Options.Cookie>>} A promise that will be
   *     resolved with the cookies visible to the current browsing context.
   */
  getCookies() {
    return this.driver_.schedule(
        new command.Command(command.Name.GET_ALL_COOKIES),
        'WebDriver.manage().getCookies()');
  }

  /**
   * Schedules a command to retrieve the cookie with the given name. Returns null
   * if there is no such cookie. The cookie will be returned as a JSON object as
   * described by the WebDriver wire protocol.
   *
   * @param {string} name The name of the cookie to retrieve.
   * @return {!promise.Thenable<?Options.Cookie>} A promise that will be resolved
   *     with the named cookie, or `null` if there is no such cookie.
   */
  getCookie(name) {
    return this.getCookies().then(function(cookies) {
      for (let cookie of cookies) {
        if (cookie && cookie['name'] === name) {
          return cookie;
        }
      }
      return null;
    });
  }

  /**
   * @return {!Logs} The interface for managing driver
   *     logs.
   */
  logs() {
    return new Logs(this.driver_);
  }

  /**
   * @return {!Timeouts} The interface for managing driver timeouts.
   */
  timeouts() {
    return new Timeouts(this.driver_);
  }

  /**
   * @return {!Window} The interface for managing the current window.
   */
  window() {
    return new Window(this.driver_);
  }
}


/**
 * A record object describing a browser cookie.
 *
 * @record
 */
Options.Cookie = function() {};


/**
 * The name of the cookie.
 *
 * @type {string}
 */
Options.Cookie.prototype.name;


/**
 * The cookie value.
 *
 * @type {string}
 */
Options.Cookie.prototype.value;


/**
 * The cookie path. Defaults to "/" when adding a cookie.
 *
 * @type {(string|undefined)}
 */
Options.Cookie.prototype.path;


/**
 * The domain the cookie is visible to. Defaults to the current browsing
 * context's document's URL when adding a cookie.
 *
 * @type {(string|undefined)}
 */
Options.Cookie.prototype.domain;


/**
 * Whether the cookie is a secure cookie. Defaults to false when adding a new
 * cookie.
 *
 * @type {(boolean|undefined)}
 */
Options.Cookie.prototype.secure;


/**
 * Whether the cookie is an HTTP only cookie. Defaults to false when adding a
 * new cookie.
 *
 * @type {(boolean|undefined)}
 */
Options.Cookie.prototype.httpOnly;


/**
 * When the cookie expires.
 *
 * When {@linkplain Options#addCookie() adding a cookie}, this may be specified
 * in _seconds_ since Unix epoch (January 1, 1970). The expiry will default to
 * 20 years in the future if omitted.
 *
 * The expiry is always returned in seconds since epoch when
 * {@linkplain Options#getCookies() retrieving cookies} from the browser.
 *
 * @type {(!Date|number|undefined)}
 */
Options.Cookie.prototype.expiry;


/**
 * An interface for managing timeout behavior for WebDriver instances.
 *
 * This class should never be instantiated directly. Insead, obtain an instance
 * with
 *
 *    webdriver.manage().timeouts()
 *
 * @see WebDriver#manage()
 * @see Options#timeouts()
 */
class Timeouts {
  /**
   * @param {!WebDriver} driver The parent driver.
   * @private
   */
  constructor(driver) {
    /** @private {!WebDriver} */
    this.driver_ = driver;
  }

  /**
   * Specifies the amount of time the driver should wait when searching for an
   * element if it is not immediately present.
   *
   * When searching for a single element, the driver should poll the page
   * until the element has been found, or this timeout expires before failing
   * with a {@link bot.ErrorCode.NO_SUCH_ELEMENT} error. When searching
   * for multiple elements, the driver should poll the page until at least one
   * element has been found or this timeout has expired.
   *
   * Setting the wait timeout to 0 (its default value), disables implicit
   * waiting.
   *
   * Increasing the implicit wait timeout should be used judiciously as it
   * will have an adverse effect on test run time, especially when used with
   * slower location strategies like XPath.
   *
   * @param {number} ms The amount of time to wait, in milliseconds.
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when the implicit wait timeout has been set.
   */
  implicitlyWait(ms) {
    return this._scheduleCommand(ms, 'implicit', 'implicitlyWait');
  }

  /**
   * Sets the amount of time to wait, in milliseconds, for an asynchronous
   * script to finish execution before returning an error. If the timeout is
   * less than or equal to 0, the script will be allowed to run indefinitely.
   *
   * @param {number} ms The amount of time to wait, in milliseconds.
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when the script timeout has been set.
   */
  setScriptTimeout(ms) {
    return this._scheduleCommand(ms, 'script', 'setScriptTimeout');
  }

  /**
   * Sets the amount of time to wait for a page load to complete before
   * returning an error.  If the timeout is negative, page loads may be
   * indefinite.
   *
   * @param {number} ms The amount of time to wait, in milliseconds.
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when the timeout has been set.
   */
  pageLoadTimeout(ms) {
    return this._scheduleCommand(ms, 'page load', 'pageLoadTimeout');
  }

  _scheduleCommand(ms, timeoutIdentifier, timeoutName) {
    return this.driver_.schedule(
        new command.Command(command.Name.SET_TIMEOUT).
            setParameter('type', timeoutIdentifier).
            setParameter('ms', ms),
        `WebDriver.manage().timeouts().${timeoutName}(${ms})`);
  }
}


/**
 * An interface for managing the current window.
 *
 * This class should never be instantiated directly. Instead, obtain an instance
 * with
 *
 *    webdriver.manage().window()
 *
 * @see WebDriver#manage()
 * @see Options#window()
 */
class Window {
  /**
   * @param {!WebDriver} driver The parent driver.
   * @private
   */
  constructor(driver) {
    /** @private {!WebDriver} */
    this.driver_ = driver;
  }

  /**
   * Retrieves the window's current position, relative to the top left corner of
   * the screen.
   * @return {!promise.Thenable<{x: number, y: number}>} A promise
   *     that will be resolved with the window's position in the form of a
   *     {x:number, y:number} object literal.
   */
  getPosition() {
    return this.driver_.schedule(
        new command.Command(command.Name.GET_WINDOW_POSITION).
            setParameter('windowHandle', 'current'),
        'WebDriver.manage().window().getPosition()');
  }

  /**
   * Repositions the current window.
   * @param {number} x The desired horizontal position, relative to the left
   *     side of the screen.
   * @param {number} y The desired vertical position, relative to the top of the
   *     of the screen.
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when the command has completed.
   */
  setPosition(x, y) {
    return this.driver_.schedule(
        new command.Command(command.Name.SET_WINDOW_POSITION).
            setParameter('windowHandle', 'current').
            setParameter('x', x).
            setParameter('y', y),
        'WebDriver.manage().window().setPosition(' + x + ', ' + y + ')');
  }

  /**
   * Retrieves the window's current size.
   * @return {!promise.Thenable<{width: number, height: number}>} A
   *     promise that will be resolved with the window's size in the form of a
   *     {width:number, height:number} object literal.
   */
  getSize() {
    return this.driver_.schedule(
        new command.Command(command.Name.GET_WINDOW_SIZE).
            setParameter('windowHandle', 'current'),
        'WebDriver.manage().window().getSize()');
  }

  /**
   * Resizes the current window.
   * @param {number} width The desired window width.
   * @param {number} height The desired window height.
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when the command has completed.
   */
  setSize(width, height) {
    return this.driver_.schedule(
        new command.Command(command.Name.SET_WINDOW_SIZE).
            setParameter('windowHandle', 'current').
            setParameter('width', width).
            setParameter('height', height),
        'WebDriver.manage().window().setSize(' + width + ', ' + height + ')');
  }

  /**
   * Maximizes the current window.
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when the command has completed.
   */
  maximize() {
    return this.driver_.schedule(
        new command.Command(command.Name.MAXIMIZE_WINDOW).
            setParameter('windowHandle', 'current'),
        'WebDriver.manage().window().maximize()');
  }
}


/**
 * Interface for managing WebDriver log records.
 *
 * This class should never be instantiated directly. Instead, obtain an
 * instance with
 *
 *     webdriver.manage().logs()
 *
 * @see WebDriver#manage()
 * @see Options#logs()
 */
class Logs {
  /**
   * @param {!WebDriver} driver The parent driver.
   * @private
   */
  constructor(driver) {
    /** @private {!WebDriver} */
    this.driver_ = driver;
  }

  /**
   * Fetches available log entries for the given type.
   *
   * Note that log buffers are reset after each call, meaning that available
   * log entries correspond to those entries not yet returned for a given log
   * type. In practice, this means that this call will return the available log
   * entries since the last call, or from the start of the session.
   *
   * @param {!logging.Type} type The desired log type.
   * @return {!promise.Thenable<!Array.<!logging.Entry>>} A
   *   promise that will resolve to a list of log entries for the specified
   *   type.
   */
  get(type) {
    let cmd = new command.Command(command.Name.GET_LOG).
        setParameter('type', type);
    return this.driver_.schedule(
        cmd, 'WebDriver.manage().logs().get(' + type + ')').
        then(function(entries) {
          return entries.map(function(entry) {
            if (!(entry instanceof logging.Entry)) {
              return new logging.Entry(
                  entry['level'], entry['message'], entry['timestamp'],
                  entry['type']);
            }
            return entry;
          });
        });
  }

  /**
   * Retrieves the log types available to this driver.
   * @return {!promise.Thenable<!Array<!logging.Type>>} A
   *     promise that will resolve to a list of available log types.
   */
  getAvailableLogTypes() {
    return this.driver_.schedule(
        new command.Command(command.Name.GET_AVAILABLE_LOG_TYPES),
        'WebDriver.manage().logs().getAvailableLogTypes()');
  }
}


/**
 * An interface for changing the focus of the driver to another frame or window.
 *
 * This class should never be instantiated directly. Instead, obtain an
 * instance with
 *
 *     webdriver.switchTo()
 *
 * @see WebDriver#switchTo()
 */
class TargetLocator {
  /**
   * @param {!WebDriver} driver The parent driver.
   * @private
   */
  constructor(driver) {
    /** @private {!WebDriver} */
    this.driver_ = driver;
  }

  /**
   * Schedules a command retrieve the {@code document.activeElement} element on
   * the current document, or {@code document.body} if activeElement is not
   * available.
   * @return {!WebElementPromise} The active element.
   */
  activeElement() {
    var id = this.driver_.schedule(
        new command.Command(command.Name.GET_ACTIVE_ELEMENT),
        'WebDriver.switchTo().activeElement()');
    return new WebElementPromise(this.driver_, id);
  }

  /**
   * Schedules a command to switch focus of all future commands to the topmost
   * frame on the page.
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when the driver has changed focus to the default content.
   */
  defaultContent() {
    return this.driver_.schedule(
        new command.Command(command.Name.SWITCH_TO_FRAME).
            setParameter('id', null),
        'WebDriver.switchTo().defaultContent()');
  }

  /**
   * Schedules a command to switch the focus of all future commands to another
   * frame on the page. The target frame may be specified as one of the
   * following:
   *
   * - A number that specifies a (zero-based) index into [window.frames](
   *   https://developer.mozilla.org/en-US/docs/Web/API/Window.frames).
   * - A {@link WebElement} reference, which correspond to a `frame` or `iframe`
   *   DOM element.
   * - The `null` value, to select the topmost frame on the page. Passing `null`
   *   is the same as calling {@link #defaultContent defaultContent()}.
   *
   * If the specified frame can not be found, the returned promise will be
   * rejected with a {@linkplain error.NoSuchFrameError}.
   *
   * @param {(number|WebElement|null)} id The frame locator.
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when the driver has changed focus to the specified frame.
   */
  frame(id) {
    return this.driver_.schedule(
        new command.Command(command.Name.SWITCH_TO_FRAME).
            setParameter('id', id),
        'WebDriver.switchTo().frame(' + id + ')');
  }

  /**
   * Schedules a command to switch the focus of all future commands to another
   * window. Windows may be specified by their {@code window.name} attribute or
   * by its handle (as returned by {@link WebDriver#getWindowHandles}).
   *
   * If the specified window cannot be found, the returned promise will be
   * rejected with a {@linkplain error.NoSuchWindowError}.
   *
   * @param {string} nameOrHandle The name or window handle of the window to
   *     switch focus to.
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when the driver has changed focus to the specified window.
   */
  window(nameOrHandle) {
    return this.driver_.schedule(
        new command.Command(command.Name.SWITCH_TO_WINDOW).
            // "name" supports the legacy drivers. "handle" is the W3C
            // compliant parameter.
            setParameter('name', nameOrHandle).
            setParameter('handle', nameOrHandle),
        'WebDriver.switchTo().window(' + nameOrHandle + ')');
  }

  /**
   * Schedules a command to change focus to the active modal dialog, such as
   * those opened by `window.alert()`, `window.confirm()`, and
   * `window.prompt()`. The returned promise will be rejected with a
   * {@linkplain error.NoSuchAlertError} if there are no open alerts.
   *
   * @return {!AlertPromise} The open alert.
   */
  alert() {
    var text = this.driver_.schedule(
        new command.Command(command.Name.GET_ALERT_TEXT),
        'WebDriver.switchTo().alert()');
    var driver = this.driver_;
    return new AlertPromise(driver, text.then(function(text) {
      return new Alert(driver, text);
    }));
  }
}


//////////////////////////////////////////////////////////////////////////////
//
//  WebElement
//
//////////////////////////////////////////////////////////////////////////////


const LEGACY_ELEMENT_ID_KEY = 'ELEMENT';
const ELEMENT_ID_KEY = 'element-6066-11e4-a52e-4f735466cecf';


/**
 * Represents a DOM element. WebElements can be found by searching from the
 * document root using a {@link WebDriver} instance, or by searching
 * under another WebElement:
 *
 *     driver.get('http://www.google.com');
 *     var searchForm = driver.findElement(By.tagName('form'));
 *     var searchBox = searchForm.findElement(By.name('q'));
 *     searchBox.sendKeys('webdriver');
 */
class WebElement {
  /**
   * @param {!WebDriver} driver the parent WebDriver instance for this element.
   * @param {(!IThenable<string>|string)} id The server-assigned opaque ID for
   *     the underlying DOM element.
   */
  constructor(driver, id) {
    /** @private {!WebDriver} */
    this.driver_ = driver;

    /** @private {!promise.Thenable<string>} */
    this.id_ = driver.controlFlow().promise(resolve => resolve(id));
  }

  /**
   * @param {string} id The raw ID.
   * @param {boolean=} opt_noLegacy Whether to exclude the legacy element key.
   * @return {!Object} The element ID for use with WebDriver's wire protocol.
   */
  static buildId(id, opt_noLegacy) {
    return opt_noLegacy
        ? {[ELEMENT_ID_KEY]: id}
        : {[ELEMENT_ID_KEY]: id, [LEGACY_ELEMENT_ID_KEY]: id};
  }

  /**
   * Extracts the encoded WebElement ID from the object.
   *
   * @param {?} obj The object to extract the ID from.
   * @return {string} the extracted ID.
   * @throws {TypeError} if the object is not a valid encoded ID.
   */
  static extractId(obj) {
    if (obj && typeof obj === 'object') {
      if (typeof obj[ELEMENT_ID_KEY] === 'string') {
        return obj[ELEMENT_ID_KEY];
      } else if (typeof obj[LEGACY_ELEMENT_ID_KEY] === 'string') {
        return obj[LEGACY_ELEMENT_ID_KEY];
      }
    }
    throw new TypeError('object is not a WebElement ID');
  }

  /**
   * @param {?} obj the object to test.
   * @return {boolean} whether the object is a valid encoded WebElement ID.
   */
  static isId(obj) {
    return obj && typeof obj === 'object'
        && (typeof obj[ELEMENT_ID_KEY] === 'string'
            || typeof obj[LEGACY_ELEMENT_ID_KEY] === 'string');
  }

  /**
   * Compares two WebElements for equality.
   *
   * @param {!WebElement} a A WebElement.
   * @param {!WebElement} b A WebElement.
   * @return {!promise.Thenable<boolean>} A promise that will be
   *     resolved to whether the two WebElements are equal.
   */
  static equals(a, b) {
    if (a === b) {
      return a.driver_.controlFlow().promise(resolve => resolve(true));
    }
    let ids = [a.getId(), b.getId()];
    return promise.all(ids).then(function(ids) {
      // If the two element's have the same ID, they should be considered
      // equal. Otherwise, they may still be equivalent, but we'll need to
      // ask the server to check for us.
      if (ids[0] === ids[1]) {
        return true;
      }

      let cmd = new command.Command(command.Name.ELEMENT_EQUALS);
      cmd.setParameter('id', ids[0]);
      cmd.setParameter('other', ids[1]);
      return a.driver_.schedule(cmd, 'WebElement.equals()');
    });
  }

  /** @return {!WebDriver} The parent driver for this instance. */
  getDriver() {
    return this.driver_;
  }

  /**
   * @return {!promise.Thenable<string>} A promise that resolves to
   *     the server-assigned opaque ID assigned to this element.
   */
  getId() {
    return this.id_;
  }

  /**
   * @return {!Object} Returns the serialized representation of this WebElement.
   */
  [Symbols.serialize]() {
    return this.getId().then(WebElement.buildId);
  }

  /**
   * Schedules a command that targets this element with the parent WebDriver
   * instance. Will ensure this element's ID is included in the command
   * parameters under the "id" key.
   *
   * @param {!command.Command} command The command to schedule.
   * @param {string} description A description of the command for debugging.
   * @return {!promise.Thenable<T>} A promise that will be resolved
   *     with the command result.
   * @template T
   * @see WebDriver#schedule
   * @private
   */
  schedule_(command, description) {
    command.setParameter('id', this);
    return this.driver_.schedule(command, description);
  }

  /**
   * Schedule a command to find a descendant of this element. If the element
   * cannot be found, the returned promise will be rejected with a
   * {@linkplain error.NoSuchElementError NoSuchElementError}.
   *
   * The search criteria for an element may be defined using one of the static
   * factories on the {@link by.By} class, or as a short-hand
   * {@link ./by.ByHash} object. For example, the following two statements
   * are equivalent:
   *
   *     var e1 = element.findElement(By.id('foo'));
   *     var e2 = element.findElement({id:'foo'});
   *
   * You may also provide a custom locator function, which takes as input this
   * instance and returns a {@link WebElement}, or a promise that will resolve
   * to a WebElement. If the returned promise resolves to an array of
   * WebElements, WebDriver will use the first element. For example, to find the
   * first visible link on a page, you could write:
   *
   *     var link = element.findElement(firstVisibleLink);
   *
   *     function firstVisibleLink(element) {
   *       var links = element.findElements(By.tagName('a'));
   *       return promise.filter(links, function(link) {
   *         return link.isDisplayed();
   *       });
   *     }
   *
   * @param {!(by.By|Function)} locator The locator strategy to use when
   *     searching for the element.
   * @return {!WebElementPromise} A WebElement that can be used to issue
   *     commands against the located element. If the element is not found, the
   *     element will be invalidated and all scheduled commands aborted.
   */
  findElement(locator) {
    locator = by.checkedLocator(locator);
    let id;
    if (typeof locator === 'function') {
      id = this.driver_.findElementInternal_(locator, this);
    } else {
      let cmd = new command.Command(
          command.Name.FIND_CHILD_ELEMENT).
          setParameter('using', locator.using).
          setParameter('value', locator.value);
      id = this.schedule_(cmd, 'WebElement.findElement(' + locator + ')');
    }
    return new WebElementPromise(this.driver_, id);
  }

  /**
   * Schedules a command to find all of the descendants of this element that
   * match the given search criteria.
   *
   * @param {!(by.By|Function)} locator The locator strategy to use when
   *     searching for the element.
   * @return {!promise.Thenable<!Array<!WebElement>>} A
   *     promise that will resolve to an array of WebElements.
   */
  findElements(locator) {
    locator = by.checkedLocator(locator);
    let id;
    if (typeof locator === 'function') {
      return this.driver_.findElementsInternal_(locator, this);
    } else {
      var cmd = new command.Command(
          command.Name.FIND_CHILD_ELEMENTS).
          setParameter('using', locator.using).
          setParameter('value', locator.value);
      return this.schedule_(cmd, 'WebElement.findElements(' + locator + ')');
    }
  }

  /**
   * Schedules a command to click on this element.
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when the click command has completed.
   */
  click() {
    return this.schedule_(
        new command.Command(command.Name.CLICK_ELEMENT),
        'WebElement.click()');
  }

  /**
   * Schedules a command to type a sequence on the DOM element represented by
   * this instance.
   *
   * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is
   * processed in the keysequence, that key state is toggled until one of the
   * following occurs:
   *
   * - The modifier key is encountered again in the sequence. At this point the
   *   state of the key is toggled (along with the appropriate keyup/down
   *   events).
   * - The {@link input.Key.NULL} key is encountered in the sequence. When
   *   this key is encountered, all modifier keys current in the down state are
   *   released (with accompanying keyup events). The NULL key can be used to
   *   simulate common keyboard shortcuts:
   *
   *         element.sendKeys("text was",
   *                          Key.CONTROL, "a", Key.NULL,
   *                          "now text is");
   *         // Alternatively:
   *         element.sendKeys("text was",
   *                          Key.chord(Key.CONTROL, "a"),
   *                          "now text is");
   *
   * - The end of the keysequence is encountered. When there are no more keys
   *   to type, all depressed modifier keys are released (with accompanying
   *   keyup events).
   *
   * If this element is a file input ({@code <input type="file">}), the
   * specified key sequence should specify the path to the file to attach to
   * the element. This is analgous to the user clicking "Browse..." and entering
   * the path into the file select dialog.
   *
   *     var form = driver.findElement(By.css('form'));
   *     var element = form.findElement(By.css('input[type=file]'));
   *     element.sendKeys('/path/to/file.txt');
   *     form.submit();
   *
   * For uploads to function correctly, the entered path must reference a file
   * on the _browser's_ machine, not the local machine running this script. When
   * running against a remote Selenium server, a {@link input.FileDetector}
   * may be used to transparently copy files to the remote machine before
   * attempting to upload them in the browser.
   *
   * __Note:__ On browsers where native keyboard events are not supported
   * (e.g. Firefox on OS X), key events will be synthesized. Special
   * punctionation keys will be synthesized according to a standard QWERTY en-us
   * keyboard layout.
   *
   * @param {...(number|string|!IThenable<(number|string)>)} var_args The
   *     sequence of keys to type. Number keys may be referenced numerically or
   *     by string (1 or '1'). All arguments will be joined into a single
   *     sequence.
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when all keys have been typed.
   */
  sendKeys(var_args) {
    let keys = Promise.all(Array.prototype.slice.call(arguments, 0)).
        then(keys => {
          let ret = [];
          keys.forEach(key => {
            let type = typeof key;
            if (type === 'number') {
              key = String(key);
            } else if (type !== 'string') {
              throw TypeError(
                  'each key must be a number of string; got ' + type);
            }

            // The W3C protocol requires keys to be specified as an array where
            // each element is a single key.
            ret.push.apply(ret, key.split(''));
          });
          return ret;
        });

    if (!this.driver_.fileDetector_) {
      return this.schedule_(
          new command.Command(command.Name.SEND_KEYS_TO_ELEMENT).
              setParameter('value', keys),
          'WebElement.sendKeys()');
    }

    // Suppress unhandled rejection errors until the flow executes the command.
    keys.catch(function() {});

    var element = this;
    return this.getDriver().controlFlow().execute(function() {
      return keys.then(function(keys) {
        return element.driver_.fileDetector_
            .handleFile(element.driver_, keys.join(''));
      }).then(function(keys) {
        return element.schedule_(
            new command.Command(command.Name.SEND_KEYS_TO_ELEMENT).
                setParameter('value', keys.split('')),
            'WebElement.sendKeys()');
      });
    }, 'WebElement.sendKeys()');
  }

  /**
   * Schedules a command to query for the tag/node name of this element.
   * @return {!promise.Thenable<string>} A promise that will be
   *     resolved with the element's tag name.
   */
  getTagName() {
    return this.schedule_(
        new command.Command(command.Name.GET_ELEMENT_TAG_NAME),
        'WebElement.getTagName()');
  }

  /**
   * Schedules a command to query for the computed style of the element
   * represented by this instance. If the element inherits the named style from
   * its parent, the parent will be queried for its value.  Where possible, color
   * values will be converted to their hex representation (e.g. #00ff00 instead
   * of rgb(0, 255, 0)).
   *
   * _Warning:_ the value returned will be as the browser interprets it, so
   * it may be tricky to form a proper assertion.
   *
   * @param {string} cssStyleProperty The name of the CSS style property to look
   *     up.
   * @return {!promise.Thenable<string>} A promise that will be
   *     resolved with the requested CSS value.
   */
  getCssValue(cssStyleProperty) {
    var name = command.Name.GET_ELEMENT_VALUE_OF_CSS_PROPERTY;
    return this.schedule_(
        new command.Command(name).
            setParameter('propertyName', cssStyleProperty),
        'WebElement.getCssValue(' + cssStyleProperty + ')');
  }

  /**
   * Schedules a command to query for the value of the given attribute of the
   * element. Will return the current value, even if it has been modified after
   * the page has been loaded. More exactly, this method will return the value
   * of the given attribute, unless that attribute is not present, in which case
   * the value of the property with the same name is returned. If neither value
   * is set, null is returned (for example, the "value" property of a textarea
   * element). The "style" attribute is converted as best can be to a
   * text representation with a trailing semi-colon. The following are deemed to
   * be "boolean" attributes and will return either "true" or null:
   *
   * async, autofocus, autoplay, checked, compact, complete, controls, declare,
   * defaultchecked, defaultselected, defer, disabled, draggable, ended,
   * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope,
   * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open,
   * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking,
   * selected, spellcheck, truespeed, willvalidate
   *
   * Finally, the following commonly mis-capitalized attribute/property names
   * are evaluated as expected:
   *
   * - "class"
   * - "readonly"
   *
   * @param {string} attributeName The name of the attribute to query.
   * @return {!promise.Thenable<?string>} A promise that will be
   *     resolved with the attribute's value. The returned value will always be
   *     either a string or null.
   */
  getAttribute(attributeName) {
    return this.schedule_(
        new command.Command(command.Name.GET_ELEMENT_ATTRIBUTE).
            setParameter('name', attributeName),
        'WebElement.getAttribute(' + attributeName + ')');
  }

  /**
   * Get the visible (i.e. not hidden by CSS) innerText of this element,
   * including sub-elements, without any leading or trailing whitespace.
   *
   * @return {!promise.Thenable<string>} A promise that will be
   *     resolved with the element's visible text.
   */
  getText() {
    return this.schedule_(
        new command.Command(command.Name.GET_ELEMENT_TEXT),
        'WebElement.getText()');
  }

  /**
   * Schedules a command to compute the size of this element's bounding box, in
   * pixels.
   * @return {!promise.Thenable<{width: number, height: number}>} A
   *     promise that will be resolved with the element's size as a
   *     {@code {width:number, height:number}} object.
   */
  getSize() {
    return this.schedule_(
        new command.Command(command.Name.GET_ELEMENT_SIZE),
        'WebElement.getSize()');
  }

  /**
   * Schedules a command to compute the location of this element in page space.
   * @return {!promise.Thenable<{x: number, y: number}>} A promise that
   *     will be resolved to the element's location as a
   *     {@code {x:number, y:number}} object.
   */
  getLocation() {
    return this.schedule_(
        new command.Command(command.Name.GET_ELEMENT_LOCATION),
        'WebElement.getLocation()');
  }

  /**
   * Schedules a command to query whether the DOM element represented by this
   * instance is enabled, as dicted by the {@code disabled} attribute.
   * @return {!promise.Thenable<boolean>} A promise that will be
   *     resolved with whether this element is currently enabled.
   */
  isEnabled() {
    return this.schedule_(
        new command.Command(command.Name.IS_ELEMENT_ENABLED),
        'WebElement.isEnabled()');
  }

  /**
   * Schedules a command to query whether this element is selected.
   * @return {!promise.Thenable<boolean>} A promise that will be
   *     resolved with whether this element is currently selected.
   */
  isSelected() {
    return this.schedule_(
        new command.Command(command.Name.IS_ELEMENT_SELECTED),
        'WebElement.isSelected()');
  }

  /**
   * Schedules a command to submit the form containing this element (or this
   * element if it is a FORM element). This command is a no-op if the element is
   * not contained in a form.
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when the form has been submitted.
   */
  submit() {
    return this.schedule_(
        new command.Command(command.Name.SUBMIT_ELEMENT),
        'WebElement.submit()');
  }

  /**
   * Schedules a command to clear the `value` of this element. This command has
   * no effect if the underlying DOM element is neither a text INPUT element
   * nor a TEXTAREA element.
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when the element has been cleared.
   */
  clear() {
    return this.schedule_(
        new command.Command(command.Name.CLEAR_ELEMENT),
        'WebElement.clear()');
  }

  /**
   * Schedules a command to test whether this element is currently displayed.
   * @return {!promise.Thenable<boolean>} A promise that will be
   *     resolved with whether this element is currently visible on the page.
   */
  isDisplayed() {
    return this.schedule_(
        new command.Command(command.Name.IS_ELEMENT_DISPLAYED),
        'WebElement.isDisplayed()');
  }

  /**
   * Take a screenshot of the visible region encompassed by this element's
   * bounding rectangle.
   *
   * @param {boolean=} opt_scroll Optional argument that indicates whether the
   *     element should be scrolled into view before taking a screenshot.
   *     Defaults to false.
   * @return {!promise.Thenable<string>} A promise that will be
   *     resolved to the screenshot as a base-64 encoded PNG.
   */
  takeScreenshot(opt_scroll) {
    var scroll = !!opt_scroll;
    return this.schedule_(
        new command.Command(command.Name.TAKE_ELEMENT_SCREENSHOT)
            .setParameter('scroll', scroll),
        'WebElement.takeScreenshot(' + scroll + ')');
  }
}


/**
 * WebElementPromise is a promise that will be fulfilled with a WebElement.
 * This serves as a forward proxy on WebElement, allowing calls to be
 * scheduled without directly on this instance before the underlying
 * WebElement has been fulfilled. In other words, the following two statements
 * are equivalent:
 *
 *     driver.findElement({id: 'my-button'}).click();
 *     driver.findElement({id: 'my-button'}).then(function(el) {
 *       return el.click();
 *     });
 *
 * @implements {promise.CancellableThenable<!WebElement>}
 * @final
 */
class WebElementPromise extends WebElement {
  /**
   * @param {!WebDriver} driver The parent WebDriver instance for this
   *     element.
   * @param {!promise.Thenable<!WebElement>} el A promise
   *     that will resolve to the promised element.
   */
  constructor(driver, el) {
    super(driver, 'unused');

    /**
     * Cancel operation is only supported if the wrapped thenable is also
     * cancellable.
     * @param {(string|Error)=} opt_reason
     * @override
     */
    this.cancel = function(opt_reason) {
      if (promise.CancellableThenable.isImplementation(el)) {
        /** @type {!promise.CancellableThenable} */(el).cancel(opt_reason);
      }
    }

    /** @override */
    this.then = el.then.bind(el);

    /** @override */
    this.catch = el.catch.bind(el);

    /**
     * Defers returning the element ID until the wrapped WebElement has been
     * resolved.
     * @override
     */
    this.getId = function() {
      return el.then(function(el) {
        return el.getId();
      });
    };
  }
}
promise.CancellableThenable.addImplementation(WebElementPromise);


//////////////////////////////////////////////////////////////////////////////
//
//  Alert
//
//////////////////////////////////////////////////////////////////////////////


/**
 * Represents a modal dialog such as {@code alert}, {@code confirm}, or
 * {@code prompt}. Provides functions to retrieve the message displayed with
 * the alert, accept or dismiss the alert, and set the response text (in the
 * case of {@code prompt}).
 */
class Alert {
  /**
   * @param {!WebDriver} driver The driver controlling the browser this alert
   *     is attached to.
   * @param {string} text The message text displayed with this alert.
   */
  constructor(driver, text) {
    /** @private {!WebDriver} */
    this.driver_ = driver;

    /** @private {!promise.Thenable<string>} */
    this.text_ = driver.controlFlow().promise(resolve => resolve(text));
  }

  /**
   * Retrieves the message text displayed with this alert. For instance, if the
   * alert were opened with alert("hello"), then this would return "hello".
   *
   * @return {!promise.Thenable<string>} A promise that will be
   *     resolved to the text displayed with this alert.
   */
  getText() {
    return this.text_;
  }

  /**
   * Sets the username and password in an alert prompting for credentials (such
   * as a Basic HTTP Auth prompt). This method will implicitly
   * {@linkplain #accept() submit} the dialog.
   *
   * @param {string} username The username to send.
   * @param {string} password The password to send.
   * @return {!promise.Thenable<void>} A promise that will be resolved when this
   *     command has completed.
   */
  authenticateAs(username, password) {
    return this.driver_.schedule(
        new command.Command(command.Name.SET_ALERT_CREDENTIALS),
        'WebDriver.switchTo().alert()'
            + `.authenticateAs("${username}", "${password}")`);
  }

  /**
   * Accepts this alert.
   *
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when this command has completed.
   */
  accept() {
    return this.driver_.schedule(
        new command.Command(command.Name.ACCEPT_ALERT),
        'WebDriver.switchTo().alert().accept()');
  }

  /**
   * Dismisses this alert.
   *
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when this command has completed.
   */
  dismiss() {
    return this.driver_.schedule(
        new command.Command(command.Name.DISMISS_ALERT),
        'WebDriver.switchTo().alert().dismiss()');
  }

  /**
   * Sets the response text on this alert. This command will return an error if
   * the underlying alert does not support response text (e.g. window.alert and
   * window.confirm).
   *
   * @param {string} text The text to set.
   * @return {!promise.Thenable<void>} A promise that will be resolved
   *     when this command has completed.
   */
  sendKeys(text) {
    return this.driver_.schedule(
        new command.Command(command.Name.SET_ALERT_TEXT).
            setParameter('text', text),
        'WebDriver.switchTo().alert().sendKeys(' + text + ')');
  }
}


/**
 * AlertPromise is a promise that will be fulfilled with an Alert. This promise
 * serves as a forward proxy on an Alert, allowing calls to be scheduled
 * directly on this instance before the underlying Alert has been fulfilled. In
 * other words, the following two statements are equivalent:
 *
 *     driver.switchTo().alert().dismiss();
 *     driver.switchTo().alert().then(function(alert) {
 *       return alert.dismiss();
 *     });
 *
 * @implements {promise.CancellableThenable<!webdriver.Alert>}
 * @final
 */
class AlertPromise extends Alert {
  /**
   * @param {!WebDriver} driver The driver controlling the browser this
   *     alert is attached to.
   * @param {!promise.Thenable<!Alert>} alert A thenable
   *     that will be fulfilled with the promised alert.
   */
  constructor(driver, alert) {
    super(driver, 'unused');

    /**
     * Cancel operation is only supported if the wrapped thenable is also
     * cancellable.
     * @param {(string|Error)=} opt_reason
     * @override
     */
    this.cancel = function(opt_reason) {
      if (promise.CancellableThenable.isImplementation(alert)) {
        /** @type {!promise.CancellableThenable} */(alert).cancel(opt_reason);
      }
    };

    /** @override */
    this.then = alert.then.bind(alert);

    /** @override */
    this.catch = alert.catch.bind(alert);

    /**
     * Defer returning text until the promised alert has been resolved.
     * @override
     */
    this.getText = function() {
      return alert.then(function(alert) {
        return alert.getText();
      });
    };

    /**
     * Defers action until the alert has been located.
     * @override
     */
    this.authenticateAs = function(username, password) {
      return alert.then(function(alert) {
        return alert.authenticateAs(username, password);
      });
    };

    /**
     * Defers action until the alert has been located.
     * @override
     */
    this.accept = function() {
      return alert.then(function(alert) {
        return alert.accept();
      });
    };

    /**
     * Defers action until the alert has been located.
     * @override
     */
    this.dismiss = function() {
      return alert.then(function(alert) {
        return alert.dismiss();
      });
    };

    /**
     * Defers action until the alert has been located.
     * @override
     */
    this.sendKeys = function(text) {
      return alert.then(function(alert) {
        return alert.sendKeys(text);
      });
    };
  }
}
promise.CancellableThenable.addImplementation(AlertPromise);


// PUBLIC API


module.exports = {
  Alert: Alert,
  AlertPromise: AlertPromise,
  Condition: Condition,
  Logs: Logs,
  Navigation: Navigation,
  Options: Options,
  TargetLocator: TargetLocator,
  Timeouts: Timeouts,
  IWebDriver: IWebDriver,
  WebDriver: WebDriver,
  WebElement: WebElement,
  WebElementCondition: WebElementCondition,
  WebElementPromise: WebElementPromise,
  Window: Window
};