From 0ca3a26acd16e3edfe0afd1133de9a636db0428c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Usarz?= Date: Wed, 30 May 2018 16:46:09 +0200 Subject: [PATCH] refactor: refactor lib/reporter in to ES6 (#3021) --- lib/reporter.js | 140 ++++++++++++++++------------------------ lib/utils/path-utils.js | 9 +++ 2 files changed, 66 insertions(+), 83 deletions(-) create mode 100644 lib/utils/path-utils.js diff --git a/lib/reporter.js b/lib/reporter.js index 752c14f69..8b70f288c 100644 --- a/lib/reporter.js +++ b/lib/reporter.js @@ -1,31 +1,24 @@ -var util = require('util') -var resolve = require('url').resolve -var SourceMapConsumer = require('source-map').SourceMapConsumer -var _ = require('lodash') +'use strict' -var log = require('./logger').create('reporter') -var MultiReporter = require('./reporters/multi') -var baseReporterDecoratorFactory = require('./reporters/base').decoratorFactory +const resolve = require('url').resolve +const SourceMapConsumer = require('source-map').SourceMapConsumer +const _ = require('lodash') -var createErrorFormatter = function (config, emitter, SourceMapConsumer) { - var basePath = config.basePath - var urlRoot = config.urlRoot === '/' ? '' : (config.urlRoot || '') - var lastServedFiles = [] +const PathUtils = require('./utils/path-utils') +const log = require('./logger').create('reporter') +const MultiReporter = require('./reporters/multi') +const baseReporterDecoratorFactory = require('./reporters/base').decoratorFactory - emitter.on('file_list_modified', function (files) { +function createErrorFormatter (config, emitter, SourceMapConsumer) { + const basePath = config.basePath + const urlRoot = config.urlRoot === '/' ? '' : (config.urlRoot || '') + let lastServedFiles = [] + + emitter.on('file_list_modified', (files) => { lastServedFiles = files.served }) - var findFile = function (path) { - for (var i = 0; i < lastServedFiles.length; i++) { - if (lastServedFiles[i].path === path) { - return lastServedFiles[i] - } - } - return null - } - - var URL_REGEXP = new RegExp('(?:https?:\\/\\/' + + const URL_REGEXP = new RegExp('(?:https?:\\/\\/' + config.hostname + '(?:\\:' + config.port + ')?' + ')?\\/?' + urlRoot + '\\/?' + '(base/|absolute)' + // prefix, including slash for base/ to create relative paths. @@ -35,15 +28,14 @@ var createErrorFormatter = function (config, emitter, SourceMapConsumer) { '(\\:(\\d+))?' + // column '', 'g') - var getSourceMapConsumer = (function () { - var cache = new WeakMap() - return function (sourceMap) { - if (!cache.has(sourceMap)) { - cache.set(sourceMap, new SourceMapConsumer(sourceMap)) - } - return cache.get(sourceMap) + const cache = new WeakMap() + + function getSourceMapConsumer (sourceMap) { + if (!cache.has(sourceMap)) { + cache.set(sourceMap, new SourceMapConsumer(sourceMap)) } - }()) + return cache.get(sourceMap) + } return function (input, indentation) { indentation = _.isString(indentation) ? indentation : '' @@ -55,69 +47,56 @@ var createErrorFormatter = function (config, emitter, SourceMapConsumer) { input = JSON.stringify(input, null, indentation) } - // remove domain and timestamp from source files - // and resolve base path / absolute path urls into absolute path var msg = input.replace(URL_REGEXP, function (_, prefix, path, __, ___, line, ____, column) { - // Find the file using basePath + path, but use the more readable path down below. - var file = findFile(prefix === 'base/' ? basePath + '/' + path : path) + const normalizedPath = prefix === 'base/' ? `${basePath}/${path}` : path + const file = lastServedFiles.find((file) => file.path === normalizedPath) if (file && file.sourceMap && line) { - line = parseInt(line || '0', 10) - - column = parseInt(column, 10) + line = +line + column = +column // When no column is given and we default to 0, it doesn't make sense to only search for smaller // or equal columns in the sourcemap, let's search for equal or greater columns. - var bias = column ? SourceMapConsumer.GREATEST_LOWER_BOUND : SourceMapConsumer.LEAST_UPPER_BOUND + const bias = column ? SourceMapConsumer.GREATEST_LOWER_BOUND : SourceMapConsumer.LEAST_UPPER_BOUND try { - var original = getSourceMapConsumer(file.sourceMap) - .originalPositionFor({line: line, column: (column || 0), bias: bias}) + const original = getSourceMapConsumer(file.sourceMap).originalPositionFor({ line, column: (column || 0), bias }) // Source maps often only have a local file name, resolve to turn into a full path if // the path is not absolute yet. - var sourcePath = resolve(path, original.source) - var formattedColumn = column ? util.format(':%s', column) : '' - return util.format('%s:%d:%d <- %s:%d%s', sourcePath, original.line, original.column, - path, line, formattedColumn) + return `${PathUtils.formatPathMapping(resolve(path, original.source), original.line, original.column)} <- ${PathUtils.formatPathMapping(path, line, column)}` } catch (e) { - log.warn('SourceMap position not found for trace: %s', msg) - // Fall back to non-source-mapped formatting. + log.warn(`SourceMap position not found for trace: ${input}`) } } - var result = path + (line ? ':' + line : '') + (column ? ':' + column : '') - return result || prefix + return PathUtils.formatPathMapping(path, line, column) || prefix }) - // indent every line if (indentation) { msg = indentation + msg.replace(/\n/g, '\n' + indentation) } - // allow the user to format the error - if (config.formatError) { - return config.formatError(msg) - } - - return msg + '\n' + return config.formatError ? config.formatError(msg) : msg + '\n' } } -var createReporters = function (names, config, emitter, injector) { - var errorFormatter = createErrorFormatter(config, emitter, SourceMapConsumer) - var reporters = [] +function createReporters (names, config, emitter, injector) { + const errorFormatter = createErrorFormatter(config, emitter, SourceMapConsumer) + const reporters = [] - // TODO(vojta): instantiate all reporters through DI - names.forEach(function (name) { + names.forEach((name) => { if (['dots', 'progress'].indexOf(name) !== -1) { - var Cls = require('./reporters/' + name) - var ClsColor = require('./reporters/' + name + '_color') - reporters.push(new Cls(errorFormatter, config.reportSlowerThan, config.colors, config.browserConsoleLogOptions)) - return reporters.push(new ClsColor(errorFormatter, config.reportSlowerThan, config.colors, config.browserConsoleLogOptions)) + [ + require('./reporters/' + name), + require('./reporters/' + name + '_color') + ].forEach((Reporter) => { + reporters.push(new Reporter(errorFormatter, config.reportSlowerThan, config.colors, config.browserConsoleLogOptions)) + }) + return } - var locals = { + const locals = { baseReporterDecorator: ['factory', baseReporterDecoratorFactory], formatError: ['value', errorFormatter] } @@ -126,31 +105,27 @@ var createReporters = function (names, config, emitter, injector) { log.debug('Trying to load reporter: %s', name) reporters.push(injector.createChild([locals], ['reporter:' + name]).get('reporter:' + name)) } catch (e) { - if (e.message.indexOf('No provider for "reporter:' + name + '"') !== -1) { - log.error('Can not load reporter "%s", it is not registered!\n ' + - 'Perhaps you are missing some plugin?', name) + if (e.message.indexOf(`No provider for "reporter:${name}"`) !== -1) { + log.error(`Can not load reporter "${name}", it is not registered!\n Perhaps you are missing some plugin?`) } else { - log.error('Can not load "%s"!\n ' + e.stack, name) + log.error(`Can not load "${name}"!\n ${e.stack}`) } emitter.emit('load_error', 'reporter', name) return } - var colorName = name + '_color' - if (names.indexOf(colorName) !== -1) { - return - } - try { - log.debug('Trying to load color-version of reporter: %s (%s)', name, colorName) - reporters.push(injector.createChild([locals], ['reporter:' + name + '_color']).get('reporter:' + name)) - } catch (e) { - log.debug('Couldn\'t load color-version.') + + const colorName = name + '_color' + if (names.indexOf(colorName) === -1) { + try { + log.debug(`Trying to load color-version of reporter: ${name} (${colorName})`) + reporters.push(injector.createChild([locals], ['reporter:' + colorName]).get('reporter:' + name)) + } catch (e) { + log.debug('Couldn\'t load color-version.') + } } }) - // bind all reporters - reporters.forEach(function (reporter) { - emitter.bind(reporter) - }) + reporters.forEach((reporter) => emitter.bind(reporter)) return new MultiReporter(reporters) } @@ -162,5 +137,4 @@ createReporters.$inject = [ 'injector' ] -// PUBLISH exports.createReporters = createReporters diff --git a/lib/utils/path-utils.js b/lib/utils/path-utils.js new file mode 100644 index 000000000..0990e9168 --- /dev/null +++ b/lib/utils/path-utils.js @@ -0,0 +1,9 @@ +'use strict' + +const PathUtils = { + formatPathMapping (path, line, column) { + return path + (line ? `:${line}` : '') + (column ? `:${column}` : '') + } +} + +module.exports = PathUtils