Ejemplo n.º 1
0
function redactJavascript(code, features, keepDescriptor) {
  keepDescriptor = keepDescriptor || false;
  var nextByte = 0;

  function recurse(redactedCode, toggleIfStatement) {
    var nextToConditional = "{} // " + toggleIfStatement.name + " redacted";
    var beginning = toggleIfStatement.start;
    var newNextByte = toggleIfStatement.end;

    if (toggleIfStatement.toggled) {
      nextToConditional = '';
      beginning = toggleIfStatement.conditional_start;
      newNextByte = toggleIfStatement.start;
    }

    if (beginning > nextByte || nextByte == 0) {
      redactedCode += code.substring(nextByte, toggleIfStatement.conditional_start);
      if (keepDescriptor) {
        redactedCode += code.substring(toggleIfStatement.conditional_start, toggleIfStatement.start) + nextToConditional;
      }
      nextByte = newNextByte;
    }

    return redactedCode;
  }

  return _.foldl(collectIfStatements(code, features), recurse, "") + code.substring(nextByte, code.length);
}
Ejemplo n.º 2
0
 function addIfStatements(accumulator, node) {
   if (isIfStatement(node) && isFeatureToggle(node, toggles)) {
     accumulator.push({name: node.test.property.name, toggled: toggles[node.test.property.name],
       start: node.consequent.start, end: node.consequent.end, conditional_start: node.start });
     return _.foldl([node.consequent], addIfStatements, accumulator);
   } else if (_.has(node, "body") && _.isArray(node.body)) {
     return _.foldl(node.body, addIfStatements, accumulator);
   } else if (_.has(node, "body") && !_.isArray(node.body)) {
     return _.foldl([node.body], addIfStatements, accumulator);
   } else if (_.has(node, "callee")) {
     return _.foldl([node.callee], addIfStatements, accumulator);
   } else if (_.has(node, "expression")) {
     return _.foldl([node.expression], addIfStatements, accumulator);
   } else {
     return accumulator;
   }
 }
					function(result) {					
						if(result.facets.namespace.total > 0){
							return lodash.foldl(result.facets.namespace.terms,function(namespaces,term){
								namespaces[term.term] = term.count;
								return namespaces;
							},{});
						}
						return {};										
					},
Ejemplo n.º 4
0
function getCurrentUniforms (transition) {
  var uniforms = transition.getUniforms().uniforms;
  var uniformsKeys = _.difference(
      _.keys(uniforms),
      ignoredUniforms
      );
  return _.foldl(uniformsKeys, function (obj, k) {
    obj[k] = uniforms[k];
    return obj;
  }, {});
}
Ejemplo n.º 5
0
    throughSuccessors: function (g, v, filter) {
      var succ = g.successors(v);
      var visited = {};
      var r = _.memoize(function (accum, value) {
          visited[value] = true;
          return accum.concat(_.foldl(_.filter(g.successors(value), function (v) { return !_.has(visited, v); }), r, [value]));
        }, function (accum, value) { return value; });
      r.cache = msfc.cache;

      if (typeof succ === 'undefined') {
        return 0;
      }
      else if (typeof filter === 'undefined') {
        return _.uniq(_.foldl(succ, r, [v])).length;
      }
      else {
        // TODO this intersection is still quite expensive; moar memoization
        return _.uniq(_.intersection(_.foldl(succ, r, [v]), filter)).length;
      }
    }
Ejemplo n.º 6
0
 mapChunked: function(xs, chunksize, f) {
     return Promise.all(_.foldl(
         _.chunk(xs, chunksize),
         function(acc, chunk) {
             return acc.then(function() {
                 return Promise.all(
                     _.map(chunk, function(val) { return f(val); })
                 );
             })
         },
         new Promise(function(resolve, reject) { resolve(); })
     ));
 }
Ejemplo n.º 7
0
    $scope.$watch('ctrl.orgServerStats', stats => {
        if (!stats) return;
        const serverStats = _.foldl(
            stats,
            (acc, stat) => {
                const virtualCount = acc.virtualCount + stat.virtualCount;
                const physicalCount = acc.physicalCount + stat.physicalCount;
                return { virtualCount, physicalCount };
            },
            { virtualCount: 0, physicalCount: 0});

        enrichServerStats(serverStats);

        vm.serverStats = serverStats;
    });
Ejemplo n.º 8
0
  recordPlay: function(flow) {
    this.stats.flowsPlayed += 1;
    this.stats.moves += flow.moves.length;

    var secondsPlayed = _.foldl(flow.moves, function(total, current) {
      return total + current.duration;
    }, 0);

    this.stats.secondsPlayed += secondsPlayed;
    if (secondsPlayed > this.stats.longestFlow) {
      this.stats.longestFlow = secondsPlayed;
    }
    
    return this.addRecentPlay(flow._id);
  },
var BestEV = function BestEV() {
    betDist = lib.getDistribution(currentBets);
    winDist = lib.getDistribution(scores);
    var TotalBet = _.foldl(currentBets, function (acc, elem) {
        return acc + elem;
    }, 0);
    var EV_Tuples = [];
    currentBets.forEach(function (v, i) {
        var maxBet = Math.max(lib.minbet,Math.ceil((winDist[i] * myCoins) / 15));
        var myBet = lib.bestValue(TotalBet, currentBets[i], winDist[i], maxBet);
        var valueBet = lib.expectedValue(myBet, winDist[i], TotalBet, currentBets[i]);
        EV_Tuples.push({ bet: myBet, value: valueBet, index: i });
    });
    EV_Tuples.sort(function (a, b) {
        return ((a.value - a.bet) < (b.value - b.bet))? 1: -1;
    });
    return EV_Tuples;
}
 var Troll_Bet = function Troll_Bet(proportion, gs) {
     winDist = lib.getDistribution(gs.scores);
     var TotalBet = _.foldl(gs.currentBets, function (acc, elem) {
         return acc + elem;
     }, 0);
     var EVs = BetEVs(gs);
     var lastPos = (function () {
         var ret = 1; // Start at one so if we mess up, we can use it as noninclusive right side
         for (; ret < EVs.length; ret++) {
             if (EVs[ret].value - EVs[ret].bet <= 0) {
                 break;
             }
         }
         return ret;
     })();
     var ind = EVs[randomIntFromInterval(0, lastPos - 1)].index;
     bot.say("#amiibofighter", "!bet " + Math.max(myCoins + 1, Math.ceil(TotalBet * winDist[ind] * proportion)) + " " + (ind + 1));
     console.log(("Trolling on index: " + ind).bgRed.white);
 }
Ejemplo n.º 11
0
tasks.packageFiles = function(options, blobs, done) {
  var content,
      coreFile  = _.head(blobs),
      languages = _.tail(blobs),

      lines     = coreFile.result
                    .replace(utility.regex.header, '')
                    .split('\n\n'),
      lastLine  = _.last(lines),
      langStr   = _.foldl(languages, function(str, language) {
                    return str + language.result + '\n';
                  }, '');

  lines[lines.length - 1] = langStr.trim();

  lines   = lines.concat(lastLine);
  content = lines.join('\n\n');

  return done(null, [new gear.Blob(content)]);
};
Ejemplo n.º 12
0
    ee.on('done', function(stats) {
      var requests = stats.aggregate.requestsCompleted;
      var scenarios = stats.aggregate.scenariosCompleted;
      console.log('requests = %s, scenarios = %s', requests, scenarios);

      t.assert(completedPhases === script.config.phases.length,
        'Should\'ve completed all phases');
      var completedAt = process.hrtime(startedAt);
      var delta = ((completedAt[0] * 1e9) + completedAt[1]) / 1e6;
      var minDuration = l.foldl(script.config.phases, function(acc, phaseSpec) {
        return acc + (phaseSpec.duration * 1000);
      }, 0);
      t.assert(delta >= minDuration,
        'Should run for at least the total duration of phases');

      t.assert(requests > 0, 'Should have successful requests');
      t.assert(scenarios > 0, 'Should have successful scenarios');

      t.end();
    });
		var createType = function createType(type, constraints) {
			return lodash.foldl(constraints, function(type, constraint) {
				if (constraint.method === 'objectSchemaType') {
					type.objectSchemaType = function(namespace, version, type) {
						this.add('objectSchemaType', function(value, obj, key, errors, keyPath) {
							var objectShemaTypeKey = {
								namespace : namespace,
								version : version,
								type : type
							};
							var objectSchemaType = getObjectSchemaFxn(objectShemaTypeKey);
							if (objectSchemaType === null) {
								errors.add('Unknown ObjectSchema Type: ' + JSON.stringify(objectShemaTypeKey), keyPath);
								return false;
							}
							try {
								objectSchemaType.validate(value, getObjectSchemaFxn);
								return true;
							} catch (err) {
								errors.add(err.message, keyPath);
								return false;
							}

						}, arguments);

						return this;
					};
					return type.objectSchemaType(constraint.args[0], constraint.args[1], constraint.args[2]);
				}

				if (type.type === 'Array' && (constraint.method === 'includes' || constraint.method === 'excludes')) {
					var constraintMethodArgs = lodash.map(constraint.args, function(arg) {
						var arrayElementType = joi.types[arg.type]();
						return createType(arrayElementType, arg.constraints);
					});
					return type[constraint.method].apply(type, constraintMethodArgs);
				}

				return type[constraint.method].apply(type, constraint.args);
			}, type);
		};
		return when.promise(function(resolve, reject) {
			if (!lodash.isArray(entities)) {
				reject(new Error('entities is required to be an Array'));
				if (log.isDebugEnabled()) {
					log.debug('createEntities(): entities is not an array\n' + JSON.stringify(entities, undefined, 2));
				}
				return;
			}

			if (entities.length === 0) {
				resolve();
				return;
			}

			if (log.isDebugEnabled()) {
				log.debug('createEntities():\n' + JSON.stringify(entities, undefined, 2));
			}

			var newEntity;
			var payload = lodash.foldl(entities, function(payload, entity) {
				newEntity = new self.Entity(entity);
				extend(newEntity,entity);
				payload += JSON.stringify({
					index : {
						_index : self.index,
						_type : self.type,
						_id : entity.id
					}
				});
				payload += '\n';
				payload += JSON.stringify(newEntity);
				payload += '\n';
				return payload;
			}, '');

			/*
			 * elastic.js does not support the elasticsearch's bulk api, so
			 * let's make the HTTP request ourselves
			 */
			self.ejs.client.post('/' + self.index + '/' + self.type + '/_bulk', payload, resolve, reject);
		});
Ejemplo n.º 15
0
var _generateEither = function(either) {

    // Collect all adjacent option nodes into groups.
    var collected = _.foldl(either, function(acc, node) {
        var last = _.last(acc);
        return (last && _.last(last) && _.last(last).type === nodes.TYPE.OPTION)
          ? (last.push(node)) && acc
          : acc.push([ node ]) && acc;
    }, []);

    return base.cons.apply(null, _.map(collected, function(collection) {
        // XXX This is ugly - we know the collection is not empty and
        //     homogenous, hence we can sample it like this. Should be written
        //     differently.
        if ((_.head(collection).type === nodes.TYPE.OPTION)) {
            var available = _.map(collection, _generateNode);
            return parse.rec(function(self) {
                return parse.optional(
                    []
                  , parse.choicea(_.map(available, function(parser) {
                        return parse.attempt(base.$(parser))
                            .chain(function(output) {
                                available = _.without(parser);
                                return self.map(function(outputs) {
                                    return [ output ].concat(outputs);
                                });
                            });
                  }))
                );
            });
        } else {
            return parse.choicea(_.map(
                collection
              , _.flow(_generateNode, base.$, parse.attempt)
            ));
        }
    })).map(_.flatten);
};
		return when.promise(function(resolve, reject) {
			if (!lodash.isArray(ids)) {
				reject(new Error('ids is required to be an Array'));
				if (log.isDebugEnabled()) {
					log.debug('deleteEntities(): ids is not an array\n' + JSON.stringify(ids, undefined, 2));
				}
				return;
			}

			if (ids.length === 0) {
				resolve();
				return;
			}

			validateIdsArray(ids);

			if (log.isDebugEnabled()) {
				log.debug('ids():\n' + JSON.stringify(ids, undefined, 2));
			}

			var payload = lodash.foldl(ids, function(payload, id) {
				payload += JSON.stringify({
					"delete" : {
						_index : self.index,
						_type : self.type,
						_id : id
					}
				});
				payload += '\n';
				return payload;
			}, '');

			/*
			 * elastic.js does not support the elasticsearch's bulk api, so
			 * let's make the HTTP request ourselves
			 */
			self.ejs.client.post('/' + self.index + '/' + self.type + '/_bulk', payload, resolve, reject);
		});
	it('#getObjectSchemas',function(done){
		var objectSchemas = [];
		var i;
		for(i=0;i<10;i++){
			objectSchemas.push(new ObjectSchema({
				namespace : 'ns://runrightfast.co/runrightfast-api-gateway',
				version : '1.0.' + i,
				description : 'runrightfast-api-gateway config'
			}));
		}

		var promises = lodash.foldl(objectSchemas,function(promises,objectSchema){
			idsToDelete.push(objectSchema.id);
			promises.push(database.createObjectSchema(objectSchema));
			return promises;
		},[]);

		when(when.all(promises),
			function(result){
				console.log(JSON.stringify(result,undefined,2));
				var ids = objectSchemas.map(function(objectSchema){
					return objectSchema.id;
				});
				when(database.getObjectSchemas(ids),
					function(result){
						try{
							console.log(JSON.stringify(result,undefined,2));
							expect(result.docs.length).to.equal(10);
							done();
						}catch(err){
							done(err);
						}
					}
				);				
			},
			done
		);
	});
var EV_Bet = function EV_Bet() {
    var evs = BestEV();
    var doThis = evs[0];
    bot.say("#amiibofighter", "!bet " + doThis.bet + " " + (doThis.index + 1));
    // allocate other good bets among highroller bots
    highRollAccounts = lib.shuffle(highRollAccounts);
    for (var i = 1; (i < evs.length) && ((evs[i].value - evs[i].bet) >= 0); i++) {
        if (highRollAccounts[i]) {
            highRollAccounts[i].bet(evs[i].index, evs[i].bet);
        }
    }
    // Redoing some calculations after we dispatch the message
    betDist = lib.getDistribution(currentBets);
    winDist = lib.getDistribution(scores);
    var TotalBet = _.foldl(currentBets, function (acc, elem) {
        return acc + elem;
    }, 0);
    console.log(("Betting " + doThis.bet + " on index " + doThis.index).bgWhite.blue);
    console.log(("We expect to gain " + (doThis.value - doThis.bet) + " with total bet: " + TotalBet).green.bgWhite);
    console.log(("Best Case: " + Math.floor((doThis.bet / (currentBets[doThis.index] + doThis.bet)) * TotalBet)).black.bgWhite);
    console.log(("Bet Distribution:" + JSON.stringify(_.map(betDist, function (p) { return Math.floor(p * 100); }))).bgWhite.red);
    console.log(("Win Distribution:" + JSON.stringify(_.map(winDist, function (p) { return Math.floor(p * 100); }))).bgWhite.magenta);
}
Ejemplo n.º 19
0
		.then( function( reply ) {
			if ( reply.content ) {
				log.debug( 'Get "%s" from "%s" returned %d documents with %d bytes',
					key,
					bucketName,
					reply.content.length,
					_.foldl( reply.content, function( x, y ) {
						return x + y.value.length;
					}, 0 )
				);
				var docs = scrubDocs( reply, includeDeleted );
				if ( _.isEmpty( docs ) ) {
					return undefined;
				} else if ( docs.length === 1 ) {
					return docs[ 0 ];
				} else {
					return docs;
				}
			} else {
				log.error( 'Get "%s" from "%s" return an empty document!', key, bucketName );
				throw new Errors.EmptyResult( bucketName, key );
			}
		} );
Ejemplo n.º 20
0
function parseHeader(content) {
  var headers,
      match = content.match(headerRegex);

  if (!match) {
    return null;
  }

  headers = _.compact(match[1].split('\n'));

  return _.foldl(headers, function(result, header) {
    var keyVal = header.trim().split(': '),
        key    = keyVal[0],
        value  = keyVal[1] || '';

    if(key !== 'Description' && key !== 'Language') {
      value = value.split(/\s*,\s*/);
    }

    result[key] = value;

    return result;
  }, {});
}
			var handleSearchResults = function(results) {				
				return lodash.foldl(results.hits.hits, function(versions, item) {
					versions.push(item.fields.version);
					return versions;
				}, []);
			};
Ejemplo n.º 22
0
  var f = function(context, callback) {

    let method = _.keys(requestSpec)[0].toUpperCase();
    let params = requestSpec[method.toLowerCase()];
    let uri = maybePrependBase(template(params.url, context), config);
    let tls = config.tls || {};
    let timeout = config.timeout || 10;

    let requestParams = _.cloneDeep(params);
    requestParams = _.extend(requestParams, {
      uri: uri,
      method: method,
      headers: {
      },
      timeout: timeout * 1000,
      jar: context._jar
    });
    requestParams = _.extend(requestParams, tls);

    if (params.json) {
      requestParams.json = template(params.json, context);
    } else if (params.body) {
      requestParams.body = template(params.body, context);
    }

    // Assign default headers then overwrite as needed
    let defaultHeaders = lowcaseKeys(
      (config.defaults && config.defaults.headers) ?
        config.defaults.headers : {'user-agent': USER_AGENT});
    requestParams.headers = _.extend(defaultHeaders,
                                     lowcaseKeys(params.headers));
    let headers = _.foldl(requestParams.headers,
                          function(acc, v, k) {
                            acc[k] = template(v, context);
                            return acc;
                          }, {});
    requestParams.headers = headers;

    let defaultCookie = config.defaults ? config.defaults.cookie || {} : {};
    let cookie = _.foldl(
      params.cookie,
      function(acc, v, k) {
        acc[k] = v;
        return acc;
      },
      defaultCookie);

    if (cookie) {
      _.each(cookie, function(v, k) {
        context._jar.setCookie(k + '=' + template(v, context), uri);
      });
    }

    if (config.http2) {
      requestParams.http2 = true;
    } else {
      requestParams.agent = context._agent;
    }

    request(requestParams, function requestCallback(err, res, body) {
      debug('request: %s', JSON.stringify({
	uri: requestParams.uri,
	method: requestParams.method,
	headers: requestParams.headers,
	json: requestParams.json
      }, null, 2));

      if (err) {
        let errCode = err.code || err.message;
        ee.emit('error', errCode);
        debug(err);
        // this aborts the scenario
        return callback(err, context);
      }

      debugResponse(JSON.stringify(res.headers, null, 2));
      debugResponse(JSON.stringify(res.body, null, 2));

      if (params.capture || params.match) {
        let parser;
        let extractor;
        if ((params.capture && params.capture.json) || (params.match && params.match.json)) {
          parser = parseJSON;
          extractor = extractJSONPath;
        } else if ((params.capture && params.capture.xpath) || (params.match && params.match.xpath)) {
          parser = parseXML;
          extractor = extractXPath;
        } else if ((params.capture && params.capture.regexp) || (params.match && params.match.regexp)) {
          parser = dummyParser;
          extractor = extractRegExp;
        } else {
          if (isJSON(res)) {
            parser = parseJSON;
            extractor = extractJSONPath;
          } else if (isXML(res)) {
            parser = parseXML;
            extractor = extractXPath;
          } else {
            // We really don't know what to do here.
            parser = dummyParser;
            extractor = dummyExtractor;
          }
        }

        parser(res.body, function(err2, doc) {
          if (err2) {
            return callback(err2, null);
          }

          if (params.match) {
            let expr = params.match.json || params.match.xpath;
            let result = extractor(doc, expr);
            let expected = template(params.match.value, context);
            debug('match: %s, expected: %s, got: %s', expr, expected, result);
            if (result !== expected) {
              ee.emit('match', false, {
                expected: expected,
                got: result,
                request: requestParams
              });
              if (params.match.strict) {
                // it's not an error but we finish the scenario
                return callback(null, context);
              }
            } else {
              ee.emit('match', true);
            }
          }

          if (params.capture) {
            let expr = params.capture.json || params.capture.xpath || params.capture.regexp;
            let result = extractor(doc, expr);
            context.vars[params.capture.as] = result;
            debug('capture: %s = %s', params.capture.as, result);

            if (params.capture.transform) {
              let result2 = engineUtil.evil(
                context.vars,
                params.capture.transform);
              context.vars[params.capture.as] = result2;
              debug('transform: %s = %s', params.capture.as, context.vars[params.capture.as]);
            }
          }

          debug('context.vars.$ = %j', doc);
          context.vars.$ = doc;
          context._successCount++;
          context._pendingRequests--;
          return callback(null, context);
        });
      } else {
        context.vars.$ = res.body;
        context._successCount++;
        context._pendingRequests--;
        return callback(null, context);
      }
    })
    .on('request', function(req) {
      ee.emit('request');

      const startedAt = process.hrtime();

      req.on('response', function updateLatency(res) {
        let code = res.statusCode;
        const endedAt = process.hrtime(startedAt);
        let delta = (endedAt[0] * 1e9) + endedAt[1];
        ee.emit('response', delta, code, context._uid);
      });
    }).on('end', function() {
    });
  };
Ejemplo n.º 23
0
 .then(ratings => {
     model.capabilityUsage = _.foldl(
         ratings,
         (acc, r) => { acc[r.capability.id] = true; return acc; },
         {});
 });
Ejemplo n.º 24
0
 var r = _.memoize(function (accum, value) {
     visited[value] = true;
     return accum.concat(_.foldl(_.filter(g.successors(value), function (v) { return !_.has(visited, v); }), r, [value]));
   }, function (accum, value) { return value; });
Ejemplo n.º 25
0
     .then(function (result) {
     // End the timer
     endtime = new Date().getTime();
     grunt.log.writeln('');
     // Analyze the results of our tsc execution,
     //   then tell the user our analysis results
     //   and mark the build as fail or success
     if (!result) {
         grunt.log.error('Error: No result from tsc.'.red);
         return false;
     }
     if (result.code === 8) {
         grunt.log.error('Error: Node was unable to run tsc.  Possibly it could not be found?'.red);
         return false;
     }
     // In TypeScript 1.3 and above, the result code corresponds to the ExitCode enum in
     //   TypeScript/src/compiler/sys.ts
     var isError = (result.code !== 0);
     // If the compilation errors contain only type errors, JS files are still
     //   generated. If tsc finds type errors, it will return an error code, even
     //   if JS files are generated. We should check this for this,
     //   only type errors, and call this a successful compilation.
     // Assumptions:
     //   Level 1 errors = syntax errors - prevent JS emit.
     //   Level 2 errors = semantic errors - *not* prevents JS emit.
     //   Level 5 errors = compiler flag misuse - prevents JS emit.
     var level1ErrorCount = 0, level5ErrorCount = 0, nonEmitPreventingWarningCount = 0;
     var hasTS7017Error = false;
     var hasPreventEmitErrors = _.foldl(result.output.split('\n'), function (memo, errorMsg) {
         var isPreventEmitError = false;
         if (errorMsg.search(/error TS7017:/g) >= 0) {
             hasTS7017Error = true;
         }
         if (errorMsg.search(/error TS1\d+:/g) >= 0) {
             level1ErrorCount += 1;
             isPreventEmitError = true;
         }
         else if (errorMsg.search(/error TS5\d+:/) >= 0) {
             level5ErrorCount += 1;
             isPreventEmitError = true;
         }
         else if (errorMsg.search(/error TS\d+:/) >= 0) {
             nonEmitPreventingWarningCount += 1;
         }
         return memo || isPreventEmitError;
     }, false) || false;
     // Because we can't think of a better way to determine it,
     //   assume that emitted JS in spite of error codes implies type-only errors.
     var isOnlyTypeErrors = !hasPreventEmitErrors;
     if (hasTS7017Error) {
         grunt.log.writeln(('Note:  You may wish to enable the suppressImplicitAnyIndexErrors' +
             ' grunt-ts option to allow dynamic property access by index.  This will' +
             ' suppress TypeScript error TS7017.').magenta);
     }
     // Log error summary
     if (level1ErrorCount + level5ErrorCount + nonEmitPreventingWarningCount > 0) {
         if ((level1ErrorCount + level5ErrorCount > 0) || options.failOnTypeErrors) {
             grunt.log.write(('>> ').red);
         }
         else {
             grunt.log.write(('>> ').green);
         }
         if (level5ErrorCount > 0) {
             grunt.log.write(level5ErrorCount.toString() + ' compiler flag error' +
                 (level5ErrorCount === 1 ? '' : 's') + '  ');
         }
         if (level1ErrorCount > 0) {
             grunt.log.write(level1ErrorCount.toString() + ' syntax error' +
                 (level1ErrorCount === 1 ? '' : 's') + '  ');
         }
         if (nonEmitPreventingWarningCount > 0) {
             grunt.log.write(nonEmitPreventingWarningCount.toString() +
                 ' non-emit-preventing type warning' +
                 (nonEmitPreventingWarningCount === 1 ? '' : 's') + '  ');
         }
         grunt.log.writeln('');
         if (isOnlyTypeErrors && !options.failOnTypeErrors) {
             grunt.log.write(('>> ').green);
             grunt.log.writeln('Type errors only.');
         }
     }
     // !!! To do: To really be confident that the build was actually successful,
     //   we have to check timestamps of the generated files in the destination.
     var isSuccessfulBuild = (!isError ||
         (isError && isOnlyTypeErrors && !options.failOnTypeErrors));
     if (isSuccessfulBuild) {
         // Report successful build.
         var time = (endtime - starttime) / 1000;
         grunt.log.writeln('');
         grunt.log.writeln(('TypeScript compilation complete: ' + time.toFixed(2) +
             's for ' + result.fileCount + ' typescript files').green);
     }
     else {
         // Report unsuccessful build.
         grunt.log.error(('Error: tsc return code: ' + result.code).yellow);
     }
     return isSuccessfulBuild;
 }).catch(function (err) {
Ejemplo n.º 26
0
export function talliesById(tallies) {
    return _.foldl(
        tallies,
        (acc, tally) => { acc[tally.id] = tally.count; return acc; },
        {});
};
Ejemplo n.º 27
0
                return compileModule.compileAllFiles(filesToCompile, target, options, currenttask.target).then(function (result) {
                    // End the timer
                    endtime = new Date().getTime();

                    grunt.log.writeln('');

                    // Analyze the results of our tsc execution,
                    //   then tell the user our analysis results
                    //   and mark the build as fail or success
                    if (!result) {
                        grunt.log.error('Error: No result from tsc.'.red);
                        return false;
                    }

                    var isError = (result.code === 1);

                    // If the compilation errors contain only type errors, JS files are still
                    //   generated. If tsc finds type errors, it will return an error code, even
                    //   if JS files are generated. We should check this for this,
                    //   only type errors, and call this a successful compilation.
                    // Assumptions:
                    //   Level 1 errors = syntax errors - prevent JS emit.
                    //   Level 2 errors = semantic errors - *not* prevents JS emit.
                    //   Level 5 errors = compiler flag misuse - prevents JS emit.
                    var level1ErrorCount = 0, level5ErrorCount = 0, nonEmitPreventingWarningCount = 0;
                    var hasPreventEmitErrors = _.foldl(result.output.split('\n'), function (memo, errorMsg) {
                        var isPreventEmitError = false;
                        if (errorMsg.search(/error TS1\d+:/g) >= 0) {
                            level1ErrorCount += 1;
                            isPreventEmitError = true;
                        } else if (errorMsg.search(/error TS5\d+:/) >= 0) {
                            level5ErrorCount += 1;
                            isPreventEmitError = true;
                        } else if (errorMsg.search(/error TS\d+:/) >= 0) {
                            nonEmitPreventingWarningCount += 1;
                        }
                        return memo || isPreventEmitError;
                    }, false) || false;

                    // Because we can't think of a better way to determine it,
                    //   assume that emitted JS in spite of error codes implies type-only errors.
                    var isOnlyTypeErrors = !hasPreventEmitErrors;

                    // Log error summary
                    if (level1ErrorCount + level5ErrorCount + nonEmitPreventingWarningCount > 0) {
                        if (level1ErrorCount + level5ErrorCount > 0) {
                            grunt.log.write(('>> ').red);
                        } else {
                            grunt.log.write(('>> ').green);
                        }

                        if (level5ErrorCount > 0) {
                            grunt.log.write(level5ErrorCount.toString() + ' compiler flag error' + (level5ErrorCount === 1 ? '' : 's') + '  ');
                        }
                        if (level1ErrorCount > 0) {
                            grunt.log.write(level1ErrorCount.toString() + ' syntax error' + (level1ErrorCount === 1 ? '' : 's') + '  ');
                        }
                        if (nonEmitPreventingWarningCount > 0) {
                            grunt.log.write(nonEmitPreventingWarningCount.toString() + ' non-emit-preventing type warning' + (nonEmitPreventingWarningCount === 1 ? '' : 's') + '  ');
                        }

                        grunt.log.writeln('');

                        if (isOnlyTypeErrors) {
                            grunt.log.write(('>> ').green);
                            grunt.log.writeln('Type errors only.');
                        }
                    }

                    // !!! To do: To really be confident that the build was actually successful,
                    //   we have to check timestamps of the generated files in the destination.
                    var isSuccessfulBuild = (!isError || (isError && isOnlyTypeErrors && !options.failOnTypeErrors));

                    if (isSuccessfulBuild) {
                        // Report successful build.
                        var time = (endtime - starttime) / 1000;
                        grunt.log.writeln('');
                        grunt.log.writeln(('TypeScript compilation complete: ' + time.toFixed(2) + 's for ' + result.fileCount + ' typescript files').green);
                    } else {
                        // Report unsuccessful build.
                        grunt.log.error(('Error: tsc return code: ' + result.code).yellow);
                    }

                    return isSuccessfulBuild;
                });