config.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. 'use strict'
  2. const path = require('path')
  3. const assert = require('assert')
  4. const logger = require('./logger')
  5. const log = logger.create('config')
  6. const helper = require('./helper')
  7. const constant = require('./constants')
  8. const _ = require('lodash')
  9. let COFFEE_SCRIPT_AVAILABLE = false
  10. let LIVE_SCRIPT_AVAILABLE = false
  11. let TYPE_SCRIPT_AVAILABLE = false
  12. try {
  13. require('coffeescript').register()
  14. COFFEE_SCRIPT_AVAILABLE = true
  15. } catch {}
  16. // LiveScript is required here to enable config files written in LiveScript.
  17. // It's not directly used in this file.
  18. try {
  19. require('LiveScript')
  20. LIVE_SCRIPT_AVAILABLE = true
  21. } catch {}
  22. try {
  23. require('ts-node')
  24. TYPE_SCRIPT_AVAILABLE = true
  25. } catch {}
  26. class Pattern {
  27. constructor (pattern, served, included, watched, nocache, type, isBinary) {
  28. this.pattern = pattern
  29. this.served = helper.isDefined(served) ? served : true
  30. this.included = helper.isDefined(included) ? included : true
  31. this.watched = helper.isDefined(watched) ? watched : true
  32. this.nocache = helper.isDefined(nocache) ? nocache : false
  33. this.weight = helper.mmPatternWeight(pattern)
  34. this.type = type
  35. this.isBinary = isBinary
  36. }
  37. compare (other) {
  38. return helper.mmComparePatternWeights(this.weight, other.weight)
  39. }
  40. }
  41. class UrlPattern extends Pattern {
  42. constructor (url, type) {
  43. super(url, false, true, false, false, type)
  44. }
  45. }
  46. function createPatternObject (pattern) {
  47. if (pattern && helper.isString(pattern)) {
  48. return helper.isUrlAbsolute(pattern)
  49. ? new UrlPattern(pattern)
  50. : new Pattern(pattern)
  51. } else if (helper.isObject(pattern) && pattern.pattern && helper.isString(pattern.pattern)) {
  52. return helper.isUrlAbsolute(pattern.pattern)
  53. ? new UrlPattern(pattern.pattern, pattern.type)
  54. : new Pattern(pattern.pattern, pattern.served, pattern.included, pattern.watched, pattern.nocache, pattern.type)
  55. } else {
  56. log.warn(`Invalid pattern ${pattern}!\n\tExpected string or object with "pattern" property.`)
  57. return new Pattern(null, false, false, false, false)
  58. }
  59. }
  60. function normalizeUrl (url) {
  61. if (!url.startsWith('/')) {
  62. url = `/${url}`
  63. }
  64. if (!url.endsWith('/')) {
  65. url = url + '/'
  66. }
  67. return url
  68. }
  69. function normalizeUrlRoot (urlRoot) {
  70. const normalizedUrlRoot = normalizeUrl(urlRoot)
  71. if (normalizedUrlRoot !== urlRoot) {
  72. log.warn(`urlRoot normalized to "${normalizedUrlRoot}"`)
  73. }
  74. return normalizedUrlRoot
  75. }
  76. function normalizeProxyPath (proxyPath) {
  77. const normalizedProxyPath = normalizeUrl(proxyPath)
  78. if (normalizedProxyPath !== proxyPath) {
  79. log.warn(`proxyPath normalized to "${normalizedProxyPath}"`)
  80. }
  81. return normalizedProxyPath
  82. }
  83. function normalizeConfig (config, configFilePath) {
  84. function basePathResolve (relativePath) {
  85. if (helper.isUrlAbsolute(relativePath)) {
  86. return relativePath
  87. } else if (helper.isDefined(config.basePath) && helper.isDefined(relativePath)) {
  88. return path.resolve(config.basePath, relativePath)
  89. } else {
  90. return ''
  91. }
  92. }
  93. function createPatternMapper (resolve) {
  94. return (objectPattern) => Object.assign(objectPattern, { pattern: resolve(objectPattern.pattern) })
  95. }
  96. if (helper.isString(configFilePath)) {
  97. config.basePath = path.resolve(path.dirname(configFilePath), config.basePath) // resolve basePath
  98. config.exclude.push(configFilePath) // always ignore the config file itself
  99. } else {
  100. config.basePath = path.resolve(config.basePath || '.')
  101. }
  102. config.files = config.files.map(createPatternObject).map(createPatternMapper(basePathResolve))
  103. config.exclude = config.exclude.map(basePathResolve)
  104. config.customContextFile = config.customContextFile && basePathResolve(config.customContextFile)
  105. config.customDebugFile = config.customDebugFile && basePathResolve(config.customDebugFile)
  106. config.customClientContextFile = config.customClientContextFile && basePathResolve(config.customClientContextFile)
  107. // normalize paths on windows
  108. config.basePath = helper.normalizeWinPath(config.basePath)
  109. config.files = config.files.map(createPatternMapper(helper.normalizeWinPath))
  110. config.exclude = config.exclude.map(helper.normalizeWinPath)
  111. config.customContextFile = helper.normalizeWinPath(config.customContextFile)
  112. config.customDebugFile = helper.normalizeWinPath(config.customDebugFile)
  113. config.customClientContextFile = helper.normalizeWinPath(config.customClientContextFile)
  114. // normalize urlRoot
  115. config.urlRoot = normalizeUrlRoot(config.urlRoot)
  116. // normalize and default upstream proxy settings if given
  117. if (config.upstreamProxy) {
  118. const proxy = config.upstreamProxy
  119. proxy.path = helper.isDefined(proxy.path) ? normalizeProxyPath(proxy.path) : '/'
  120. proxy.hostname = helper.isDefined(proxy.hostname) ? proxy.hostname : 'localhost'
  121. proxy.port = helper.isDefined(proxy.port) ? proxy.port : 9875
  122. // force protocol to end with ':'
  123. proxy.protocol = (proxy.protocol || 'http').split(':')[0] + ':'
  124. if (proxy.protocol.match(/https?:/) === null) {
  125. log.warn(`"${proxy.protocol}" is not a supported upstream proxy protocol, defaulting to "http:"`)
  126. proxy.protocol = 'http:'
  127. }
  128. }
  129. // force protocol to end with ':'
  130. config.protocol = (config.protocol || 'http').split(':')[0] + ':'
  131. if (config.protocol.match(/https?:/) === null) {
  132. log.warn(`"${config.protocol}" is not a supported protocol, defaulting to "http:"`)
  133. config.protocol = 'http:'
  134. }
  135. if (config.proxies && Object.prototype.hasOwnProperty.call(config.proxies, config.urlRoot)) {
  136. log.warn(`"${config.urlRoot}" is proxied, you should probably change urlRoot to avoid conflicts`)
  137. }
  138. if (config.singleRun && config.autoWatch) {
  139. log.debug('autoWatch set to false, because of singleRun')
  140. config.autoWatch = false
  141. }
  142. if (config.runInParent) {
  143. log.debug('useIframe set to false, because using runInParent')
  144. config.useIframe = false
  145. }
  146. if (!config.singleRun && !config.useIframe && config.runInParent) {
  147. log.debug('singleRun set to true, because using runInParent')
  148. config.singleRun = true
  149. }
  150. if (helper.isString(config.reporters)) {
  151. config.reporters = config.reporters.split(',')
  152. }
  153. if (config.client && config.client.args) {
  154. assert(Array.isArray(config.client.args), 'Invalid configuration: client.args must be an array of strings')
  155. }
  156. if (config.browsers) {
  157. assert(Array.isArray(config.browsers), 'Invalid configuration: browsers option must be an array')
  158. }
  159. if (config.formatError) {
  160. assert(helper.isFunction(config.formatError), 'Invalid configuration: formatError option must be a function.')
  161. }
  162. if (config.processKillTimeout) {
  163. assert(helper.isNumber(config.processKillTimeout), 'Invalid configuration: processKillTimeout option must be a number.')
  164. }
  165. if (config.browserSocketTimeout) {
  166. assert(helper.isNumber(config.browserSocketTimeout), 'Invalid configuration: browserSocketTimeout option must be a number.')
  167. }
  168. if (config.pingTimeout) {
  169. assert(helper.isNumber(config.pingTimeout), 'Invalid configuration: pingTimeout option must be a number.')
  170. }
  171. const defaultClient = config.defaultClient || {}
  172. Object.keys(defaultClient).forEach(function (key) {
  173. const option = config.client[key]
  174. config.client[key] = helper.isDefined(option) ? option : defaultClient[key]
  175. })
  176. // normalize preprocessors
  177. const preprocessors = config.preprocessors || {}
  178. const normalizedPreprocessors = config.preprocessors = Object.create(null)
  179. Object.keys(preprocessors).forEach(function (pattern) {
  180. const normalizedPattern = helper.normalizeWinPath(basePathResolve(pattern))
  181. normalizedPreprocessors[normalizedPattern] = helper.isString(preprocessors[pattern])
  182. ? [preprocessors[pattern]] : preprocessors[pattern]
  183. })
  184. // define custom launchers/preprocessors/reporters - create a new plugin
  185. const module = Object.create(null)
  186. let hasSomeInlinedPlugin = false
  187. const types = ['launcher', 'preprocessor', 'reporter']
  188. types.forEach(function (type) {
  189. const definitions = config[`custom${helper.ucFirst(type)}s`] || {}
  190. Object.keys(definitions).forEach(function (name) {
  191. const definition = definitions[name]
  192. if (!helper.isObject(definition)) {
  193. return log.warn(`Can not define ${type} ${name}. Definition has to be an object.`)
  194. }
  195. if (!helper.isString(definition.base)) {
  196. return log.warn(`Can not define ${type} ${name}. Missing base ${type}.`)
  197. }
  198. const token = type + ':' + definition.base
  199. const locals = {
  200. args: ['value', definition]
  201. }
  202. module[type + ':' + name] = ['factory', function (injector) {
  203. const plugin = injector.createChild([locals], [token]).get(token)
  204. if (type === 'launcher' && helper.isDefined(definition.displayName)) {
  205. plugin.displayName = definition.displayName
  206. }
  207. return plugin
  208. }]
  209. hasSomeInlinedPlugin = true
  210. })
  211. })
  212. if (hasSomeInlinedPlugin) {
  213. config.plugins.push(module)
  214. }
  215. return config
  216. }
  217. /**
  218. * @class
  219. */
  220. class Config {
  221. constructor () {
  222. this.LOG_DISABLE = constant.LOG_DISABLE
  223. this.LOG_ERROR = constant.LOG_ERROR
  224. this.LOG_WARN = constant.LOG_WARN
  225. this.LOG_INFO = constant.LOG_INFO
  226. this.LOG_DEBUG = constant.LOG_DEBUG
  227. // DEFAULT CONFIG
  228. this.frameworks = []
  229. this.protocol = 'http:'
  230. this.port = constant.DEFAULT_PORT
  231. this.listenAddress = constant.DEFAULT_LISTEN_ADDR
  232. this.hostname = constant.DEFAULT_HOSTNAME
  233. this.httpsServerConfig = {}
  234. this.basePath = ''
  235. this.files = []
  236. this.browserConsoleLogOptions = {
  237. level: 'debug',
  238. format: '%b %T: %m',
  239. terminal: true
  240. }
  241. this.customContextFile = null
  242. this.customDebugFile = null
  243. this.customClientContextFile = null
  244. this.exclude = []
  245. this.logLevel = constant.LOG_INFO
  246. this.colors = true
  247. this.autoWatch = true
  248. this.autoWatchBatchDelay = 250
  249. this.restartOnFileChange = false
  250. this.usePolling = process.platform === 'linux'
  251. this.reporters = ['progress']
  252. this.singleRun = false
  253. this.browsers = []
  254. this.captureTimeout = 60000
  255. this.pingTimeout = 5000
  256. this.proxies = {}
  257. this.proxyValidateSSL = true
  258. this.preprocessors = {}
  259. this.preprocessor_priority = {}
  260. this.urlRoot = '/'
  261. this.upstreamProxy = undefined
  262. this.reportSlowerThan = 0
  263. this.loggers = [constant.CONSOLE_APPENDER]
  264. this.transports = ['polling', 'websocket']
  265. this.forceJSONP = false
  266. this.plugins = ['karma-*']
  267. this.defaultClient = this.client = {
  268. args: [],
  269. useIframe: true,
  270. runInParent: false,
  271. captureConsole: true,
  272. clearContext: true,
  273. allowedReturnUrlPatterns: ['^https?://']
  274. }
  275. this.browserDisconnectTimeout = 2000
  276. this.browserDisconnectTolerance = 0
  277. this.browserNoActivityTimeout = 30000
  278. this.processKillTimeout = 2000
  279. this.concurrency = Infinity
  280. this.failOnEmptyTestSuite = true
  281. this.retryLimit = 2
  282. this.detached = false
  283. this.crossOriginAttribute = true
  284. this.browserSocketTimeout = 20000
  285. }
  286. set (newConfig) {
  287. _.mergeWith(this, newConfig, (obj, src) => {
  288. // Overwrite arrays to keep consistent with #283
  289. if (Array.isArray(src)) {
  290. return src
  291. }
  292. })
  293. }
  294. }
  295. const CONFIG_SYNTAX_HELP = ' module.exports = function(config) {\n' +
  296. ' config.set({\n' +
  297. ' // your config\n' +
  298. ' });\n' +
  299. ' };\n'
  300. /**
  301. * Retrieve a parsed and finalized Karma `Config` instance. This `karmaConfig`
  302. * object may be used to configure public API methods such a `Server`,
  303. * `runner.run`, and `stopper.stop`.
  304. *
  305. * @param {?string} [configFilePath=null]
  306. * A string representing a file system path pointing to the config file
  307. * whose default export is a function that will be used to set Karma
  308. * configuration options. This function will be passed an instance of the
  309. * `Config` class as its first argument. If this option is not provided,
  310. * then only the options provided by the `cliOptions` argument will be
  311. * set.
  312. * @param {Object} cliOptions
  313. * An object whose values will take priority over options set in the
  314. * config file. The config object passed to function exported by the
  315. * config file will already have these options applied. Any changes the
  316. * config file makes to these options will effectively be ignored in the
  317. * final configuration.
  318. *
  319. * `cliOptions` all the same options as the config file and is applied
  320. * using the same `config.set()` method.
  321. * @param {Object} parseOptions
  322. * @param {boolean} [parseOptions.promiseConfig=false]
  323. * When `true`, a promise that resolves to a `Config` object will be
  324. * returned. This also allows the function exported by config files (if
  325. * provided) to be asynchronous by returning a promise. Resolving this
  326. * promise indicates that all async activity has completed. The resolution
  327. * value itself is ignored, all configuration must be done with
  328. * `config.set`.
  329. * @param {boolean} [parseOptions.throwErrors=false]
  330. * When `true`, process exiting on critical failures will be disabled. In
  331. * The error will be thrown as an exception. If
  332. * `parseOptions.promiseConfig` is also `true`, then the error will
  333. * instead be used as the promise's reject reason.
  334. * @returns {Config|Promise<Config>}
  335. */
  336. function parseConfig (configFilePath, cliOptions, parseOptions) {
  337. const promiseConfig = parseOptions && parseOptions.promiseConfig === true
  338. const throwErrors = parseOptions && parseOptions.throwErrors === true
  339. const shouldSetupLoggerEarly = promiseConfig
  340. if (shouldSetupLoggerEarly) {
  341. // `setupFromConfig` provides defaults for `colors` and `logLevel`.
  342. // `setup` provides defaults for `appenders`
  343. // The first argument MUST BE an object
  344. logger.setupFromConfig({})
  345. }
  346. function fail () {
  347. log.error(...arguments)
  348. if (throwErrors) {
  349. const errorMessage = Array.from(arguments).join(' ')
  350. const err = new Error(errorMessage)
  351. if (promiseConfig) {
  352. return Promise.reject(err)
  353. }
  354. throw err
  355. } else {
  356. const warningMessage =
  357. 'The `parseConfig()` function historically called `process.exit(1)`' +
  358. ' when it failed. This behavior is now deprecated and function will' +
  359. ' throw an error in the next major release. To suppress this warning' +
  360. ' pass `throwErrors: true` as a third argument to opt-in into the new' +
  361. ' behavior and adjust your code to respond to the exception' +
  362. ' accordingly.' +
  363. ' Example: `parseConfig(path, cliOptions, { throwErrors: true })`'
  364. log.warn(warningMessage)
  365. process.exit(1)
  366. }
  367. }
  368. let configModule
  369. if (configFilePath) {
  370. try {
  371. if (path.extname(configFilePath) === '.ts' && TYPE_SCRIPT_AVAILABLE) {
  372. require('ts-node').register()
  373. }
  374. configModule = require(configFilePath)
  375. if (typeof configModule === 'object' && typeof configModule.default !== 'undefined') {
  376. configModule = configModule.default
  377. }
  378. } catch (e) {
  379. const extension = path.extname(configFilePath)
  380. if (extension === '.coffee' && !COFFEE_SCRIPT_AVAILABLE) {
  381. log.error('You need to install CoffeeScript.\n npm install coffeescript --save-dev')
  382. } else if (extension === '.ls' && !LIVE_SCRIPT_AVAILABLE) {
  383. log.error('You need to install LiveScript.\n npm install LiveScript --save-dev')
  384. } else if (extension === '.ts' && !TYPE_SCRIPT_AVAILABLE) {
  385. log.error('You need to install TypeScript.\n npm install typescript ts-node --save-dev')
  386. }
  387. return fail('Error in config file!\n ' + e.stack || e)
  388. }
  389. if (!helper.isFunction(configModule)) {
  390. return fail('Config file must export a function!\n' + CONFIG_SYNTAX_HELP)
  391. }
  392. } else {
  393. configModule = () => {} // if no config file path is passed, we define a dummy config module.
  394. }
  395. const config = new Config()
  396. // save and reset hostname and listenAddress so we can detect if the user
  397. // changed them
  398. const defaultHostname = config.hostname
  399. config.hostname = null
  400. const defaultListenAddress = config.listenAddress
  401. config.listenAddress = null
  402. // add the user's configuration in
  403. config.set(cliOptions)
  404. let configModuleReturn
  405. try {
  406. configModuleReturn = configModule(config)
  407. } catch (e) {
  408. return fail('Error in config file!\n', e)
  409. }
  410. function finalizeConfig (config) {
  411. // merge the config from config file and cliOptions (precedence)
  412. config.set(cliOptions)
  413. // if the user changed listenAddress, but didn't set a hostname, warn them
  414. if (config.hostname === null && config.listenAddress !== null) {
  415. log.warn(`ListenAddress was set to ${config.listenAddress} but hostname was left as the default: ` +
  416. `${defaultHostname}. If your browsers fail to connect, consider changing the hostname option.`)
  417. }
  418. // restore values that weren't overwritten by the user
  419. if (config.hostname === null) {
  420. config.hostname = defaultHostname
  421. }
  422. if (config.listenAddress === null) {
  423. config.listenAddress = defaultListenAddress
  424. }
  425. // configure the logger as soon as we can
  426. logger.setup(config.logLevel, config.colors, config.loggers)
  427. log.debug(configFilePath ? `Loading config ${configFilePath}` : 'No config file specified.')
  428. return normalizeConfig(config, configFilePath)
  429. }
  430. /**
  431. * Return value is a function or (non-null) object that has a `then` method.
  432. *
  433. * @type {boolean}
  434. * @see {@link https://promisesaplus.com/}
  435. */
  436. const returnIsThenable = (
  437. (
  438. (configModuleReturn != null && typeof configModuleReturn === 'object') ||
  439. typeof configModuleReturn === 'function'
  440. ) && typeof configModuleReturn.then === 'function'
  441. )
  442. if (returnIsThenable) {
  443. if (promiseConfig !== true) {
  444. const errorMessage =
  445. 'The `parseOptions.promiseConfig` option must be set to `true` to ' +
  446. 'enable promise return values from configuration files. ' +
  447. 'Example: `parseConfig(path, cliOptions, { promiseConfig: true })`'
  448. return fail(errorMessage)
  449. }
  450. return configModuleReturn.then(
  451. function onKarmaConfigModuleFulfilled (/* ignoredResolutionValue */) {
  452. return finalizeConfig(config)
  453. },
  454. function onKarmaConfigModuleRejected (reason) {
  455. return fail('Error in config file!\n', reason)
  456. }
  457. )
  458. } else {
  459. if (promiseConfig) {
  460. try {
  461. return Promise.resolve(finalizeConfig(config))
  462. } catch (exception) {
  463. return Promise.reject(exception)
  464. }
  465. } else {
  466. return finalizeConfig(config)
  467. }
  468. }
  469. }
  470. // PUBLIC API
  471. exports.parseConfig = parseConfig
  472. exports.Pattern = Pattern
  473. exports.createPatternObject = createPatternObject
  474. exports.Config = Config