Our own version of wd's waitForElement. wd's version of waitFor* has the unfortunate habit of generating really unhelpful error messages. eslint-disable-next-line no-underscore-dangle
6452
function _waitForElement(browser, selector, asserter, timeout, pollFreq) {
  /* eslint no-use-before-define:0 */
  timeout = timeout || 2000;
  pollFreq = pollFreq || 50;

  const endTime = Date.now() + timeout;

  function attempt() {
    const element = browser.elementByCssSelectorOrNull(selector);
    return element
      .then(asserter.assert)
      .catch(retry)
      .then(_.constant(element));
  }

  function retry(error) {
    if (!error.retriable) {
      throw error;
    }
    if (Date.now() >= endTime) {
      error.message = `Timeout (${timeout}ms): ${error.message}`;
      throw error;
    }
    return new Promise(resolve => setTimeout(resolve, pollFreq)).then(attempt);
  }

  return attempt();
}
758602
async function withRetrys(fn) {
  let tryCount = 0
  while (true) {
    try {
      return await fn() // Do our action.
    } catch (e) {
      // Roughly double wait time each failure
      let waitTime = Math.pow(100, 1 + tryCount / 6)
      // Randomly jiggle wait time by 20% either way. No thundering herd.
      waitTime = Math.floor(waitTime * (1.2 - Math.random() * 0.4))
      // Max out at two minutes
      waitTime = Math.min(waitTime, MAX_RETRY_WAIT_MS)
      console.log('ERROR', e)
      console.log(`will retry in ${waitTime / 1000} seconds`)
      tryCount += 1
      await new Promise(resolve => setTimeout(resolve, waitTime))
    }
    if (tryCount >= MAX_RETRYS) {
      console.log('Exiting. Maximum number of retrys reached.')
      // Now it's up to our environment to restart us.
      // Hopefully with a clean start, things will work better
      process.exit(1)
    }
  }
}
91296
async function withRetries(opts, fn) {
  const maxRetries = opts.maxRetries || 7
  const verbose = opts.verbose || false

  let tryCount = 0
  while (tryCount < maxRetries) {
    try {
      return await fn() // Do our action.
    } catch (e) {
      // Double wait time each failure
      let waitTime = 1000 * 2**(tryCount - 1)
      // Randomly jiggle wait time by 20% either way. No thundering herd.
      waitTime = Math.floor(waitTime * (1.2 - Math.random() * 0.4))
      // Max out at two minutes
      waitTime = Math.min(waitTime, MAX_RETRY_WAIT_MS)
      if (verbose) {
        console.log('retryable error:', e.message)
        console.log(`will retry in ${waitTime / 1000} seconds`)
      }
      tryCount += 1
      await new Promise(resolve => setTimeout(resolve, waitTime))
    }
  }
  throw new Error('number of retries exceeded')
}
1306602
function wait_for(condition, proceed)
		{
			function check()
			{
				// if the condition is met, then proceed
				if (condition())
				{
					return proceed()
				}

				message_timer += check_interval

				if (message_timer >= message_interval)
				{
					message_timer = 0

					tools.log.debug(`(${tools.webpack_assets_path} not found)`)
					tools.log.info('(waiting for the first Webpack build to finish)')
				}

				setTimeout(check, check_interval)
			}

			check()
		}
693556
function modCompletePreDefine(currentId) {
        // HACK: 这里在IE下有个性能陷阱，不能使用任何变量。
        //       否则貌似会形成变量引用和修改的读写锁，导致wait4PreDefine释放困难
        each(wait4PreDefine, function (mod) {
            modPreDefine(
                currentId,
                mod.deps,
                mod.factory
            );
        });

        wait4PreDefine.length = 0;
    }
765857
function error(error) {

  const line = error.loc ? error.loc.line : (error.line ? error.line : 'Unknown');
  const file = (error.fileName ? error.fileName : (error.file ? error.file : (error.relativePath ? error.relativePath : ''))).replace(process.cwd(), '');
  const path = error.relativePath || 'path';
  const task = error.plugin || 'Task unknown';
  const name = error.name || 'Name unknown';

  // Easy error reporting

  if ( options.popups ) {
    notify({
      icon: options.error,
      title: name,
      subtitle: options.project,
      message: `Line ${line} in ${file}`,
    }).write(error);
  }

  let message = `${name} in ${file}: ${" line " + line + " "} \n ${error.message ? error.message.replace(process.cwd(), '') : error.toString()}`

  log(task + " Error", message)

  // Prevents any watchers from stopping
  this.emit('end');

}
737750
function getWithFallback (id) {

            if (!this.isReady) {
                throw new L10nError('Context not ready');
            }

            var cur = 0;
            var loc;
            var locale;
            while (loc = this.supportedLocales[cur]) { // eslint-disable-line no-cond-assign
                locale = this.getLocale(loc);
                if (!locale.isReady) {
                    // build without callback, synchronously
                    locale.build(null);
                }
                var entry = locale.getEntry(id);
                if (entry === undefined) {
                    cur++;
                    warning.call(this, new L10nError(id + ' not found in ' + loc, id,
                        loc));
                    continue;
                }
                return entry;
            }

            error.call(this, new L10nError(id + ' not found', id));
            return null;
        }
195178
function ErrorStackParser$$parseOpera11(error) {
	            var filtered = _filter(error.stack.split('\n'), function (line) {
	                return !!line.match(FIREFOX_SAFARI_STACK_REGEXP) &&
	                    !line.match(/^Error created at/);
	            }, this);
	
	            return _map(filtered, function (line) {
	                var tokens = line.split('@');
	                var locationParts = this.extractLocation(tokens.pop());
	                var functionCall = (tokens.shift() || '');
	                var functionName = functionCall
	                        .replace(/<anonymous function(: (\w+))?>/, '$2')
	                        .replace(/\([^\)]*\)/g, '') || undefined;
	                var argsRaw;
	                if (functionCall.match(/\(([^\)]*)\)/)) {
	                    argsRaw = functionCall.replace(/^[^\(]+\(([^\)]*)\)$/, '$1');
	                }
	                var args = (argsRaw === undefined || argsRaw === '[arguments not available]') ? undefined : argsRaw.split(',');
	                return new StackFrame(functionName, args, locationParts[0], locationParts[1], locationParts[2], line);
	            }, this);
	        }
982204
function() {
    var i, arg;
    for (i = 0 ; i < arguments.length ; i++) {
      arg = arguments[i];
      if (typeof arg === 'number') arg = "" + arg;
      if (typeof arg === 'undefined' || typeof arg === 'null'
          || (typeof arg !== 'object' && typeof arg !== 'string')) {
        console.error("[Widget.append] Argument #" + i + " is invalid!", arguments);
        console.error("[Widget.append] Is type is: " + (typeof arg));
        continue;
      };
      if (typeof arg === 'string') {
        if (arg.length < 1) arg = " ";
        arg = window.document.createTextNode(arg);
        if (!arg) {
          console.error(
            "[Widget.append] Unable to create a text node with this text: ", arg
          );
          console.error("[wdg] arguments=...", arguments);
          throw Error(
            "[Widget.append] Unable to create a text node with this text: "
              + JSON.stringify(arg)
          );
        }
      }
      if (Array.isArray(arg)) {
        arg.forEach(
          function(item) {
            this.append(item);
          }, this
        );
      }
      else {
        var e = arg;
        if( !(e instanceof Node) ) {
          if( e.$ instanceof Node ) e = e.$;
          else if( typeof e.element === 'function' ) e = e.element();
          else if( e.element ) e = e.element;
        }
        this._element.appendChild(e);
      }
    }
    return this;
  }
405006
async function crash (reason_, runHooks_, timeout_) {
    const reason = reason_ || 0;
    const runHooks = (typeof runHooks_ !== 'undefined') ? runHooks_ : true
    const timeout = timeout_ || 5000;

    // NOTE: All hooks are stored as promise-returning functions.  This allows
    // this code to be uniform as hell.

    /* Avoid running hooks multiple times */
    const wasCrashed = G.crashed;
    G.crashed = true;

    /* wait for hooks to complete */
    if (runHooks && !wasCrashed) {
        /* Set the timeout */
        setTimeout(crash.bind(null, EXIT_TIMEOUT, false), timeout).unref();

        /* Get all hook promises */
        const promises = G.hooks.map(fn => fn(reason));
        await Promise.settle(promises);
    }

    /* find out the exit code we should use */
    const exitCode = calcExitCode(reason);
    process.exit(exitCode);
}
1270647
function parseError(error: Error | string | string[]): StackFrame[] {
  if (error == null) {
    throw new Error('You cannot pass a null object.')
  }
  if (typeof error === 'string') {
    return parseStack(error.split('\n'))
  }
  if (Array.isArray(error)) {
    return parseStack(error)
  }
  if (typeof error.stack === 'string') {
    return parseStack(error.stack.split('\n'))
  }
  throw new Error('The error you provided does not contain a stack trace.')
}
602061
function getError (errors) {
    var data = errors[0].data
    var err = data.error
    err.message = err.message + ' [jsdom]'

    // clean up stack trace
    if (err.stack) {
      err.stack = err.stack
        .split('\n')
        .reduce(function (list, line) {
          if (line.match(/node_modules.+(jsdom|mocha)/)) {
            return list
          }

          line = line
            .replace(/file:\/\/.*<script>/g, '<script>')
            .replace(/:undefined:undefined/g, '')
          list.push(line)
          return list
        }, [])
        .join('\n')
    }

    return err
  }
459145
def wait_for(element)
      case element
        when :page_load
          browser.wait_for(:wait_for => :page)
        when :ajax
          browser.wait_for(:wait_for => :ajax, :javascript_framework => Pyrite.js_framework)
        else
          browser.wait_for(:element => "jquery=#{element}")
      end
    end
986014
public void waitFor(Flag flag,
                        int waitDelay)
        throws ServerException,
               IOException,
               InterruptedException {
        waitFor(flag, waitDelay, WAIT_FOREVER);
    }
736097
function(promise, result, output, isProgress) {
				var element = document.createElement("div"); //$NON-NLS-0$

				var waitCount = 0;
				var successFn = function(file) {
					this.callback = function() {
						var string = i18nUtil.formatMessage(
							messages["WroteMsg"],
							typeof(file) === "string" ? file : this.shellPageFileService.computePathString(file)); //$NON-NLS-0$
						var writer = new mResultWriters.ShellStringWriter(element);
						writer.write(string + "\n"); //$NON-NLS-0$
						if (--waitCount !== 0 || isProgress) {
							promise.progress(element);
						} else {
							promise.resolve(element);
						}
					}.bind(this);
					return this;
				}.bind(this);
				var errorFn = function(file) {
					this.callback = function(error) {
						var string = i18nUtil.formatMessage(
							messages["WriteFailMsg"],
							typeof(file) === "string" ? file : this.shellPageFileService.computePathString(file)); //$NON-NLS-0$
						string += " [" + error + "]"; //$NON-NLS-1$ //$NON-NLS-0$
						var writer = new mResultWriters.ShellStringWriter(element);
						writer.write(string + "\n"); //$NON-NLS-0$
						if (--waitCount !== 0 || isProgress) {
							promise.progress(element);
						} else {
							promise.resolve(element);
						}
					}.bind(this);
					return this;
				}.bind(this);

				var destination = output || this.shellPageFileService.getCurrentDirectory();
				waitCount++;
				this.shellPageFileService.ensureDirectory(null, destination).then(
					function(directory) {
						waitCount--;

						var files = result.getValue();
						if (!result.isArray()) {
							files = [files];
						}
						files.forEach(function(file) {
							waitCount++;
							var pathSegments = file.path.split(this.shellPageFileService.SEPARATOR);

							/* normalize instances of '.' and '..' in the path */
							var index = 0;
							while (index < pathSegments.length) {
								var segment = pathSegments[index];
								if (segment === ".") { //$NON-NLS-0$
									pathSegments.splice(index, 1);
								} else if (segment === "..") { //$NON-NLS-0$
									if (index === 0) {
										/* invalid, destination must be a descendent of the cwd */
										errorFn(i18nUtil.formatMessage(messages["WriteFailNotDescendentOfOutputDir"], file.path));
										return;
									}
									pathSegments.splice(index-- - 1, 2);
								} else {
									index++;
								}
							}

							var writeFile = function(parentNode, fileToWrite, pathSegments) {
								var segment = pathSegments[0];
								pathSegments.splice(0,1);
								var nodeString = this.shellPageFileService.computePathString(parentNode) + this.shellPageFileService.SEPARATOR + segment;
								if (pathSegments.length === 0) {
									/* attempt to write the new resource */
									if (fileToWrite.isDirectory) {
										this.shellPageFileService.ensureDirectory(parentNode, segment).then(successFn(nodeString).callback, errorFn(nodeString).callback);
									} else {
										this.shellPageFileService.ensureFile(parentNode, segment).then(
											function(file) {
												var writer = new mResultWriters.FileBlobWriter(file, this.shellPageFileService);
												writer.addBlob(fileToWrite.blob);
												writer.write().then(successFn(file).callback, errorFn(file).callback);
											}.bind(this),
											errorFn(nodeString).callback
										);
									}
									return;
								}
								/* more lead-up path segments to go */
								this.shellPageFileService.ensureDirectory(parentNode, segment).then(
									function(newNode) {
										writeFile(newNode, fileToWrite, pathSegments);
									},
									errorFn(this.shellPageFileService.computePathString(parentNode) + this.shellPageFileService.SEPARATOR + segment).callback
								);
							}.bind(this);
							writeFile(directory, file, pathSegments);
						}.bind(this));
					}.bind(this),
					errorFn(destination).callback
				);
			}
48336
function warning(message) {
  /* eslint-disable no-console */
  if (typeof console !== 'undefined' && typeof console.error === 'function') {
    console.error(message);
  }
  /* eslint-enable no-console */
  try {
    // This error was thrown as a convenience so that if you enable
    // "break on all exceptions" in your console,
    // it would pause the execution at this line.
    throw new Error(message);
    /* eslint-disable no-empty */
  } catch (e) {}
  /* eslint-enable no-empty */
}
223531
function done(error) {
      global.clearTimeout(timer);
      eventLoop.removeListener('tick', ontick);
      eventLoop.removeListener('idle', done);
      eventLoop.browser.removeListener('error', done);

      --eventLoop.waiting;
      try {
        callback(error);
      } catch (error) {
        // If callback makes an assertion that fails, we end here.
        // If we throw error synchronously, it gets swallowed.
        setImmediate(function() {
          throw error;
        });
      }
    }