plugin-loader.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. /**
  2. * @typedef {import('./types.d.ts').PluginDefinition} PluginDefinition
  3. */
  4. /**
  5. * Provides a way to load "plugins" as provided by the user.
  6. *
  7. * Currently supports:
  8. *
  9. * - Root hooks
  10. * - Global fixtures (setup/teardown)
  11. * @private
  12. * @module plugin
  13. */
  14. 'use strict';
  15. const debug = require('debug')('mocha:plugin-loader');
  16. const {
  17. createInvalidPluginDefinitionError,
  18. createInvalidPluginImplementationError
  19. } = require('./errors');
  20. const {castArray} = require('./utils');
  21. /**
  22. * @typedef {import('./types.d.ts').PluginLoaderOptions} PluginLoaderOptions
  23. */
  24. /**
  25. * Built-in plugin definitions.
  26. */
  27. const MochaPlugins = [
  28. /**
  29. * Root hook plugin definition
  30. * @type {PluginDefinition}
  31. */
  32. {
  33. exportName: 'mochaHooks',
  34. optionName: 'rootHooks',
  35. validate(value) {
  36. if (
  37. Array.isArray(value) ||
  38. (typeof value !== 'function' && typeof value !== 'object')
  39. ) {
  40. throw createInvalidPluginImplementationError(
  41. `mochaHooks must be an object or a function returning (or fulfilling with) an object`
  42. );
  43. }
  44. },
  45. async finalize(rootHooks) {
  46. if (rootHooks.length) {
  47. const rootHookObjects = await Promise.all(
  48. rootHooks.map(async hook =>
  49. typeof hook === 'function' ? hook() : hook
  50. )
  51. );
  52. return rootHookObjects.reduce(
  53. (acc, hook) => {
  54. hook = {
  55. beforeAll: [],
  56. beforeEach: [],
  57. afterAll: [],
  58. afterEach: [],
  59. ...hook
  60. };
  61. return {
  62. beforeAll: [...acc.beforeAll, ...castArray(hook.beforeAll)],
  63. beforeEach: [...acc.beforeEach, ...castArray(hook.beforeEach)],
  64. afterAll: [...acc.afterAll, ...castArray(hook.afterAll)],
  65. afterEach: [...acc.afterEach, ...castArray(hook.afterEach)]
  66. };
  67. },
  68. {beforeAll: [], beforeEach: [], afterAll: [], afterEach: []}
  69. );
  70. }
  71. }
  72. },
  73. /**
  74. * Global setup fixture plugin definition
  75. * @type {PluginDefinition}
  76. */
  77. {
  78. exportName: 'mochaGlobalSetup',
  79. optionName: 'globalSetup',
  80. validate(value) {
  81. let isValid = true;
  82. if (Array.isArray(value)) {
  83. if (value.some(item => typeof item !== 'function')) {
  84. isValid = false;
  85. }
  86. } else if (typeof value !== 'function') {
  87. isValid = false;
  88. }
  89. if (!isValid) {
  90. throw createInvalidPluginImplementationError(
  91. `mochaGlobalSetup must be a function or an array of functions`,
  92. {pluginDef: this, pluginImpl: value}
  93. );
  94. }
  95. }
  96. },
  97. /**
  98. * Global teardown fixture plugin definition
  99. * @type {PluginDefinition}
  100. */
  101. {
  102. exportName: 'mochaGlobalTeardown',
  103. optionName: 'globalTeardown',
  104. validate(value) {
  105. let isValid = true;
  106. if (Array.isArray(value)) {
  107. if (value.some(item => typeof item !== 'function')) {
  108. isValid = false;
  109. }
  110. } else if (typeof value !== 'function') {
  111. isValid = false;
  112. }
  113. if (!isValid) {
  114. throw createInvalidPluginImplementationError(
  115. `mochaGlobalTeardown must be a function or an array of functions`,
  116. {pluginDef: this, pluginImpl: value}
  117. );
  118. }
  119. }
  120. }
  121. ];
  122. /**
  123. * Contains a registry of [plugin definitions]{@link PluginDefinition} and discovers plugin implementations in user-supplied code.
  124. *
  125. * - [load()]{@link #load} should be called for all required modules
  126. * - The result of [finalize()]{@link #finalize} should be merged into the options for the [Mocha]{@link Mocha} constructor.
  127. * @private
  128. */
  129. class PluginLoader {
  130. /**
  131. * Initializes plugin names, plugin map, etc.
  132. * @param {PluginLoaderOptions} [opts] - Options
  133. */
  134. constructor({pluginDefs = MochaPlugins, ignore = []} = {}) {
  135. /**
  136. * Map of registered plugin defs
  137. * @type {Map<string,PluginDefinition>}
  138. */
  139. this.registered = new Map();
  140. /**
  141. * Cache of known `optionName` values for checking conflicts
  142. * @type {Set<string>}
  143. */
  144. this.knownOptionNames = new Set();
  145. /**
  146. * Cache of known `exportName` values for checking conflicts
  147. * @type {Set<string>}
  148. */
  149. this.knownExportNames = new Set();
  150. /**
  151. * Map of user-supplied plugin implementations
  152. * @type {Map<string,Array<*>>}
  153. */
  154. this.loaded = new Map();
  155. /**
  156. * Set of ignored plugins by export name
  157. * @type {Set<string>}
  158. */
  159. this.ignoredExportNames = new Set(castArray(ignore));
  160. castArray(pluginDefs).forEach(pluginDef => {
  161. this.register(pluginDef);
  162. });
  163. debug(
  164. 'registered %d plugin defs (%d ignored)',
  165. this.registered.size,
  166. this.ignoredExportNames.size
  167. );
  168. }
  169. /**
  170. * Register a plugin
  171. * @param {PluginDefinition} pluginDef - Plugin definition
  172. */
  173. register(pluginDef) {
  174. if (!pluginDef || typeof pluginDef !== 'object') {
  175. throw createInvalidPluginDefinitionError(
  176. 'pluginDef is non-object or falsy',
  177. pluginDef
  178. );
  179. }
  180. if (!pluginDef.exportName) {
  181. throw createInvalidPluginDefinitionError(
  182. `exportName is expected to be a non-empty string`,
  183. pluginDef
  184. );
  185. }
  186. let {exportName} = pluginDef;
  187. if (this.ignoredExportNames.has(exportName)) {
  188. debug(
  189. 'refusing to register ignored plugin with export name "%s"',
  190. exportName
  191. );
  192. return;
  193. }
  194. exportName = String(exportName);
  195. pluginDef.optionName = String(pluginDef.optionName || exportName);
  196. if (this.knownExportNames.has(exportName)) {
  197. throw createInvalidPluginDefinitionError(
  198. `Plugin definition conflict: ${exportName}; exportName must be unique`,
  199. pluginDef
  200. );
  201. }
  202. this.loaded.set(exportName, []);
  203. this.registered.set(exportName, pluginDef);
  204. this.knownExportNames.add(exportName);
  205. this.knownOptionNames.add(pluginDef.optionName);
  206. debug('registered plugin def "%s"', exportName);
  207. }
  208. /**
  209. * Inspects a module's exports for known plugins and keeps them in memory.
  210. *
  211. * @param {*} requiredModule - The exports of a module loaded via `--require`
  212. * @returns {boolean} If one or more plugins was found, return `true`.
  213. */
  214. load(requiredModule) {
  215. // we should explicitly NOT fail if other stuff is exported.
  216. // we only care about the plugins we know about.
  217. if (requiredModule && typeof requiredModule === 'object') {
  218. return Array.from(this.knownExportNames).reduce(
  219. (pluginImplFound, pluginName) => {
  220. const pluginImpl = requiredModule[pluginName];
  221. if (pluginImpl) {
  222. const plugin = this.registered.get(pluginName);
  223. if (typeof plugin.validate === 'function') {
  224. plugin.validate(pluginImpl);
  225. }
  226. this.loaded.set(pluginName, [
  227. ...this.loaded.get(pluginName),
  228. ...castArray(pluginImpl)
  229. ]);
  230. return true;
  231. }
  232. return pluginImplFound;
  233. },
  234. false
  235. );
  236. }
  237. return false;
  238. }
  239. /**
  240. * Call the `finalize()` function of each known plugin definition on the plugins found by [load()]{@link PluginLoader#load}.
  241. *
  242. * Output suitable for passing as input into {@link Mocha} constructor.
  243. * @returns {Promise<object>} Object having keys corresponding to registered plugin definitions' `optionName` prop (or `exportName`, if none), and the values are the implementations as provided by a user.
  244. */
  245. async finalize() {
  246. const finalizedPlugins = Object.create(null);
  247. for await (const [exportName, pluginImpls] of this.loaded.entries()) {
  248. if (pluginImpls.length) {
  249. const plugin = this.registered.get(exportName);
  250. finalizedPlugins[plugin.optionName] =
  251. typeof plugin.finalize === 'function'
  252. ? await plugin.finalize(pluginImpls)
  253. : pluginImpls;
  254. }
  255. }
  256. debug('finalized plugins: %O', finalizedPlugins);
  257. return finalizedPlugins;
  258. }
  259. /**
  260. * Constructs a {@link PluginLoader}
  261. * @param {PluginLoaderOptions} [opts] - Plugin loader options
  262. */
  263. static create({pluginDefs = MochaPlugins, ignore = []} = {}) {
  264. return new PluginLoader({pluginDefs, ignore});
  265. }
  266. }
  267. module.exports = PluginLoader;