function vuexEasyFirestore(easyFirestoreModule, _a) {
    var _b = _a === void 0 ? {
        logging: false,
        preventInitialDocInsertion: false,
        FirebaseDependency: Firebase$2
    } : _a, _c = _b.logging, logging = _c === void 0 ? false : _c, _d = _b.preventInitialDocInsertion, preventInitialDocInsertion = _d === void 0 ? false : _d, _e = _b.FirebaseDependency, FirebaseDependency = _e === void 0 ? Firebase$2 : _e;
    if (FirebaseDependency) {
        setFirebaseDependency(FirebaseDependency);
        setFirebaseDependency$1(FirebaseDependency);
    }
    return function (store) {
        // Get an array of config files
        if (!isWhat.isArray(easyFirestoreModule))
            easyFirestoreModule = [easyFirestoreModule];
        // Create a module for each config file
        easyFirestoreModule.forEach(function (config) {
            config.logging = logging;
            if (config.sync && config.sync.preventInitialDocInsertion === undefined) {
                config.sync.preventInitialDocInsertion = preventInitialDocInsertion;
            }
            var moduleName = vuexEasyAccess.getKeysFromPath(config.moduleName);
            store.registerModule(moduleName, iniModule(config, FirebaseDependency));
        });
    };
}

function
vuexEasyFirestore
(
easyFirestoreModule
,
_a
)
{
var
_b
=
_a
===
void
0
{
logging
:
false
,
preventInitialDocInsertion
:
false
,
FirebaseDependency
:
Firebase$2
}
:
_a
,
_c
=
_b
.
logging
,
logging
=
_c
===
void
0
false
:
_c
,
_d
=
_b
.
preventInitialDocInsertion
,
preventInitialDocInsertion
=
_d
===
void
0
false
:
_d
,
_e
=
_b
.
FirebaseDependency
,
FirebaseDependency
=
_e
===
void
0
Firebase$2
:
_e
;
if
(
FirebaseDependency
)
{
setFirebaseDependency
(
FirebaseDependency
)
;
setFirebaseDependency$1
(
FirebaseDependency
)
;
}
return
function
(
store
)
{
// Get an array of config files
if
(
!
isWhat
.
isArray
(
easyFirestoreModule
)
)
easyFirestoreModule
=
[
easyFirestoreModule
]
;
// Create a module for each config file
easyFirestoreModule
.
forEach
(
function
(
config
)
{
config
.
logging
=
logging
;
if
(
config
.
sync
&&
config
.
sync
.
preventInitialDocInsertion
===
undefined
)
{
config
.
sync
.
preventInitialDocInsertion
=
preventInitialDocInsertion
;
}
var
moduleName
=
vuexEasyAccess
.
getKeysFromPath
(
config
.
moduleName
)
;
store
.
registerModule
(
moduleName
,
iniModule
(
config
,
FirebaseDependency
)
)
;
}
)
;
}
;
}

Firebase
Create vuex-easy-firestore modules. Add as single plugin to Vuex Store.

@export
@param {(IEasyFirestoreModule | IEasyFirestoreModule[])} easyFirestoreModule A vuex-easy-firestore module (or array of modules) with proper configuration as per the documentation.
@param {{logging?: boolean, FirebaseDependency?: any}} extraConfig An object with `logging` and `FirebaseDependency` props. `logging` enables console logs for debugging. `FirebaseDependency` is the non-instanciated Firebase class you can pass. (defaults to the Firebase peer dependency)
@returns {*}

Firebase Create vuex - easy - firestore modules . Add as single plugin to Vuex Store .


function parseCSV(csvFilePath, attributeFields) {
  return new Promise((resolve, reject) => {
    try {
      csv(csvFilePath, data => resolve(_transformToHierarchy(data, attributeFields))); // lol hello Lisp
    } catch (err) {
      reject(err);
    }
  });
}

function
parseCSV
(
csvFilePath
,
attributeFields
)
{
return
new
Promise
(
(
resolve
,
reject
)
=>
{
try
{
csv
(
csvFilePath
,
data
=>
resolve
(
_transformToHierarchy
(
data
,
attributeFields
)
)
)
;
// lol hello Lisp
}
catch
(
err
)
{
reject
(
err
)
;
}
}
)
;
}

parseCSV - Parses a CSV file into a hierarchy structure.

@param {string} csvFilePath     Path to CSV file to be parsed.
@param {array<string>|undefined} attributeFields Set of column names to be used as attributes (optional)

@return {Promise} Returns hierarchy array if resolved, error object if rejected.

parseCSV - Parses a CSV file into a hierarchy structure .


function parseJSON(jsonFilePath) {
  return new Promise((resolve, reject) => {
    try {
      json(jsonFilePath, data => resolve([data]));
    } catch (err) {
      reject(err);
    }
  });
}

function parseJSON ( jsonFilePath ) { return new Promise ( ( resolve , reject ) => { try { json ( jsonFilePath , data => resolve ( [ data ] ) ) ; } catch ( err ) { reject ( err ) ; } } ) ; }

parseJSON - Parses a hierarchical JSON file that requires no further transformation.

@param {string} jsonFilePath Path to JSON file to be parsed.

@return {Promise} Returns hierarchy array if resolved, error object if rejected.

parseJSON - Parses a hierarchical JSON file that requires no further transformation .


function parseFlatJSON(jsonFilePath, attributeFields) {
  return new Promise((resolve, reject) => {
    try {
      json(jsonFilePath, data => resolve(_transformToHierarchy(data, attributeFields)));
    } catch (err) {
      reject(err);
    }
  });
}

function parseFlatJSON ( jsonFilePath , attributeFields ) { return new Promise ( ( resolve , reject ) => { try { json ( jsonFilePath , data => resolve ( _transformToHierarchy ( data , attributeFields ) ) ) ; } catch ( err ) { reject ( err ) ; } } ) ; }

parseFlatJSON - Parses a flat JSON file into a hierarchy structure.

@param {string} jsonFilePath Path to flat JSON file to be parsed.
@param {array<string>|undefined} attributeFields Set of `link` fields to be used as attributes

@return {Promise} Returns hierarchy array if resolved, error object if rejected.

parseFlatJSON - Parses a flat JSON file into a hierarchy structure .


function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
  if (true) {
    for (var typeSpecName in typeSpecs) {
      if (typeSpecs.hasOwnProperty(typeSpecName)) {
        var error;
        // Prop type validation may throw. In case they do, we don't want to
        // fail the render phase where it didn't fail before. So we log it.
        // After these have been cleaned up, we'll let them throw.
        try {
          // This is intentionally an invariant that gets caught. It's the same
          // behavior as without this statement except with a better message.
          if (typeof typeSpecs[typeSpecName] !== 'function') {
            var err = Error(
              (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +
              'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.'
            );
            err.name = 'Invariant Violation';
            throw err;
          }
          error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
        } catch (ex) {
          error = ex;
        }
        if (error && !(error instanceof Error)) {
          printWarning(
            (componentName || 'React class') + ': type specification of ' +
            location + ' `' + typeSpecName + '` is invalid; the type checker ' +
            'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +
            'You may have forgotten to pass an argument to the type checker ' +
            'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
            'shape all require an argument).'
          )

        }
        if (error instanceof Error && !(error.message in loggedTypeFailures)) {
          // Only monitor this failure once because there tends to be a lot of the
          // same error.
          loggedTypeFailures[error.message] = true;

          var stack = getStack ? getStack() : '';

          printWarning(
            'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
          );
        }
      }
    }
  }
}

Assert that the values match with the type specs.
Error messages are memorized and will only be shown once.

@param {object} typeSpecs Map of name to a ReactPropType
@param {object} values Runtime values that need to be type-checked
@param {string} location e.g. "prop", "context", "child context"
@param {string} componentName Name of the component for error messages.
@param {?Function} getStack Returns the component stack.
@private

Assert that the values match with the type specs . Error messages are memorized and will only be shown once .


function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
  hasError = false;
  caughtError = null;
  invokeGuardedCallbackImpl$1.apply(reporter, arguments);
}

function invokeGuardedCallback ( name , func , context , a , b , c , d , e , f ) { hasError = false ; caughtError = null ; invokeGuardedCallbackImpl$1 . apply ( reporter , arguments ) ; }

Call a function while guarding against errors that happens within it.
Returns an error if it throws, otherwise null.

In production, this is implemented using a try-catch. The reason we don't
use a try-catch directly is so that we can swap out a different
implementation in DEV mode.

@param {String} name of the guard to use for logging or debugging
@param {Function} func The function to invoke
@param {*} context The context to use when calling the function
@param {...*} args Arguments for function

Call a function while guarding against errors that happens within it . Returns an error if it throws otherwise null .


function getClosestInstanceFromNode(node) {
  if (node[internalInstanceKey]) {
    return node[internalInstanceKey];
  }

  while (!node[internalInstanceKey]) {
    if (node.parentNode) {
      node = node.parentNode;
    } else {
      // Top of the tree. This node must not be part of a React tree (or is
      // unmounted, potentially).
      return null;
    }
  }

  var inst = node[internalInstanceKey];
  if (inst.tag === HostComponent || inst.tag === HostText) {
    // In Fiber, this will always be the deepest root.
    return inst;
  }

  return null;
}

Given a DOM node, return the closest ReactDOMComponent or
ReactDOMTextComponent instance ancestor.

Given a DOM node return the closest ReactDOMComponent or ReactDOMTextComponent instance ancestor .


function getInstanceFromNode$1(node) {
  var inst = node[internalInstanceKey];
  if (inst) {
    if (inst.tag === HostComponent || inst.tag === HostText) {
      return inst;
    } else {
      return null;
    }
  }
  return null;
}

function getInstanceFromNode$1 ( node ) { var inst = node [ internalInstanceKey ] ; if ( inst ) { if ( inst . tag === HostComponent || inst . tag === HostText ) { return inst ; } else { return null ; } } return null ; }

Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent
instance, or null if the node was not rendered by this React.

Given a DOM node return the ReactDOMComponent or ReactDOMTextComponent instance or null if the node was not rendered by this React .


function getNodeFromInstance$1(inst) {
  if (inst.tag === HostComponent || inst.tag === HostText) {
    // In Fiber this, is just the state node right now. We assume it will be
    // a host component or host text.
    return inst.stateNode;
  }

  // Without this first invariant, passing a non-DOM-component triggers the next
  // invariant for a missing parent, which is super confusing.
  invariant(false, 'getNodeFromInstance: Invalid argument.');
}

Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding
DOM node.

Given a ReactDOMComponent or ReactDOMTextComponent return the corresponding DOM node .


function traverseEnterLeave(from, to, fn, argFrom, argTo) {
  var common = from && to ? getLowestCommonAncestor(from, to) : null;
  var pathFrom = [];
  while (true) {
    if (!from) {
      break;
    }
    if (from === common) {
      break;
    }
    var alternate = from.alternate;
    if (alternate !== null && alternate === common) {
      break;
    }
    pathFrom.push(from);
    from = getParent(from);
  }
  var pathTo = [];
  while (true) {
    if (!to) {
      break;
    }
    if (to === common) {
      break;
    }
    var _alternate = to.alternate;
    if (_alternate !== null && _alternate === common) {
      break;
    }
    pathTo.push(to);
    to = getParent(to);
  }
  for (var i = 0; i < pathFrom.length; i++) {
    fn(pathFrom[i], 'bubbled', argFrom);
  }
  for (var _i = pathTo.length; _i-- > 0;) {
    fn(pathTo[_i], 'captured', argTo);
  }
}

function traverseEnterLeave ( from , to , fn , argFrom , argTo ) { var common = from && to ? getLowestCommonAncestor ( from , to ) : null ; var pathFrom = [ ] ; while ( true ) { if ( ! from ) { break ; } if ( from === common ) { break ; } var alternate = from . alternate ; if ( alternate !== null && alternate === common ) { break ; } pathFrom . push ( from ) ; from = getParent ( from ) ; } var pathTo = [ ] ; while ( true ) { if ( ! to ) { break ; } if ( to === common ) { break ; } var _alternate = to . alternate ; if ( _alternate !== null && _alternate === common ) { break ; } pathTo . push ( to ) ; to = getParent ( to ) ; } for ( var i = 0 ; i < pathFrom . length ; i ++ ) { fn ( pathFrom [ i ] , 'bubbled' , argFrom ) ; } for ( var _i = pathTo . length ; _i -- > 0 ; ) { fn ( pathTo [ _i ] , 'captured' , argTo ) ; } }

Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
should would receive a `mouseEnter` or `mouseLeave` event.

Does not invoke the callback on the nearest common ancestor because nothing
"entered" or "left" that element.

Traverses the ID hierarchy and invokes the supplied cb on any IDs that should would receive a mouseEnter or mouseLeave event .


function makePrefixMap(styleProp, eventName) {
  var prefixes = {};

  prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
  prefixes['Webkit' + styleProp] = 'webkit' + eventName;
  prefixes['Moz' + styleProp] = 'moz' + eventName;

  return prefixes;
}

function makePrefixMap ( styleProp , eventName ) { var prefixes = { } ; prefixes [ styleProp . toLowerCase ( ) ] = eventName . toLowerCase ( ) ; prefixes [ 'Webkit' + styleProp ] = 'webkit' + eventName ; prefixes [ 'Moz' + styleProp ] = 'moz' + eventName ; return prefixes ; }

Generate a mapping of standard vendor prefixes using the defined style property and event name.

@param {string} styleProp
@param {string} eventName
@returns {object}

Generate a mapping of standard vendor prefixes using the defined style property and event name .


function () {
    var Interface = this.constructor.Interface;
    for (var propName in Interface) {
      {
        Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));
      }
    }
    this.dispatchConfig = null;
    this._targetInst = null;
    this.nativeEvent = null;
    this.isDefaultPrevented = functionThatReturnsFalse;
    this.isPropagationStopped = functionThatReturnsFalse;
    this._dispatchListeners = null;
    this._dispatchInstances = null;
    {
      Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));
      Object.defineProperty(this, 'isDefaultPrevented', getPooledWarningPropertyDefinition('isDefaultPrevented', functionThatReturnsFalse));
      Object.defineProperty(this, 'isPropagationStopped', getPooledWarningPropertyDefinition('isPropagationStopped', functionThatReturnsFalse));
      Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', function () {}));
      Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', function () {}));
    }
  }

function ( ) { var Interface = this . constructor . Interface ; for ( var propName in Interface ) { { Object . defineProperty ( this , propName , getPooledWarningPropertyDefinition ( propName , Interface [ propName ] ) ) ; } } this . dispatchConfig = null ; this . _targetInst = null ; this . nativeEvent = null ; this . isDefaultPrevented = functionThatReturnsFalse ; this . isPropagationStopped = functionThatReturnsFalse ; this . _dispatchListeners = null ; this . _dispatchInstances = null ; { Object . defineProperty ( this , 'nativeEvent' , getPooledWarningPropertyDefinition ( 'nativeEvent' , null ) ) ; Object . defineProperty ( this , 'isDefaultPrevented' , getPooledWarningPropertyDefinition ( 'isDefaultPrevented' , functionThatReturnsFalse ) ) ; Object . defineProperty ( this , 'isPropagationStopped' , getPooledWarningPropertyDefinition ( 'isPropagationStopped' , functionThatReturnsFalse ) ) ; Object . defineProperty ( this , 'preventDefault' , getPooledWarningPropertyDefinition ( 'preventDefault' , function ( ) { } ) ) ; Object . defineProperty ( this , 'stopPropagation' , getPooledWarningPropertyDefinition ( 'stopPropagation' , function ( ) { } ) ) ; } }

`PooledClass` looks for `destructor` on each instance it releases.

PooledClass looks for destructor on each instance it releases .


function getCompositionEventType(topLevelType) {
  switch (topLevelType) {
    case TOP_COMPOSITION_START:
      return eventTypes.compositionStart;
    case TOP_COMPOSITION_END:
      return eventTypes.compositionEnd;
    case TOP_COMPOSITION_UPDATE:
      return eventTypes.compositionUpdate;
  }
}

function getCompositionEventType ( topLevelType ) { switch ( topLevelType ) { case TOP_COMPOSITION_START : return eventTypes . compositionStart ; case TOP_COMPOSITION_END : return eventTypes . compositionEnd ; case TOP_COMPOSITION_UPDATE : return eventTypes . compositionUpdate ; } }

Translate native top level events into event types.

@param {string} topLevelType
@return {object}

Translate native top level events into event types .


function isFallbackCompositionEnd(topLevelType, nativeEvent) {
  switch (topLevelType) {
    case TOP_KEY_UP:
      // Command keys insert or clear IME input.
      return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
    case TOP_KEY_DOWN:
      // Expect IME keyCode on each keydown. If we get any other
      // code we must have exited earlier.
      return nativeEvent.keyCode !== START_KEYCODE;
    case TOP_KEY_PRESS:
    case TOP_MOUSE_DOWN:
    case TOP_BLUR:
      // Events are not possible without cancelling IME.
      return true;
    default:
      return false;
  }
}

Does our fallback mode think that this event is the end of composition?

@param {string} topLevelType
@param {object} nativeEvent
@return {boolean}


function getValueForProperty(node, name, expected, propertyInfo) {
  {
    if (propertyInfo.mustUseProperty) {
      var propertyName = propertyInfo.propertyName;

      return node[propertyName];
    } else {
      var attributeName = propertyInfo.attributeName;

      var stringValue = null;

      if (propertyInfo.type === OVERLOADED_BOOLEAN) {
        if (node.hasAttribute(attributeName)) {
          var value = node.getAttribute(attributeName);
          if (value === '') {
            return true;
          }
          if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
            return value;
          }
          if (value === '' + expected) {
            return expected;
          }
          return value;
        }
      } else if (node.hasAttribute(attributeName)) {
        if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
          // We had an attribute but shouldn't have had one, so read it
          // for the error message.
          return node.getAttribute(attributeName);
        }
        if (propertyInfo.type === BOOLEAN) {
          // If this was a boolean, it doesn't matter what the value is
          // the fact that we have it is the same as the expected.
          return expected;
        }
        // Even if this property uses a namespace we use getAttribute
        // because we assume its namespaced name is the same as our config.
        // To use getAttributeNS we need the local name which we don't have
        // in our config atm.
        stringValue = node.getAttribute(attributeName);
      }

      if (shouldRemoveAttribute(name, expected, propertyInfo, false)) {
        return stringValue === null ? expected : stringValue;
      } else if (stringValue === '' + expected) {
        return expected;
      } else {
        return stringValue;
      }
    }
  }
}

Get the value for a property on a node. Only used in DEV for SSR validation.
The "expected" argument is used as a hint of what the expected value is.
Some properties have multiple equivalent values.

Get the value for a property on a node . Only used in DEV for SSR validation . The expected argument is used as a hint of what the expected value is . Some properties have multiple equivalent values .


function getTargetInstForInputEventPolyfill(topLevelType, targetInst) {
  if (topLevelType === TOP_SELECTION_CHANGE || topLevelType === TOP_KEY_UP || topLevelType === TOP_KEY_DOWN) {
    // On the selectionchange event, the target is just document which isn't
    // helpful for us so just check activeElement instead.
    //
    // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
    // propertychange on the first input event after setting `value` from a
    // script and fires only keydown, keypress, keyup. Catching keyup usually
    // gets it and catching keydown lets us fire an event for the first
    // keystroke if user does a key repeat (it'll be a little delayed: right
    // before the second keystroke). Other input methods (e.g., paste) seem to
    // fire selectionchange normally.
    return getInstIfValueChanged(activeElementInst);
  }
}


function (topLevelType, targetInst, nativeEvent, nativeEventTarget) {
    var isOverEvent = topLevelType === TOP_MOUSE_OVER || topLevelType === TOP_POINTER_OVER;
    var isOutEvent = topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_POINTER_OUT;

    if (isOverEvent && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {
      return null;
    }

    if (!isOutEvent && !isOverEvent) {
      // Must not be a mouse or pointer in or out - ignoring.
      return null;
    }

    var win = void 0;
    if (nativeEventTarget.window === nativeEventTarget) {
      // `nativeEventTarget` is probably a window object.
      win = nativeEventTarget;
    } else {
      // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
      var doc = nativeEventTarget.ownerDocument;
      if (doc) {
        win = doc.defaultView || doc.parentWindow;
      } else {
        win = window;
      }
    }

    var from = void 0;
    var to = void 0;
    if (isOutEvent) {
      from = targetInst;
      var related = nativeEvent.relatedTarget || nativeEvent.toElement;
      to = related ? getClosestInstanceFromNode(related) : null;
    } else {
      // Moving to a node from outside the window.
      from = null;
      to = targetInst;
    }

    if (from === to) {
      // Nothing pertains to our managed components.
      return null;
    }

    var eventInterface = void 0,
        leaveEventType = void 0,
        enterEventType = void 0,
        eventTypePrefix = void 0;

    if (topLevelType === TOP_MOUSE_OUT || topLevelType === TOP_MOUSE_OVER) {
      eventInterface = SyntheticMouseEvent;
      leaveEventType = eventTypes$2.mouseLeave;
      enterEventType = eventTypes$2.mouseEnter;
      eventTypePrefix = 'mouse';
    } else if (topLevelType === TOP_POINTER_OUT || topLevelType === TOP_POINTER_OVER) {
      eventInterface = SyntheticPointerEvent;
      leaveEventType = eventTypes$2.pointerLeave;
      enterEventType = eventTypes$2.pointerEnter;
      eventTypePrefix = 'pointer';
    }

    var fromNode = from == null ? win : getNodeFromInstance$1(from);
    var toNode = to == null ? win : getNodeFromInstance$1(to);

    var leave = eventInterface.getPooled(leaveEventType, from, nativeEvent, nativeEventTarget);
    leave.type = eventTypePrefix + 'leave';
    leave.target = fromNode;
    leave.relatedTarget = toNode;

    var enter = eventInterface.getPooled(enterEventType, to, nativeEvent, nativeEventTarget);
    enter.type = eventTypePrefix + 'enter';
    enter.target = toNode;
    enter.relatedTarget = fromNode;

    accumulateEnterLeaveDispatches(leave, enter, from, to);

    return [leave, enter];
  }

For almost every interaction we care about, there will be both a top-level
`mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
we do not extract duplicate events. However, moving the mouse into the
browser from outside will not fire a `mouseout` event. In this case, we use
the `mouseover` top-level event.

For almost every interaction we care about there will be both a top - level mouseover and mouseout event that occurs . Only use mouseout so that we do not extract duplicate events . However moving the mouse into the browser from outside will not fire a mouseout event . In this case we use the mouseover top - level event .


function listenTo(registrationName, mountAt) {
  var isListening = getListeningForDocument(mountAt);
  var dependencies = registrationNameDependencies[registrationName];

  for (var i = 0; i < dependencies.length; i++) {
    var dependency = dependencies[i];
    if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) {
      switch (dependency) {
        case TOP_SCROLL:
          trapCapturedEvent(TOP_SCROLL, mountAt);
          break;
        case TOP_FOCUS:
        case TOP_BLUR:
          trapCapturedEvent(TOP_FOCUS, mountAt);
          trapCapturedEvent(TOP_BLUR, mountAt);
          // We set the flag for a single dependency later in this function,
          // but this ensures we mark both as attached rather than just one.
          isListening[TOP_BLUR] = true;
          isListening[TOP_FOCUS] = true;
          break;
        case TOP_CANCEL:
        case TOP_CLOSE:
          if (isEventSupported(getRawEventName(dependency))) {
            trapCapturedEvent(dependency, mountAt);
          }
          break;
        case TOP_INVALID:
        case TOP_SUBMIT:
        case TOP_RESET:
          // We listen to them on the target DOM elements.
          // Some of them bubble so we don't want them to fire twice.
          break;
        default:
          // By default, listen on the top level to all non-media events.
          // Media events don't bubble so adding the listener wouldn't do anything.
          var isMediaEvent = mediaEventTypes.indexOf(dependency) !== -1;
          if (!isMediaEvent) {
            trapBubbledEvent(dependency, mountAt);
          }
          break;
      }
      isListening[dependency] = true;
    }
  }
}

We listen for bubbled touch events on the document object.

Firefox v8.01 (and possibly others) exhibited strange behavior when
mounting `onmousemove` events at some node that was not the document
element. The symptoms were that if your mouse is not moving over something
contained within that mount point (for example on the background) the
top-level listeners for `onmousemove` won't be called. However, if you
register the `mousemove` on the document object, then it will of course
catch all `mousemove`s. This along with iOS quirks, justifies restricting
top-level listeners to the document object only, at least for these
movement types of events and possibly all events.

@see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html

Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
they bubble to document.

@param {string} registrationName Name of listener (e.g. `onClick`).
@param {object} mountAt Container where to mount the listener

We listen for bubbled touch events on the document object .


function getEventTargetDocument(eventTarget) {
  return eventTarget.window === eventTarget ? eventTarget.document : eventTarget.nodeType === DOCUMENT_NODE ? eventTarget : eventTarget.ownerDocument;
}

function getEventTargetDocument ( eventTarget ) { return eventTarget . window === eventTarget ? eventTarget . document : eventTarget . nodeType === DOCUMENT_NODE ? eventTarget : eventTarget . ownerDocument ; }

Get document associated with the event target.

@param {object} nativeEventTarget
@return {Document}

Get document associated with the event target .


function constructSelectEvent(nativeEvent, nativeEventTarget) {
  // Ensure we have the right element, and that the user is not dragging a
  // selection (this matches native `select` event behavior). In HTML5, select
  // fires only on input and textarea thus if there's no focused element we
  // won't dispatch.
  var doc = getEventTargetDocument(nativeEventTarget);

  if (mouseDown || activeElement$1 == null || activeElement$1 !== getActiveElement(doc)) {
    return null;
  }

  // Only fire when selection has actually changed.
  var currentSelection = getSelection(activeElement$1);
  if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
    lastSelection = currentSelection;

    var syntheticEvent = SyntheticEvent.getPooled(eventTypes$3.select, activeElementInst$1, nativeEvent, nativeEventTarget);

    syntheticEvent.type = 'select';
    syntheticEvent.target = activeElement$1;

    accumulateTwoPhaseDispatches(syntheticEvent);

    return syntheticEvent;
  }

  return null;
}

Poll selection to see whether it's changed.

@param {object} nativeEvent
@param {object} nativeEventTarget
@return {?SyntheticEvent}

Poll selection to see whether it s changed .


function (node, text) {
  if (text) {
    var firstChild = node.firstChild;

    if (firstChild && firstChild === node.lastChild && firstChild.nodeType === TEXT_NODE) {
      firstChild.nodeValue = text;
      return;
    }
  }
  node.textContent = text;
}

function ( node , text ) { if ( text ) { var firstChild = node . firstChild ; if ( firstChild && firstChild === node . lastChild && firstChild . nodeType === TEXT_NODE ) { firstChild . nodeValue = text ; return ; } } node . textContent = text ; }

Set the textContent property of a node. For text updates, it's faster
to set the `nodeValue` of the Text node directly instead of using
`.textContent` which will remove the existing node and create a new one.

@param {DOMElement} node
@param {string} text
@internal

Set the textContent property of a node . For text updates it s faster to set the nodeValue of the Text node directly instead of using . textContent which will remove the existing node and create a new one .


function createDangerousStringForStyles(styles) {
  {
    var serialized = '';
    var delimiter = '';
    for (var styleName in styles) {
      if (!styles.hasOwnProperty(styleName)) {
        continue;
      }
      var styleValue = styles[styleName];
      if (styleValue != null) {
        var isCustomProperty = styleName.indexOf('--') === 0;
        serialized += delimiter + hyphenateStyleName(styleName) + ':';
        serialized += dangerousStyleValue(styleName, styleValue, isCustomProperty);

        delimiter = ';';
      }
    }
    return serialized || null;
  }
}

function createDangerousStringForStyles ( styles ) { { var serialized = '' ; var delimiter = '' ; for ( var styleName in styles ) { if ( ! styles . hasOwnProperty ( styleName ) ) { continue ; } var styleValue = styles [ styleName ] ; if ( styleValue != null ) { var isCustomProperty = styleName . indexOf ( '--' ) === 0 ; serialized += delimiter + hyphenateStyleName ( styleName ) + ':' ; serialized += dangerousStyleValue ( styleName , styleValue , isCustomProperty ) ; delimiter = ';' ; } } return serialized || null ; } }

Operations for dealing with CSS properties.

This creates a string that is expected to be equivalent to the style
attribute generated by server-side rendering. It by-passes warnings and
security checks so it's not safe to use this value for anything other than
comparison. It is only used in DEV for SSR validation.

Operations for dealing with CSS properties . This creates a string that is expected to be equivalent to the style attribute generated by server - side rendering . It by - passes warnings and security checks so it s not safe to use this value for anything other than comparison . It is only used in DEV for SSR validation .


function (containerChildSet, workInProgress) {
    // We only have the top Fiber that was created but we need recurse down its
    // children to find all the terminal nodes.
    var node = workInProgress.child;
    while (node !== null) {
      if (node.tag === HostComponent || node.tag === HostText) {
        appendChildToContainerChildSet(containerChildSet, node.stateNode);
      } else if (node.tag === HostPortal) {
        // If we have a portal child, then we don't want to traverse
        // down its children. Instead, we'll get insertions from each child in
        // the portal directly.
      } else if (node.child !== null) {
        node.child.return = node;
        node = node.child;
        continue;
      }
      if (node === workInProgress) {
        return;
      }
      while (node.sibling === null) {
        if (node.return === null || node.return === workInProgress) {
          return;
        }
        node = node.return;
      }
      node.sibling.return = node.return;
      node = node.sibling;
    }
  }

Persistent host tree mode An unfortunate fork of appendAllChildren because we have two different parent types.

Persistent host tree mode An unfortunate fork of appendAllChildren because we have two different parent types .


function safelyCallComponentWillUnmount(current$$1, instance) {
  {
    invokeGuardedCallback(null, callComponentWillUnmountWithTimer, null, current$$1, instance);
    if (hasCaughtError()) {
      var unmountError = clearCaughtError();
      captureCommitPhaseError(current$$1, unmountError);
    }
  }
}

function safelyCallComponentWillUnmount ( current$$1 , instance ) { { invokeGuardedCallback ( null , callComponentWillUnmountWithTimer , null , current$$1 , instance ) ; if ( hasCaughtError ( ) ) { var unmountError = clearCaughtError ( ) ; captureCommitPhaseError ( current$$1 , unmountError ) ; } } }

Capture errors so they don't interrupt unmounting.

Capture errors so they don t interrupt unmounting .


function computeUniqueAsyncExpiration() {
  var currentTime = requestCurrentTime();
  var result = computeAsyncExpiration(currentTime);
  if (result <= lastUniqueAsyncExpiration) {
    // Since we assume the current time monotonically increases, we only hit
    // this branch when computeUniqueAsyncExpiration is fired multiple times
    // within a 200ms window (or whatever the async bucket size is).
    result = lastUniqueAsyncExpiration + 1;
  }
  lastUniqueAsyncExpiration = result;
  return lastUniqueAsyncExpiration;
}

Creates a unique async expiration time .


function stringify(content) {
  if (typeof content === 'string' && stringifiedRegexp.test(content)) {
    return content;
  }
  return JSON.stringify(content, null, 2);
}

function stringify ( content ) { if ( typeof content === 'string' && stringifiedRegexp . test ( content ) ) { return content ; } return JSON . stringify ( content , null , 2 ) ; }

If already stringified - return original content
@param {Object|Array} content
@return {string}


function getLoaderOptions(loaderPath, rule) {
  let multiRuleProp;

  if (isWebpack1) {
    multiRuleProp = 'loaders';
  } else if (rule.oneOf) {
    multiRuleProp = 'oneOf';
  } else {
    multiRuleProp = 'use';
  }

  const multiRule = typeof rule === 'object' && Array.isArray(rule[multiRuleProp]) ? rule[multiRuleProp] : null;
  let options;

  if (multiRule) {
    const rules = [].concat(...multiRule.map(r => (r.use || r)));
    options = rules.map(normalizeRule).find(r => loaderPath.includes(r.loader)).options;
  } else {
    options = normalizeRule(rule).options;
  }

  return options;
}

function getLoaderOptions ( loaderPath , rule ) { let multiRuleProp ; if ( isWebpack1 ) { multiRuleProp = 'loaders' ; } else if ( rule . oneOf ) { multiRuleProp = 'oneOf' ; } else { multiRuleProp = 'use' ; } const multiRule = typeof rule === 'object' && Array . isArray ( rule [ multiRuleProp ] ) ? rule [ multiRuleProp ] : null ; let options ; if ( multiRule ) { const rules = [ ] . concat ( ... multiRule . map ( r => ( r . use || r ) ) ) ; options = rules . map ( normalizeRule ) . find ( r => loaderPath . includes ( r . loader ) ) . options ; } else { options = normalizeRule ( rule ) . options ; } return options ; }

webpack 1 compat loader options finder. Returns normalized options.
@param {string} loaderPath
@param {Object|Rule} rule
@return {Object|null}

webpack 1 compat loader options finder . Returns normalized options .


function normalizeRule(rule) {
  if (!rule) {
    throw new Error('Rule should be string or object');
  }

  let data;

  if (typeof rule === 'string') {
    const parts = rule.split('?');
    data = {
      loader: parts[0],
      options: parts[1] ? parseQuery(`?${parts[1]}`) : null
    };
  } else {
    const options = isWebpack1 ? rule.query : rule.options;
    data = {
      loader: rule.loader,
      options: options || null
    };
  }

  return data;
}

function
normalizeRule
(
rule
)
{
if
(
!
rule
)
{
throw
new
Error
(
'Rule should be string or object'
)
;
}
let
data
;
if
(
typeof
rule
===
'string'
)
{
const
parts
=
rule
.
split
(
'?'
)
;
data
=
{
loader
:
parts
[
0
]
,
options
:
parts
[
1
]
parseQuery
(
`
${
parts
[
1
]
}
`
)
:
}
;
}
else
{
const
options
=
isWebpack1
rule
.
query
:
rule
.
options
;
data
=
{
loader
:
rule
.
loader
,
options
:
options
||
}
;
}
return
data
;
}

webpack 1 compat rule normalizer
@param {string|Rule} rule (string - webpack 1, Object - webpack 2)
@return {Object<loader: string, options: Object|null>}


function findParent(node, handle) {
  let current = node
  while (current) {
    if (handle(current)) {
      return current
    }
    current = current.parent
  }
}

function findParent ( node , handle ) { let current = node while ( current ) { if ( handle ( current ) ) { return current } current = current . parent } }


function pure(node, withChildren, after) {
      var _this2 = this;

      var t = assign$1({}, node);

      delete t._id;
      delete t.parent;
      delete t.children;
      delete t.open;
      delete t.active;
      delete t.style;
      delete t.class;
      delete t.innerStyle;
      delete t.innerClass;
      delete t.innerBackStyle;
      delete t.innerBackClass;

      var _arr = keys$1(t);

      for (var _i = 0; _i < _arr.length; _i++) {
        var key = _arr[_i];

        if (key[0] === '_') {
          delete t[key];
        }
      }

      if (withChildren && node.children) {
        t.children = node.children.slice();
        t.children.forEach(function (v, k) {
          t.children[k] = _this2.pure(v, withChildren);
        });
      }

      if (after) {
        return after(t, node) || t;
      }

      return t;
    }

function pure ( node , withChildren , after ) { var _this2 = this ; var t = assign$1 ( { } , node ) ; delete t . _id ; delete t . parent ; delete t . children ; delete t . open ; delete t . active ; delete t . style ; delete t . class ; delete t . innerStyle ; delete t . innerClass ; delete t . innerBackStyle ; delete t . innerBackClass ; var _arr = keys$1 ( t ) ; for ( var _i = 0 ; _i < _arr . length ; _i ++ ) { var key = _arr [ _i ] ; if ( key [ 0 ] === '_' ) { delete t [ key ] ; } } if ( withChildren && node . children ) { t . children = node . children . slice ( ) ; t . children . forEach ( function ( v , k ) { t . children [ k ] = _this2 . pure ( v , withChildren ) ; } ) ; } if ( after ) { return after ( t , node ) || t ; } return t ; }


function offset2() {
      return {
        x: this.offset.x + this.nodeInnerEl.offsetWidth,
        y: this.offset.y + this.nodeInnerEl.offsetHeight
      };
    }

function offset2 ( ) { return { x : this . offset . x + this . nodeInnerEl . offsetWidth , y : this . offset . y + this . nodeInnerEl . offsetHeight } ; }


function offsetToViewPort() {
      var r = this.nodeInnerEl.getBoundingClientRect();
      r.x = r.left;
      r.y = r.top;
      return r;
    }

function offsetToViewPort ( ) { var r = this . nodeInnerEl . getBoundingClientRect ( ) ; r . x = r . left ; r . y = r . top ; return r ; }


function currentTreeRootSecondChildExcludingDragging() {
      var _this = this;

      return this.currentTree.rootData.children.slice(0, 3).filter(function (v) {
        return v !== _this.node;
      })[1];
    }

the second child of currentTree root, excluding dragging node

the second child of currentTree root excluding dragging node


function appendPrev(info) {
    if (isNodeDroppable(info.targetPrev)) {
      th.appendTo(info.dplh, info.targetPrev);
      if (!info.targetPrev.open) info.store.toggleOpen(info.targetPrev);
    } else {
      insertDplhAfterTo(info.dplh, info.targetPrev, info);
    }
  }

function appendPrev ( info ) { if ( isNodeDroppable ( info . targetPrev ) ) { th . appendTo ( info . dplh , info . targetPrev ) ; if ( ! info . targetPrev . open ) info . store . toggleOpen ( info . targetPrev ) ; } else { insertDplhAfterTo ( info . dplh , info . targetPrev , info ) ; } }


function appendCurrentTree(info) {
    if (isNodeDroppable(info.currentTree.rootData)) {
      th.appendTo(info.dplh, info.currentTree.rootData);
    }
  }

function appendCurrentTree ( info ) { if ( isNodeDroppable ( info . currentTree . rootData ) ) { th . appendTo ( info . dplh , info . currentTree . rootData ) ; } }


function stripViewFromSelector (selector) {
    // Don't strip it out if it's one of these 4 element types
    // (see https://github.com/facebook/WebDriverAgent/blob/master/WebDriverAgentLib/Utilities/FBElementTypeTransformer.m for reference)
    const keepView = [
      'XCUIElementTypeScrollView',
      'XCUIElementTypeCollectionView',
      'XCUIElementTypeTextView',
      'XCUIElementTypeWebView',
    ].includes(selector);

    if (!keepView && selector.indexOf('View') === selector.length - 4) {
      return selector.substr(0, selector.length - 4);
    } else {
      return selector;
    }
  }

Check if the word 'View' is appended to selector and if it is, strip it out

Check if the word View is appended to selector and if it is strip it out


async function getPidUsingPattern (pgrepPattern) {
  const args = ['-nif', pgrepPattern];
  try {
    const {stdout} = await exec('pgrep', args);
    const pid = parseInt(stdout, 10);
    if (isNaN(pid)) {
      log.debug(`Cannot parse process id from 'pgrep ${args.join(' ')}' output: ${stdout}`);
      return null;
    }
    return `${pid}`;
  } catch (err) {
    log.debug(`'pgrep ${args.join(' ')}' didn't detect any matching processes. Return code: ${err.code}`);
    return null;
  }
}

async
function
getPidUsingPattern
(
pgrepPattern
)
{
const
args
=
[
'-nif'
,
pgrepPattern
]
;
try
{
const
{
stdout
}
=
await
exec
(
'pgrep'
,
args
)
;
const
pid
=
parseInt
(
stdout
,
10
)
;
if
(
isNaN
(
pid
)
)
{
log
.
debug
(
`
${
args
.
join
(
' '
)
}
${
stdout
}
`
)
;
return
;
}
return
`
${
pid
}
`
;
}
catch
(
err
)
{
log
.
debug
(
`
${
args
.
join
(
' '
)
}
${
err
.
code
}
`
)
;
return
;
}
}

Get the process id of the most recent running application
having the particular command line pattern.

@param {string} pgrepPattern - pgrep-compatible search pattern.
@return {string} Either a process id or null if no matches were found.

Get the process id of the most recent running application having the particular command line pattern .


async function killAppUsingPattern (pgrepPattern) {
  for (const signal of [2, 15, 9]) {
    if (!await getPidUsingPattern(pgrepPattern)) {
      return;
    }
    const args = [`-${signal}`, '-if', pgrepPattern];
    try {
      await exec('pkill', args);
    } catch (err) {
      log.debug(`pkill ${args.join(' ')} -> ${err.message}`);
    }
    await B.delay(100);
  }
}

async
function
killAppUsingPattern
(
pgrepPattern
)
{
for
(
const
signal
of
[
2
,
15
,
9
]
)
{
if
(
!
await
getPidUsingPattern
(
pgrepPattern
)
)
{
return
;
}
const
args
=
[
`
${
signal
}
`
,
'-if'
,
pgrepPattern
]
;
try
{
await
exec
(
'pkill'
,
args
)
;
}
catch
(
err
)
{
log
.
debug
(
`
${
args
.
join
(
' '
)
}
${
err
.
message
}
`
)
;
}
await
B
.
delay
(
100
)
;
}
}

Kill a process having the particular command line pattern.
This method tries to send SIGINT, SIGTERM and SIGKILL to the
matched processes in this order if the process is still running.

@param {string} pgrepPattern - pgrep-compatible search pattern.

Kill a process having the particular command line pattern . This method tries to send SIGINT SIGTERM and SIGKILL to the matched processes in this order if the process is still running .


async function getPIDsListeningOnPort (port, filteringFunc = null) {
  const result = [];
  try {
    // This only works since Mac OS X El Capitan
    const {stdout} = await exec('lsof', ['-ti', `tcp:${port}`]);
    result.push(...(stdout.trim().split(/\n+/)));
  } catch (e) {
    return result;
  }

  if (!_.isFunction(filteringFunc)) {
    return result;
  }
  return await B.filter(result, async (x) => {
    const {stdout} = await exec('ps', ['-p', x, '-o', 'command']);
    return await filteringFunc(stdout);
  });
}

Get the IDs of processes listening on the particular system port.
It is also possible to apply additional filtering based on the
process command line.

@param {string|number} port - The port number.
@param {?Function} filteringFunc - Optional lambda function, which
receives command line string of the particular process
listening on given port, and is expected to return
either true or false to include/exclude the corresponding PID
from the resulting array.
@returns {Array<string>} - the list of matched process ids.

Get the IDs of processes listening on the particular system port . It is also possible to apply additional filtering based on the process command line .


async function removeAllSessionWebSocketHandlers (server, sessionId) {
  if (!server || !_.isFunction(server.getWebSocketHandlers)) {
    return;
  }

  const activeHandlers = await server.getWebSocketHandlers(sessionId);
  for (const pathname of _.keys(activeHandlers)) {
    await server.removeWebSocketHandler(pathname);
  }
}

async function removeAllSessionWebSocketHandlers ( server , sessionId ) { if ( ! server || ! _ . isFunction ( server . getWebSocketHandlers ) ) { return ; } const activeHandlers = await server . getWebSocketHandlers ( sessionId ) ; for ( const pathname of _ . keys ( activeHandlers ) ) { await server . removeWebSocketHandler ( pathname ) ; } }

Stops and removes all web socket handlers that are listening
in scope of the currect session.

@param {Object} server - The instance of NodeJs HTTP server,
which hosts Appium
@param {string} sessionId - The id of the current session

Stops and removes all web socket handlers that are listening in scope of the currect session .


async function verifyApplicationPlatform (app, isSimulator) {
  log.debug('Verifying application platform');

  const infoPlist = path.resolve(app, 'Info.plist');
  if (!await fs.exists(infoPlist)) {
    log.debug(`'${infoPlist}' does not exist`);
    return null;
  }

  const {CFBundleSupportedPlatforms} = await plist.parsePlistFile(infoPlist);
  log.debug(`CFBundleSupportedPlatforms: ${JSON.stringify(CFBundleSupportedPlatforms)}`);
  if (!_.isArray(CFBundleSupportedPlatforms)) {
    log.debug(`CFBundleSupportedPlatforms key does not exist in '${infoPlist}'`);
    return null;
  }

  const isAppSupported = (isSimulator && CFBundleSupportedPlatforms.includes('iPhoneSimulator'))
    || (!isSimulator && CFBundleSupportedPlatforms.includes('iPhoneOS'));
  if (isAppSupported) {
    return true;
  }
  throw new Error(`${isSimulator ? 'Simulator' : 'Real device'} architecture is unsupported by the '${app}' application. ` +
                  `Make sure the correct deployment target has been selected for its compilation in Xcode.`);
}

async
function
verifyApplicationPlatform
(
app
,
isSimulator
)
{
log
.
debug
(
'Verifying application platform'
)
;
const
infoPlist
=
path
.
resolve
(
app
,
'Info.plist'
)
;
if
(
!
await
fs
.
exists
(
infoPlist
)
)
{
log
.
debug
(
`
${
infoPlist
}
`
)
;
return
;
}
const
{
CFBundleSupportedPlatforms
}
=
await
plist
.
parsePlistFile
(
infoPlist
)
;
log
.
debug
(
`
${
JSON
.
stringify
(
CFBundleSupportedPlatforms
)
}
`
)
;
if
(
!
_
.
isArray
(
CFBundleSupportedPlatforms
)
)
{
log
.
debug
(
`
${
infoPlist
}
`
)
;
return
;
}
const
isAppSupported
=
(
isSimulator
&&
CFBundleSupportedPlatforms
.
includes
(
'iPhoneSimulator'
)
)
||
(
!
isSimulator
&&
CFBundleSupportedPlatforms
.
includes
(
'iPhoneOS'
)
)
;
if
(
isAppSupported
)
{
return
true
;
}
throw
new
Error
(
`
${
isSimulator
'Simulator'
:
'Real device'
}
${
app
}
`
+
`
`
)
;
}

Verify whether the given application is compatible to the
platform where it is going to be installed and tested.

@param {string} app - The actual path to the application bundle
@param {boolean} isSimulator - Should be set to `true` if the test will be executed on Simulator
@returns {?boolean} The function returns `null` if the application does not exist or there is no
`CFBundleSupportedPlatforms` key in its Info.plist manifest.
`true` is returned if the bundle architecture matches the device architecture.
@throws {Error} If bundle architecture does not match the device architecture.

Verify whether the given application is compatible to the platform where it is going to be installed and tested .


function isLocalHost (urlString) {
  try {
    const {hostname} = url.parse(urlString);
    return ['localhost', '127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(hostname);
  } catch {
    log.warn(`'${urlString}' cannot be parsed as a valid URL`);
  }
  return false;
}

function isLocalHost ( urlString ) { try { const { hostname } = url . parse ( urlString ) ; return [ 'localhost' , '127.0.0.1' , '::1' , '::ffff:127.0.0.1' ] . includes ( hostname ) ; } catch { log . warn ( ` ${ urlString } ` ) ; } return false ; }

Returns true if the urlString is localhost
@param {?string} urlString
@returns {boolean} Return true if the urlString is localhost


function normalizePlatformVersion (originalVersion) {
  const normalizedVersion = util.coerceVersion(originalVersion, false);
  if (!normalizedVersion) {
    throw new Error(`The platform version '${originalVersion}' should be a valid version number`);
  }
  const {major, minor} = new semver.SemVer(normalizedVersion);
  return `${major}.${minor}`;
}

function normalizePlatformVersion ( originalVersion ) { const normalizedVersion = util . coerceVersion ( originalVersion , false ) ; if ( ! normalizedVersion ) { throw new Error ( ` ${ originalVersion } ` ) ; } const { major , minor } = new semver . SemVer ( normalizedVersion ) ; return ` ${ major } ${ minor } ` ; }

Normalizes platformVersion to a valid iOS version string

@param {string} originalVersion - Loose version number, that can be parsed by semver
@return {string} iOS version number in <major>.<minor> format
@throws {Error} if the version number cannot be parsed


async function updateProjectFile (agentPath, newBundleId) {
  let projectFilePath = `${agentPath}/${PROJECT_FILE}`;
  try {
    // Assuming projectFilePath is in the correct state, create .old from projectFilePath
    await fs.copyFile(projectFilePath, `${projectFilePath}.old`);
    await replaceInFile(projectFilePath, new RegExp(WDA_RUNNER_BUNDLE_ID.replace('.', '\.'), 'g'), newBundleId); // eslint-disable-line no-useless-escape
    log.debug(`Successfully updated '${projectFilePath}' with bundle id '${newBundleId}'`);
  } catch (err) {
    log.debug(`Error updating project file: ${err.message}`);
    log.warn(`Unable to update project file '${projectFilePath}' with ` +
             `bundle id '${newBundleId}'. WebDriverAgent may not start`);
  }
}

Update WebDriverAgentRunner project bundle ID with newBundleId.
This method assumes project file is in the correct state.
@param {string} agentPath - Path to the .xcodeproj directory.
@param {string} newBundleId the new bundle ID used to update.

Update WebDriverAgentRunner project bundle ID with newBundleId . This method assumes project file is in the correct state .


async function resetProjectFile (agentPath) {
  let projectFilePath = `${agentPath}/${PROJECT_FILE}`;
  try {
    // restore projectFilePath from .old file
    if (!await fs.exists(`${projectFilePath}.old`)) {
      return; // no need to reset
    }
    await fs.mv(`${projectFilePath}.old`, projectFilePath);
    log.debug(`Successfully reset '${projectFilePath}' with bundle id '${WDA_RUNNER_BUNDLE_ID}'`);
  } catch (err) {
    log.debug(`Error resetting project file: ${err.message}`);
    log.warn(`Unable to reset project file '${projectFilePath}' with ` +
             `bundle id '${WDA_RUNNER_BUNDLE_ID}'. WebDriverAgent has been ` +
             `modified and not returned to the original state.`);
  }
}

Reset WebDriverAgentRunner project bundle ID to correct state.
@param {string} agentPath - Path to the .xcodeproj directory.

Reset WebDriverAgentRunner project bundle ID to correct state .


function getAdditionalRunContent (platformName, wdaRemotePort) {
  const runner = `WebDriverAgentRunner${isTvOS(platformName) ? '_tvOS' : ''}`;

  return {
    [runner]: {
      EnvironmentVariables: {
        USE_PORT: wdaRemotePort
      }
    }
  };
}

function getAdditionalRunContent ( platformName , wdaRemotePort ) { const runner = ` ${ isTvOS ( platformName ) ? '_tvOS' : '' } ` ; return { [ runner ] : { EnvironmentVariables : { USE_PORT : wdaRemotePort } } } ; }

Return the WDA object which appends existing xctest runner content
@param {string} platformName - The name of the platform
@param {string} version - The Xcode SDK version of OS.
@return {object} returns a runner object which has USE_PORT


async function getWDAUpgradeTimestamp (bootstrapPath) {
  const carthageRootPath = path.resolve(bootstrapPath, CARTHAGE_ROOT);
  if (await fs.exists(carthageRootPath)) {
    const {mtime} = await fs.stat(carthageRootPath);
    return mtime.getTime();
  }
  return null;
}

async function getWDAUpgradeTimestamp ( bootstrapPath ) { const carthageRootPath = path . resolve ( bootstrapPath , CARTHAGE_ROOT ) ; if ( await fs . exists ( carthageRootPath ) ) { const { mtime } = await fs . stat ( carthageRootPath ) ; return mtime . getTime ( ) ; } return null ; }

Retrieves WDA upgrade timestamp

@param {string} bootstrapPath The full path to the folder where WDA source is located
@return {?number} The UNIX timestamp of the carthage root folder, where dependencies are downloaded.
This folder is created only once on module upgrade/first install.


async function parseContainerPath (remotePath, containerRootSupplier) {
  const match = CONTAINER_PATH_PATTERN.exec(remotePath);
  if (!match) {
    log.errorAndThrow(`It is expected that package identifier ` +
      `starts with '${CONTAINER_PATH_MARKER}' and is separated from the ` +
      `relative path with a single slash. '${remotePath}' is given instead`);
  }
  let [, bundleId, relativePath] = match;
  let containerType = null;
  const typeSeparatorPos = bundleId.indexOf(CONTAINER_TYPE_SEPARATOR);
  // We only consider container type exists if its length is greater than zero
  // not counting the colon
  if (typeSeparatorPos > 0 && typeSeparatorPos < bundleId.length - 1) {
    containerType = bundleId.substring(typeSeparatorPos + 1);
    log.debug(`Parsed container type: ${containerType}`);
    bundleId = bundleId.substring(0, typeSeparatorPos);
  }
  const containerRoot = _.isFunction(containerRootSupplier)
    ? await containerRootSupplier(bundleId, containerType)
    : containerRootSupplier;
  const resultPath = path.posix.resolve(containerRoot, relativePath);
  verifyIsSubPath(resultPath, containerRoot);
  return [bundleId, resultPath];
}

Parses the actual path and the bundle identifier from the given path string

@param {string} remotePath - The given path string. The string should
match `CONTAINER_PATH_PATTERN` regexp, otherwise an error is going
to be thrown. A valid string example: `@bundle.identifier:container_type/relative_path_in_container`
@param {Function|string} containerRootSupplier - Either a string, that contains
full path to the mount root for real devices or a function, which accepts two parameters
(bundle identifier and optional container type) and returns full path to container
root folder on the local file system, for Simulator
@returns {Array<string>} - An array where the first item is the parsed bundle
identifier and the second one is the absolute full path of the item on the local
file system


async function pushFileToSimulator (device, remotePath, base64Data) {
  const buffer = Buffer.from(base64Data, 'base64');
  if (CONTAINER_PATH_PATTERN.test(remotePath)) {
    const [bundleId, dstPath] = await parseContainerPath(remotePath,
      async (appBundle, containerType) => await getAppContainer(device.udid, appBundle, null, containerType));
    log.info(`Parsed bundle identifier '${bundleId}' from '${remotePath}'. ` +
      `Will put the data into '${dstPath}'`);
    if (!await fs.exists(path.dirname(dstPath))) {
      log.debug(`The destination folder '${path.dirname(dstPath)}' does not exist. Creating...`);
      await mkdirp(path.dirname(dstPath));
    }
    await fs.writeFile(dstPath, buffer);
    return;
  }
  const dstFolder = await tempDir.openDir();
  const dstPath = path.resolve(dstFolder, path.basename(remotePath));
  try {
    await fs.writeFile(dstPath, buffer);
    await addMedia(device.udid, dstPath);
  } finally {
    await fs.rimraf(dstFolder);
  }
}

async function pushFileToSimulator ( device , remotePath , base64Data ) { const buffer = Buffer . from ( base64Data , 'base64' ) ; if ( CONTAINER_PATH_PATTERN . test ( remotePath ) ) { const [ bundleId , dstPath ] = await parseContainerPath ( remotePath , async ( appBundle , containerType ) => await getAppContainer ( device . udid , appBundle , null , containerType ) ) ; log . info ( ` ${ bundleId } ${ remotePath } ` + ` ${ dstPath } ` ) ; if ( ! await fs . exists ( path . dirname ( dstPath ) ) ) { log . debug ( ` ${ path . dirname ( dstPath ) } ` ) ; await mkdirp ( path . dirname ( dstPath ) ) ; } await fs . writeFile ( dstPath , buffer ) ; return ; } const dstFolder = await tempDir . openDir ( ) ; const dstPath = path . resolve ( dstFolder , path . basename ( remotePath ) ) ; try { await fs . writeFile ( dstPath , buffer ) ; await addMedia ( device . udid , dstPath ) ; } finally { await fs . rimraf ( dstFolder ) ; } }

Save the given base64 data chunk as a binary file on the Simulator under test.

@param {Object} device - The device object, which represents the device under test.
This object is expected to have the `udid` property containing the
valid device ID.
@param {string} remotePath - The remote path on the device. This variable can be prefixed with
bundle id, so then the file will be uploaded to the corresponding
application container instead of the default media folder, for example
'@com.myapp.bla:data/RelativePathInContainer/111.png'. The '@' character at the
beginning of the argument is mandatory in such case. The colon at the end of bundle identifier
is optional and is used to distinguish the container type.
Possible values there are 'app', 'data', 'groups', '<A specific App Group container>'.
The default value is 'app'.
The relative folder path is ignored if the file is going to be uploaded
to the default media folder and only the file name is considered important.
@param {string} base64Data - Base-64 encoded content of the file to be uploaded.

Save the given base64 data chunk as a binary file on the Simulator under test .


async function pullFromSimulator (device, remotePath, isFile) {
  let pathOnServer;
  if (CONTAINER_PATH_PATTERN.test(remotePath)) {
    const [bundleId, dstPath] = await parseContainerPath(remotePath,
      async (appBundle, containerType) => await getAppContainer(device.udid, appBundle, null, containerType));
    log.info(`Parsed bundle identifier '${bundleId}' from '${remotePath}'. ` +
      `Will get the data from '${dstPath}'`);
    pathOnServer = dstPath;
  } else {
    const simRoot = device.getDir();
    pathOnServer = path.posix.join(simRoot, remotePath);
    verifyIsSubPath(pathOnServer, simRoot);
    log.info(`Got the full item path: ${pathOnServer}`);
  }
  if (!await fs.exists(pathOnServer)) {
    log.errorAndThrow(`The remote ${isFile ? 'file' : 'folder'} at '${pathOnServer}' does not exist`);
  }
  const buffer = isFile
    ? await fs.readFile(pathOnServer)
    : await zip.toInMemoryZip(pathOnServer);
  return Buffer.from(buffer).toString('base64');
}

async function pullFromSimulator ( device , remotePath , isFile ) { let pathOnServer ; if ( CONTAINER_PATH_PATTERN . test ( remotePath ) ) { const [ bundleId , dstPath ] = await parseContainerPath ( remotePath , async ( appBundle , containerType ) => await getAppContainer ( device . udid , appBundle , null , containerType ) ) ; log . info ( ` ${ bundleId } ${ remotePath } ` + ` ${ dstPath } ` ) ; pathOnServer = dstPath ; } else { const simRoot = device . getDir ( ) ; pathOnServer = path . posix . join ( simRoot , remotePath ) ; verifyIsSubPath ( pathOnServer , simRoot ) ; log . info ( ` ${ pathOnServer } ` ) ; } if ( ! await fs . exists ( pathOnServer ) ) { log . errorAndThrow ( ` ${ isFile ? 'file' : 'folder' } ${ pathOnServer } ` ) ; } const buffer = isFile ? await fs . readFile ( pathOnServer ) : await zip . toInMemoryZip ( pathOnServer ) ; return Buffer . from ( buffer ) . toString ( 'base64' ) ; }

Get the content of given file or folder from iOS Simulator and return it as base-64 encoded string.
Folder content is recursively packed into a zip archive.

@param {Object} device - The device object, which represents the device under test.
This object is expected to have the `udid` property containing the
valid device ID.
@param {string} remotePath - The path to a file or a folder, which exists in the corresponding application
container on Simulator. Use
@<app_bundle_id>:<optional_container_type>/<path_to_the_file_or_folder_inside_container>
format to pull a file or a folder from an application container of the given type.
Possible container types are 'app', 'data', 'groups', '<A specific App Group container>'.
The default type is 'app'.
@param {boolean} isFile - Whether the destination item is a file or a folder
@returns {string} Base-64 encoded content of the file.

Get the content of given file or folder from iOS Simulator and return it as base - 64 encoded string . Folder content is recursively packed into a zip archive .


async function pullFromRealDevice (device, remotePath, isFile) {
  await verifyIFusePresence();
  const mntRoot = await tempDir.openDir();
  let isUnmountSuccessful = true;
  try {
    let dstPath = path.resolve(mntRoot, remotePath);
    let ifuseArgs = ['-u', device.udid, mntRoot];
    if (CONTAINER_PATH_PATTERN.test(remotePath)) {
      const [bundleId, pathInContainer] = await parseContainerPath(remotePath, mntRoot);
      dstPath = pathInContainer;
      log.info(`Parsed bundle identifier '${bundleId}' from '${remotePath}'. ` +
        `Will get the data from '${dstPath}'`);
      ifuseArgs = ['-u', device.udid, '--container', bundleId, mntRoot];
    } else {
      verifyIsSubPath(dstPath, mntRoot);
    }
    await mountDevice(device, ifuseArgs);
    isUnmountSuccessful = false;
    try {
      if (!await fs.exists(dstPath)) {
        log.errorAndThrow(`The remote ${isFile ? 'file' : 'folder'} at '${dstPath}' does not exist`);
      }
      const buffer = isFile
        ? await fs.readFile(dstPath)
        : await zip.toInMemoryZip(dstPath);
      return Buffer.from(buffer).toString('base64');
    } finally {
      await exec('umount', [mntRoot]);
      isUnmountSuccessful = true;
    }
  } finally {
    if (isUnmountSuccessful) {
      await fs.rimraf(mntRoot);
    } else {
      log.warn(`Umount has failed, so not removing '${mntRoot}'`);
    }
  }
}

async function pullFromRealDevice ( device , remotePath , isFile ) { await verifyIFusePresence ( ) ; const mntRoot = await tempDir . openDir ( ) ; let isUnmountSuccessful = true ; try { let dstPath = path . resolve ( mntRoot , remotePath ) ; let ifuseArgs = [ '-u' , device . udid , mntRoot ] ; if ( CONTAINER_PATH_PATTERN . test ( remotePath ) ) { const [ bundleId , pathInContainer ] = await parseContainerPath ( remotePath , mntRoot ) ; dstPath = pathInContainer ; log . info ( ` ${ bundleId } ${ remotePath } ` + ` ${ dstPath } ` ) ; ifuseArgs = [ '-u' , device . udid , '--container' , bundleId , mntRoot ] ; } else { verifyIsSubPath ( dstPath , mntRoot ) ; } await mountDevice ( device , ifuseArgs ) ; isUnmountSuccessful = false ; try { if ( ! await fs . exists ( dstPath ) ) { log . errorAndThrow ( ` ${ isFile ? 'file' : 'folder' } ${ dstPath } ` ) ; } const buffer = isFile ? await fs . readFile ( dstPath ) : await zip . toInMemoryZip ( dstPath ) ; return Buffer . from ( buffer ) . toString ( 'base64' ) ; } finally { await exec ( 'umount' , [ mntRoot ] ) ; isUnmountSuccessful = true ; } } finally { if ( isUnmountSuccessful ) { await fs . rimraf ( mntRoot ) ; } else { log . warn ( ` ${ mntRoot } ` ) ; } } }

Get the content of given file or folder from the real device under test and return it as base-64 encoded string.
Folder content is recursively packed into a zip archive.

@param {Object} device - The device object, which represents the device under test.
This object is expected to have the `udid` property containing the
valid device ID.
@param {string} remotePath - The path to an existing remote file on the device. This variable can be prefixed with
bundle id, so then the file will be downloaded from the corresponding
application container instead of the default media folder, for example
'@com.myapp.bla/RelativePathInContainer/111.png'. The '@' character at the
beginning of the argument is mandatory in such case.
@param {boolean} isFile - Whether the destination item is a file or a folder
@return {string} Base-64 encoded content of the remote file

Get the content of given file or folder from the real device under test and return it as base - 64 encoded string . Folder content is recursively packed into a zip archive .


async function createSim (caps, platform = PLATFORM_NAME_IOS) {
  const appiumTestDeviceName = `appiumTest-${UUID.create().toString().toUpperCase()}-${caps.deviceName}`;
  const udid = await createDevice(
    appiumTestDeviceName,
    caps.deviceName,
    caps.platformVersion,
    { platform }
  );
  return await getSimulator(udid);
}

async function createSim ( caps , platform = PLATFORM_NAME_IOS ) { const appiumTestDeviceName = ` ${ UUID . create ( ) . toString ( ) . toUpperCase ( ) } ${ caps . deviceName } ` ; const udid = await createDevice ( appiumTestDeviceName , caps . deviceName , caps . platformVersion , { platform } ) ; return await getSimulator ( udid ) ; }

Capability set by a user

@property {string} deviceName - A name for the device
@property {string} platformVersion - The version of iOS to use

Create a new simulator with `appiumTest-` prefix and return the object.

@param {object} SimCreationCaps - Capability set by a user. The options available are:
@property {string} platform [iOS] - Platform name in order to specify runtime such as 'iOS', 'tvOS', 'watchOS'
@returns {object} Simulator object associated with the udid passed in.


async function getExistingSim (opts) {
  const devices = await getDevices(opts.platformVersion);
  const appiumTestDeviceName = `appiumTest-${opts.deviceName}`;

  let appiumTestDevice;

  for (const device of _.values(devices)) {
    if (device.name === opts.deviceName) {
      return await getSimulator(device.udid);
    }

    if (device.name === appiumTestDeviceName) {
      appiumTestDevice = device;
    }
  }

  if (appiumTestDevice) {
    log.warn(`Unable to find device '${opts.deviceName}'. Found '${appiumTestDevice.name}' (udid: '${appiumTestDevice.udid}') instead`);
    return await getSimulator(appiumTestDevice.udid);
  }
  return null;
}

async function getExistingSim ( opts ) { const devices = await getDevices ( opts . platformVersion ) ; const appiumTestDeviceName = ` ${ opts . deviceName } ` ; let appiumTestDevice ; for ( const device of _ . values ( devices ) ) { if ( device . name === opts . deviceName ) { return await getSimulator ( device . udid ) ; } if ( device . name === appiumTestDeviceName ) { appiumTestDevice = device ; } } if ( appiumTestDevice ) { log . warn ( ` ${ opts . deviceName } ${ appiumTestDevice . name } ${ appiumTestDevice . udid } ` ) ; return await getSimulator ( appiumTestDevice . udid ) ; } return null ; }

Get a simulator which is already running.

@param {object} opts - Capability set by a user. The options available are:
- `deviceName` - a name for the device
- `platformVersion` - the version of iOS to use
@returns {?object} Simulator object associated with the udid passed in. Or null if no device is running.

Get a simulator which is already running .


function () {
    const data = this.data;
    let objectEls;

    // Push entities into list of els to intersect.
    if (data.objects) {
      objectEls = this.el.sceneEl.querySelectorAll(data.objects);
    } else {
      // If objects not defined, intersect with everything.
      objectEls = this.el.sceneEl.children;
    }
    // Convert from NodeList to Array
    this.els = Array.prototype.slice.call(objectEls);
  }

Update list of entities to test for collision.

Update list of entities to test for collision .


function intersect (el) {
        let radius, mesh, distance, extent;

        if (!el.isEntity) { return; }

        mesh = el.getObject3D('mesh');

        if (!mesh) { return; }

        box.setFromObject(mesh).getSize(size);
        extent = Math.max(size.x, size.y, size.z) / 2;
        radius = Math.sqrt(2 * extent * extent);
        box.getCenter(meshPosition);

        if (!radius) { return; }

        distance = position.distanceTo(meshPosition);
        if (distance < radius + colliderRadius) {
          collisions.push(el);
          distanceMap.set(el, distance);
        }
      }

function intersect ( el ) { let radius , mesh , distance , extent ; if ( ! el . isEntity ) { return ; } mesh = el . getObject3D ( 'mesh' ) ; if ( ! mesh ) { return ; } box . setFromObject ( mesh ) . getSize ( size ) ; extent = Math . max ( size . x , size . y , size . z ) / 2 ; radius = Math . sqrt ( 2 * extent * extent ) ; box . getCenter ( meshPosition ) ; if ( ! radius ) { return ; } distance = position . distanceTo ( meshPosition ) ; if ( distance < radius + colliderRadius ) { collisions . push ( el ) ; distanceMap . set ( el , distance ) ; } }


function () {
    const gamepad = this.getGamepad();
    if (!gamepad.buttons[GamepadButton.DPAD_RIGHT]) {
      return new THREE.Vector2();
    }
    return new THREE.Vector2(
      (gamepad.buttons[GamepadButton.DPAD_RIGHT].pressed ? 1 : 0)
      + (gamepad.buttons[GamepadButton.DPAD_LEFT].pressed ? -1 : 0),
      (gamepad.buttons[GamepadButton.DPAD_UP].pressed ? -1 : 0)
      + (gamepad.buttons[GamepadButton.DPAD_DOWN].pressed ? 1 : 0)
    );
  }

function ( ) { const gamepad = this . getGamepad ( ) ; if ( ! gamepad . buttons [ GamepadButton . DPAD_RIGHT ] ) { return new THREE . Vector2 ( ) ; } return new THREE . Vector2 ( ( gamepad . buttons [ GamepadButton . DPAD_RIGHT ] . pressed ? 1 : 0 ) + ( gamepad . buttons [ GamepadButton . DPAD_LEFT ] . pressed ? - 1 : 0 ) , ( gamepad . buttons [ GamepadButton . DPAD_UP ] . pressed ? - 1 : 0 ) + ( gamepad . buttons [ GamepadButton . DPAD_DOWN ] . pressed ? 1 : 0 ) ) ; }

Returns the state of the dpad as a THREE.Vector2.
@return {THREE.Vector2}

Returns the state of the dpad as a THREE . Vector2 .


function URLSearchParamsPolyfill(search) {
        search = search || "";

        // support construct object with another URLSearchParams instance
        if (search instanceof URLSearchParams || search instanceof URLSearchParamsPolyfill) {
            search = search.toString();
        }
        this [__URLSearchParams__] = parseToDict(search);
    }

Make a URLSearchParams instance

@param {object|string|URLSearchParams} search
@constructor


function RequestQueue(opts) {
  if (!opts || typeof (opts) !== 'object') {
    opts = {};
  }
  this.size = (opts.size > 0) ? opts.size : Infinity;
  this.timeout = (opts.timeout > 0) ? opts.timeout : 0;
  this._queue = [];
  this._timer = null;
  this._frozen = false;
}

function RequestQueue ( opts ) { if ( ! opts || typeof ( opts ) !== 'object' ) { opts = { } ; } this . size = ( opts . size > 0 ) ? opts . size : Infinity ; this . timeout = ( opts . timeout > 0 ) ? opts . timeout : 0 ; this . _queue = [ ] ; this . _timer = null ; this . _frozen = false ; }

Queue to contain LDAP requests.

@param {Object} opts queue options

Accepted Options:
- size: Maximum queue size
- timeout: Set timeout between first queue insertion and queue flush.


function MessageTracker(opts) {
  assert.object(opts);
  assert.string(opts.id);
  assert.object(opts.parser);

  this.id = opts.id;
  this._msgid = 0;
  this._messages = {};
  this._abandoned = {};
  this.parser = opts.parser;

  var self = this;
  this.__defineGetter__('pending', function () {
    return Object.keys(self._messages);
  });
}

function MessageTracker ( opts ) { assert . object ( opts ) ; assert . string ( opts . id ) ; assert . object ( opts . parser ) ; this . id = opts . id ; this . _msgid = 0 ; this . _messages = { } ; this . _abandoned = { } ; this . parser = opts . parser ; var self = this ; this . __defineGetter__ ( 'pending' , function ( ) { return Object . keys ( self . _messages ) ; } ) ; }


function connectSocket(cb) {
    cb = once(cb);

    function onResult(err, res) {
      if (err) {
        if (self.connectTimer) {
          clearTimeout(self.connectTimer);
          self.connectTimer = null;
        }
        self.emit('connectError', err);
      }
      cb(err, res);
    }
    function onConnect() {
      if (self.connectTimer) {
        clearTimeout(self.connectTimer);
        self.connectTimer = null;
      }
      socket.removeAllListeners('error')
        .removeAllListeners('connect')
        .removeAllListeners('secureConnect');

      tracker.id = nextClientId() + '__' + tracker.id;
      self.log = self.log.child({ldap_id: tracker.id}, true);

      // Move on to client setup
      setupClient(cb);
    }

    var port = (self.port || self.socketPath);
    if (self.secure) {
      socket = tls.connect(port, self.host, self.tlsOptions);
      socket.once('secureConnect', onConnect);
    } else {
      socket = net.connect(port, self.host);
      socket.once('connect', onConnect);
    }
    socket.once('error', onResult);
    initSocket();

    // Setup connection timeout handling, if desired
    if (self.connectTimeout) {
      self.connectTimer = setTimeout(function onConnectTimeout() {
        if (!socket || !socket.readable || !socket.writeable) {
          socket.destroy();
          self._socket = null;
          onResult(new ConnectionError('connection timeout'));
        }
      }, self.connectTimeout);
    }
  }


function initSocket() {
    tracker = new MessageTracker({
      id: self.url ? self.url.href : self.socketPath,
      parser: new Parser({log: log})
    });

    // This won't be set on TLS. So. Very. Annoying.
    if (typeof (socket.setKeepAlive) !== 'function') {
      socket.setKeepAlive = function setKeepAlive(enable, delay) {
        return socket.socket ?
          socket.socket.setKeepAlive(enable, delay) : false;
      };
    }

    socket.on('data', function onData(data) {
      if (log.trace())
        log.trace('data event: %s', util.inspect(data));

      tracker.parser.write(data);
    });

    // The "router"
    tracker.parser.on('message', function onMessage(message) {
      message.connection = self._socket;
      var callback = tracker.fetch(message.messageID);

      if (!callback) {
        log.error({message: message.json}, 'unsolicited message');
        return false;
      }

      return callback(message);
    });

    tracker.parser.on('error', function onParseError(err) {
      self.emit('error', new VError(err, 'Parser error for %s',
            tracker.id));
      self.connected = false;
      socket.end();
    });
  }

Initialize socket events and LDAP parser.

Initialize socket events and LDAP parser .


function setupClient(cb) {
    cb = once(cb);

    // Indicate failure if anything goes awry during setup
    function bail(err) {
      socket.destroy();
      cb(err || new Error('client error during setup'));
    }
    // Work around lack of close event on tls.socket in node < 0.11
    ((socket.socket) ? socket.socket : socket).once('close', bail);
    socket.once('error', bail);
    socket.once('end', bail);
    socket.once('timeout', bail);

    self._socket = socket;
    self._tracker = tracker;

    // Run any requested setup (such as automatically performing a bind) on
    // socket before signalling successful connection.
    // This setup needs to bypass the request queue since all other activity is
    // blocked until the connection is considered fully established post-setup.
    // Only allow bind/search/starttls for now.
    var basicClient = {
      bind: function bindBypass(name, credentials, controls, callback) {
        return self.bind(name, credentials, controls, callback, true);
      },
      search: function searchBypass(base, options, controls, callback) {
        return self.search(base, options, controls, callback, true);
      },
      starttls: function starttlsBypass(options, controls, callback) {
        return self.starttls(options, controls, callback, true);
      },
      unbind: self.unbind.bind(self)
    };
    vasync.forEachPipeline({
      func: function (f, callback) {
        f(basicClient, callback);
      },
      inputs: self.listeners('setup')
    }, function (err, res) {
      if (err) {
        self.emit('setupError', err);
      }
      cb(err);
    });
  }

After connect, register socket event handlers and run any setup actions

After connect register socket event handlers and run any setup actions


function Graph(gridIn, options) {
  options = options || {};
  this.nodes = [];
  this.diagonal = !!options.diagonal;
  this.grid = [];
  for (var x = 0; x < gridIn.length; x++) {
    this.grid[x] = [];

    for (var y = 0, row = gridIn[x]; y < row.length; y++) {
      var node = new GridNode(x, y, row[y]);
      this.grid[x][y] = node;
      this.nodes.push(node);
    }
  }
  this.init();
}

function Graph ( gridIn , options ) { options = options || { } ; this . nodes = [ ] ; this . diagonal = ! ! options . diagonal ; this . grid = [ ] ; for ( var x = 0 ; x < gridIn . length ; x ++ ) { this . grid [ x ] = [ ] ; for ( var y = 0 , row = gridIn [ x ] ; y < row . length ; y ++ ) { var node = new GridNode ( x , y , row [ y ] ) ; this . grid [ x ] [ y ] = node ; this . nodes . push ( node ) ; } } this . init ( ) ; }

A graph memory structure
@param {Array} gridIn 2D array of input weights
@param {Object} [options]
@param {bool} [options.diagonal] Specifies whether diagonal moves are allowed


function(path, i) {
        if(i >= path.length) { // finished removing path, set start positions
            return setStartClass(path, i);
        }
        elementFromNode(path[i]).removeClass(css.active);
        setTimeout(function() {
            removeClass(path, i+1);
        }, timeout*path[i].getCost());
    }


function forEach(array, callback) {
        if (array) {
            for (var i = 0, len = array.length; i < len; i++) {
                var result = callback(array[i], i);
                if (result) {
                    return result;
                }
            }
        }
        return undefined;
    }

function forEach ( array , callback ) { if ( array ) { for ( var i = 0 , len = array . length ; i < len ; i ++ ) { var result = callback ( array [ i ] , i ) ; if ( result ) { return result ; } } } return undefined ; }

Iterates through 'array' by index and performs the callback on each element of array until the callback
returns a truthy value, then returns that value.
If no such value is found, the callback is applied to each element of array and undefined is returned.

Iterates through array by index and performs the callback on each element of array until the callback returns a truthy value then returns that value . If no such value is found the callback is applied to each element of array and undefined is returned .


function arrayToMap(array, makeKey) {
        var result = {};
        forEach(array, function (value) {
            result[makeKey(value)] = value;
        });
        return result;
    }

function arrayToMap ( array , makeKey ) { var result = { } ; forEach ( array , function ( value ) { result [ makeKey ( value ) ] = value ; } ) ; return result ; }

Creates a map from the elements of an array.

@param array the array of input elements.
@param makeKey a function that produces a key for a given element.

This function makes no effort to avoid collisions; if any two elements produce
the same key with the given 'makeKey' function, then the element with the higher
index in the array will be the one associated with the produced key.

Creates a map from the elements of an array .


function createWatchedFileSet(interval, chunkSize) {
                if (interval === void 0) { interval = 2500; }
                if (chunkSize === void 0) { chunkSize = 30; }
                var watchedFiles = [];
                var nextFileToCheck = 0;
                var watchTimer;
                function getModifiedTime(fileName) {
                    return _fs.statSync(fileName).mtime;
                }
                function poll(checkedIndex) {
                    var watchedFile = watchedFiles[checkedIndex];
                    if (!watchedFile) {
                        return;
                    }
                    _fs.stat(watchedFile.fileName, function (err, stats) {
                        if (err) {
                            watchedFile.callback(watchedFile.fileName);
                        }
                        else if (watchedFile.mtime.getTime() !== stats.mtime.getTime()) {
                            watchedFile.mtime = getModifiedTime(watchedFile.fileName);
                            watchedFile.callback(watchedFile.fileName, watchedFile.mtime.getTime() === 0);
                        }
                    });
                }
                // this implementation uses polling and
                // stat due to inconsistencies of fs.watch
                // and efficiency of stat on modern filesystems
                function startWatchTimer() {
                    watchTimer = setInterval(function () {
                        var count = 0;
                        var nextToCheck = nextFileToCheck;
                        var firstCheck = -1;
                        while ((count < chunkSize) && (nextToCheck !== firstCheck)) {
                            poll(nextToCheck);
                            if (firstCheck < 0) {
                                firstCheck = nextToCheck;
                            }
                            nextToCheck++;
                            if (nextToCheck === watchedFiles.length) {
                                nextToCheck = 0;
                            }
                            count++;
                        }
                        nextFileToCheck = nextToCheck;
                    }, interval);
                }
                function addFile(fileName, callback) {
                    var file = {
                        fileName: fileName,
                        callback: callback,
                        mtime: getModifiedTime(fileName)
                    };
                    watchedFiles.push(file);
                    if (watchedFiles.length === 1) {
                        startWatchTimer();
                    }
                    return file;
                }
                function removeFile(file) {
                    watchedFiles = ts.copyListRemovingItem(file, watchedFiles);
                }
                return {
                    getModifiedTime: getModifiedTime,
                    poll: poll,
                    startWatchTimer: startWatchTimer,
                    addFile: addFile,
                    removeFile: removeFile
                };
            }

average async stat takes about 30 microseconds set chunk size to do 30 files in < 1 millisecond


function startWatchTimer() {
                    watchTimer = setInterval(function () {
                        var count = 0;
                        var nextToCheck = nextFileToCheck;
                        var firstCheck = -1;
                        while ((count < chunkSize) && (nextToCheck !== firstCheck)) {
                            poll(nextToCheck);
                            if (firstCheck < 0) {
                                firstCheck = nextToCheck;
                            }
                            nextToCheck++;
                            if (nextToCheck === watchedFiles.length) {
                                nextToCheck = 0;
                            }
                            count++;
                        }
                        nextFileToCheck = nextToCheck;
                    }, interval);
                }

function startWatchTimer ( ) { watchTimer = setInterval ( function ( ) { var count = 0 ; var nextToCheck = nextFileToCheck ; var firstCheck = - 1 ; while ( ( count < chunkSize ) && ( nextToCheck !== firstCheck ) ) { poll ( nextToCheck ) ; if ( firstCheck < 0 ) { firstCheck = nextToCheck ; } nextToCheck ++ ; if ( nextToCheck === watchedFiles . length ) { nextToCheck = 0 ; } count ++ ; } nextFileToCheck = nextToCheck ; } , interval ) ; }

this implementation uses polling and stat due to inconsistencies of fs.watch and efficiency of stat on modern filesystems

this implementation uses polling and stat due to inconsistencies of fs . watch and efficiency of stat on modern filesystems


function scanTemplateAndSetTokenValue() {
            var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */;
            pos++;
            var start = pos;
            var contents = "";
            var resultingToken;
            while (true) {
                if (pos >= end) {
                    contents += text.substring(start, pos);
                    tokenIsUnterminated = true;
                    error(ts.Diagnostics.Unterminated_template_literal);
                    resultingToken = startedWithBacktick ? 11 /* NoSubstitutionTemplateLiteral */ : 14 /* TemplateTail */;
                    break;
                }
                var currChar = text.charCodeAt(pos);
                // '`'
                if (currChar === 96 /* backtick */) {
                    contents += text.substring(start, pos);
                    pos++;
                    resultingToken = startedWithBacktick ? 11 /* NoSubstitutionTemplateLiteral */ : 14 /* TemplateTail */;
                    break;
                }
                // '${'
                if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) {
                    contents += text.substring(start, pos);
                    pos += 2;
                    resultingToken = startedWithBacktick ? 12 /* TemplateHead */ : 13 /* TemplateMiddle */;
                    break;
                }
                // Escape character
                if (currChar === 92 /* backslash */) {
                    contents += text.substring(start, pos);
                    contents += scanEscapeSequence();
                    start = pos;
                    continue;
                }
                // Speculated ECMAScript 6 Spec 11.8.6.1:
                // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for Template Values
                if (currChar === 13 /* carriageReturn */) {
                    contents += text.substring(start, pos);
                    pos++;
                    if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
                        pos++;
                    }
                    contents += "\n";
                    start = pos;
                    continue;
                }
                pos++;
            }
            ts.Debug.assert(resultingToken !== undefined);
            tokenValue = contents;
            return resultingToken;
        }

Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or
a literal component of a TemplateExpression.

Sets the current tokenValue and returns a NoSubstitutionTemplateLiteral or a literal component of a TemplateExpression .


function utf16EncodeAsString(codePoint) {
            ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF);
            if (codePoint <= 65535) {
                return String.fromCharCode(codePoint);
            }
            var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800;
            var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00;
            return String.fromCharCode(codeUnit1, codeUnit2);
        }

function utf16EncodeAsString ( codePoint ) { ts . Debug . assert ( 0x0 <= codePoint && codePoint <= 0x10FFFF ) ; if ( codePoint <= 65535 ) { return String . fromCharCode ( codePoint ) ; } var codeUnit1 = Math . floor ( ( codePoint - 65536 ) / 1024 ) + 0xD800 ; var codeUnit2 = ( ( codePoint - 65536 ) % 1024 ) + 0xDC00 ; return String . fromCharCode ( codeUnit1 , codeUnit2 ) ; }

Derived from the 10.1.1 UTF16Encoding of the ES6 Spec.


function peekUnicodeEscape() {
            if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) {
                var start_1 = pos;
                pos += 2;
                var value = scanExactNumberOfHexDigits(4);
                pos = start_1;
                return value;
            }
            return -1;
        }

function
peekUnicodeEscape
(
)
{
if
(
pos
+
5
<
end
&&
text
.
charCodeAt
(
pos
+
1
)
===
117
/* u */
)
{
var
start_1
=
pos
;
pos
+=
2
;
var
value
=
scanExactNumberOfHexDigits
(
4
)
;
pos
=
start_1
;
return
value
;
}
return
1
;
}

Current character is known to be a backslash. Check for Unicode escape of the form '\uXXXX' and return code point value if valid Unicode escape is found. Otherwise return -1.

Current character is known to be a backslash . Check for Unicode escape of the form \ uXXXX and return code point value if valid Unicode escape is found . Otherwise return - 1 .


function scanJsxIdentifier() {
            if (tokenIsIdentifierOrKeyword(token)) {
                var firstCharPosition = pos;
                while (pos < end) {
                    var ch = text.charCodeAt(pos);
                    if (ch === 45 /* minus */ || ((firstCharPosition === pos) ? isIdentifierStart(ch, languageVersion) : isIdentifierPart(ch, languageVersion))) {
                        pos++;
                    }
                    else {
                        break;
                    }
                }
                tokenValue += text.substr(firstCharPosition, pos - firstCharPosition);
            }
            return token;
        }

function
scanJsxIdentifier
(
)
{
if
(
tokenIsIdentifierOrKeyword
(
token
)
)
{
var
firstCharPosition
=
pos
;
while
(
pos
<
end
)
{
var
ch
=
text
.
charCodeAt
(
pos
)
;
if
(
ch
===
45
/* minus */
||
(
(
firstCharPosition
===
pos
)
isIdentifierStart
(
ch
,
languageVersion
)
:
isIdentifierPart
(
ch
,
languageVersion
)
)
)
{
pos
++
;
}
else
{
break
;
}
}
tokenValue
+=
text
.
substr
(
firstCharPosition
,
pos
firstCharPosition
)
;
}
return
token
;
}

Scans a JSX identifier; these differ from normal identifiers in that they allow dashes

Scans a JSX identifier ; these differ from normal identifiers in that they allow dashes


function getDeclarationName(node) {
            if (node.name) {
                if (node.kind === 218 /* ModuleDeclaration */ && node.name.kind === 9 /* StringLiteral */) {
                    return "\"" + node.name.text + "\"";
                }
                if (node.name.kind === 136 /* ComputedPropertyName */) {
                    var nameExpression = node.name.expression;
                    ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
                    return ts.getPropertyNameForKnownSymbolName(nameExpression.name.text);
                }
                return node.name.text;
            }
            switch (node.kind) {
                case 144 /* Constructor */:
                    return "__constructor";
                case 152 /* FunctionType */:
                case 147 /* CallSignature */:
                    return "__call";
                case 153 /* ConstructorType */:
                case 148 /* ConstructSignature */:
                    return "__new";
                case 149 /* IndexSignature */:
                    return "__index";
                case 228 /* ExportDeclaration */:
                    return "__export";
                case 227 /* ExportAssignment */:
                    return node.isExportEquals ? "export=" : "default";
                case 213 /* FunctionDeclaration */:
                case 214 /* ClassDeclaration */:
                    return node.flags & 1024 /* Default */ ? "default" : undefined;
            }
        }

function
getDeclarationName
(
node
)
{
if
(
node
.
name
)
{
if
(
node
.
kind
===
218
/* ModuleDeclaration */
&&
node
.
name
.
kind
===
9
/* StringLiteral */
)
{
return
"\""
+
node
.
name
.
text
+
"\""
;
}
if
(
node
.
name
.
kind
===
136
/* ComputedPropertyName */
)
{
var
nameExpression
=
node
.
name
.
expression
;
ts
.
Debug
.
assert
(
ts
.
isWellKnownSymbolSyntactically
(
nameExpression
)
)
;
return
ts
.
getPropertyNameForKnownSymbolName
(
nameExpression
.
name
.
text
)
;
}
return
node
.
name
.
text
;
}
switch
(
node
.
kind
)
{
case
144
/* Constructor */
:
return
"__constructor"
;
case
152
/* FunctionType */
:
case
147
/* CallSignature */
:
return
"__call"
;
case
153
/* ConstructorType */
:
case
148
/* ConstructSignature */
:
return
"__new"
;
case
149
/* IndexSignature */
:
return
"__index"
;
case
228
/* ExportDeclaration */
:
return
"__export"
;
case
227
/* ExportAssignment */
:
return
node
.
isExportEquals
"export="
:
"default"
;
case
213
/* FunctionDeclaration */
:
case
214
/* ClassDeclaration */
:
return
node
.
flags
&
1024
/* Default */
"default"
:
undefined
;
}
}

Should not be called on a declaration with a computed property name, unless it is a well known Symbol.

Should not be called on a declaration with a computed property name unless it is a well known Symbol .


function bindChildren(node) {
            // Before we recurse into a node's chilren, we first save the existing parent, container
            // and block-container.  Then after we pop out of processing the children, we restore
            // these saved values.
            var saveParent = parent;
            var saveContainer = container;
            var savedBlockScopeContainer = blockScopeContainer;
            // This node will now be set as the parent of all of its children as we recurse into them.
            parent = node;
            // Depending on what kind of node this is, we may have to adjust the current container
            // and block-container.   If the current node is a container, then it is automatically
            // considered the current block-container as well.  Also, for containers that we know
            // may contain locals, we proactively initialize the .locals field. We do this because
            // it's highly likely that the .locals will be needed to place some child in (for example,
            // a parameter, or variable declaration).
            //
            // However, we do not proactively create the .locals for block-containers because it's
            // totally normal and common for block-containers to never actually have a block-scoped
            // variable in them.  We don't want to end up allocating an object for every 'block' we
            // run into when most of them won't be necessary.
            //
            // Finally, if this is a block-container, then we clear out any existing .locals object
            // it may contain within it.  This happens in incremental scenarios.  Because we can be
            // reusing a node from a previous compilation, that node may have had 'locals' created
            // for it.  We must clear this so we don't accidently move any stale data forward from
            // a previous compilation.
            var containerFlags = getContainerFlags(node);
            if (containerFlags & 1 /* IsContainer */) {
                container = blockScopeContainer = node;
                if (containerFlags & 4 /* HasLocals */) {
                    container.locals = {};
                }
                addToContainerChain(container);
            }
            else if (containerFlags & 2 /* IsBlockScopedContainer */) {
                blockScopeContainer = node;
                blockScopeContainer.locals = undefined;
            }
            if (node.kind === 215 /* InterfaceDeclaration */) {
                seenThisKeyword = false;
                ts.forEachChild(node, bind);
                node.flags = seenThisKeyword ? node.flags | 524288 /* ContainsThis */ : node.flags & ~524288 /* ContainsThis */;
            }
            else {
                ts.forEachChild(node, bind);
            }
            container = saveContainer;
            parent = saveParent;
            blockScopeContainer = savedBlockScopeContainer;
        }

All container nodes are kept on a linked list in declaration order. This list is used by the getLocalNameOfContainer function in the type checker to validate that the local name used for a container is unique.

All container nodes are kept on a linked list in declaration order . This list is used by the getLocalNameOfContainer function in the type checker to validate that the local name used for a container is unique .


function nodePosToString(node) {
        var file = getSourceFileOfNode(node);
        var loc = ts.getLineAndCharacterOfPosition(file, node.pos);
        return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")";
    }

function nodePosToString ( node ) { var file = getSourceFileOfNode ( node ) ; var loc = ts . getLineAndCharacterOfPosition ( file , node . pos ) ; return file . fileName + "(" + ( loc . line + 1 ) + "," + ( loc . character + 1 ) + ")" ; }

This is a useful function for debugging purposes.

This is a useful function for debugging purposes .


function unescapeIdentifier(identifier) {
        return identifier.length >= 3 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ && identifier.charCodeAt(2) === 95 /* _ */ ? identifier.substr(1) : identifier;
    }

function
unescapeIdentifier
(
identifier
)
{
return
identifier
.
length
>=
3
&&
identifier
.
charCodeAt
(
0
)
===
95
/* _ */
&&
identifier
.
charCodeAt
(
1
)
===
95
/* _ */
&&
identifier
.
charCodeAt
(
2
)
===
95
/* _ */
identifier
.
substr
(
1
)
:
identifier
;
}

Remove extra underscore from escaped identifier