lib/webdriver/promise.js

1// Copyright 2011 Software Freedom Conservancy. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15/**
16 * @license Portions of this code are from the Dojo toolkit, received under the
17 * BSD License:
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are met:
20 *
21 * * Redistributions of source code must retain the above copyright notice,
22 * this list of conditions and the following disclaimer.
23 * * Redistributions in binary form must reproduce the above copyright notice,
24 * this list of conditions and the following disclaimer in the documentation
25 * and/or other materials provided with the distribution.
26 * * Neither the name of the Dojo Foundation nor the names of its contributors
27 * may be used to endorse or promote products derived from this software
28 * without specific prior written permission.
29 *
30 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
31 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
34 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
35 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
36 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
37 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
38 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
39 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
40 * POSSIBILITY OF SUCH DAMAGE.
41 */
42
43/**
44 * @fileoverview A promise implementation based on the CommonJS promise/A and
45 * promise/B proposals. For more information, see
46 * http://wiki.commonjs.org/wiki/Promises.
47 */
48
49goog.provide('webdriver.promise');
50goog.provide('webdriver.promise.ControlFlow');
51goog.provide('webdriver.promise.ControlFlow.Timer');
52goog.provide('webdriver.promise.Deferred');
53goog.provide('webdriver.promise.Promise');
54
55goog.require('goog.array');
56goog.require('goog.debug.Error');
57goog.require('goog.object');
58goog.require('webdriver.EventEmitter');
59goog.require('webdriver.stacktrace.Snapshot');
60
61
62
63/**
64 * Represents the eventual value of a completed operation. Each promise may be
65 * in one of three states: pending, resolved, or rejected. Each promise starts
66 * in the pending state and may make a single transition to either a
67 * fulfilled or failed state.
68 *
69 * <p/>This class is based on the Promise/A proposal from CommonJS. Additional
70 * functions are provided for API compatibility with Dojo Deferred objects.
71 *
72 * @constructor
73 * @template T
74 * @see http://wiki.commonjs.org/wiki/Promises/A
75 */
76webdriver.promise.Promise = function() {
77};
78
79
80/**
81 * Cancels the computation of this promise's value, rejecting the promise in the
82 * process.
83 * @param {*} reason The reason this promise is being cancelled. If not an
84 * {@code Error}, one will be created using the value's string
85 * representation.
86 */
87webdriver.promise.Promise.prototype.cancel = function(reason) {
88 throw new TypeError('Unimplemented function: "cancel"');
89};
90
91
92/** @return {boolean} Whether this promise's value is still being computed. */
93webdriver.promise.Promise.prototype.isPending = function() {
94 throw new TypeError('Unimplemented function: "isPending"');
95};
96
97
98/**
99 * Registers listeners for when this instance is resolved. This function most
100 * overridden by subtypes.
101 *
102 * @param {?(function(T): (R|webdriver.promise.Promise.<R>))=} opt_callback The
103 * function to call if this promise is successfully resolved. The function
104 * should expect a single argument: the promise's resolved value.
105 * @param {?(function(*): (R|webdriver.promise.Promise.<R>))=} opt_errback The
106 * function to call if this promise is rejected. The function should expect
107 * a single argument: the rejection reason.
108 * @return {!webdriver.promise.Promise.<R>} A new promise which will be
109 * resolved with the result of the invoked callback.
110 * @template R
111 */
112webdriver.promise.Promise.prototype.then = function(
113 opt_callback, opt_errback) {
114 throw new TypeError('Unimplemented function: "then"');
115};
116
117
118/**
119 * Registers a listener for when this promise is rejected. This is synonymous
120 * with the {@code catch} clause in a synchronous API:
121 * <pre><code>
122 * // Synchronous API:
123 * try {
124 * doSynchronousWork();
125 * } catch (ex) {
126 * console.error(ex);
127 * }
128 *
129 * // Asynchronous promise API:
130 * doAsynchronousWork().thenCatch(function(ex) {
131 * console.error(ex);
132 * });
133 * </code></pre>
134 *
135 * @param {function(*): (R|webdriver.promise.Promise.<R>)} errback The function
136 * to call if this promise is rejected. The function should expect a single
137 * argument: the rejection reason.
138 * @return {!webdriver.promise.Promise.<R>} A new promise which will be
139 * resolved with the result of the invoked callback.
140 * @template R
141 */
142webdriver.promise.Promise.prototype.thenCatch = function(errback) {
143 return this.then(null, errback);
144};
145
146
147/**
148 * Registers a listener to invoke when this promise is resolved, regardless
149 * of whether the promise's value was successfully computed. This function
150 * is synonymous with the {@code finally} clause in a synchronous API:
151 * <pre><code>
152 * // Synchronous API:
153 * try {
154 * doSynchronousWork();
155 * } finally {
156 * cleanUp();
157 * }
158 *
159 * // Asynchronous promise API:
160 * doAsynchronousWork().thenFinally(cleanUp);
161 * </code></pre>
162 *
163 * <b>Note:</b> similar to the {@code finally} clause, if the registered
164 * callback returns a rejected promise or throws an error, it will silently
165 * replace the rejection error (if any) from this promise:
166 * <pre><code>
167 * try {
168 * throw Error('one');
169 * } finally {
170 * throw Error('two'); // Hides Error: one
171 * }
172 *
173 * webdriver.promise.rejected(Error('one'))
174 * .thenFinally(function() {
175 * throw Error('two'); // Hides Error: one
176 * });
177 * </code></pre>
178 *
179 *
180 * @param {function(): (R|webdriver.promise.Promise.<R>)} callback The function
181 * to call when this promise is resolved.
182 * @return {!webdriver.promise.Promise.<R>} A promise that will be fulfilled
183 * with the callback result.
184 * @template R
185 */
186webdriver.promise.Promise.prototype.thenFinally = function(callback) {
187 return this.then(callback, callback);
188};
189
190
191
192/**
193 * Represents a value that will be resolved at some point in the future. This
194 * class represents the protected "producer" half of a Promise - each Deferred
195 * has a {@code promise} property that may be returned to consumers for
196 * registering callbacks, reserving the ability to resolve the deferred to the
197 * producer.
198 *
199 * <p>If this Deferred is rejected and there are no listeners registered before
200 * the next turn of the event loop, the rejection will be passed to the
201 * {@link webdriver.promise.ControlFlow} as an unhandled failure.
202 *
203 * <p>If this Deferred is cancelled, the cancellation reason will be forward to
204 * the Deferred's canceller function (if provided). The canceller may return a
205 * truth-y value to override the reason provided for rejection.
206 *
207 * @param {Function=} opt_canceller Function to call when cancelling the
208 * computation of this instance's value.
209 * @param {webdriver.promise.ControlFlow=} opt_flow The control flow
210 * this instance was created under. This should only be provided during
211 * unit tests.
212 * @constructor
213 * @extends {webdriver.promise.Promise.<T>}
214 * @template T
215 */
216webdriver.promise.Deferred = function(opt_canceller, opt_flow) {
217 /* NOTE: This class's implementation diverges from the prototypical style
218 * used in the rest of the atoms library. This was done intentionally to
219 * protect the internal Deferred state from consumers, as outlined by
220 * http://wiki.commonjs.org/wiki/Promises
221 */
222 goog.base(this);
223
224 var flow = opt_flow || webdriver.promise.controlFlow();
225
226 /**
227 * The listeners registered with this Deferred. Each element in the list will
228 * be a 3-tuple of the callback function, errback function, and the
229 * corresponding deferred object.
230 * @type {!Array.<!webdriver.promise.Deferred.Listener_>}
231 */
232 var listeners = [];
233
234 /**
235 * Whether this Deferred's resolution was ever handled by a listener.
236 * If the Deferred is rejected and its value is not handled by a listener
237 * before the next turn of the event loop, the error will be passed to the
238 * global error handler.
239 * @type {boolean}
240 */
241 var handled = false;
242
243 /**
244 * Key for the timeout used to delay reproting an unhandled rejection to the
245 * parent {@link webdriver.promise.ControlFlow}.
246 * @type {?number}
247 */
248 var pendingRejectionKey = null;
249
250 /**
251 * This Deferred's current state.
252 * @type {!webdriver.promise.Deferred.State_}
253 */
254 var state = webdriver.promise.Deferred.State_.PENDING;
255
256 /**
257 * This Deferred's resolved value; set when the state transitions from
258 * {@code webdriver.promise.Deferred.State_.PENDING}.
259 * @type {*}
260 */
261 var value;
262
263 /** @return {boolean} Whether this promise's value is still pending. */
264 function isPending() {
265 return state == webdriver.promise.Deferred.State_.PENDING;
266 }
267
268 /**
269 * Removes all of the listeners previously registered on this deferred.
270 * @throws {Error} If this deferred has already been resolved.
271 */
272 function removeAll() {
273 listeners = [];
274 }
275
276 /**
277 * Resolves this deferred. If the new value is a promise, this function will
278 * wait for it to be resolved before notifying the registered listeners.
279 * @param {!webdriver.promise.Deferred.State_} newState The deferred's new
280 * state.
281 * @param {*} newValue The deferred's new value.
282 */
283 function resolve(newState, newValue) {
284 if (webdriver.promise.Deferred.State_.PENDING !== state) {
285 return;
286 }
287
288 state = webdriver.promise.Deferred.State_.BLOCKED;
289
290 if (webdriver.promise.isPromise(newValue) && newValue !== self) {
291 var onFulfill = goog.partial(notifyAll, newState);
292 var onReject = goog.partial(
293 notifyAll, webdriver.promise.Deferred.State_.REJECTED);
294 if (newValue instanceof webdriver.promise.Deferred) {
295 newValue.then(onFulfill, onReject);
296 } else {
297 webdriver.promise.asap(newValue, onFulfill, onReject);
298 }
299
300 } else {
301 notifyAll(newState, newValue);
302 }
303 }
304
305 /**
306 * Notifies all of the listeners registered with this Deferred that its state
307 * has changed.
308 * @param {!webdriver.promise.Deferred.State_} newState The deferred's new
309 * state.
310 * @param {*} newValue The deferred's new value.
311 */
312 function notifyAll(newState, newValue) {
313 if (newState === webdriver.promise.Deferred.State_.REJECTED &&
314 // We cannot check instanceof Error since the object may have been
315 // created in a different JS context.
316 goog.isObject(newValue) && goog.isString(newValue.message)) {
317 newValue = flow.annotateError(/** @type {!Error} */(newValue));
318 }
319
320 state = newState;
321 value = newValue;
322 while (listeners.length) {
323 notify(listeners.shift());
324 }
325
326 if (!handled && state == webdriver.promise.Deferred.State_.REJECTED) {
327 pendingRejectionKey = propagateError(value);
328 }
329 }
330
331 /**
332 * Propagates an unhandled rejection to the parent ControlFlow in a
333 * future turn of the JavaScript event loop.
334 * @param {*} error The error value to report.
335 * @return {number} The key for the registered timeout.
336 */
337 function propagateError(error) {
338 flow.pendingRejections_ += 1;
339 return flow.timer.setTimeout(function() {
340 flow.pendingRejections_ -= 1;
341 flow.abortFrame_(error);
342 }, 0);
343 }
344
345 /**
346 * Notifies a single listener of this Deferred's change in state.
347 * @param {!webdriver.promise.Deferred.Listener_} listener The listener to
348 * notify.
349 */
350 function notify(listener) {
351 var func = state == webdriver.promise.Deferred.State_.RESOLVED ?
352 listener.callback : listener.errback;
353 if (func) {
354 flow.runInNewFrame_(goog.partial(func, value),
355 listener.fulfill, listener.reject);
356 } else if (state == webdriver.promise.Deferred.State_.REJECTED) {
357 listener.reject(value);
358 } else {
359 listener.fulfill(value);
360 }
361 }
362
363 /**
364 * The consumer promise for this instance. Provides protected access to the
365 * callback registering functions.
366 * @type {!webdriver.promise.Promise.<T>}
367 */
368 var promise = new webdriver.promise.Promise();
369
370 /**
371 * Registers a callback on this Deferred.
372 *
373 * @param {?(function(T): (R|webdriver.promise.Promise.<R>))=} opt_callback .
374 * @param {?(function(*): (R|webdriver.promise.Promise.<R>))=} opt_errback .
375 * @return {!webdriver.promise.Promise.<R>} A new promise representing the
376 * result of the callback.
377 * @template R
378 * @see webdriver.promise.Promise#then
379 */
380 function then(opt_callback, opt_errback) {
381 // Avoid unnecessary allocations if we weren't given any callback functions.
382 if (!opt_callback && !opt_errback) {
383 return promise;
384 }
385
386 // The moment a listener is registered, we consider this deferred to be
387 // handled; the callback must handle any rejection errors.
388 handled = true;
389 if (pendingRejectionKey) {
390 flow.pendingRejections_ -= 1;
391 flow.timer.clearTimeout(pendingRejectionKey);
392 }
393
394 var deferred = new webdriver.promise.Deferred(cancel, flow);
395 var listener = {
396 callback: opt_callback,
397 errback: opt_errback,
398 fulfill: deferred.fulfill,
399 reject: deferred.reject
400 };
401
402 if (state == webdriver.promise.Deferred.State_.PENDING ||
403 state == webdriver.promise.Deferred.State_.BLOCKED) {
404 listeners.push(listener);
405 } else {
406 notify(listener);
407 }
408
409 return deferred.promise;
410 }
411
412 var self = this;
413
414 /**
415 * Resolves this promise with the given value. If the value is itself a
416 * promise and not a reference to this deferred, this instance will wait for
417 * it before resolving.
418 * @param {T=} opt_value The fulfilled value.
419 */
420 function fulfill(opt_value) {
421 resolve(webdriver.promise.Deferred.State_.RESOLVED, opt_value);
422 }
423
424 /**
425 * Rejects this promise. If the error is itself a promise, this instance will
426 * be chained to it and be rejected with the error's resolved value.
427 * @param {*=} opt_error The rejection reason, typically either a
428 * {@code Error} or a {@code string}.
429 */
430 function reject(opt_error) {
431 resolve(webdriver.promise.Deferred.State_.REJECTED, opt_error);
432 }
433
434 /**
435 * Attempts to cancel the computation of this instance's value. This attempt
436 * will silently fail if this instance has already resolved.
437 * @param {*=} opt_reason The reason for cancelling this promise.
438 */
439 function cancel(opt_reason) {
440 if (!isPending()) {
441 return;
442 }
443
444 if (opt_canceller) {
445 opt_reason = opt_canceller(opt_reason) || opt_reason;
446 }
447
448 reject(opt_reason);
449 }
450
451 this.promise = promise;
452 this.promise.then = this.then = then;
453 this.promise.cancel = this.cancel = cancel;
454 this.promise.isPending = this.isPending = isPending;
455 this.fulfill = fulfill;
456 this.reject = this.errback = reject;
457
458 // Only expose this function to our internal classes.
459 // TODO: find a cleaner way of handling this.
460 if (this instanceof webdriver.promise.Task_) {
461 this.removeAll = removeAll;
462 }
463
464 // Export symbols necessary for the contract on this object to work in
465 // compiled mode.
466 goog.exportProperty(this, 'then', this.then);
467 goog.exportProperty(this, 'cancel', cancel);
468 goog.exportProperty(this, 'fulfill', fulfill);
469 goog.exportProperty(this, 'reject', reject);
470 goog.exportProperty(this, 'isPending', isPending);
471 goog.exportProperty(this, 'promise', this.promise);
472 goog.exportProperty(this.promise, 'then', this.then);
473 goog.exportProperty(this.promise, 'cancel', cancel);
474 goog.exportProperty(this.promise, 'isPending', isPending);
475};
476goog.inherits(webdriver.promise.Deferred, webdriver.promise.Promise);
477
478
479/**
480 * Type definition for a listener registered on a Deferred object.
481 * @typedef {{callback:(Function|undefined),
482 * errback:(Function|undefined),
483 * fulfill: function(*), reject: function(*)}}
484 * @private
485 */
486webdriver.promise.Deferred.Listener_;
487
488
489/**
490 * The three states a {@link webdriver.promise.Deferred} object may be in.
491 * @enum {number}
492 * @private
493 */
494webdriver.promise.Deferred.State_ = {
495 REJECTED: -1,
496 PENDING: 0,
497 BLOCKED: 1,
498 RESOLVED: 2
499};
500
501
502/**
503 * Tests if a value is an Error-like object. This is more than an straight
504 * instanceof check since the value may originate from another context.
505 * @param {*} value The value to test.
506 * @return {boolean} Whether the value is an error.
507 * @private
508 */
509webdriver.promise.isError_ = function(value) {
510 return value instanceof Error ||
511 goog.isObject(value) &&
512 (Object.prototype.toString.call(value) === '[object Error]' ||
513 // A special test for goog.testing.JsUnitException.
514 value.isJsUnitException);
515
516};
517
518
519/**
520 * Determines whether a {@code value} should be treated as a promise.
521 * Any object whose "then" property is a function will be considered a promise.
522 *
523 * @param {*} value The value to test.
524 * @return {boolean} Whether the value is a promise.
525 */
526webdriver.promise.isPromise = function(value) {
527 return !!value && goog.isObject(value) &&
528 // Use array notation so the Closure compiler does not obfuscate away our
529 // contract.
530 goog.isFunction(value['then']);
531};
532
533
534/**
535 * Creates a promise that will be resolved at a set time in the future.
536 * @param {number} ms The amount of time, in milliseconds, to wait before
537 * resolving the promise.
538 * @return {!webdriver.promise.Promise} The promise.
539 */
540webdriver.promise.delayed = function(ms) {
541 var timer = webdriver.promise.controlFlow().timer;
542 var key;
543 var deferred = new webdriver.promise.Deferred(function() {
544 timer.clearTimeout(key);
545 });
546 key = timer.setTimeout(deferred.fulfill, ms);
547 return deferred.promise;
548};
549
550
551/**
552 * Creates a new deferred object.
553 * @param {Function=} opt_canceller Function to call when cancelling the
554 * computation of this instance's value.
555 * @return {!webdriver.promise.Deferred.<T>} The new deferred object.
556 * @template T
557 */
558webdriver.promise.defer = function(opt_canceller) {
559 return new webdriver.promise.Deferred(opt_canceller);
560};
561
562
563/**
564 * Creates a promise that has been resolved with the given value.
565 * @param {T=} opt_value The resolved value.
566 * @return {!webdriver.promise.Promise.<T>} The resolved promise.
567 * @template T
568 */
569webdriver.promise.fulfilled = function(opt_value) {
570 if (opt_value instanceof webdriver.promise.Promise) {
571 return opt_value;
572 }
573 var deferred = new webdriver.promise.Deferred();
574 deferred.fulfill(opt_value);
575 return deferred.promise;
576};
577
578
579/**
580 * Creates a promise that has been rejected with the given reason.
581 * @param {*=} opt_reason The rejection reason; may be any value, but is
582 * usually an Error or a string.
583 * @return {!webdriver.promise.Promise.<T>} The rejected promise.
584 * @template T
585 */
586webdriver.promise.rejected = function(opt_reason) {
587 var deferred = new webdriver.promise.Deferred();
588 deferred.reject(opt_reason);
589 return deferred.promise;
590};
591
592
593/**
594 * Wraps a function that is assumed to be a node-style callback as its final
595 * argument. This callback takes two arguments: an error value (which will be
596 * null if the call succeeded), and the success value as the second argument.
597 * If the call fails, the returned promise will be rejected, otherwise it will
598 * be resolved with the result.
599 * @param {!Function} fn The function to wrap.
600 * @return {!webdriver.promise.Promise} A promise that will be resolved with the
601 * result of the provided function's callback.
602 */
603webdriver.promise.checkedNodeCall = function(fn) {
604 var deferred = new webdriver.promise.Deferred(function() {
605 throw Error('This Deferred may not be cancelled');
606 });
607 try {
608 fn(function(error, value) {
609 error ? deferred.reject(error) : deferred.fulfill(value);
610 });
611 } catch (ex) {
612 deferred.reject(ex);
613 }
614 return deferred.promise;
615};
616
617
618/**
619 * Registers an observer on a promised {@code value}, returning a new promise
620 * that will be resolved when the value is. If {@code value} is not a promise,
621 * then the return promise will be immediately resolved.
622 * @param {*} value The value to observe.
623 * @param {Function=} opt_callback The function to call when the value is
624 * resolved successfully.
625 * @param {Function=} opt_errback The function to call when the value is
626 * rejected.
627 * @return {!webdriver.promise.Promise} A new promise.
628 */
629webdriver.promise.when = function(value, opt_callback, opt_errback) {
630 if (value instanceof webdriver.promise.Promise) {
631 return value.then(opt_callback, opt_errback);
632 }
633
634 var deferred = new webdriver.promise.Deferred();
635
636 webdriver.promise.asap(value, deferred.fulfill, deferred.reject);
637
638 return deferred.then(opt_callback, opt_errback);
639};
640
641
642/**
643 * Invokes the appropriate callback function as soon as a promised
644 * {@code value} is resolved. This function is similar to
645 * {@link webdriver.promise.when}, except it does not return a new promise.
646 * @param {*} value The value to observe.
647 * @param {Function} callback The function to call when the value is
648 * resolved successfully.
649 * @param {Function=} opt_errback The function to call when the value is
650 * rejected.
651 */
652webdriver.promise.asap = function(value, callback, opt_errback) {
653 if (webdriver.promise.isPromise(value)) {
654 value.then(callback, opt_errback);
655
656 // Maybe a Dojo-like deferred object?
657 } else if (!!value && goog.isObject(value) &&
658 goog.isFunction(value.addCallbacks)) {
659 value.addCallbacks(callback, opt_errback);
660
661 // A raw value, return a resolved promise.
662 } else if (callback) {
663 callback(value);
664 }
665};
666
667
668/**
669 * Given an array of promises, will return a promise that will be fulfilled
670 * with the fulfillment values of the input array's values. If any of the
671 * input array's promises are rejected, the returned promise will be rejected
672 * with the same reason.
673 *
674 * @param {!Array.<(T|!webdriver.promise.Promise.<T>)>} arr An array of
675 * promises to wait on.
676 * @return {!webdriver.promise.Promise.<!Array.<T>>} A promise that is
677 * fulfilled with an array containing the fulfilled values of the
678 * input array, or rejected with the same reason as the first
679 * rejected value.
680 * @template T
681 */
682webdriver.promise.all = function(arr) {
683 var n = arr.length;
684 if (!n) {
685 return webdriver.promise.fulfilled([]);
686 }
687
688 var toFulfill = n;
689 var result = webdriver.promise.defer();
690 var values = [];
691
692 var onFulfill = function(index, value) {
693 values[index] = value;
694 toFulfill--;
695 if (toFulfill == 0) {
696 result.fulfill(values);
697 }
698 };
699
700 for (var i = 0; i < n; ++i) {
701 webdriver.promise.asap(
702 arr[i], goog.partial(onFulfill, i), result.reject);
703 }
704
705 return result.promise;
706};
707
708
709/**
710 * Calls a function for each element in an array and inserts the result into a
711 * new array, which is used as the fulfillment value of the promise returned
712 * by this function.
713 *
714 * <p>If the return value of the mapping function is a promise, this function
715 * will wait for it to be fulfilled before inserting it into the new array.
716 *
717 * <p>If the mapping function throws or returns a rejected promise, the
718 * promise returned by this function will be rejected with the same reason.
719 * Only the first failure will be reported; all subsequent errors will be
720 * silently ignored.
721 *
722 * @param {!(Array.<TYPE>|webdriver.promise.Promise.<!Array.<TYPE>>)} arr The
723 * array to iterator over, or a promise that will resolve to said array.
724 * @param {function(this: SELF, TYPE, number, !Array.<TYPE>): ?} fn The
725 * function to call for each element in the array. This function should
726 * expect three arguments (the element, the index, and the array itself.
727 * @param {SELF=} opt_self The object to be used as the value of 'this' within
728 * {@code fn}.
729 * @template TYPE, SELF
730 */
731webdriver.promise.map = function(arr, fn, opt_self) {
732 return webdriver.promise.when(arr, function(arr) {
733 var result = goog.array.map(arr, fn, opt_self);
734 return webdriver.promise.all(result);
735 });
736};
737
738
739/**
740 * Calls a function for each element in an array, and if the function returns
741 * true adds the element to a new array.
742 *
743 * <p>If the return value of the filter function is a promise, this function
744 * will wait for it to be fulfilled before determining whether to insert the
745 * element into the new array.
746 *
747 * <p>If the filter function throws or returns a rejected promise, the promise
748 * returned by this function will be rejected with the same reason. Only the
749 * first failure will be reported; all subsequent errors will be silently
750 * ignored.
751 *
752 * @param {!(Array.<TYPE>|webdriver.promise.Promise.<!Array.<TYPE>>)} arr The
753 * array to iterator over, or a promise that will resolve to said array.
754 * @param {function(this: SELF, TYPE, number, !Array.<TYPE>): (
755 * boolean|webdriver.promise.Promise.<boolean>)} fn The function
756 * to call for each element in the array.
757 * @param {SELF=} opt_self The object to be used as the value of 'this' within
758 * {@code fn}.
759 * @template TYPE, SELF
760 */
761webdriver.promise.filter = function(arr, fn, opt_self) {
762 return webdriver.promise.when(arr, function(arr) {
763 var originalValues = goog.array.clone(arr);
764 return webdriver.promise.map(arr, fn, opt_self).then(function(include) {
765 return goog.array.filter(originalValues, function(value, index) {
766 return include[index];
767 });
768 });
769 });
770};
771
772
773/**
774 * Returns a promise that will be resolved with the input value in a
775 * fully-resolved state. If the value is an array, each element will be fully
776 * resolved. Likewise, if the value is an object, all keys will be fully
777 * resolved. In both cases, all nested arrays and objects will also be
778 * fully resolved. All fields are resolved in place; the returned promise will
779 * resolve on {@code value} and not a copy.
780 *
781 * Warning: This function makes no checks against objects that contain
782 * cyclical references:
783 * <pre><code>
784 * var value = {};
785 * value['self'] = value;
786 * webdriver.promise.fullyResolved(value); // Stack overflow.
787 * </code></pre>
788 *
789 * @param {*} value The value to fully resolve.
790 * @return {!webdriver.promise.Promise} A promise for a fully resolved version
791 * of the input value.
792 */
793webdriver.promise.fullyResolved = function(value) {
794 if (webdriver.promise.isPromise(value)) {
795 return webdriver.promise.when(value, webdriver.promise.fullyResolveValue_);
796 }
797 return webdriver.promise.fullyResolveValue_(value);
798};
799
800
801/**
802 * @param {*} value The value to fully resolve. If a promise, assumed to
803 * already be resolved.
804 * @return {!webdriver.promise.Promise} A promise for a fully resolved version
805 * of the input value.
806 * @private
807 */
808webdriver.promise.fullyResolveValue_ = function(value) {
809 switch (goog.typeOf(value)) {
810 case 'array':
811 return webdriver.promise.fullyResolveKeys_(
812 /** @type {!Array} */ (value));
813
814 case 'object':
815 if (webdriver.promise.isPromise(value)) {
816 // We get here when the original input value is a promise that
817 // resolves to itself. When the user provides us with such a promise,
818 // trust that it counts as a "fully resolved" value and return it.
819 // Of course, since it's already a promise, we can just return it
820 // to the user instead of wrapping it in another promise.
821 return /** @type {!webdriver.promise.Promise} */ (value);
822 }
823
824 if (goog.isNumber(value.nodeType) &&
825 goog.isObject(value.ownerDocument) &&
826 goog.isNumber(value.ownerDocument.nodeType)) {
827 // DOM node; return early to avoid infinite recursion. Should we
828 // only support objects with a certain level of nesting?
829 return webdriver.promise.fulfilled(value);
830 }
831
832 return webdriver.promise.fullyResolveKeys_(
833 /** @type {!Object} */ (value));
834
835 default: // boolean, function, null, number, string, undefined
836 return webdriver.promise.fulfilled(value);
837 }
838};
839
840
841/**
842 * @param {!(Array|Object)} obj the object to resolve.
843 * @return {!webdriver.promise.Promise} A promise that will be resolved with the
844 * input object once all of its values have been fully resolved.
845 * @private
846 */
847webdriver.promise.fullyResolveKeys_ = function(obj) {
848 var isArray = goog.isArray(obj);
849 var numKeys = isArray ? obj.length : goog.object.getCount(obj);
850 if (!numKeys) {
851 return webdriver.promise.fulfilled(obj);
852 }
853
854 var numResolved = 0;
855 var deferred = new webdriver.promise.Deferred();
856
857 // In pre-IE9, goog.array.forEach will not iterate properly over arrays
858 // containing undefined values because "index in array" returns false
859 // when array[index] === undefined (even for x = [undefined, 1]). To get
860 // around this, we need to use our own forEach implementation.
861 // DO NOT REMOVE THIS UNTIL WE NO LONGER SUPPORT IE8. This cannot be
862 // reproduced in IE9 by changing the browser/document modes, it requires an
863 // actual pre-IE9 browser. Yay, IE!
864 var forEachKey = !isArray ? goog.object.forEach : function(arr, fn) {
865 var n = arr.length;
866 for (var i = 0; i < n; ++i) {
867 fn.call(null, arr[i], i, arr);
868 }
869 };
870
871 forEachKey(obj, function(partialValue, key) {
872 var type = goog.typeOf(partialValue);
873 if (type != 'array' && type != 'object') {
874 maybeResolveValue();
875 return;
876 }
877
878 webdriver.promise.fullyResolved(partialValue).then(
879 function(resolvedValue) {
880 obj[key] = resolvedValue;
881 maybeResolveValue();
882 },
883 deferred.reject);
884 });
885
886 return deferred.promise;
887
888 function maybeResolveValue() {
889 if (++numResolved == numKeys) {
890 deferred.fulfill(obj);
891 }
892 }
893};
894
895
896//////////////////////////////////////////////////////////////////////////////
897//
898// webdriver.promise.ControlFlow
899//
900//////////////////////////////////////////////////////////////////////////////
901
902
903
904/**
905 * Handles the execution of scheduled tasks, each of which may be an
906 * asynchronous operation. The control flow will ensure tasks are executed in
907 * the ordered scheduled, starting each task only once those before it have
908 * completed.
909 *
910 * <p>Each task scheduled within this flow may return a
911 * {@link webdriver.promise.Promise} to indicate it is an asynchronous
912 * operation. The ControlFlow will wait for such promises to be resolved before
913 * marking the task as completed.
914 *
915 * <p>Tasks and each callback registered on a {@link webdriver.promise.Deferred}
916 * will be run in their own ControlFlow frame. Any tasks scheduled within a
917 * frame will have priority over previously scheduled tasks. Furthermore, if
918 * any of the tasks in the frame fails, the remainder of the tasks in that frame
919 * will be discarded and the failure will be propagated to the user through the
920 * callback/task's promised result.
921 *
922 * <p>Each time a ControlFlow empties its task queue, it will fire an
923 * {@link webdriver.promise.ControlFlow.EventType.IDLE} event. Conversely,
924 * whenever the flow terminates due to an unhandled error, it will remove all
925 * remaining tasks in its queue and fire an
926 * {@link webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION} event. If
927 * there are no listeners registered with the flow, the error will be
928 * rethrown to the global error handler.
929 *
930 * @param {webdriver.promise.ControlFlow.Timer=} opt_timer The timer object
931 * to use. Should only be set for testing.
932 * @constructor
933 * @extends {webdriver.EventEmitter}
934 */
935webdriver.promise.ControlFlow = function(opt_timer) {
936 webdriver.EventEmitter.call(this);
937
938 /**
939 * The timer used by this instance.
940 * @type {webdriver.promise.ControlFlow.Timer}
941 */
942 this.timer = opt_timer || webdriver.promise.ControlFlow.defaultTimer;
943
944 /**
945 * A list of recent tasks. Each time a new task is started, or a frame is
946 * completed, the previously recorded task is removed from this list. If
947 * there are multiple tasks, task N+1 is considered a sub-task of task
948 * N.
949 * @private {!Array.<!webdriver.promise.Task_>}
950 */
951 this.history_ = [];
952};
953goog.inherits(webdriver.promise.ControlFlow, webdriver.EventEmitter);
954
955
956/**
957 * @typedef {{clearInterval: function(number),
958 * clearTimeout: function(number),
959 * setInterval: function(!Function, number): number,
960 * setTimeout: function(!Function, number): number}}
961 */
962webdriver.promise.ControlFlow.Timer;
963
964
965/**
966 * The default timer object, which uses the global timer functions.
967 * @type {webdriver.promise.ControlFlow.Timer}
968 */
969webdriver.promise.ControlFlow.defaultTimer = (function() {
970 // The default timer functions may be defined as free variables for the
971 // current context, so do not reference them using "window" or
972 // "goog.global". Also, we must invoke them in a closure, and not using
973 // bind(), so we do not get "TypeError: Illegal invocation" (WebKit) or
974 // "Invalid calling object" (IE) errors.
975 return {
976 clearInterval: wrap(clearInterval),
977 clearTimeout: wrap(clearTimeout),
978 setInterval: wrap(setInterval),
979 setTimeout: wrap(setTimeout)
980 };
981
982 function wrap(fn) {
983 return function() {
984 // Cannot use .call() or .apply() since we do not know which variable
985 // the function is bound to, and using the wrong one will generate
986 // an error.
987 return fn(arguments[0], arguments[1]);
988 };
989 }
990})();
991
992
993/**
994 * Events that may be emitted by an {@link webdriver.promise.ControlFlow}.
995 * @enum {string}
996 */
997webdriver.promise.ControlFlow.EventType = {
998
999 /** Emitted when all tasks have been successfully executed. */
1000 IDLE: 'idle',
1001
1002 /** Emitted whenever a new task has been scheduled. */
1003 SCHEDULE_TASK: 'scheduleTask',
1004
1005 /**
1006 * Emitted whenever a control flow aborts due to an unhandled promise
1007 * rejection. This event will be emitted along with the offending rejection
1008 * reason. Upon emitting this event, the control flow will empty its task
1009 * queue and revert to its initial state.
1010 */
1011 UNCAUGHT_EXCEPTION: 'uncaughtException'
1012};
1013
1014
1015/**
1016 * How often, in milliseconds, the event loop should run.
1017 * @type {number}
1018 * @const
1019 */
1020webdriver.promise.ControlFlow.EVENT_LOOP_FREQUENCY = 10;
1021
1022
1023/**
1024 * Tracks the active execution frame for this instance. Lazily initialized
1025 * when the first task is scheduled.
1026 * @private {webdriver.promise.Frame_}
1027 */
1028webdriver.promise.ControlFlow.prototype.activeFrame_ = null;
1029
1030
1031/**
1032 * A reference to the frame in which new tasks should be scheduled. If
1033 * {@code null}, tasks will be scheduled within the active frame. When forcing
1034 * a function to run in the context of a new frame, this pointer is used to
1035 * ensure tasks are scheduled within the newly created frame, even though it
1036 * won't be active yet.
1037 * @private {webdriver.promise.Frame_}
1038 * @see {#runInNewFrame_}
1039 */
1040webdriver.promise.ControlFlow.prototype.schedulingFrame_ = null;
1041
1042
1043/**
1044 * Timeout ID set when the flow is about to shutdown without any errors
1045 * being detected. Upon shutting down, the flow will emit an
1046 * {@link webdriver.promise.ControlFlow.EventType.IDLE} event. Idle events
1047 * always follow a brief timeout in order to catch latent errors from the last
1048 * completed task. If this task had a callback registered, but no errback, and
1049 * the task fails, the unhandled failure would not be reported by the promise
1050 * system until the next turn of the event loop:
1051 *
1052 * // Schedule 1 task that fails.
1053 * var result = webriver.promise.controlFlow().schedule('example',
1054 * function() { return webdriver.promise.rejected('failed'); });
1055 * // Set a callback on the result. This delays reporting the unhandled
1056 * // failure for 1 turn of the event loop.
1057 * result.then(goog.nullFunction);
1058 *
1059 * @private {?number}
1060 */
1061webdriver.promise.ControlFlow.prototype.shutdownId_ = null;
1062
1063
1064/**
1065 * Interval ID for this instance's event loop.
1066 * @private {?number}
1067 */
1068webdriver.promise.ControlFlow.prototype.eventLoopId_ = null;
1069
1070
1071/**
1072 * The number of "pending" promise rejections.
1073 *
1074 * <p>Each time a promise is rejected and is not handled by a listener, it will
1075 * schedule a 0-based timeout to check if it is still unrejected in the next
1076 * turn of the JS-event loop. This allows listeners to attach to, and handle,
1077 * the rejected promise at any point in same turn of the event loop that the
1078 * promise was rejected.
1079 *
1080 * <p>When this flow's own event loop triggers, it will not run if there
1081 * are any outstanding promise rejections. This allows unhandled promises to
1082 * be reported before a new task is started, ensuring the error is reported to
1083 * the current task queue.
1084 *
1085 * @private {number}
1086 */
1087webdriver.promise.ControlFlow.prototype.pendingRejections_ = 0;
1088
1089
1090/**
1091 * The number of aborted frames since the last time a task was executed or a
1092 * frame completed successfully.
1093 * @private {number}
1094 */
1095webdriver.promise.ControlFlow.prototype.numAbortedFrames_ = 0;
1096
1097
1098/**
1099 * Resets this instance, clearing its queue and removing all event listeners.
1100 */
1101webdriver.promise.ControlFlow.prototype.reset = function() {
1102 this.activeFrame_ = null;
1103 this.clearHistory();
1104 this.removeAllListeners();
1105 this.cancelShutdown_();
1106 this.cancelEventLoop_();
1107};
1108
1109
1110/**
1111 * Returns a summary of the recent task activity for this instance. This
1112 * includes the most recently completed task, as well as any parent tasks. In
1113 * the returned summary, the task at index N is considered a sub-task of the
1114 * task at index N+1.
1115 * @return {!Array.<string>} A summary of this instance's recent task
1116 * activity.
1117 */
1118webdriver.promise.ControlFlow.prototype.getHistory = function() {
1119 var pendingTasks = [];
1120 var currentFrame = this.activeFrame_;
1121 while (currentFrame) {
1122 var task = currentFrame.getPendingTask();
1123 if (task) {
1124 pendingTasks.push(task);
1125 }
1126 // A frame's parent node will always be another frame.
1127 currentFrame =
1128 /** @type {webdriver.promise.Frame_} */ (currentFrame.getParent());
1129 }
1130
1131 var fullHistory = goog.array.concat(this.history_, pendingTasks);
1132 return goog.array.map(fullHistory, function(task) {
1133 return task.toString();
1134 });
1135};
1136
1137
1138/** Clears this instance's task history. */
1139webdriver.promise.ControlFlow.prototype.clearHistory = function() {
1140 this.history_ = [];
1141};
1142
1143
1144/**
1145 * Removes a completed task from this instance's history record. If any
1146 * tasks remain from aborted frames, those will be removed as well.
1147 * @private
1148 */
1149webdriver.promise.ControlFlow.prototype.trimHistory_ = function() {
1150 if (this.numAbortedFrames_) {
1151 goog.array.splice(this.history_,
1152 this.history_.length - this.numAbortedFrames_,
1153 this.numAbortedFrames_);
1154 this.numAbortedFrames_ = 0;
1155 }
1156 this.history_.pop();
1157};
1158
1159
1160/**
1161 * Property used to track whether an error has been annotated by
1162 * {@link webdriver.promise.ControlFlow#annotateError}.
1163 * @private {string}
1164 * @const
1165 */
1166webdriver.promise.ControlFlow.ANNOTATION_PROPERTY_ =
1167 'webdriver_promise_error_';
1168
1169
1170/**
1171 * Appends a summary of this instance's recent task history to the given
1172 * error's stack trace. This function will also ensure the error's stack trace
1173 * is in canonical form.
1174 * @param {!(Error|goog.testing.JsUnitException)} e The error to annotate.
1175 * @return {!(Error|goog.testing.JsUnitException)} The annotated error.
1176 */
1177webdriver.promise.ControlFlow.prototype.annotateError = function(e) {
1178 if (!!e[webdriver.promise.ControlFlow.ANNOTATION_PROPERTY_]) {
1179 return e;
1180 }
1181
1182 var history = this.getHistory();
1183 if (history.length) {
1184 e = webdriver.stacktrace.format(e);
1185
1186 /** @type {!Error} */(e).stack += [
1187 '\n==== async task ====\n',
1188 history.join('\n==== async task ====\n')
1189 ].join('');
1190
1191 e[webdriver.promise.ControlFlow.ANNOTATION_PROPERTY_] = true;
1192 }
1193
1194 return e;
1195};
1196
1197
1198/**
1199 * @return {string} The scheduled tasks still pending with this instance.
1200 */
1201webdriver.promise.ControlFlow.prototype.getSchedule = function() {
1202 return this.activeFrame_ ? this.activeFrame_.getRoot().toString() : '[]';
1203};
1204
1205
1206/**
1207 * Schedules a task for execution. If there is nothing currently in the
1208 * queue, the task will be executed in the next turn of the event loop.
1209 *
1210 * @param {function(): (T|webdriver.promise.Promise.<T>)} fn The function to
1211 * call to start the task. If the function returns a
1212 * {@link webdriver.promise.Promise}, this instance will wait for it to be
1213 * resolved before starting the next task.
1214 * @param {string=} opt_description A description of the task.
1215 * @return {!webdriver.promise.Promise.<T>} A promise that will be resolved
1216 * with the result of the action.
1217 * @template T
1218 */
1219webdriver.promise.ControlFlow.prototype.execute = function(
1220 fn, opt_description) {
1221 this.cancelShutdown_();
1222
1223 if (!this.activeFrame_) {
1224 this.activeFrame_ = new webdriver.promise.Frame_(this);
1225 }
1226
1227 // Trim an extra frame off the generated stack trace for the call to this
1228 // function.
1229 var snapshot = new webdriver.stacktrace.Snapshot(1);
1230 var task = new webdriver.promise.Task_(
1231 this, fn, opt_description || '', snapshot);
1232 var scheduleIn = this.schedulingFrame_ || this.activeFrame_;
1233 scheduleIn.addChild(task);
1234
1235 this.emit(webdriver.promise.ControlFlow.EventType.SCHEDULE_TASK, opt_description);
1236
1237 this.scheduleEventLoopStart_();
1238 return task.promise;
1239};
1240
1241
1242/**
1243 * Inserts a {@code setTimeout} into the command queue. This is equivalent to
1244 * a thread sleep in a synchronous programming language.
1245 *
1246 * @param {number} ms The timeout delay, in milliseconds.
1247 * @param {string=} opt_description A description to accompany the timeout.
1248 * @return {!webdriver.promise.Promise} A promise that will be resolved with
1249 * the result of the action.
1250 */
1251webdriver.promise.ControlFlow.prototype.timeout = function(
1252 ms, opt_description) {
1253 return this.execute(function() {
1254 return webdriver.promise.delayed(ms);
1255 }, opt_description);
1256};
1257
1258
1259/**
1260 * Schedules a task that shall wait for a condition to hold. Each condition
1261 * function may return any value, but it will always be evaluated as a boolean.
1262 *
1263 * <p>Condition functions may schedule sub-tasks with this instance, however,
1264 * their execution time will be factored into whether a wait has timed out.
1265 *
1266 * <p>In the event a condition returns a Promise, the polling loop will wait for
1267 * it to be resolved before evaluating whether the condition has been satisfied.
1268 * The resolution time for a promise is factored into whether a wait has timed
1269 * out.
1270 *
1271 * <p>If the condition function throws, or returns a rejected promise, the
1272 * wait task will fail.
1273 *
1274 * @param {!Function} condition The condition function to poll.
1275 * @param {number} timeout How long to wait, in milliseconds, for the condition
1276 * to hold before timing out.
1277 * @param {string=} opt_message An optional error message to include if the
1278 * wait times out; defaults to the empty string.
1279 * @return {!webdriver.promise.Promise} A promise that will be resolved when the
1280 * condition has been satisified. The promise shall be rejected if the wait
1281 * times out waiting for the condition.
1282 */
1283webdriver.promise.ControlFlow.prototype.wait = function(
1284 condition, timeout, opt_message) {
1285 var sleep = Math.min(timeout, 100);
1286 var self = this;
1287
1288 return this.execute(function() {
1289 var startTime = goog.now();
1290 var waitResult = new webdriver.promise.Deferred();
1291 var waitFrame = self.activeFrame_;
1292 waitFrame.isWaiting = true;
1293 pollCondition();
1294 return waitResult.promise;
1295
1296 function pollCondition() {
1297 self.runInNewFrame_(condition, function(value) {
1298 var elapsed = goog.now() - startTime;
1299 if (!!value) {
1300 waitFrame.isWaiting = false;
1301 waitResult.fulfill(value);
1302 } else if (elapsed >= timeout) {
1303 waitResult.reject(new Error((opt_message ? opt_message + '\n' : '') +
1304 'Wait timed out after ' + elapsed + 'ms'));
1305 } else {
1306 self.timer.setTimeout(pollCondition, sleep);
1307 }
1308 }, waitResult.reject, true);
1309 }
1310 }, opt_message);
1311};
1312
1313
1314/**
1315 * Schedules a task that will wait for another promise to resolve. The resolved
1316 * promise's value will be returned as the task result.
1317 * @param {!webdriver.promise.Promise} promise The promise to wait on.
1318 * @return {!webdriver.promise.Promise} A promise that will resolve when the
1319 * task has completed.
1320 */
1321webdriver.promise.ControlFlow.prototype.await = function(promise) {
1322 return this.execute(function() {
1323 return promise;
1324 });
1325};
1326
1327
1328/**
1329 * Schedules the interval for this instance's event loop, if necessary.
1330 * @private
1331 */
1332webdriver.promise.ControlFlow.prototype.scheduleEventLoopStart_ = function() {
1333 if (!this.eventLoopId_) {
1334 this.eventLoopId_ = this.timer.setInterval(
1335 goog.bind(this.runEventLoop_, this),
1336 webdriver.promise.ControlFlow.EVENT_LOOP_FREQUENCY);
1337 }
1338};
1339
1340
1341/**
1342 * Cancels the event loop, if necessary.
1343 * @private
1344 */
1345webdriver.promise.ControlFlow.prototype.cancelEventLoop_ = function() {
1346 if (this.eventLoopId_) {
1347 this.timer.clearInterval(this.eventLoopId_);
1348 this.eventLoopId_ = null;
1349 }
1350};
1351
1352
1353/**
1354 * Executes the next task for the current frame. If the current frame has no
1355 * more tasks, the frame's result will be resolved, returning control to the
1356 * frame's creator. This will terminate the flow if the completed frame was at
1357 * the top of the stack.
1358 * @private
1359 */
1360webdriver.promise.ControlFlow.prototype.runEventLoop_ = function() {
1361 // If we get here and there are pending promise rejections, then those
1362 // promises are queued up to run as soon as this (JS) event loop terminates.
1363 // Short-circuit our loop to give those promises a chance to run. Otherwise,
1364 // we might start a new task only to have it fail because of one of these
1365 // pending rejections.
1366 if (this.pendingRejections_) {
1367 return;
1368 }
1369
1370 // If the flow aborts due to an unhandled exception after we've scheduled
1371 // another turn of the execution loop, we can end up in here with no tasks
1372 // left. This is OK, just quietly return.
1373 if (!this.activeFrame_) {
1374 this.commenceShutdown_();
1375 return;
1376 }
1377
1378 var task;
1379 if (this.activeFrame_.getPendingTask() || !(task = this.getNextTask_())) {
1380 // Either the current frame is blocked on a pending task, or we don't have
1381 // a task to finish because we've completed a frame. When completing a
1382 // frame, we must abort the event loop to allow the frame's promise's
1383 // callbacks to execute.
1384 return;
1385 }
1386
1387 var activeFrame = this.activeFrame_;
1388 activeFrame.setPendingTask(task);
1389 var markTaskComplete = goog.bind(function() {
1390 this.history_.push(/** @type {!webdriver.promise.Task_} */ (task));
1391 activeFrame.setPendingTask(null);
1392 }, this);
1393
1394 this.trimHistory_();
1395 var self = this;
1396 this.runInNewFrame_(task.execute, function(result) {
1397 markTaskComplete();
1398 task.fulfill(result);
1399 }, function(error) {
1400 markTaskComplete();
1401
1402 if (!webdriver.promise.isError_(error) &&
1403 !webdriver.promise.isPromise(error)) {
1404 error = Error(error);
1405 }
1406
1407 task.reject(self.annotateError(/** @type {!Error} */ (error)));
1408 }, true);
1409};
1410
1411
1412/**
1413 * @return {webdriver.promise.Task_} The next task to execute, or
1414 * {@code null} if a frame was resolved.
1415 * @private
1416 */
1417webdriver.promise.ControlFlow.prototype.getNextTask_ = function() {
1418 var firstChild = this.activeFrame_.getFirstChild();
1419 if (!firstChild) {
1420 if (!this.activeFrame_.isWaiting) {
1421 this.resolveFrame_(this.activeFrame_);
1422 }
1423 return null;
1424 }
1425
1426 if (firstChild instanceof webdriver.promise.Frame_) {
1427 this.activeFrame_ = firstChild;
1428 return this.getNextTask_();
1429 }
1430
1431 firstChild.getParent().removeChild(firstChild);
1432 return firstChild;
1433};
1434
1435
1436/**
1437 * @param {!webdriver.promise.Frame_} frame The frame to resolve.
1438 * @private
1439 */
1440webdriver.promise.ControlFlow.prototype.resolveFrame_ = function(frame) {
1441 if (this.activeFrame_ === frame) {
1442 // Frame parent is always another frame, but the compiler is not smart
1443 // enough to recognize this.
1444 this.activeFrame_ =
1445 /** @type {webdriver.promise.Frame_} */ (frame.getParent());
1446 }
1447
1448 if (frame.getParent()) {
1449 frame.getParent().removeChild(frame);
1450 }
1451 this.trimHistory_();
1452 frame.fulfill();
1453
1454 if (!this.activeFrame_) {
1455 this.commenceShutdown_();
1456 }
1457};
1458
1459
1460/**
1461 * Aborts the current frame. The frame, and all of the tasks scheduled within it
1462 * will be discarded. If this instance does not have an active frame, it will
1463 * immediately terminate all execution.
1464 * @param {*} error The reason the frame is being aborted; typically either
1465 * an Error or string.
1466 * @private
1467 */
1468webdriver.promise.ControlFlow.prototype.abortFrame_ = function(error) {
1469 // Annotate the error value if it is Error-like.
1470 if (webdriver.promise.isError_(error)) {
1471 this.annotateError(/** @type {!Error} */ (error));
1472 }
1473 this.numAbortedFrames_++;
1474
1475 if (!this.activeFrame_) {
1476 this.abortNow_(error);
1477 return;
1478 }
1479
1480 // Frame parent is always another frame, but the compiler is not smart
1481 // enough to recognize this.
1482 var parent = /** @type {webdriver.promise.Frame_} */ (
1483 this.activeFrame_.getParent());
1484 if (parent) {
1485 parent.removeChild(this.activeFrame_);
1486 }
1487
1488 var frame = this.activeFrame_;
1489 this.activeFrame_ = parent;
1490 frame.reject(error);
1491};
1492
1493
1494/**
1495 * Executes a function in a new frame. If the function does not schedule any new
1496 * tasks, the frame will be discarded and the function's result returned
1497 * immediately. Otherwise, a promise will be returned. This promise will be
1498 * resolved with the function's result once all of the tasks scheduled within
1499 * the function have been completed. If the function's frame is aborted, the
1500 * returned promise will be rejected.
1501 *
1502 * @param {!Function} fn The function to execute.
1503 * @param {function(*)} callback The function to call with a successful result.
1504 * @param {function(*)} errback The function to call if there is an error.
1505 * @param {boolean=} opt_activate Whether the active frame should be updated to
1506 * the newly created frame so tasks are treated as sub-tasks.
1507 * @private
1508 */
1509webdriver.promise.ControlFlow.prototype.runInNewFrame_ = function(
1510 fn, callback, errback, opt_activate) {
1511 var newFrame = new webdriver.promise.Frame_(this),
1512 self = this,
1513 oldFrame = this.activeFrame_;
1514
1515 try {
1516 if (!this.activeFrame_) {
1517 this.activeFrame_ = newFrame;
1518 } else {
1519 this.activeFrame_.addChild(newFrame);
1520 }
1521
1522 // Activate the new frame to force tasks to be treated as sub-tasks of
1523 // the parent frame.
1524 if (opt_activate) {
1525 this.activeFrame_ = newFrame;
1526 }
1527
1528 try {
1529 this.schedulingFrame_ = newFrame;
1530 webdriver.promise.pushFlow_(this);
1531 var result = fn();
1532 } finally {
1533 webdriver.promise.popFlow_();
1534 this.schedulingFrame_ = null;
1535 }
1536 newFrame.lockFrame();
1537
1538 // If there was nothing scheduled in the new frame we can discard the
1539 // frame and return immediately.
1540 if (!newFrame.children_.length) {
1541 removeNewFrame();
1542 webdriver.promise.asap(result, callback, errback);
1543 return;
1544 }
1545
1546 newFrame.then(function() {
1547 webdriver.promise.asap(result, callback, errback);
1548 }, function(e) {
1549 if (result instanceof webdriver.promise.Promise && result.isPending()) {
1550 result.cancel(e);
1551 e = result;
1552 }
1553 errback(e);
1554 });
1555 } catch (ex) {
1556 removeNewFrame(new webdriver.promise.CanceledTaskError_(ex));
1557 errback(ex);
1558 }
1559
1560 /**
1561 * @param {webdriver.promise.CanceledTaskError_=} opt_err If provided, the
1562 * error that triggered the removal of this frame.
1563 */
1564 function removeNewFrame(opt_err) {
1565 var parent = newFrame.getParent();
1566 if (parent) {
1567 parent.removeChild(newFrame);
1568 }
1569
1570 if (opt_err) {
1571 newFrame.cancelRemainingTasks(opt_err);
1572 }
1573 self.activeFrame_ = oldFrame;
1574 }
1575};
1576
1577
1578/**
1579 * Commences the shutdown sequence for this instance. After one turn of the
1580 * event loop, this object will emit the
1581 * {@link webdriver.promise.ControlFlow.EventType.IDLE} event to signal
1582 * listeners that it has completed. During this wait, if another task is
1583 * scheduled, the shutdown will be aborted.
1584 * @private
1585 */
1586webdriver.promise.ControlFlow.prototype.commenceShutdown_ = function() {
1587 if (!this.shutdownId_) {
1588 // Go ahead and stop the event loop now. If we're in here, then there are
1589 // no more frames with tasks to execute. If we waited to cancel the event
1590 // loop in our timeout below, the event loop could trigger *before* the
1591 // timeout, generating an error from there being no frames.
1592 // If #execute is called before the timeout below fires, it will cancel
1593 // the timeout and restart the event loop.
1594 this.cancelEventLoop_();
1595
1596 var self = this;
1597 self.shutdownId_ = self.timer.setTimeout(function() {
1598 self.shutdownId_ = null;
1599 self.emit(webdriver.promise.ControlFlow.EventType.IDLE);
1600 }, 0);
1601 }
1602};
1603
1604
1605/**
1606 * Cancels the shutdown sequence if it is currently scheduled.
1607 * @private
1608 */
1609webdriver.promise.ControlFlow.prototype.cancelShutdown_ = function() {
1610 if (this.shutdownId_) {
1611 this.timer.clearTimeout(this.shutdownId_);
1612 this.shutdownId_ = null;
1613 }
1614};
1615
1616
1617/**
1618 * Aborts this flow, abandoning all remaining tasks. If there are
1619 * listeners registered, an {@code UNCAUGHT_EXCEPTION} will be emitted with the
1620 * offending {@code error}, otherwise, the {@code error} will be rethrown to the
1621 * global error handler.
1622 * @param {*} error Object describing the error that caused the flow to
1623 * abort; usually either an Error or string value.
1624 * @private
1625 */
1626webdriver.promise.ControlFlow.prototype.abortNow_ = function(error) {
1627 this.activeFrame_ = null;
1628 this.cancelShutdown_();
1629 this.cancelEventLoop_();
1630
1631 var listeners = this.listeners(
1632 webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION);
1633 if (!listeners.length) {
1634 this.timer.setTimeout(function() {
1635 throw error;
1636 }, 0);
1637 } else {
1638 this.emit(webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION,
1639 error);
1640 }
1641};
1642
1643
1644
1645/**
1646 * A single node in an {@link webdriver.promise.ControlFlow}'s task tree.
1647 * @param {!webdriver.promise.ControlFlow} flow The flow this instance belongs
1648 * to.
1649 * @constructor
1650 * @extends {webdriver.promise.Deferred}
1651 * @private
1652 */
1653webdriver.promise.Node_ = function(flow) {
1654 webdriver.promise.Deferred.call(this, null, flow);
1655};
1656goog.inherits(webdriver.promise.Node_, webdriver.promise.Deferred);
1657
1658
1659/**
1660 * This node's parent.
1661 * @private {webdriver.promise.Node_}
1662 */
1663webdriver.promise.Node_.prototype.parent_ = null;
1664
1665
1666/** @return {webdriver.promise.Node_} This node's parent. */
1667webdriver.promise.Node_.prototype.getParent = function() {
1668 return this.parent_;
1669};
1670
1671
1672/**
1673 * @param {webdriver.promise.Node_} parent This node's new parent.
1674 */
1675webdriver.promise.Node_.prototype.setParent = function(parent) {
1676 this.parent_ = parent;
1677};
1678
1679
1680/**
1681 * @return {!webdriver.promise.Node_} The root of this node's tree.
1682 */
1683webdriver.promise.Node_.prototype.getRoot = function() {
1684 var root = this;
1685 while (root.parent_) {
1686 root = root.parent_;
1687 }
1688 return root;
1689};
1690
1691
1692
1693/**
1694 * An execution frame within a {@link webdriver.promise.ControlFlow}. Each
1695 * frame represents the execution context for either a
1696 * {@link webdriver.promise.Task_} or a callback on a
1697 * {@link webdriver.promise.Deferred}.
1698 *
1699 * <p>Each frame may contain sub-frames. If child N is a sub-frame, then the
1700 * items queued within it are given priority over child N+1.
1701 *
1702 * @param {!webdriver.promise.ControlFlow} flow The flow this instance belongs
1703 * to.
1704 * @constructor
1705 * @extends {webdriver.promise.Node_}
1706 * @private
1707 */
1708webdriver.promise.Frame_ = function(flow) {
1709 webdriver.promise.Node_.call(this, flow);
1710
1711 var reject = goog.bind(this.reject, this);
1712 var cancelRemainingTasks = goog.bind(this.cancelRemainingTasks, this);
1713
1714 /** @override */
1715 this.reject = function(e) {
1716 cancelRemainingTasks(new webdriver.promise.CanceledTaskError_(e));
1717 reject(e);
1718 };
1719
1720 /**
1721 * @private {!Array.<!(webdriver.promise.Frame_|webdriver.promise.Task_)>}
1722 */
1723 this.children_ = [];
1724};
1725goog.inherits(webdriver.promise.Frame_, webdriver.promise.Node_);
1726
1727
1728/**
1729 * The task currently being executed within this frame.
1730 * @private {webdriver.promise.Task_}
1731 */
1732webdriver.promise.Frame_.prototype.pendingTask_ = null;
1733
1734
1735/**
1736 * Whether this frame is active. A frame is considered active once one of its
1737 * descendants has been removed for execution.
1738 *
1739 * Adding a sub-frame as a child to an active frame is an indication that
1740 * a callback to a {@link webdriver.promise.Deferred} is being invoked and any
1741 * tasks scheduled within it should have priority over previously scheduled
1742 * tasks:
1743 * <code><pre>
1744 * var flow = webdriver.promise.controlFlow();
1745 * flow.execute('start here', goog.nullFunction).then(function() {
1746 * flow.execute('this should execute 2nd', goog.nullFunction);
1747 * });
1748 * flow.execute('this should execute last', goog.nullFunction);
1749 * </pre></code>
1750 *
1751 * @private {boolean}
1752 */
1753webdriver.promise.Frame_.prototype.isActive_ = false;
1754
1755
1756/**
1757 * Whether this frame is currently locked. A locked frame represents a callback
1758 * or task function which has run to completion and scheduled all of its tasks.
1759 *
1760 * <p>Once a frame becomes {@link #isActive_ active}, any new frames which are
1761 * added represent callbacks on a {@link webdriver.promise.Deferred}, whose
1762 * tasks must be given priority over previously scheduled tasks.
1763 *
1764 * @private {boolean}
1765 */
1766webdriver.promise.Frame_.prototype.isLocked_ = false;
1767
1768
1769/**
1770 * A reference to the last node inserted in this frame.
1771 * @private {webdriver.promise.Node_}
1772 */
1773webdriver.promise.Frame_.prototype.lastInsertedChild_ = null;
1774
1775
1776/**
1777 * Marks all of the tasks that are descendants of this frame in the execution
1778 * tree as cancelled. This is necessary for callbacks scheduled asynchronous.
1779 * For example:
1780 *
1781 * var someResult;
1782 * webdriver.promise.createFlow(function(flow) {
1783 * someResult = flow.execute(function() {});
1784 * throw Error();
1785 * }).addErrback(function(err) {
1786 * console.log('flow failed: ' + err);
1787 * someResult.then(function() {
1788 * console.log('task succeeded!');
1789 * }, function(err) {
1790 * console.log('task failed! ' + err);
1791 * });
1792 * });
1793 * // flow failed: Error: boom
1794 * // task failed! CanceledTaskError: Task discarded due to a previous
1795 * // task failure: Error: boom
1796 *
1797 * @param {!webdriver.promise.CanceledTaskError_} error The cancellation
1798 * error.
1799 */
1800webdriver.promise.Frame_.prototype.cancelRemainingTasks = function(error) {
1801 goog.array.forEach(this.children_, function(child) {
1802 if (child instanceof webdriver.promise.Frame_) {
1803 child.cancelRemainingTasks(error);
1804 } else {
1805 // None of the previously registered listeners should be notified that
1806 // the task is being canceled, however, we need at least one errback
1807 // to prevent the cancellation from bubbling up.
1808 child.removeAll();
1809 child.thenCatch(goog.nullFunction);
1810 child.cancel(error);
1811 }
1812 });
1813};
1814
1815
1816/**
1817 * @return {webdriver.promise.Task_} The task currently executing
1818 * within this frame, if any.
1819 */
1820webdriver.promise.Frame_.prototype.getPendingTask = function() {
1821 return this.pendingTask_;
1822};
1823
1824
1825/**
1826 * @param {webdriver.promise.Task_} task The task currently
1827 * executing within this frame, if any.
1828 */
1829webdriver.promise.Frame_.prototype.setPendingTask = function(task) {
1830 this.pendingTask_ = task;
1831};
1832
1833
1834/** Locks this frame. */
1835webdriver.promise.Frame_.prototype.lockFrame = function() {
1836 this.isLocked_ = true;
1837};
1838
1839
1840/**
1841 * Adds a new node to this frame.
1842 * @param {!(webdriver.promise.Frame_|webdriver.promise.Task_)} node
1843 * The node to insert.
1844 */
1845webdriver.promise.Frame_.prototype.addChild = function(node) {
1846 if (this.lastInsertedChild_ &&
1847 this.lastInsertedChild_ instanceof webdriver.promise.Frame_ &&
1848 !this.lastInsertedChild_.isLocked_) {
1849 this.lastInsertedChild_.addChild(node);
1850 return;
1851 }
1852
1853 node.setParent(this);
1854
1855 if (this.isActive_ && node instanceof webdriver.promise.Frame_) {
1856 var index = 0;
1857 if (this.lastInsertedChild_ instanceof
1858 webdriver.promise.Frame_) {
1859 index = goog.array.indexOf(this.children_, this.lastInsertedChild_) + 1;
1860 }
1861 goog.array.insertAt(this.children_, node, index);
1862 this.lastInsertedChild_ = node;
1863 return;
1864 }
1865
1866 this.lastInsertedChild_ = node;
1867 this.children_.push(node);
1868};
1869
1870
1871/**
1872 * @return {(webdriver.promise.Frame_|webdriver.promise.Task_)} This frame's
1873 * fist child.
1874 */
1875webdriver.promise.Frame_.prototype.getFirstChild = function() {
1876 this.isActive_ = true;
1877 this.lastInsertedChild_ = null;
1878 return this.children_[0];
1879};
1880
1881
1882/**
1883 * Removes a child from this frame.
1884 * @param {!(webdriver.promise.Frame_|webdriver.promise.Task_)} child
1885 * The child to remove.
1886 */
1887webdriver.promise.Frame_.prototype.removeChild = function(child) {
1888 var index = goog.array.indexOf(this.children_, child);
1889 child.setParent(null);
1890 goog.array.removeAt(this.children_, index);
1891 if (this.lastInsertedChild_ === child) {
1892 this.lastInsertedChild_ = null;
1893 }
1894};
1895
1896
1897/** @override */
1898webdriver.promise.Frame_.prototype.toString = function() {
1899 return '[' + goog.array.map(this.children_, function(child) {
1900 return child.toString();
1901 }).join(', ') + ']';
1902};
1903
1904
1905
1906/**
1907 * A task to be executed by a {@link webdriver.promise.ControlFlow}.
1908 *
1909 * @param {!webdriver.promise.ControlFlow} flow The flow this instances belongs
1910 * to.
1911 * @param {!Function} fn The function to call when the task executes. If it
1912 * returns a {@code webdriver.promise.Promise}, the flow will wait
1913 * for it to be resolved before starting the next task.
1914 * @param {string} description A description of the task for debugging.
1915 * @param {!webdriver.stacktrace.Snapshot} snapshot A snapshot of the stack
1916 * when this task was scheduled.
1917 * @constructor
1918 * @extends {webdriver.promise.Node_}
1919 * @private
1920 */
1921webdriver.promise.Task_ = function(flow, fn, description, snapshot) {
1922 webdriver.promise.Node_.call(this, flow);
1923
1924 /**
1925 * Executes this task.
1926 * @type {!Function}
1927 */
1928 this.execute = fn;
1929
1930 /** @private {string} */
1931 this.description_ = description;
1932
1933 /** @private {!webdriver.stacktrace.Snapshot} */
1934 this.snapshot_ = snapshot;
1935};
1936goog.inherits(webdriver.promise.Task_, webdriver.promise.Node_);
1937
1938
1939/** @return {string} This task's description. */
1940webdriver.promise.Task_.prototype.getDescription = function() {
1941 return this.description_;
1942};
1943
1944
1945/** @override */
1946webdriver.promise.Task_.prototype.toString = function() {
1947 var stack = this.snapshot_.getStacktrace();
1948 var ret = this.description_;
1949 if (stack.length) {
1950 if (this.description_) {
1951 ret += '\n';
1952 }
1953 ret += stack.join('\n');
1954 }
1955 return ret;
1956};
1957
1958
1959
1960/**
1961 * Special error used to signal when a task is canceled because a previous
1962 * task in the same frame failed.
1963 * @param {*} err The error that caused the task cancellation.
1964 * @constructor
1965 * @extends {goog.debug.Error}
1966 * @private
1967 */
1968webdriver.promise.CanceledTaskError_ = function(err) {
1969 goog.base(this, 'Task discarded due to a previous task failure: ' + err);
1970};
1971goog.inherits(webdriver.promise.CanceledTaskError_, goog.debug.Error);
1972
1973
1974/** @override */
1975webdriver.promise.CanceledTaskError_.prototype.name = 'CanceledTaskError';
1976
1977
1978
1979/**
1980 * The default flow to use if no others are active.
1981 * @private {!webdriver.promise.ControlFlow}
1982 */
1983webdriver.promise.defaultFlow_ = new webdriver.promise.ControlFlow();
1984
1985
1986/**
1987 * A stack of active control flows, with the top of the stack used to schedule
1988 * commands. When there are multiple flows on the stack, the flow at index N
1989 * represents a callback triggered within a task owned by the flow at index
1990 * N-1.
1991 * @private {!Array.<!webdriver.promise.ControlFlow>}
1992 */
1993webdriver.promise.activeFlows_ = [];
1994
1995
1996/**
1997 * Changes the default flow to use when no others are active.
1998 * @param {!webdriver.promise.ControlFlow} flow The new default flow.
1999 * @throws {Error} If the default flow is not currently active.
2000 */
2001webdriver.promise.setDefaultFlow = function(flow) {
2002 if (webdriver.promise.activeFlows_.length) {
2003 throw Error('You may only change the default flow while it is active');
2004 }
2005 webdriver.promise.defaultFlow_ = flow;
2006};
2007
2008
2009/**
2010 * @return {!webdriver.promise.ControlFlow} The currently active control flow.
2011 */
2012webdriver.promise.controlFlow = function() {
2013 return /** @type {!webdriver.promise.ControlFlow} */ (
2014 goog.array.peek(webdriver.promise.activeFlows_) ||
2015 webdriver.promise.defaultFlow_);
2016};
2017
2018
2019/**
2020 * @param {!webdriver.promise.ControlFlow} flow The new flow.
2021 * @private
2022 */
2023webdriver.promise.pushFlow_ = function(flow) {
2024 webdriver.promise.activeFlows_.push(flow);
2025};
2026
2027
2028/** @private */
2029webdriver.promise.popFlow_ = function() {
2030 webdriver.promise.activeFlows_.pop();
2031};
2032
2033
2034/**
2035 * Creates a new control flow. The provided callback will be invoked as the
2036 * first task within the new flow, with the flow as its sole argument. Returns
2037 * a promise that resolves to the callback result.
2038 * @param {function(!webdriver.promise.ControlFlow)} callback The entry point
2039 * to the newly created flow.
2040 * @return {!webdriver.promise.Promise} A promise that resolves to the callback
2041 * result.
2042 */
2043webdriver.promise.createFlow = function(callback) {
2044 var flow = new webdriver.promise.ControlFlow(
2045 webdriver.promise.defaultFlow_.timer);
2046 return flow.execute(function() {
2047 return callback(flow);
2048 });
2049};