code
stringlengths
10
343k
docstring
stringlengths
36
21.9k
func_name
stringlengths
1
3.35k
language
stringclasses
1 value
repo
stringlengths
7
58
path
stringlengths
4
131
url
stringlengths
44
195
license
stringclasses
5 values
run() { return new Promise((resolve) => { this.sqz.cli.log.console( colors.green.bold(this.sqz.version.msg().replace(/^/gm, ' '.repeat(1), '\n'), '\n') ); resolve(); }); }
Display's cli version information to the console
run ( )
javascript
SqueezerIO/squeezer
lib/plugins/version/lib/index.js
https://github.com/SqueezerIO/squeezer/blob/master/lib/plugins/version/lib/index.js
MIT
constructor(sqz, type, stage) { this.sqz = sqz; this.stage = stage; this.compileType = type; const projectPath = this.sqz.vars.project.path; this.checksumsFilePath = path.join(projectPath, '.build', this.compileType, 'checksums.json'); this.options = this.sqz.cli.params.get().options; }
Constructor @param sqz main object @param type - compiling type - can be "run" or "deploy"
constructor ( sqz , type , stage )
javascript
SqueezerIO/squeezer
lib/plugins/functions/lib/compile/lib/index.js
https://github.com/SqueezerIO/squeezer/blob/master/lib/plugins/functions/lib/compile/lib/index.js
MIT
function isMicrosoftBrowser(userAgent) { var userAgentPatterns = ['MSIE ', 'Trident/', 'Edge/']; return new RegExp(userAgentPatterns.join('|')).test(userAgent); }
indicates if a the current browser is made by Microsoft @method isMicrosoftBrowser @param {String} userAgent @returns {Boolean}
isMicrosoftBrowser ( userAgent )
javascript
locomotivemtl/locomotive-scroll
dist/locomotive-scroll.esm.js
https://github.com/locomotivemtl/locomotive-scroll/blob/master/dist/locomotive-scroll.esm.js
MIT
function scrollElement(x, y) { this.scrollLeft = x; this.scrollTop = y; }
changes scroll position inside an element @method scrollElement @param {Number} x @param {Number} y @returns {undefined}
scrollElement ( x , y )
javascript
locomotivemtl/locomotive-scroll
dist/locomotive-scroll.esm.js
https://github.com/locomotivemtl/locomotive-scroll/blob/master/dist/locomotive-scroll.esm.js
MIT
function ease(k) { return 0.5 * (1 - Math.cos(Math.PI * k)); }
returns result of applying ease math function to a number @method ease @param {Number} k @returns {Number}
ease ( k )
javascript
locomotivemtl/locomotive-scroll
dist/locomotive-scroll.esm.js
https://github.com/locomotivemtl/locomotive-scroll/blob/master/dist/locomotive-scroll.esm.js
MIT
function shouldBailOut(firstArg) { if ( firstArg === null || typeof firstArg !== 'object' || firstArg.behavior === undefined || firstArg.behavior === 'auto' || firstArg.behavior === 'instant' ) { // first argument is not an object/null // or behavior is auto, instant or undefined return true; } if (typeof firstArg === 'object' && firstArg.behavior === 'smooth') { // first argument is an object and behavior is smooth return false; } // throw error when behavior is not supported throw new TypeError( 'behavior member of ScrollOptions ' + firstArg.behavior + ' is not a valid value for enumeration ScrollBehavior.' ); }
indicates if a smooth behavior should be applied @method shouldBailOut @param {Number|Object} firstArg @returns {Boolean}
shouldBailOut ( firstArg )
javascript
locomotivemtl/locomotive-scroll
dist/locomotive-scroll.esm.js
https://github.com/locomotivemtl/locomotive-scroll/blob/master/dist/locomotive-scroll.esm.js
MIT
function hasScrollableSpace(el, axis) { if (axis === 'Y') { return el.clientHeight + ROUNDING_TOLERANCE < el.scrollHeight; } if (axis === 'X') { return el.clientWidth + ROUNDING_TOLERANCE < el.scrollWidth; } }
indicates if an element has scrollable space in the provided axis @method hasScrollableSpace @param {Node} el @param {String} axis @returns {Boolean}
hasScrollableSpace ( el , axis )
javascript
locomotivemtl/locomotive-scroll
dist/locomotive-scroll.esm.js
https://github.com/locomotivemtl/locomotive-scroll/blob/master/dist/locomotive-scroll.esm.js
MIT
function canOverflow(el, axis) { var overflowValue = w.getComputedStyle(el, null)['overflow' + axis]; return overflowValue === 'auto' || overflowValue === 'scroll'; }
indicates if an element has a scrollable overflow property in the axis @method canOverflow @param {Node} el @param {String} axis @returns {Boolean}
canOverflow ( el , axis )
javascript
locomotivemtl/locomotive-scroll
dist/locomotive-scroll.esm.js
https://github.com/locomotivemtl/locomotive-scroll/blob/master/dist/locomotive-scroll.esm.js
MIT
function isScrollable(el) { var isScrollableY = hasScrollableSpace(el, 'Y') && canOverflow(el, 'Y'); var isScrollableX = hasScrollableSpace(el, 'X') && canOverflow(el, 'X'); return isScrollableY || isScrollableX; }
indicates if an element can be scrolled in either axis @method isScrollable @param {Node} el @param {String} axis @returns {Boolean}
isScrollable ( el )
javascript
locomotivemtl/locomotive-scroll
dist/locomotive-scroll.esm.js
https://github.com/locomotivemtl/locomotive-scroll/blob/master/dist/locomotive-scroll.esm.js
MIT
function findScrollableParent(el) { while (el !== d.body && isScrollable(el) === false) { el = el.parentNode || el.host; } return el; }
finds scrollable parent of an element @method findScrollableParent @param {Node} el @returns {Node} el
findScrollableParent ( el )
javascript
locomotivemtl/locomotive-scroll
dist/locomotive-scroll.esm.js
https://github.com/locomotivemtl/locomotive-scroll/blob/master/dist/locomotive-scroll.esm.js
MIT
function step(context) { var time = now(); var value; var currentX; var currentY; var elapsed = (time - context.startTime) / SCROLL_TIME; // avoid elapsed times higher than one elapsed = elapsed > 1 ? 1 : elapsed; // apply easing to elapsed time value = ease(elapsed); currentX = context.startX + (context.x - context.startX) * value; currentY = context.startY + (context.y - context.startY) * value; context.method.call(context.scrollable, currentX, currentY); // scroll more if we have not reached our destination if (currentX !== context.x || currentY !== context.y) { w.requestAnimationFrame(step.bind(w, context)); } }
self invoked function that, given a context, steps through scrolling @method step @param {Object} context @returns {undefined}
step ( context )
javascript
locomotivemtl/locomotive-scroll
dist/locomotive-scroll.esm.js
https://github.com/locomotivemtl/locomotive-scroll/blob/master/dist/locomotive-scroll.esm.js
MIT
function smoothScroll(el, x, y) { var scrollable; var startX; var startY; var method; var startTime = now(); // define scroll context if (el === d.body) { scrollable = w; startX = w.scrollX || w.pageXOffset; startY = w.scrollY || w.pageYOffset; method = original.scroll; } else { scrollable = el; startX = el.scrollLeft; startY = el.scrollTop; method = scrollElement; } // scroll looping over a frame step({ scrollable: scrollable, method: method, startTime: startTime, startX: startX, startY: startY, x: x, y: y }); }
scrolls window or element with a smooth behavior @method smoothScroll @param {Object|Node} el @param {Number} x @param {Number} y @returns {undefined}
smoothScroll ( el , x , y )
javascript
locomotivemtl/locomotive-scroll
dist/locomotive-scroll.esm.js
https://github.com/locomotivemtl/locomotive-scroll/blob/master/dist/locomotive-scroll.esm.js
MIT
function getParents(elem) { // Set up a parent array var parents = []; // Push each parent element to the array for (; elem && elem !== document; elem = elem.parentNode) { parents.push(elem); } // Return our parent array return parents; } // https://gomakethings.com/how-to-get-the-closest-parent-element-with-a-matching-selector-using-vanilla-javascript/
Returns an array containing all the parent nodes of the given node @param {object} node @return {array} parent nodes
getParents ( elem )
javascript
locomotivemtl/locomotive-scroll
dist/locomotive-scroll.esm.js
https://github.com/locomotivemtl/locomotive-scroll/blob/master/dist/locomotive-scroll.esm.js
MIT
var getNextFrameNo = function () { var delta = (forward ? 1 : -1); return (i + delta + frames.length) % frames.length; }; var stepFrame = function (amount) { // XXX: Name is confusing. i = i + amount; putFrame(); }; var step = (function () { var stepping = false; var completeLoop = function () { if (onEndListener !== null) onEndListener(gif); iterationCount++; if (overrideLoopMode !== false || iterationCount < 0) { doStep(); } else { stepping = false; playing = false; } }; var doStep = function () { stepping = playing; if (!stepping) return; stepFrame(1); var delay = frames[i].delay * 10; if (!delay) delay = 100; // FIXME: Should this even default at all? What should it be? var nextFrameNo = getNextFrameNo(); if (nextFrameNo === 0) { delay += loopDelay; setTimeout(completeLoop, delay); } else { setTimeout(doStep, delay); } }; return function () { if (!stepping) setTimeout(doStep, 0); }; }()); var putFrame = function () { var offset; i = parseInt(i, 10); if (i > frames.length - 1) { i = 0; } if (i < 0) { i = 0; } offset = frameOffsets[i]; // Attempt to save battery/cpu. if (first_time == false && _RefreshGifs == false) { if (frames.length == 1) { return; } var Elm = document.elementFromPoint(0, 100); if (Elm != options.canvas) { if (options.canvas.RelatedCanvas) { if (Elm != options.canvas.RelatedCanvas) { return; } } else { return; } } } else { first_time = false; //setTimeout(function () //{ // tmpCanvas.getContext("2d").putImageData(frames[i].data, offset.x, offset.y); // ctx.globalCompositeOperation = "copy"; // ctx.drawImage(tmpCanvas, 0, 0); // options.canvas.getContext("2d").drawImage(canvas, options.x, options.y) //}, 100); //return; } tmpCanvas.getContext("2d", { willReadFrequently: true }).putImageData(frames[i].data, offset.x, offset.y); ctx.globalCompositeOperation = "copy"; ctx.drawImage(tmpCanvas, 0, 0); options.canvas.getContext("2d", { willReadFrequently: true }).drawImage(canvas, options.x, options.y) }; var play = function () { playing = true; step(); }; var pause = function () { playing = false; }; return { init: function () { if (loadError) return; if (!(options.c_w && options.c_h)) { ctx.scale(get_canvas_scale(), get_canvas_scale()); } if (options.auto_play) { step(); } else { i = 0; putFrame(); } }, step: step, play: play, pause: pause, playing: playing, move_relative: stepFrame, current_frame: function () { return i; }, length: function () { return frames.length }, move_to: function (frame_idx) { i = frame_idx; putFrame(); } } }());
Gets the index of the frame "up next". @returns {number}
getNextFrameNo ( )
javascript
vbguyny/ws4kp
Scripts/libgif.js
https://github.com/vbguyny/ws4kp/blob/master/Scripts/libgif.js
MIT
var withProgress = function (fn, draw) { return function (block) { fn(block); doDecodeProgress(draw); }; };
@param{boolean=} draw Whether to draw progress bar or not; this is not idempotent because of translucency. Note that this means that the text will be unsynchronized with the progress bar on non-frames; but those are typically so small (GCE etc.) that it doesn't really matter. TODO: Do this properly.
withProgress ( fn , draw )
javascript
vbguyny/ws4kp
Scripts/libgif.js
https://github.com/vbguyny/ws4kp/blob/master/Scripts/libgif.js
MIT
IntervalBuilder.prototype.addEvent = function(objectId, message) { switch (message) { case 'up': if (!this.isUp(objectId)) { this.states[objectId] = UP; return true; } break; case 'down': if (!this.isDown(objectId)) { this.states[objectId] = DOWN; return true; } break; case 'paused': case 'restarted': default: if (!this.isPaused(objectId)) { this.states[objectId] = PAUSED; return true; } break; } return false; };
Add an event for a given check. Returns true if the event modifies the state of a given check, false otherwise
IntervalBuilder.prototype.addEvent ( objectId , message )
javascript
fzaninotto/uptime
lib/intervalBuilder.js
https://github.com/fzaninotto/uptime/blob/master/lib/intervalBuilder.js
MIT
IntervalBuilder.prototype.updateCurrentState = function(timestamp) { timestamp = this.getTimestamp(timestamp); var currentState = this.getGlobalState(); if (currentState !== this.currentState) { this.completeCurrentInterval(timestamp); this.currentInterval = currentState == 1 ? [] : [timestamp]; this.currentState = currentState; return true; } return false; };
Return true if the global state was updated, false otherwise.
IntervalBuilder.prototype.updateCurrentState ( timestamp )
javascript
fzaninotto/uptime
lib/intervalBuilder.js
https://github.com/fzaninotto/uptime/blob/master/lib/intervalBuilder.js
MIT
QosAggregator.prototype.updateHourlyCheckQos = function(start, end, callback) { var CheckHourlyStat = require('../models/checkHourlyStat'); this.aggregatePingsIntoStatsGroupedByCheck(start, end, function(err, stats) { async.forEach(stats, function(stat, next) { CheckHourlyStat.update( { check: stat.check, timestamp: stat.timestamp }, { $set: stat }, { upsert: true }, next ); }, callback); }); };
Aggregate Qos data of Pings from all checks around a timestamp into CheckHourlyStat documents The method finds the boundaries of the hour by resetting/completing the hour of the timestamp. @param {Int|Date} timestamp or Date object of a moment inside the chosen hour @param {Function} callback(err) to be called upon completion @api public
QosAggregator.prototype.updateHourlyCheckQos ( start , end , callback )
javascript
fzaninotto/uptime
lib/qosAggregator.js
https://github.com/fzaninotto/uptime/blob/master/lib/qosAggregator.js
MIT
QosAggregator.prototype.updateLast24HoursQos = function(callback) { var start = new Date(Date.now() - (24 * 60 * 60 * 1000)); var end = new Date(); async.parallel([ async.apply(this.updateLast24HoursCheckQos.bind(this), start, end), async.apply(this.updateLast24HoursTagQos.bind(this), start, end), ], callback); };
Aggregate Qos data of Pings from the last 24h into the qos property of checks and tags @param {Function} callback(err) to be called upon completion @api public
QosAggregator.prototype.updateLast24HoursQos ( callback )
javascript
fzaninotto/uptime
lib/qosAggregator.js
https://github.com/fzaninotto/uptime/blob/master/lib/qosAggregator.js
MIT
QosAggregator.prototype.aggregatePingsIntoStatsGroupedByCheck = function(start, end, callback) { async.waterfall([ function (next) { next(null, start, end) }, // pass the parameters to the next function this.aggregatePingsByCheck, this.getCheckStats.bind(this) ], callback); };
Aggregate Qos data of Pings from all checks between two boundaries @param {Date} Date object of a the beginning of the search period @param {Date} Date object of a the end of the search period @param {Function} callback(err) to be called upon completion @api public
QosAggregator.prototype.aggregatePingsIntoStatsGroupedByCheck ( start , end , callback )
javascript
fzaninotto/uptime
lib/qosAggregator.js
https://github.com/fzaninotto/uptime/blob/master/lib/qosAggregator.js
MIT
QosAggregator.prototype.aggregatePingsIntoStatsGroupedByTag = function(start, end, callback) { async.waterfall([ function (next) { next(null, start, end) }, // pass the parameters to the next function this.aggregatePingsByTag, this.getTagStats.bind(this) ], callback); };
Aggregate Qos data of Pings from all tags between two boundaries @param {Date} Date object of a the beginning of the search period @param {Date} Date object of a the end of the search period @param {Function} callback(err) to be called upon completion @api public
QosAggregator.prototype.aggregatePingsIntoStatsGroupedByTag ( start , end , callback )
javascript
fzaninotto/uptime
lib/qosAggregator.js
https://github.com/fzaninotto/uptime/blob/master/lib/qosAggregator.js
MIT
QosAggregator.prototype.updateDailyQos = function(now, callback) { var start = moment(now).clone().startOf('day').toDate(); var end = moment(now).clone().endOf('day').toDate(); async.parallel([ async.apply(this.updateDailyCheckQos.bind(this), start, end), async.apply(this.updateDailyTagQos.bind(this), start, end) ], callback); };
Aggregate hourly Qos data from all checks and tags around a timestamp into daily stat documents. The method finds the boundaries of the day by resetting/completing the day of the timestamp. @param {Int|Date} timestamp or Date object of a moment inside the chosen day @param {Function} callback(err) to be called upon completion @api public
QosAggregator.prototype.updateDailyQos ( now , callback )
javascript
fzaninotto/uptime
lib/qosAggregator.js
https://github.com/fzaninotto/uptime/blob/master/lib/qosAggregator.js
MIT
QosAggregator.prototype.updateMonthlyQos = function(now, callback) { var start = moment(now).clone().startOf('month').toDate(); var end = moment(now).clone().endOf('month').toDate(); var CheckDailyStat = require('../models/checkDailyStat'); var CheckMonthlyStat = require('../models/checkMonthlyStat'); var TagDailyStat = require('../models/tagDailyStat'); var TagMonthlyStat = require('../models/tagMonthlyStat'); async.series([ async.apply(this.updateMonthlyQosStats.bind(this), start, end, CheckDailyStat, CheckMonthlyStat, "$check"), async.apply(this.updateMonthlyQosStats.bind(this), start, end, TagDailyStat, TagMonthlyStat, "$name"), ], callback); };
Aggregate daily Qos data from all checks and tags around a timestamp into monthly stat documents. The method finds the boundaries of the month by resetting/completing the month of the timestamp. @param {Int|Date} timestamp or Date object of a moment inside the chosen month @param {Function} callback(err) to be called upon completion @api public
QosAggregator.prototype.updateMonthlyQos ( now , callback )
javascript
fzaninotto/uptime
lib/qosAggregator.js
https://github.com/fzaninotto/uptime/blob/master/lib/qosAggregator.js
MIT
QosAggregator.prototype.updateYearlyQos = function(now, callback) { var start = moment(now).clone().startOf('year').toDate(); var end = moment(now).clone().endOf('year').toDate(); var CheckMonthlyStat = require('../models/checkMonthlyStat'); var CheckYearlyStat = require('../models/checkYearlyStat'); var TagMonthlyStat = require('../models/tagMonthlyStat'); var TagYearlyStat = require('../models/tagYearlyStat'); async.series([ async.apply(this.updateYearlyQosStats.bind(this), start, end, CheckMonthlyStat, CheckYearlyStat, "$check"), async.apply(this.updateYearlyQosStats.bind(this), start, end, TagMonthlyStat, TagYearlyStat, "$name"), ], callback); };
Aggregate daily Qos data from all checks and tags around a timestamp into yearly stat documents. The method finds the boundaries of the month by resetting/completing the month of the timestamp. @param {Int|Date} timestamp or Date object of a moment inside the chosen month @param {Function} callback(err) to be called upon completion @api public
QosAggregator.prototype.updateYearlyQos ( now , callback )
javascript
fzaninotto/uptime
lib/qosAggregator.js
https://github.com/fzaninotto/uptime/blob/master/lib/qosAggregator.js
MIT
QosAggregator.prototype.updateLastHourQos = function(callback) { var now = new Date(Date.now() - 1000 * 60 * 6); // 6 minutes in the past, to accommodate script running every 5 minutes this.updateHourlyQos(now, callback); };
Aggregate Qos data of Pings from all checks from the last hour into CheckHourlyStat and TagHourlyStat documents. @param {Function} callback(err) to be called upon completion @api public
QosAggregator.prototype.updateLastHourQos ( callback )
javascript
fzaninotto/uptime
lib/qosAggregator.js
https://github.com/fzaninotto/uptime/blob/master/lib/qosAggregator.js
MIT
QosAggregator.prototype.updateLastDayQos = function(callback) { var now = new Date(Date.now() - 1000 * 60 * 66); // 1 hour and 6 minutes in the past, to accommodate script running every hour this.updateDailyQos(now, callback); };
Aggregate Qos data of CheckHourlyStat from all checks from the last day into CheckDailyStat documents. @param {Function} callback(err) to be called upon completion @api public
QosAggregator.prototype.updateLastDayQos ( callback )
javascript
fzaninotto/uptime
lib/qosAggregator.js
https://github.com/fzaninotto/uptime/blob/master/lib/qosAggregator.js
MIT
QosAggregator.prototype.updateLastMonthQos = function(callback) { var now = new Date(Date.now() - 1000 * 60 * 66); // 1 hour and 6 minutes in the past, to accommodate script running every hour this.updateMonthlyQos(now, callback); };
Aggregate Qos data of CheckDailyStat from all checks from the last month into CheckMonthlyStat documents. @param {Function} callback(err) to be called upon completion @api public
QosAggregator.prototype.updateLastMonthQos ( callback )
javascript
fzaninotto/uptime
lib/qosAggregator.js
https://github.com/fzaninotto/uptime/blob/master/lib/qosAggregator.js
MIT
QosAggregator.prototype.updateLastYearQos = function(callback) { var now = new Date(Date.now() - 1000 * 60 * 66); // 1 hour and 6 minutes in the past, to accommodate script running every hour this.updateYearlyQos(now, callback); };
Aggregate Qos data of CheckMonthlyStat from all checks from the last month into CheckYearlyStat documents. @param {Function} callback(err) to be called upon completion @api public
QosAggregator.prototype.updateLastYearQos ( callback )
javascript
fzaninotto/uptime
lib/qosAggregator.js
https://github.com/fzaninotto/uptime/blob/master/lib/qosAggregator.js
MIT
function Analyzer(config) { config.updateInterval = config.updateInterval || 60 * 1000; config.qosAggregationInterval = config.qosAggregationInterval || 60 * 60 * 1000; config.pingHistory = config.pingHistory || 3 * 31 * 24 * 60 * 60 * 1000; this.config = config; }
Analyzer constructor The analyzer aggregates the ping data into QoS scores for checks and tags. The constructor expects a configuration object as parameter, with these properties: updateInterval: Interval between each update of the QoS score in milliseconds, defaults to 1 minute qosAggregationInterval: Interval between each daily and hourly aggregation the QoS score in milliseconds, defaults to 1 hour pingHistory: Oldest ping and checkEvent age to keep in milliseconds, defaults to 3 months @param {Object} Monitor configuration @api public
Analyzer ( config )
javascript
fzaninotto/uptime
lib/analyzer.js
https://github.com/fzaninotto/uptime/blob/master/lib/analyzer.js
MIT
Analyzer.prototype.start = function() { // schedule updates this.intervalForUpdate = setInterval(this.updateAllChecks.bind(this), this.config.updateInterval); this.intervalForAggregation = setInterval(this.aggregateQos.bind(this), this.config.qosAggregationInterval); };
Start the analysis of all checks. The polling actually starts after the pollingInterval set to the constructor. @api public
Analyzer.prototype.start ( )
javascript
fzaninotto/uptime
lib/analyzer.js
https://github.com/fzaninotto/uptime/blob/master/lib/analyzer.js
MIT
Analyzer.prototype.stop = function() { clearInterval(this.intervalForUpdate); clearInterval(this.intervalForAggregation); };
Stop the analysis of all checks @api public
Analyzer.prototype.stop ( )
javascript
fzaninotto/uptime
lib/analyzer.js
https://github.com/fzaninotto/uptime/blob/master/lib/analyzer.js
MIT
Analyzer.prototype.aggregateQos = function() { QosAggregator.updateLastDayQos.apply(QosAggregator); QosAggregator.updateLastMonthQos.apply(QosAggregator); QosAggregator.updateLastYearQos.apply(QosAggregator); Ping.cleanup(this.config.pingHistory); CheckEvent.cleanup(this.config.pingHistory); };
Aggregate the QoS scores for each check @api private
Analyzer.prototype.aggregateQos ( )
javascript
fzaninotto/uptime
lib/analyzer.js
https://github.com/fzaninotto/uptime/blob/master/lib/analyzer.js
MIT
exports.createAnalyzer = function(config) { return new Analyzer(config); };
Create an analyzer to update the check and tag qos scores. Example: m = analyzer.createAnalyzer({ updateInterval: 60000}); m.start(); // the analysis starts, every 60 seconds m.stop(); @param {Object} Configuration object @api public
exports.createAnalyzer ( config )
javascript
fzaninotto/uptime
lib/analyzer.js
https://github.com/fzaninotto/uptime/blob/master/lib/analyzer.js
MIT
var isProxyRequired = function(hostname) { if (!process.env.no_proxy) { return true; } var exclusionPatterns = process.env.no_proxy.split(','); for (var i in exclusionPatterns) { if (hostname.search(exclusionPatterns[i]) >= 0) { return false; } } return true; };
Returns weather proxy should be used when requesting given host ie. returns false if hostname match any pattern in no_proxy environment variable
isProxyRequired ( hostname )
javascript
fzaninotto/uptime
lib/proxy.js
https://github.com/fzaninotto/uptime/blob/master/lib/proxy.js
MIT
function Timer(timeout, timeoutCallback) { this.finalTime = false; this.time = Date.now(); this.TimerFunction = setTimeout(timeoutCallback, timeout); }
Timer constructor @param {Number} timeout in milliseconds @param {Function} timeout callback @api public
Timer ( timeout , timeoutCallback )
javascript
fzaninotto/uptime
lib/timer.js
https://github.com/fzaninotto/uptime/blob/master/lib/timer.js
MIT
Timer.prototype.getTime = function() { return this.finalTime || Date.now() - this.time; };
Get time elapsed since timer construction @return {Number} time in milliseconds @api public
Timer.prototype.getTime ( )
javascript
fzaninotto/uptime
lib/timer.js
https://github.com/fzaninotto/uptime/blob/master/lib/timer.js
MIT
Timer.prototype.stop = function() { this.finalTime = this.getTime(); clearTimeout(this.TimerFunction); };
Stop the timer and prevent the call to the timeout callback @api public
Timer.prototype.stop ( )
javascript
fzaninotto/uptime
lib/timer.js
https://github.com/fzaninotto/uptime/blob/master/lib/timer.js
MIT
exports.createTimer = function(timeout, timeoutCallback) { return new Timer(timeout, timeoutCallback); };
Create a timer. Example: t = timer.createTimer(60000, function() { console.log('60 seconds have passed'); }); t.getTime(); // 12345 t.stop(); // prevents the execution of the timeout callback @param {Number} Delay to schedule execution of the callback in milliseconds @param {Function} Callback to be executed at the end of the delay, unless the timer is stopped @api public
exports.createTimer ( timeout , timeoutCallback )
javascript
fzaninotto/uptime
lib/timer.js
https://github.com/fzaninotto/uptime/blob/master/lib/timer.js
MIT
function Monitor(config) { config.pollingInterval = config.pollingInterval || 10 * 1000; config.timeout = config.timeout || 5 * 1000; this.config = config; this.pollerCollection = new PollerCollection(); this.apiHttpOptions = {}; }
Monitor constructor The monitor pings the checks regularly and saves the response status and time. The monitor doesn't interact with the model classes directly, but instead uses the REST HTTP API. This way, the monitor can run on a separate process, so that the ping measurements don't get distorted by a heavy usage of the GUI. The constructor expects a configuration object as parameter, with these properties: pollingInterval: Interval between each poll in milliseconds, defaults to 10 seconds timeout: Request timeout in milliseconds, defaults to 5 seconds @param {Object} Monitor configuration @api public
Monitor ( config )
javascript
fzaninotto/uptime
lib/monitor.js
https://github.com/fzaninotto/uptime/blob/master/lib/monitor.js
MIT
Monitor.prototype.start = function() { // start polling right away this.pollChecksNeedingPoll(); // schedule future polls this.intervalForPoll = setInterval(this.pollChecksNeedingPoll.bind(this), this.config.pollingInterval); console.log('Monitor ' + this.config.name + ' started'); };
Start the monitoring of all checks. The polling actually starts after the pollingInterval set to the constructor. @api public
Monitor.prototype.start ( )
javascript
fzaninotto/uptime
lib/monitor.js
https://github.com/fzaninotto/uptime/blob/master/lib/monitor.js
MIT
Monitor.prototype.stop = function() { clearInterval(this.intervalForPoll); console.log('Monitor ' + this.config.name + ' stopped'); };
Stop the monitoring of all checks @api public
Monitor.prototype.stop ( )
javascript
fzaninotto/uptime
lib/monitor.js
https://github.com/fzaninotto/uptime/blob/master/lib/monitor.js
MIT
Monitor.prototype.pollChecksNeedingPoll = function(callback) { var self = this; this.findChecksNeedingPoll(function(err, checks) { if (err) { console.error(err); if (callback) callback(err); return; } checks.forEach(function(check) { self.pollCheck(check, function(err) { if (err) console.error(err); }); }); }); };
Find checks that need to be polled. A check needs to be polled if it was last polled sine a longer time than its own interval. @param {Function} Callback function to be called with each Check @api private
Monitor.prototype.pollChecksNeedingPoll ( callback )
javascript
fzaninotto/uptime
lib/monitor.js
https://github.com/fzaninotto/uptime/blob/master/lib/monitor.js
MIT
Monitor.prototype.pollCheck = function(check, callback) { if (!check) return; var Poller, p; var now = Date.now(); var self = this; // change lastTested date right away to avoid polling twice if the target doesn't answer in timely fashion this.declarePoll(check, function(err) { }); var details = {}; try { Poller = this.pollerCollection.getForType(check.type || 'http'); } catch (unknownPollerError) { return self.createPing(unknownPollerError, check, now, 0, details, callback); } var pollerCallback = function(err, time, res, pollerDetails) { if (err) { return self.createPing(err, check, now, time, pollerDetails || details, callback); } try { self.emit('pollerPolled', check, res, pollerDetails || details); self.createPing(null, check, now, time, pollerDetails || details, callback); } catch (error) { return self.createPing(error, check, now, time, pollerDetails || details, callback); } }; try { p = new Poller(check.url, this.config.timeout, pollerCallback); if ('setUserAgent' in p) { p.setUserAgent(this.config.userAgent); } self.emit('pollerCreated', p, check, details); } catch (incorrectPollerUrl) { return self.createPing(incorrectPollerUrl, check, now, 0, details, callback); } //p.setDebug(true); p.poll(); };
Poll a given check, and create a ping according to the result. @param {Object} check is a simple JSON object returned by the API, NOT a Check object @api private
Monitor.prototype.pollCheck ( check , callback )
javascript
fzaninotto/uptime
lib/monitor.js
https://github.com/fzaninotto/uptime/blob/master/lib/monitor.js
MIT
Monitor.prototype.addApiHttpOption = function(key, value) { this.apiHttpOptions[key] = value; };
Add custom HTTP options to all the API calls Useful to add proxy headers, Basic HTTP auth, etc.
Monitor.prototype.addApiHttpOption ( key , value )
javascript
fzaninotto/uptime
lib/monitor.js
https://github.com/fzaninotto/uptime/blob/master/lib/monitor.js
MIT
exports.createMonitor = function(config) { return new Monitor(config); };
Create a monitor to poll all checks at a given interval. Example: m = monitor.createMonitor({ pollingInterval: 60000}); m.start(); // the polling starts, every 60 seconds m.stop(); @param {Object} Configuration object @api public
exports.createMonitor ( config )
javascript
fzaninotto/uptime
lib/monitor.js
https://github.com/fzaninotto/uptime/blob/master/lib/monitor.js
MIT
function BasePoller(target, timeout, callback) { this.target = target; this.timeout = timeout || 5000; this.callback = callback; this.isDebugEnabled = false; this.initialize(); }
Base Poller constructor @param {Mixed} Poller Target (e.g. URL) @param {Number} Poller timeout in milliseconds. Without response before this duration, the poller stops and executes the error callback. @param {Function} Error/success callback @api public
BasePoller ( target , timeout , callback )
javascript
fzaninotto/uptime
lib/pollers/basePoller.js
https://github.com/fzaninotto/uptime/blob/master/lib/pollers/basePoller.js
MIT
BasePoller.prototype.initialize = function() {};
Initializer method Override this method in child classes to prepare the target property. @api public
BasePoller.prototype.initialize ( )
javascript
fzaninotto/uptime
lib/pollers/basePoller.js
https://github.com/fzaninotto/uptime/blob/master/lib/pollers/basePoller.js
MIT
BasePoller.prototype.setDebug = function(bool) { this.isDebugEnabled = bool; };
Enable or disable debug console output @param {Boolean} bool @api public
BasePoller.prototype.setDebug ( bool )
javascript
fzaninotto/uptime
lib/pollers/basePoller.js
https://github.com/fzaninotto/uptime/blob/master/lib/pollers/basePoller.js
MIT
BasePoller.prototype.debug = function(msg) { if (this.isDebugEnabled) console.log(msg); };
Log debug message if debug is enabled @param {String} Message to log @api private
BasePoller.prototype.debug ( msg )
javascript
fzaninotto/uptime
lib/pollers/basePoller.js
https://github.com/fzaninotto/uptime/blob/master/lib/pollers/basePoller.js
MIT
BasePoller.prototype.poll = function() { if (!this.timer) { // timer already exists in case of a redirect this.timer = timer.createTimer(this.timeout, this.timeoutReached.bind(this)); } this.debug(this.getTime() + "ms - Emitting Request"); };
Launch the actual polling @api public
BasePoller.prototype.poll ( )
javascript
fzaninotto/uptime
lib/pollers/basePoller.js
https://github.com/fzaninotto/uptime/blob/master/lib/pollers/basePoller.js
MIT
BasePoller.prototype.getTime = function() { return this.timer.getTime(); };
Proxy to the timer's getTime() method @api private
BasePoller.prototype.getTime ( )
javascript
fzaninotto/uptime
lib/pollers/basePoller.js
https://github.com/fzaninotto/uptime/blob/master/lib/pollers/basePoller.js
MIT
BasePoller.validateTarget = function(target) { return false; };
Validate poller target URL (static method) Override this method in child classes to prepare the target property. @api public
BasePoller.validateTarget ( target )
javascript
fzaninotto/uptime
lib/pollers/basePoller.js
https://github.com/fzaninotto/uptime/blob/master/lib/pollers/basePoller.js
MIT
function WebPageTestPoller(target, timeout, callback) { WebPageTestPoller.super_.call(this, target, timeout, callback); }
WebPageTest Poller, to perform WebPageTest analysis on web pages @param {Mixed} Poller Target (e.g. URL) @param {Number} Poller timeout in milliseconds. Without response before this duration, the poller stops and executes the error callback. @param {Function} Error/success callback @api public
WebPageTestPoller ( target , timeout , callback )
javascript
fzaninotto/uptime
lib/pollers/webpagetest/webPageTestPoller.js
https://github.com/fzaninotto/uptime/blob/master/lib/pollers/webpagetest/webPageTestPoller.js
MIT
WebPageTestPoller.prototype.onTestStartedCallback = function(err,data){ if (err) { console.log(err); this.timer.stop(); } else { if (data.statusCode && data.statusCode == 200) { this.testId = data.data.testId; if (data.data.userUrl) { this.userUrl = data.data.userUrl; } this.debug('WebPageTest test started [testId='+this.testId+']'); this.checkTestStatus(); } else { return this.onErrorCallback({ name: "Test not started", message: data.statusText}); } } };
Test started callback @api private
WebPageTestPoller.prototype.onTestStartedCallback ( err , data )
javascript
fzaninotto/uptime
lib/pollers/webpagetest/webPageTestPoller.js
https://github.com/fzaninotto/uptime/blob/master/lib/pollers/webpagetest/webPageTestPoller.js
MIT
function HttpPoller(target, timeout, callback) { HttpPoller.super_.call(this, target, timeout, callback); }
HTTP Poller, to check web pages @param {Mixed} Poller Target (e.g. URL) @param {Number} Poller timeout in milliseconds. Without response before this duration, the poller stops and executes the error callback. @param {Function} Error/success callback @api public
HttpPoller ( target , timeout , callback )
javascript
fzaninotto/uptime
lib/pollers/http/httpPoller.js
https://github.com/fzaninotto/uptime/blob/master/lib/pollers/http/httpPoller.js
MIT
function BaseHttpPoller(target, timeout, callback) { BaseHttpPoller.super_.call(this, target, timeout, callback); }
Abstract class for HTTP and HTTPS Pollers, to check web pages @param {Mixed} Poller Target (e.g. URL) @param {Number} Poller timeout in milliseconds. Without response before this duration, the poller stops and executes the error callback. @param {Function} Error/success callback @api public
BaseHttpPoller ( target , timeout , callback )
javascript
fzaninotto/uptime
lib/pollers/http/baseHttpPoller.js
https://github.com/fzaninotto/uptime/blob/master/lib/pollers/http/baseHttpPoller.js
MIT
BaseHttpPoller.prototype.setUserAgent = function(userAgent) { if (typeof this.target.headers == 'undefined') { this.target.headers = {}; } this.target.headers['User-Agent'] = userAgent; };
Set the User Agent, which identifies the poller to the outside world @param {String} user agent @api public
BaseHttpPoller.prototype.setUserAgent ( userAgent )
javascript
fzaninotto/uptime
lib/pollers/http/baseHttpPoller.js
https://github.com/fzaninotto/uptime/blob/master/lib/pollers/http/baseHttpPoller.js
MIT
function HttpsPoller(target, timeout, callback) { HttpsPoller.super_.call(this, target, timeout, callback); }
HTTPS Poller, to check web pages served via SSL @param {Mixed} Poller Target (e.g. URL) @param {Number} Poller timeout in milliseconds. Without response before this duration, the poller stops and executes the error callback. @param {Function} Error/success callback @api public
HttpsPoller ( target , timeout , callback )
javascript
fzaninotto/uptime
lib/pollers/https/httpsPoller.js
https://github.com/fzaninotto/uptime/blob/master/lib/pollers/https/httpsPoller.js
MIT
var getUdpServer = function() { var udpServer = dgram.createSocket('udp4'); // binding required for getting responses udpServer.bind(); udpServer.on('error', function () {}); getUdpServer = function() { return udpServer; }; return getUdpServer(); };
UdpServer Singleton, using self-redefining function
getUdpServer ( )
javascript
fzaninotto/uptime
lib/pollers/udp/udpPoller.js
https://github.com/fzaninotto/uptime/blob/master/lib/pollers/udp/udpPoller.js
MIT
function UdpPoller(target, timeout, callback) { UdpPoller.super_.call(this, target, timeout, callback); }
UDP Poller, to check UDP services @param {Mixed} Poller Target (e.g. URL) @param {Number} Poller timeout in milliseconds. Without response before this duration, the poller stops and executes the error callback. @param {Function} Error/success callback @api public
UdpPoller ( target , timeout , callback )
javascript
fzaninotto/uptime
lib/pollers/udp/udpPoller.js
https://github.com/fzaninotto/uptime/blob/master/lib/pollers/udp/udpPoller.js
MIT
Check.statics.callForChecksNeedingPoll = function(callback) { var stream = this.needingPoll().stream(); stream.on('data', function(check) { callback(check); }); };
Calls a function for all checks that need to be polled. A check needs to be polled if it was last polled since a longer time than its own interval. @param {Function} Callback function to be called with each Check @api public
Check.statics.callForChecksNeedingPoll ( callback )
javascript
fzaninotto/uptime
models/check.js
https://github.com/fzaninotto/uptime/blob/master/models/check.js
MIT
function fixHtmlSubresourceUrls(result, buildOptions) { if (!result.metafile) throw new Error('expected metafile'); const htmls = Object.keys(result.metafile.outputs).filter(o => o.endsWith('.html')); const csss = Object.keys(result.metafile.outputs).filter(o => o.endsWith('.css')); const jss = Object.keys(result.metafile.outputs).filter(o => o.endsWith('.js')); if (htmls.length !== 1) throw new Error('expected exactly one generated html ' + htmls); if (csss.length !== 1) throw new Error('expected exactly one generated css ' + csss); const htmlDistPath = htmls[0]; const cssDistPath = csss[0]; // Viewer uses a publicPath of ./, Server uses /app. if (!buildOptions.outdir || !buildOptions.publicPath) { throw new Error('missing args'); } const relativeCssPath = path.relative(buildOptions.outdir, cssDistPath); // Rewrite the HTML const htmlText = fs.readFileSync(htmlDistPath, 'utf-8'); const newHtmlText = htmlText // Inject publicPath on JS references .replace('<script src="chunks/', `<script src="${buildOptions.publicPath}chunks/`) // noop @chialab/esbuild-plugin-html's stupid css loading technique .replace('<script type="application/javascript">', '<script type="dumb-dont-run-this">') // ... and instead use a proper stylesheet link. (with a fixed path) .replace( '</head>', ` <link rel="stylesheet" href="${buildOptions.publicPath}${relativeCssPath}"> </head> ` ); fs.writeFileSync(htmlDistPath, newHtmlText); // Rewrite the CSS, making sure we don't source icons relative to the chunks/css file. const newCssText = fs .readFileSync(cssDistPath, 'utf-8') .replaceAll(`url("./assets`, `url("../assets`); fs.writeFileSync(cssDistPath, newCssText); for (const jsPath of jss) { const newJsText = fs .readFileSync(jsPath, 'utf-8') .replaceAll('sourceMappingURL=chunks/', 'sourceMappingURL='); fs.writeFileSync(jsPath, newJsText); } }
All of this is dumb but esbuild-plugin-html is limited and paths are hard. FYI If you see a static resource served as HTML, then the express router attempted use a static file, but didnt see it on disk, and instead served the HTML. The problem will probably be in here. @param {esbuild.BuildResult} result @param {esbuild.BuildOptions} buildOptions
fixHtmlSubresourceUrls ( result , buildOptions )
javascript
GoogleChrome/lighthouse-ci
scripts/build-app.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/scripts/build-app.js
Apache-2.0
const dispatchEvent = (element, evt) => testingLibrary.fireEvent(element, evt);
@type {any} @param {Document | Element | Window} element @param {Event} evt
dispatchEvent
javascript
GoogleChrome/lighthouse-ci
packages/server/test/test-utils.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/test/test-utils.js
Apache-2.0
async function createApp(options) { const {storage, useBodyParser} = options; log('[createApp] initializing storage method'); const storageMethod = StorageMethod.from(storage); await storageMethod.initialize(storage); log('[createApp] creating express app'); const context = {storageMethod, options}; const app = express(); if (options.logLevel !== 'silent') app.use(morgan('short')); // While LHCI should be served behind nginx/apache that handles compression, it won't always be. app.use(compression()); if (typeof useBodyParser === 'undefined' || useBodyParser) { // 1. Optional if you want to overwrite by other middleware like koa or fastify // 2. Support large payloads because LHRs are big. // 3. Support JSON primitives because `PUT /builds/<id>/lifecycle "sealed"` app.use(bodyParser.json({limit: '10mb', strict: false})); } // Add a health check route before auth app.use('/healthz', (_, res) => res.send('healthy')); // The rest of the server can be protected by HTTP Basic Authentication const authMiddleware = createBasicAuthMiddleware(context); if (authMiddleware) app.use(authMiddleware); app.get('/', (_, res) => res.redirect('/app')); app.use('/version', (_, res) => res.send(version)); app.use('/v1/projects', createProjectsRouter(context)); app.use('/v1/viewer', createViewerRouter(options)); app.use('/app', express.static(DIST_FOLDER)); app.get('/app/*', (_, res) => res.sendFile(path.join(DIST_FOLDER, 'index.html'))); app.use(errorMiddleware); log('[createApp] launching cron jobs'); startPsiCollectCron(storageMethod, options); startDeleteOldBuildsCron(storageMethod, options); return {app, storageMethod}; }
@param {LHCI.ServerCommand.Options} options @return {Promise<{app: Parameters<typeof createHttpServer>[1], storageMethod: StorageMethod}>}
createApp ( options )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/server.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/server.js
Apache-2.0
function startPsiCollectCron(storageMethod, options) { if (!options.psiCollectCron) return; const uniqueProjectBranches = new Set( options.psiCollectCron.sites.map(site => `${site.projectSlug}@${site.branch}`) ); if (uniqueProjectBranches.size < options.psiCollectCron.sites.length) { throw new Error('Cannot configure more than one cron per project-branch pair'); } /** @type {(msg: string) => void} */ const log = options.logLevel === 'silent' ? () => {} : msg => process.stdout.write(`${new Date().toISOString()} - ${msg}\n`); const psi = new PsiRunner(options.psiCollectCron); for (const site of options.psiCollectCron.sites) { const index = options.psiCollectCron.sites.indexOf(site); const label = site.label || `Site #${index}`; log(`Scheduling cron for ${label} with schedule ${site.schedule}`); let inProgress = false; const cron = new CronJob(normalizeCronSchedule(site.schedule), () => { if (inProgress) { log(`Previous PSI collection for ${label} still in progress. Skipping...`); return; } inProgress = true; log(`Starting PSI collection for ${label}`); psiCollectForProject(storageMethod, psi, site) .then(() => { log(`Successfully completed collection for ${label}`); }) .catch(err => { log(`PSI collection failure for ${label}: ${err.message}`); }) .finally(() => { inProgress = false; }); }); cron.start(); } }
@param {LHCI.ServerCommand.StorageMethod} storageMethod @param {LHCI.ServerCommand.Options} options @return {void}
startPsiCollectCron ( storageMethod , options )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/cron/psi-collect.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/cron/psi-collect.js
Apache-2.0
function normalizeCronSchedule(schedule) { if (typeof schedule !== 'string') { throw new Error(`Schedule must be provided`); } if (process.env.OVERRIDE_SCHEDULE_FOR_TEST) { return process.env.OVERRIDE_SCHEDULE_FOR_TEST; } const parts = schedule.split(/\s+/).filter(Boolean); if (parts.length !== 5) { throw new Error(`Invalid cron format, expected <minutes> <hours> <day> <month> <day of week>`); } if (parts[0] === '*') { throw new Error(`Cron schedule "${schedule}" is too frequent`); } return ['0', ...parts].join(' '); } module.exports = {normalizeCronSchedule};
@param {string} schedule @return {string}
normalizeCronSchedule ( schedule )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/cron/utils.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/cron/utils.js
Apache-2.0
async function deleteOldBuilds(storageMethod, maxAgeInDays, skipBranches, onlyBranches) { if (!maxAgeInDays || !Number.isInteger(maxAgeInDays) || maxAgeInDays <= 0) { throw new Error('Invalid range'); } const DAY_IN_MS = 24 * 60 * 60 * 1000; const cutoffTime = new Date(Date.now() - maxAgeInDays * DAY_IN_MS); const oldBuilds = (await storageMethod.findBuildsBeforeTimestamp(cutoffTime)).filter( ({branch}) => { if (Array.isArray(skipBranches) && skipBranches.includes(branch)) { return false; } if (Array.isArray(onlyBranches) && !onlyBranches.includes(branch)) return false; return true; } ); for (const {projectId, id} of oldBuilds) { await storageMethod.deleteBuild(projectId, id); } }
@param {LHCI.ServerCommand.StorageMethod} storageMethod @param {number} maxAgeInDays @param {string[] | null} skipBranches @param {string[] | null} onlyBranches @return {Promise<void>}
deleteOldBuilds ( storageMethod , maxAgeInDays , skipBranches , onlyBranches )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/cron/delete-old-builds.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/cron/delete-old-builds.js
Apache-2.0
function runCronJob(storageMethod, log, cronConfig) { let inProgress = false; const {schedule, maxAgeInDays, skipBranches = null, onlyBranches = null} = cronConfig; const cron = new CronJob(normalizeCronSchedule(schedule), () => { if (inProgress) { log(`Deleting old builds still in progress. Skipping...`); return; } inProgress = true; log(`Starting delete old builds`); deleteOldBuilds(storageMethod, maxAgeInDays, skipBranches, onlyBranches) .then(() => { log(`Successfully delete old builds`); }) .catch(err => { log(`Delete old builds failure: ${err.message}`); }) .finally(() => { inProgress = false; }); }); cron.start(); }
@param {LHCI.ServerCommand.StorageMethod} storageMethod @param {(s: string) => void} log @param {LHCI.ServerCommand.DeleteOldBuildsCron} cronConfig
runCronJob ( storageMethod , log , cronConfig )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/cron/delete-old-builds.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/cron/delete-old-builds.js
Apache-2.0
function auditNumericValueMedian(auditId) { return lhrs => { const values = lhrs .map(lhr => lhr.audits[auditId] && lhr.audits[auditId].numericValue) .filter( /** @return {value is number} */ value => typeof value === 'number' && Number.isFinite(value) ); return median(values); }; }
@param {string} auditId @return {StatisticFn}
auditNumericValueMedian ( auditId )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/api/statistic-definitions.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/api/statistic-definitions.js
Apache-2.0
function categoryScoreMedian(categoryId) { return lhrs => { const values = lhrs .map(lhr => lhr.categories[categoryId] && lhr.categories[categoryId].score) .filter( /** @return {value is number} */ value => typeof value === 'number' && Number.isFinite(value) ); return median(values); }; }
@param {string} categoryId @return {StatisticFn}
categoryScoreMedian ( categoryId )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/api/statistic-definitions.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/api/statistic-definitions.js
Apache-2.0
function auditGroupCountOfMedianLhr(groupId, type) { return lhrs => { const [medianLhr] = computeRepresentativeRuns([lhrs.map(lhr => [lhr, lhr])]); if (!medianLhr) return {value: -1}; // Start out with -1 as "no data available" let count = -1; for (const category of Object.values(medianLhr.categories)) { for (const auditRef of category.auditRefs || []) { if (auditRef.group !== groupId) continue; const audit = medianLhr.audits[auditRef.id]; if (!audit) continue; // Once we find our first candidate audit, set the count to 0. if (count === -1) count = 0; const {score, scoreDisplayMode} = audit; if (scoreDisplayMode === 'informative' && type === 'na') count++; if (scoreDisplayMode === 'notApplicable' && type === 'na') count++; if (scoreDisplayMode === 'binary' && score === 1 && type === 'pass') count++; if (scoreDisplayMode === 'binary' && score !== 1 && type === 'fail') count++; if (scoreDisplayMode === 'error' && type === 'fail') count++; } } return {value: count}; }; }
@param {string} groupId @param {'pass'|'fail'|'na'} type @return {StatisticFn}
auditGroupCountOfMedianLhr ( groupId , type )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/api/statistic-definitions.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/api/statistic-definitions.js
Apache-2.0
handleAsyncError(handler) { return (req, res, next) => { Promise.resolve() .then(() => handler(req, res, next)) .catch(err => { if (err.name === 'SequelizeDatabaseError' && err.message.includes('value too long')) { next(new E422(err.message)); } else if (err.name === 'SequelizeDatabaseError') { next(new Error(err.message + '\n' + err.stack)); } else { next(err); } }); }; },
@param {import('express-serve-static-core').RequestHandler} handler @return {import('express-serve-static-core').RequestHandler}
handleAsyncError ( handler )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/api/express-utils.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/api/express-utils.js
Apache-2.0
validateBuildTokenMiddleware(context) { return (req, res, next) => { Promise.resolve() .then(async () => { const project = await context.storageMethod.findProjectById(req.params.projectId); if (!project) throw new Error('Invalid token'); const buildToken = req.header('x-lhci-build-token') || ''; if (buildToken !== project.token) throw new Error('Invalid token'); next(); }) .catch(err => { res.status(403); res.send(JSON.stringify({message: err.message})); }); }; },
@param {{storageMethod: LHCI.ServerCommand.StorageMethod}} context @return {import('express-serve-static-core').RequestHandler}
validateBuildTokenMiddleware ( context )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/api/express-utils.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/api/express-utils.js
Apache-2.0
createBasicAuthMiddleware(context) { if (!context.options.basicAuth) return undefined; const {username = ApiClient.DEFAULT_BASIC_AUTH_USERNAME, password} = context.options.basicAuth; if (!password) return undefined; return basicAuth({users: {[username]: password}, challenge: true}); },
@param {{options: LHCI.ServerCommand.Options}} context @return {import('express-serve-static-core').RequestHandler|undefined}
createBasicAuthMiddleware ( context )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/api/express-utils.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/api/express-utils.js
Apache-2.0
errorMiddleware(err, req, res, next) { if (err instanceof E422) { res.status(422); res.send(JSON.stringify({message: err.message})); return; } if (err instanceof E404) { res.status(404); res.send(JSON.stringify({message: err.message})); return; } next(err); },
@param {Error} err @param {import('express-serve-static-core').Request} req @param {import('express-serve-static-core').Response} res @param {*} next
errorMiddleware ( err , req , res , next )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/api/express-utils.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/api/express-utils.js
Apache-2.0
function createRouter(options) { const router = express.Router(); // eslint-disable-line new-cap // GET /viewer/origin router.get( '/origin', handleAsyncError(async (_, res) => { res.json({viewerOrigin: options.viewer?.origin}); }) ); return router; }
@param {LHCI.ServerCommand.Options} options @return {import('express').Router}
createRouter ( options )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/api/routes/viewer.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/api/routes/viewer.js
Apache-2.0
function createRouter(context) { const router = express.Router(); // eslint-disable-line new-cap // GET /projects router.get( '/', handleAsyncError(async (_, res) => { const projects = await context.storageMethod.getProjects(); res.json(projects.map(project => ({...project, token: '', adminToken: ''}))); }) ); // POST /projects router.post( '/', handleAsyncError(async (req, res) => { const unsavedProject = req.body; const project = await context.storageMethod.createProject(unsavedProject); res.json(project); }) ); // POST /projects/lookup router.post( '/lookup', handleAsyncError(async (req, res) => { const token = req.body.token; const project = await context.storageMethod.findProjectByToken(token); if (!project) return res.sendStatus(404); res.json({...project, adminToken: ''}); }) ); // GET /projects/slug::id router.get( '/slug::projectSlug', handleAsyncError(async (req, res) => { const project = await context.storageMethod.findProjectBySlug(req.params.projectSlug); if (!project) return res.sendStatus(404); res.json({...project, token: '', adminToken: ''}); }) ); // GET /projects/:id router.get( '/:projectId', handleAsyncError(async (req, res) => { const project = await context.storageMethod.findProjectById(req.params.projectId); if (!project) return res.sendStatus(404); res.json({...project, token: '', adminToken: ''}); }) ); // PUT /projects/:id router.put( '/:projectId', validateAdminTokenMiddleware(context), handleAsyncError(async (req, res) => { await context.storageMethod.updateProject({ ...req.body, id: req.params.projectId, }); res.sendStatus(204); }) ); // DELETE /projects/:id router.delete( '/:projectId', validateAdminTokenMiddleware(context), handleAsyncError(async (req, res) => { await context.storageMethod.deleteProject(req.params.projectId); res.sendStatus(204); }) ); // GET /projects/<id>/builds router.get( '/:projectId/builds', handleAsyncError(async (req, res) => { if (Number.isInteger(parseInt(req.query.limit))) { req.query.limit = parseInt(req.query.limit); } const builds = await context.storageMethod.getBuilds(req.params.projectId, req.query); res.json(builds); }) ); // GET /projects/<id>/urls router.get( '/:projectId/urls', handleAsyncError(async (req, res) => { const urls = await context.storageMethod.getUrls(req.params.projectId); res.json(urls); }) ); // GET /projects/<id>/branches router.get( '/:projectId/branches', handleAsyncError(async (req, res) => { const branches = await context.storageMethod.getBranches(req.params.projectId); res.json(branches); }) ); // POST /projects/<id>/builds router.post( '/:projectId/builds', validateBuildTokenMiddleware(context), handleAsyncError(async (req, res) => { const unsavedBuild = req.body; unsavedBuild.projectId = req.params.projectId; const build = await context.storageMethod.createBuild(unsavedBuild); res.json(build); }) ); // DELETE /projects/<id>/builds/<id> router.delete( '/:projectId/builds/:buildId', validateAdminTokenMiddleware(context), handleAsyncError(async (req, res) => { await context.storageMethod.deleteBuild(req.params.projectId, req.params.buildId); res.sendStatus(204); }) ); // GET /projects/:id/builds/:id router.get( '/:projectId/builds/:buildId', handleAsyncError(async (req, res) => { const build = await context.storageMethod.findBuildById( req.params.projectId, req.params.buildId ); if (!build) return res.sendStatus(404); res.json(build); }) ); // GET /projects/:id/builds/:id/ancestor router.get( '/:projectId/builds/:buildId/ancestor', handleAsyncError(async (req, res) => { const build = await context.storageMethod.findAncestorBuildById( req.params.projectId, req.params.buildId ); if (!build) return res.sendStatus(404); res.json(build); }) ); // GET /projects/<id>/builds/<id>/runs router.get( '/:projectId/builds/:buildId/runs', handleAsyncError(async (req, res) => { if (typeof req.query.representative === 'string') { req.query.representative = req.query.representative === 'true'; } const runs = await context.storageMethod.getRuns( req.params.projectId, req.params.buildId, req.query ); res.json(runs); }) ); // POST /projects/<id>/builds/<id>/runs router.post( '/:projectId/builds/:buildId/runs', validateBuildTokenMiddleware(context), handleAsyncError(async (req, res) => { const unsavedRun = req.body; unsavedRun.projectId = req.params.projectId; unsavedRun.buildId = req.params.buildId; const run = await context.storageMethod.createRun(unsavedRun); res.json(run); }) ); // GET /projects/<id>/builds/<id>/urls router.get( '/:projectId/builds/:buildId/urls', handleAsyncError(async (req, res) => { const urls = await context.storageMethod.getUrls(req.params.projectId, req.params.buildId); res.json(urls); }) ); // PUT /projects/<id>/builds/<id>/lifecycle router.put( '/:projectId/builds/:buildId/lifecycle', validateBuildTokenMiddleware(context), handleAsyncError(async (req, res) => { if (req.body !== 'sealed') throw new Error('Invalid lifecycle'); await context.storageMethod.sealBuild(req.params.projectId, req.params.buildId); res.sendStatus(204); }) ); // GET /projects/<id>/builds/<id>/statistics router.get( '/:projectId/builds/:buildId/statistics', handleAsyncError(async (req, res) => { const statistics = await context.storageMethod.getStatistics( req.params.projectId, req.params.buildId ); res.json(statistics); }) ); return router; }
@param {{storageMethod: LHCI.ServerCommand.StorageMethod}} context @return {import('express').Router}
createRouter ( context )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/api/routes/projects.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/api/routes/projects.js
Apache-2.0
hashAdminToken(token, salt) { const hash = crypto.createHmac('sha256', salt); hash.update(token); return hash.digest('hex'); },
Hashes an admin token with a given salt. In v0.4.x and earlier, salt is the projectId. @param {string} token @param {string} salt
hashAdminToken ( token , salt )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/api/storage/auth.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/api/storage/auth.js
Apache-2.0
async getProjects() { throw new Error('Unimplemented'); }
@return {Promise<Array<LHCI.ServerCommand.Project>>}
getProjects ( )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/api/storage/storage-method.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/api/storage/storage-method.js
Apache-2.0
static async getOrCreateStatistics(storageMethod, projectId, buildId) { const build = await storageMethod.findBuildById(projectId, buildId); if (!build) throw new E404('No build with that ID'); // If the build hasn't been sealed yet then we can't compute statistics for it yet. if (build.lifecycle !== 'sealed') return []; const urls = await storageMethod.getUrls(projectId, buildId); const statisicDefinitionEntries = Object.entries(statisticDefinitions); const existingStatistics = await storageMethod._getStatistics(projectId, buildId); if ( existingStatistics.length === urls.length * statisicDefinitionEntries.length && existingStatistics.every(stat => stat.version === STATISTIC_VERSION) ) { return existingStatistics; } const {statistics} = await this.createStatistics(storageMethod, build, {existingStatistics}); return statistics; }
@param {StorageMethod} storageMethod @param {string} projectId @param {string} buildId @return {Promise<Array<LHCI.ServerCommand.Statistic>>}
getOrCreateStatistics ( storageMethod , projectId , buildId )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/api/storage/storage-method.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/api/storage/storage-method.js
Apache-2.0
function clone(o) { if (o === undefined) return o; return JSON.parse(JSON.stringify(o)); }
Clones the object without the fancy function getters/setters. @template T @param {T} o @return {T}
clone ( o )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/api/storage/sql/sql.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/api/storage/sql/sql.js
Apache-2.0
_value(model) { return model.dataValues; }
@template {Object} T1 @template {Object} T2 @param {import('sequelize').Model<T1, T2>} model @return {T1}
_value ( model )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/api/storage/sql/sql.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/api/storage/sql/sql.js
Apache-2.0
_valueOrNull(model) { if (!model) return null; return model.dataValues; }
@template {Object} T1 @template {Object} T2 @param {import('sequelize').Model<T1, T2> | null} model @return {T1 | null}
_valueOrNull ( model )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/api/storage/sql/sql.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/api/storage/sql/sql.js
Apache-2.0
async _findByPk(model, pk) { const result = await model.findByPk(validateUuidOrEmpty(pk)); return this._valueOrNull(result); }
@template {Object} T1 @template {Object} T2 @param {import('sequelize').ModelDefined<T1, T2>} model @param {string} pk @return {Promise<T1 | null>}
_findByPk ( model , pk )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/api/storage/sql/sql.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/api/storage/sql/sql.js
Apache-2.0
async _findAll(model, options) { if (options.where) { options.where = {...options.where}; for (const key of Object.keys(options.where)) { if (!key.endsWith('Id') && key !== 'token') continue; // @ts-ignore - `options.where` is not indexable in tsc's eyes options.where[key] = validateUuidOrEmpty(options.where[key]); } } const result = await model.findAll(options); return result.map(this._value); }
@template {Object} T1 @template {Object} T2 @param {import('sequelize').ModelDefined<T1, T2>} model @param {import('sequelize').FindOptions<T1 & T2>} options @return {Promise<T1[]>}
_findAll ( model , options )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/api/storage/sql/sql.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/api/storage/sql/sql.js
Apache-2.0
async initialize(options) { if (!buildModelDefn.attributes.projectId.references) throw new Error('Invalid buildModel'); if (!runModelDefn.attributes.projectId.references) throw new Error('Invalid runModel'); if (!runModelDefn.attributes.buildId.references) throw new Error('Invalid runModel'); if (!statisticModelDefn.attributes.projectId.references) throw new Error('Invalid runModel'); if (!statisticModelDefn.attributes.buildId.references) throw new Error('Invalid runModel'); log('[initialize] initializing database connection'); const sequelize = createSequelize(options); log('[initialize] defining models'); const projectModel = sequelize.define(projectModelDefn.tableName, projectModelDefn.attributes); buildModelDefn.attributes.projectId.references.model = projectModel; const buildModel = sequelize.define(buildModelDefn.tableName, buildModelDefn.attributes); runModelDefn.attributes.projectId.references.model = projectModel; runModelDefn.attributes.buildId.references.model = buildModel; const runModel = sequelize.define(runModelDefn.tableName, runModelDefn.attributes); statisticModelDefn.attributes.projectId.references.model = projectModel; statisticModelDefn.attributes.buildId.references.model = buildModel; const statisticModel = sequelize.define( statisticModelDefn.tableName, statisticModelDefn.attributes ); const umzug = createUmzug(sequelize, options); if (options.sqlDangerouslyResetDatabase) { log('[initialize] resetting database'); await umzug.down({to: 0}); } log('[initialize] running migrations'); await umzug.up(); log('[initialize] migrations performed'); this._sequelize = {sequelize, projectModel, buildModel, runModel, statisticModel}; }
@param {LHCI.ServerCommand.StorageOptions} options @return {Promise<void>}
initialize ( options )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/api/storage/sql/sql.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/api/storage/sql/sql.js
Apache-2.0
async deleteProject(projectId) { const {sequelize, projectModel, buildModel, runModel, statisticModel} = this._sql(); const project = await this._findByPk(projectModel, projectId); if (!project) throw new E422('Invalid project ID'); const transaction = await sequelize.transaction(); try { await statisticModel.destroy({where: {projectId}, transaction}); await runModel.destroy({where: {projectId}, transaction}); await buildModel.destroy({where: {projectId}, transaction}); await projectModel.destroy({where: {id: projectId}, transaction}); await transaction.commit(); } catch (err) { await transaction.rollback(); throw err; } }
@param {string} projectId @return {Promise<void>}
deleteProject ( projectId )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/api/storage/sql/sql.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/api/storage/sql/sql.js
Apache-2.0
async findProjectByToken(token) { const {projectModel} = this._sql(); const projects = await this._findAll(projectModel, {where: {token}, limit: 1}); return clone(projects[0]); }
@param {string} token @return {Promise<LHCI.ServerCommand.Project | undefined>}
findProjectByToken ( token )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/api/storage/sql/sql.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/api/storage/sql/sql.js
Apache-2.0
async findProjectById(projectId) { const {projectModel} = this._sql(); const project = await this._findByPk(projectModel, projectId); return clone(project || undefined); }
@param {string} projectId @return {Promise<LHCI.ServerCommand.Project | undefined>}
findProjectById ( projectId )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/api/storage/sql/sql.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/api/storage/sql/sql.js
Apache-2.0
async findProjectBySlug(slug) { const {projectModel} = this._sql(); const projects = await this._findAll(projectModel, {where: {slug}}); if (projects.length !== 1) return undefined; return clone(projects[0] || undefined); }
@param {string} slug @return {Promise<LHCI.ServerCommand.Project | undefined>}
findProjectBySlug ( slug )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/api/storage/sql/sql.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/api/storage/sql/sql.js
Apache-2.0
async createProject(unsavedProject) { return StorageMethod.createProjectWithUniqueSlug(this, unsavedProject); }
@param {StrictOmit<LHCI.ServerCommand.Project, 'id'|'token'|'adminToken'>} unsavedProject @return {Promise<LHCI.ServerCommand.Project>}
createProject ( unsavedProject )
javascript
GoogleChrome/lighthouse-ci
packages/server/src/api/storage/sql/sql.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/api/storage/sql/sql.js
Apache-2.0
down: async ({queryInterface}) => { await queryInterface.dropTable('statistics'); await queryInterface.dropTable('runs'); await queryInterface.dropTable('builds'); await queryInterface.dropTable('projects'); },
@param {{queryInterface: import('sequelize').QueryInterface, options: LHCI.ServerCommand.StorageOptions}} _
async
javascript
GoogleChrome/lighthouse-ci
packages/server/src/api/storage/sql/migrations/20191008-initial.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/server/src/api/storage/sql/migrations/20191008-initial.js
Apache-2.0
function runCLIWithoutWaiting(args, overrides = {}) { const {env: extraEnvVars, cwd, useMockLhr = false} = overrides; const env = getCleanEnvironment(extraEnvVars); if (useMockLhr) env.LHCITEST_MOCK_LHR = MOCK_LHR; const childProcess = spawn('node', [CLI_PATH, ...args], { cwd, env, }); const results = {stdout: '', stderr: '', status: -1, matches: {uuids: []}}; childProcess.stdout.on('data', chunk => (results.stdout += chunk.toString())); childProcess.stderr.on('data', chunk => (results.stderr += chunk.toString())); childProcess.once('exit', code => (results.status = code)); const exitPromise = new Promise(r => childProcess.once('exit', r)); results.exitPromise = exitPromise.then(() => { results.matches.uuids = results.stdout.match(UUID_REGEX); results.stdout = cleanStdOutput(results.stdout); results.stderr = cleanStdOutput(results.stderr); }); results.childProcess = childProcess; return results; }
@param {string[]} args @param {{cwd?: string, env?: Record<string, string>, useMockLhr?: boolean}} [overrides] @return {{stdout: string, stderr: string, status: number, matches: {uuids: RegExpMatchArray}, childProcess: NodeJS.ChildProcess, exitPromise: Promise<void>}}
runCLIWithoutWaiting ( args , overrides = { } )
javascript
GoogleChrome/lighthouse-ci
packages/cli/test/test-utils.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/test/test-utils.js
Apache-2.0
async function runCLI(args, overrides = {}) { const results = runCLIWithoutWaiting(args, overrides); await results.exitPromise; return results; }
@param {string[]} args @param {{cwd?: string, env?: Record<string, string>, useMockLhr?: boolean}} [overrides] @return {Promise<{stdout: string, stderr: string, status: number, matches: {uuids: RegExpMatchArray}}>}
runCLI ( args , overrides = { } )
javascript
GoogleChrome/lighthouse-ci
packages/cli/test/test-utils.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/test/test-utils.js
Apache-2.0
async function startFallbackServer(staticDistDir, options) { const {isSinglePageApplication} = options; const pathToBuildDir = path.resolve(process.cwd(), staticDistDir); const server = new FallbackServer(pathToBuildDir, isSinglePageApplication); await server.listen(); return server; }
@param {string} staticDistDir @param {{isSinglePageApplication: boolean}} options @returns {Promise<FallbackServer>}
startFallbackServer ( staticDistDir , options )
javascript
GoogleChrome/lighthouse-ci
packages/cli/test/test-utils.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/test/test-utils.js
Apache-2.0
async function createApp() { const app = express(); app.post('/repos/GoogleChrome/lighthouse-ci/statuses/hash', (req, res) => { if (!req.headers.authorization || req.headers.authorization !== 'token githubToken') { res.status(401); res.json(); return; } setTimeout(() => { res.status(201); res.json({}); }, 100); }); return {app}; }
@return {Promise<{app: Parameters<typeof createHttpServer>[1]}>}
createApp ( )
javascript
GoogleChrome/lighthouse-ci
packages/cli/test/fixtures/autorun-github/mock-github-server.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/test/fixtures/autorun-github/mock-github-server.js
Apache-2.0
function getChromeInstallationsSafe() { if (process.env.LHCITEST_IGNORE_CHROME_INSTALLATIONS) return []; try { return ChromeLauncher.getInstallations(); } catch (err) { return []; } }
ChromeLauncher has an annoying API that *throws* instead of returning an empty array. Also enables testing of environments that don't have Chrome globally installed in tests. @return {string[]}
getChromeInstallationsSafe ( )
javascript
GoogleChrome/lighthouse-ci
packages/cli/src/utils.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/src/utils.js
Apache-2.0
function determineChromePath(options) { return ( options.chromePath || process.env.CHROME_PATH || PuppeteerManager.getChromiumPath(options) || getChromeInstallationsSafe()[0] || undefined ); }
@param {Partial<LHCI.CollectCommand.Options>} options @return {string|undefined}
determineChromePath ( options )
javascript
GoogleChrome/lighthouse-ci
packages/cli/src/utils.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/src/utils.js
Apache-2.0
async function runCommand(options) { /** @type {Array<LH.Result>} */ const lhrs = loadSavedLHRs().map(lhr => JSON.parse(lhr)); /** @type {Array<Array<[LH.Result, LH.Result]>>} */ const groupedByUrl = _.groupBy(lhrs, lhr => lhr.finalUrl).map(lhrs => lhrs.map(lhr => [lhr, lhr]) ); const representativeLhrs = computeRepresentativeRuns(groupedByUrl); if (!representativeLhrs.length) { process.stdout.write('No available reports to open. '); } const targetUrls = typeof options.url === 'string' ? [options.url] : options.url || []; for (const lhr of representativeLhrs) { if (targetUrls.length && !targetUrls.includes(lhr.finalUrl)) continue; process.stdout.write(`Opening median report for ${lhr.finalUrl}...\n`); const tmpFile = tmp.fileSync({postfix: '.html'}); fs.writeFileSync(tmpFile.name, await getHTMLReportForLHR(lhr)); await open(tmpFile.name); } process.stdout.write('Done!\n'); }
@param {LHCI.OpenCommand.Options} options @return {Promise<void>}
runCommand ( options )
javascript
GoogleChrome/lighthouse-ci
packages/cli/src/open/open.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/src/open/open.js
Apache-2.0
async function runCommand(options) { if (!Number.isInteger(options.port) || options.port < 0 || options.port > 65536) { const simpleArgv = yargsParser(process.argv.slice(2), {envPrefix: 'LHCI'}); const environment = Object.keys(process.env) .filter(key => key.startsWith('LHCI_')) .map(key => `${key}="${process.env[key]}"`) .sort() .join(', '); process.stderr.write(`Invalid port option "${options.port}"\n`); process.stderr.write(`environment: ${environment}\n`); process.stderr.write(`process.argv: ${process.argv.slice(2).join(' ')}\n`); process.stderr.write(`simpleArgv: port=${simpleArgv.port}, p=${simpleArgv.p}\n`); process.stderr.write(`configFile: ${resolveRcFilePath(simpleArgv.config)}\n`); process.exit(1); } // Require this only after they decide to run `lhci server` // eslint-disable-next-line import/no-extraneous-dependencies const {createServer} = require('@lhci/server'); return createServer(options); }
@param {LHCI.ServerCommand.Options} options @return {Promise<{port: number, close: () => void}>}
runCommand ( options )
javascript
GoogleChrome/lighthouse-ci
packages/cli/src/server/server.js
https://github.com/GoogleChrome/lighthouse-ci/blob/master/packages/cli/src/server/server.js
Apache-2.0