| 1 | /*
|
|---|
| 2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
|---|
| 3 | Author Tobias Koppers @sokra
|
|---|
| 4 | */
|
|---|
| 5 | "use strict";
|
|---|
| 6 |
|
|---|
| 7 | const util = require("util");
|
|---|
| 8 |
|
|---|
| 9 | const defaultFactory = (key, hook) => hook;
|
|---|
| 10 |
|
|---|
| 11 | class HookMap {
|
|---|
| 12 | constructor(factory, name = undefined) {
|
|---|
| 13 | this._map = new Map();
|
|---|
| 14 | this.name = name;
|
|---|
| 15 | this._factory = factory;
|
|---|
| 16 | this._interceptors = [];
|
|---|
| 17 | }
|
|---|
| 18 |
|
|---|
| 19 | get(key) {
|
|---|
| 20 | return this._map.get(key);
|
|---|
| 21 | }
|
|---|
| 22 |
|
|---|
| 23 | for(key) {
|
|---|
| 24 | // Hot path: inline the map lookup to skip the `this.get(key)`
|
|---|
| 25 | // indirection. This gets hit on every hook access in consumers
|
|---|
| 26 | // like webpack.
|
|---|
| 27 | const map = this._map;
|
|---|
| 28 | const hook = map.get(key);
|
|---|
| 29 | if (hook !== undefined) {
|
|---|
| 30 | return hook;
|
|---|
| 31 | }
|
|---|
| 32 | let newHook = this._factory(key);
|
|---|
| 33 | const interceptors = this._interceptors;
|
|---|
| 34 | for (let i = 0; i < interceptors.length; i++) {
|
|---|
| 35 | newHook = interceptors[i].factory(key, newHook);
|
|---|
| 36 | }
|
|---|
| 37 | map.set(key, newHook);
|
|---|
| 38 | return newHook;
|
|---|
| 39 | }
|
|---|
| 40 |
|
|---|
| 41 | intercept(interceptor) {
|
|---|
| 42 | this._interceptors.push(
|
|---|
| 43 | Object.assign(
|
|---|
| 44 | {
|
|---|
| 45 | factory: defaultFactory
|
|---|
| 46 | },
|
|---|
| 47 | interceptor
|
|---|
| 48 | )
|
|---|
| 49 | );
|
|---|
| 50 | }
|
|---|
| 51 | }
|
|---|
| 52 |
|
|---|
| 53 | HookMap.prototype.tap = util.deprecate(function tap(key, options, fn) {
|
|---|
| 54 | return this.for(key).tap(options, fn);
|
|---|
| 55 | }, "HookMap#tap(key,…) is deprecated. Use HookMap#for(key).tap(…) instead.");
|
|---|
| 56 |
|
|---|
| 57 | HookMap.prototype.tapAsync = util.deprecate(function tapAsync(
|
|---|
| 58 | key,
|
|---|
| 59 | options,
|
|---|
| 60 | fn
|
|---|
| 61 | ) {
|
|---|
| 62 | return this.for(key).tapAsync(options, fn);
|
|---|
| 63 | }, "HookMap#tapAsync(key,…) is deprecated. Use HookMap#for(key).tapAsync(…) instead.");
|
|---|
| 64 |
|
|---|
| 65 | HookMap.prototype.tapPromise = util.deprecate(function tapPromise(
|
|---|
| 66 | key,
|
|---|
| 67 | options,
|
|---|
| 68 | fn
|
|---|
| 69 | ) {
|
|---|
| 70 | return this.for(key).tapPromise(options, fn);
|
|---|
| 71 | }, "HookMap#tapPromise(key,…) is deprecated. Use HookMap#for(key).tapPromise(…) instead.");
|
|---|
| 72 |
|
|---|
| 73 | module.exports = HookMap;
|
|---|