Beispiel #1
0
export default function onlyWhen(predicate, ...args) {
  if (!isFunction(predicate)) {
    throw new Error('predicate must be a function.')
  }

  const message = isFunction(args[0]) ? predicate.toString() : args[0]
  const propType = isFunction(args[0]) ? args[0] : args[1]

  if (!isFunction(propType)) {
    throw new Error(`Invalid propType passed to 'onlyWhen': ${propType}.`)
  }

  return (propValue, key, componentName, location, propFullName) => {
    if (predicate(propValue)) {
      return propType(propValue, key, componentName, location, propFullName)
    }

    if (isDefined(propValue[key])) {
      return new Error(
        `Prop '${key}' is only used by '${componentName}' when ${message}.`
      )
    }
    return null
  }
}
Beispiel #2
0
                inquirer.prompt(questions).then((result) => {
                    if (options.postQuestions && isFunction(options.postQuestions)) {
                        options.postQuestions(result);
                    }

                    this.process(result, options, () => {});

                    if (options.after && isFunction(options.after)) {
                        options.after(result);
                    }

                    done();
                }).catch((err) => {
Beispiel #3
0
function RP$callback(err, response, body) {

    /* jshint validthis:true */
    var self = this;

    var origCallbackThrewException = false, thrownException;

    if (isFunction(self._rp_callbackOrig)) {
        try {
            self._rp_callbackOrig.apply(self, arguments);
        } catch (e) {
            origCallbackThrewException = true;
            thrownException = e;
        }
    }

    if (err) {

        self._rp_reject(assign(new errors.RequestError(err), {
            error: err,
            options: self._rp_options,
            response: response
        }));

    } else if (self._rp_options.simple && !(/^2/.test('' + response.statusCode))) {

        self._rp_reject(assign(new errors.StatusCodeError(response.statusCode, body), {
            error: body,
            options: self._rp_options,
            response: response
        }));

    } else {
        if (isFunction(self._rp_options.transform)) {
            try {
                self._rp_resolve(self._rp_options.transform(body, response, self._rp_options.resolveWithFullResponse));
            } catch (e) {
                self._rp_reject(e);
            }
        } else if (self._rp_options.resolveWithFullResponse) {
            self._rp_resolve(response);
        } else {
            self._rp_resolve(body);
        }
    }

    if (origCallbackThrewException) {
        throw thrownException;
    }

}
Beispiel #4
0
  Sockets.close(this._id, function() {
    self._debug('closed')

    if (isFunction(fn)) {
      fn()
    }
  });
/**
 * Resolves the value of property `key` on `object`. If the value of `key` is
 * a function it is invoked with the `this` binding of `object` and its result
 * is returned, else the property value is returned. If the property value is
 * `undefined` the `defaultValue` is used in its place.
 *
 * @static
 * @memberOf _
 * @category Object
 * @param {Object} object The object to query.
 * @param {string} key The key of the property to resolve.
 * @param {*} [defaultValue] The value returned if the property value
 *  resolves to `undefined`.
 * @returns {*} Returns the resolved value.
 * @example
 *
 * var object = { 'user': '******', 'age': _.constant(40) };
 *
 * _.result(object, 'user');
 * // => 'fred'
 *
 * _.result(object, 'age');
 * // => 40
 *
 * _.result(object, 'status', 'busy');
 * // => 'busy'
 *
 * _.result(object, 'status', _.constant('busy'));
 * // => 'busy'
 */
function result(object, key, defaultValue) {
  var value = object == null ? undefined : object[key];
  if (typeof value == 'undefined') {
    value = defaultValue;
  }
  return isFunction(value) ? value.call(object) : value;
}
Beispiel #6
0
    function intercepted() {
        var newArgs, value;
        var origArgs = toArray(arguments);

        if (isFunction(input)) {
            newArgs = input.call(this, origArgs);
        }

        value = original.apply(this, newArgs || origArgs);

        if (isFunction(output)) {
            return output.call(this, value);
        } else {
            return value;
        }
    }
Beispiel #7
0
module.exports = function intercept(host, name, input, output) {
    var original = host[name];

    if (isFunction(original)) {
        host[name] = intercepted;
        return release;
    } else {
        return noop;
    }

    function intercepted() {
        var newArgs, value;
        var origArgs = toArray(arguments);

        if (isFunction(input)) {
            newArgs = input.call(this, origArgs);
        }

        value = original.apply(this, newArgs || origArgs);

        if (isFunction(output)) {
            return output.call(this, value);
        } else {
            return value;
        }
    }

    function release() {
        host[name] = original;
    }
};
  Object.keys(yargsOptions).forEach(optKey => {
    const yargOpt = yargsOptions[optKey];
    const aliases = yargOpt.alias;
    const defaultVal = isFunction(yargOpt.default) ? yargOpt.default() : yargOpt.default;
    const isBool = yargOpt.boolean;
    let userVal = _getUserOption(userOptions, optKey, isBool);

    // Most options are single-letter so we add the aliases as properties
    if (Array.isArray(aliases) && aliases.length) {
      // If the main prop does not have a user supplied value
      // we need to check the aliases, stopping if we get a user value
      if (userVal === undefined) {
        for (let i = 0; i < aliases.length; i += 1) {
          userVal = _getUserOption(userOptions, aliases[i], isBool);
          if (userVal !== undefined) {
            break;
          }
        }
      }

      // Handle cases where the main option is not a single letter
      if (optKey.length > 1) assignVal(mergedOptions, optKey, userVal, defaultVal);

      // Loop through aliases to set val
      aliases.forEach(alias => assignVal(mergedOptions, alias, userVal, defaultVal));
    } else {
      // For options without aliases, use the option regardless of length
      assignVal(mergedOptions, optKey, userVal, defaultVal);
    }
  });
Beispiel #9
0
function inflateObject(obj) {
  var value = obj;
  if (isFunction(obj.serialize)) {
    value = obj.serialize();
  }
  return reduce(value, inflateReducer, {});
}
  getApiFetchArgsFromActionPayload(payload, token=null, authenticate=true) {
    let { headers, endpoint, method, body, credentials } = payload;
    if (isUndefined(method)) {
      method = 'GET';
    }

    headers = Object.assign({}, this.defaultHeaders, headers);

    if (token && authenticate) {
      (
        { headers, endpoint, body } = this.addTokenToRequest(
          headers, endpoint, body, token
        )
      );
    }
    if (isFunction(this.preProcessRequest)) {
      (
        { headers, endpoint, body } = this.preProcessRequest(
          headers, endpoint, body
        )
      )
    }

    return [
      endpoint, omitBy({method, body, credentials, headers}, isUndefined)
    ];
  }
Beispiel #11
0
  then: function(autocrat, governor, origHandler, context) {
    var streamsHash = this.streamsHash,
        handlerSequence, isFirstHandler, deferred, handler;

    context || (context = this.governor);

    if(isFunction(origHandler)) {
      origHandler = bind(origHandler, context);
    } else if(isString(origHandler)){
      origHandler = bind(this.governor[origHandler], context);
    }

    if(autocrat.awaiting[this.streamsHash]) {
      handlerSequence = autocrat.awaiting[this.streamsHash];
    } else {
      handlerSequence = autocrat.awaiting[this.streamsHash] = [];
      isFirstHandler = true;
    }

    deferred = new HandlerDeferred(handlerSequence);
    handler = this._buildAsyncHandler(origHandler, deferred);

    if(isFirstHandler) {
      deferred.handlerIndex = 0;
      handlerSequence.push(handler);
      this.resultStream.subscribe(handler);
    } else {
      deferred.handlerIndex = handlerSequence.length;
      handlerSequence.push(handler);
    }

    // terminate chain
    return this;
  },
Beispiel #12
0
  handleRequestConversationData(reply) {
    if (!isFunction(reply)) {
      reply = () => {}
    }

    getConversationData(reply)
  }
Beispiel #13
0
  updateProp: function(propName, updater) {
    var updaterName, handler;

    if(!isFunction(updater)) {
      updaterName = 'update' + propName[0].toUpperCase() + propName.slice(1);
      updater = this.governor[updaterName];
    }

    if(updater) {
      this.then(function(advisorEvent, deferred, consequenceActions, streamEvent) {
        var currVal = this.props[propName].value;
        var updaterArgs = [currVal].concat(advisorEvent, streamEvent);
        var retVal = updater.apply(this, updaterArgs);

        // Only trigger a reactive change if the value has actually changed;
        // if(!isEqual(retVal, currVal)) this.props[propName] = retVal;
        this.props[propName] = retVal

        deferred.resolve(retVal);
      });
    } else {
      throw new Error('An updater function was not specified and governor.' + updaterName + ' is not defined');
    }

    return this;
  },
Beispiel #14
0
function batteryRemaining(battery, callback) {
  if (isFunction(battery)) {
    callback = battery;
    battery = 'BAT0';
  }

  function getRemaining(location, callback) {
    firstLine(location, function(error, remaining) {
      if (error) {
        callback(error);
        return;
      }

      remaining = parseFloat(remaining.toString());

      // convert muWatts to Watts
      remaining *= Math.pow(10, -6);

      callback(null, remaining);
    });
  }

  var bstr = path.resolve(batteryPath(battery), 'energy_now');
  getRemaining(bstr, function(error, remaining) {
    if (error) {

      // try alternate location
      bstr = path.resolve(batteryPath(battery), 'charge_now');
      getRemaining(bstr, callback);
      return;
    }

    callback(null, remaining);
  });
}
Beispiel #15
0
function TracedCount() {
    this.trace = [];
    this.count = 0;
    for (var prop in this)
        if (isFunction(this[prop]))
            this[prop] = this[prop].bind(this);
}
Beispiel #16
0
  handleConvertJSONToCML(data, reply) {
    if (!isFunction(reply)) {
      reply = () => {}
    }

    convertJSONtoCML(data, reply)
  }
function isValidAction(action) {
    const isFunc = isFunction(action);
    const isObj = isObject(action);
    const hasType = isObj && action.hasOwnProperty('type');

    if (!isFunc && isObj && hasType) {
        return true;
    }

    if (process.env.NODE_ENV !== 'production') {
        if (isFunc) {
            console.warn( // eslint-disable-line no-console
                `[redux-storage] ACTION IGNORED! Actions should be objects`
                + ` with a type property but received a function! Your`
                + ` function resolving middleware (e.g. redux-thunk) must be`
                + ` placed BEFORE redux-storage!`
            );
        } else if (!isObj) {
            console.warn( // eslint-disable-line no-console
                `[redux-storage] ACTION IGNORED! Actions should be objects`
                + ` with a type property but received: ${action}`
            );
        } else if (!hasType) {
            console.warn( // eslint-disable-line no-console
                `[redux-storage] ACTION IGNORED! Action objects should have`
                + ` a type property.`
            );
        }
    }

    return false;
}
Beispiel #18
0
export function getBuilder(debug, target, createBuilders, extensionCreateBuilders) {
    if (isPlainObject(createBuilders)) {
        const rocBuilder = getBuildersFromObject(debug, target, createBuilders);
        once = false;
        return rocBuilder;
    } else if (Array.isArray(createBuilders)) {
        let rocBuilder = { buildConfig: {}, builder: require('webpack')};
        createBuilders.forEach((builder) => {
            rocBuilder = builder(target, rocBuilder);
        });
        if (debug && once) {
            once = false;
            console.log('createBuilder overridden in roc.config.js with an array, will use that.');
        }

        return rocBuilder;
    } else if (isFunction(createBuilders)) {
        let rocBuilder = getBuildersFromObject(debug, target, extensionCreateBuilders);

        if (debug) {
            once = false;
            console.log('Will also use the createBuilder defined in roc.config.js.');
        }

        return createBuilders(target, rocBuilder);
    }
}
Beispiel #19
0
	secureNet.getCurrentBatch = function(next) {

		//validate
		Assert.ok(isFunction(next), 'param `next` must be a next ');

		secureNet.getBatch(null, next);
	};
Beispiel #20
0
	secureNet.closeBatch = function(next) {

		//validate
		Assert.ok(isFunction(next), 'param `next` must be a next ');

		util.post('batches/Close', null, next);
	};
Beispiel #21
0
            validated = Object.keys(requestQuery).every(function (prop) {

                var validateValue = validator[prop];
                var requestQueryValue = requestQuery[prop];

                // Fail if there is no validation for this field
                if (validateValue === undefined) {
                    return;
                }

                // Accept any and everything
                if (validateValue === true) {
                    return true;
                }

                // Validate against a literal Regex
                if (validateValue.exec) {
                    return !!validateValue.exec(requestQueryValue);
                }

                if (_isFunction(validateValue)) {
                    return !!validateValue(requestQueryValue);
                }

                return validateValue === requestQueryValue;

            });
    router(routePathes, initialRouteDispatch, (...args) => {
      const dispatchResult = redux.dispatch(userRoutesActions.changeRoute(...args));
      // resolve on server after all actions in userRoutesActions.changeRoute resolved
      if (isServerCall) {
        if (!dispatchResult || !isFunction(dispatchResult.then)) {
          reject(new Error('dispatchResult must be promise on server'));
        }

        if (dispatchResult && isFunction(dispatchResult.then)) {
          dispatchResult.then(
            () => resolve(redux), // result is'n needed it's just to be sure all actions done
            err => reject(err)
          );
        }
      }
    });
Beispiel #23
0
function updateTarget(target, StateSlice, dispatch) {
  if(isFunction(target)) {
    target(StateSlice, dispatch);
  } else {
    assign(target, StateSlice, dispatch);
  }
}
Beispiel #24
0
  dial (ma, options, callback) {
    if (isFunction(options)) {
      callback = options
      options = {}
    }

    callback = once(callback || noop)

    const cOpts = ma.toOptions()
    log('Connecting to %s %s', cOpts.port, cOpts.host)

    const rawSocket = net.connect(cOpts)

    rawSocket.once('timeout', () => {
      log('timeout')
      rawSocket.emit('error', new Error('Timeout'))
    })

    rawSocket.once('error', callback)

    rawSocket.once('connect', () => {
      rawSocket.removeListener('error', callback)
      callback()
    })

    const socket = toPull.duplex(rawSocket)

    const conn = new Connection(socket)

    conn.getObservedAddrs = (callback) => {
      return callback(null, [ma])
    }

    return conn
  }
Beispiel #25
0
Rend.prototype.render = function (template, vm, callback) {
    var self = this;

    if (!isFunction(callback)) {
        throw new Error('callback is required');
    }
    else if (!template) {
        callback(new Error('template is required'));
    }
    else {
        this.getTemplateFns(function (error, templateFns) {
            if (error) {
                callback(error);
            }
            else {
                var templateFn = templateFns[template];

                if (!templateFn) {
                    callback(new Error('template not found'));
                }
                else {
                    _render(templateFn, vm, callback);
                }
            }
        });
    }
};
Beispiel #26
0
	secureNet.verify = function(data, next) {

		//validate
		Assert.ok(isObject(data), 'param `data` must be an object.');
		Assert.ok(isFunction(next), 'param `next` must be a next ');

		util.post('/Payments/Verify', data, next);
	};
Beispiel #27
0
	secureNet.createCustomer = function(data, next) {

		//validate
		Assert.ok(isObject(data), 'param `data` must be an object.');
		Assert.ok(isFunction(next), 'param `next` must be a next ');

		util.post('/Customers', data, next);
	};
Beispiel #28
0
MixedNode.prototype.sanitizer = function sanitizer(callback) {
  if (!isFunction(callback)) {
    throw new Error('The passed `callback` (first argument) is not a function');
  }

  this.options.sanitizer = callback;
  return this;
};
function getScriptsFromConfig(scripts, input) {
  if (isPlainObject(scripts)) {
    return scripts
  } else if (isFunction(scripts)) {
    return scripts(input)
  }
  return {}
}
Beispiel #30
0
 forEach(obj, function (value, key) {
   var fullKey = prefix ? prefix + "." + key : key;
   if (isObject(value) && !isArray(value) && !isFunction(value)) {
     keys = keys.concat(getKeys(value, fullKey));
   } else {
     keys.push(fullKey);
   }
 });