Gathering detailed insights and metrics for tapable
Gathering detailed insights and metrics for tapable
Gathering detailed insights and metrics for tapable
Gathering detailed insights and metrics for tapable
npm install tapable
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
3,755 Stars
235 Commits
398 Forks
48 Watching
3 Branches
101 Contributors
Updated on 27 Nov 2024
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-3.4%
7,324,937
Compared to previous day
Last week
3.7%
39,091,216
Compared to previous week
Last month
14.6%
158,890,229
Compared to previous month
Last year
3.1%
1,665,990,218
Compared to previous year
6
The tapable package expose many Hook classes, which can be used to create hooks for plugins.
1const { 2 SyncHook, 3 SyncBailHook, 4 SyncWaterfallHook, 5 SyncLoopHook, 6 AsyncParallelHook, 7 AsyncParallelBailHook, 8 AsyncSeriesHook, 9 AsyncSeriesBailHook, 10 AsyncSeriesWaterfallHook 11 } = require("tapable");
1npm install --save tapable
All Hook constructors take one optional argument, which is a list of argument names as strings.
1const hook = new SyncHook(["arg1", "arg2", "arg3"]);
The best practice is to expose all hooks of a class in a hooks
property:
1class Car { 2 constructor() { 3 this.hooks = { 4 accelerate: new SyncHook(["newSpeed"]), 5 brake: new SyncHook(), 6 calculateRoutes: new AsyncParallelHook(["source", "target", "routesList"]) 7 }; 8 } 9 10 /* ... */ 11}
Other people can now use these hooks:
1const myCar = new Car(); 2 3// Use the tap method to add a consument 4myCar.hooks.brake.tap("WarningLampPlugin", () => warningLamp.on());
It's required to pass a name to identify the plugin/reason.
You may receive arguments:
1myCar.hooks.accelerate.tap("LoggerPlugin", newSpeed => console.log(`Accelerating to ${newSpeed}`));
For sync hooks, tap
is the only valid method to add a plugin. Async hooks also support async plugins:
1myCar.hooks.calculateRoutes.tapPromise("GoogleMapsPlugin", (source, target, routesList) => { 2 // return a promise 3 return google.maps.findRoute(source, target).then(route => { 4 routesList.add(route); 5 }); 6}); 7myCar.hooks.calculateRoutes.tapAsync("BingMapsPlugin", (source, target, routesList, callback) => { 8 bing.findRoute(source, target, (err, route) => { 9 if(err) return callback(err); 10 routesList.add(route); 11 // call the callback 12 callback(); 13 }); 14}); 15 16// You can still use sync plugins 17myCar.hooks.calculateRoutes.tap("CachedRoutesPlugin", (source, target, routesList) => { 18 const cachedRoute = cache.get(source, target); 19 if(cachedRoute) 20 routesList.add(cachedRoute); 21})
The class declaring these hooks need to call them:
1class Car {
2 /**
3 * You won't get returned value from SyncHook or AsyncParallelHook,
4 * to do that, use SyncWaterfallHook and AsyncSeriesWaterfallHook respectively
5 **/
6
7 setSpeed(newSpeed) {
8 // following call returns undefined even when you returned values
9 this.hooks.accelerate.call(newSpeed);
10 }
11
12 useNavigationSystemPromise(source, target) {
13 const routesList = new List();
14 return this.hooks.calculateRoutes.promise(source, target, routesList).then((res) => {
15 // res is undefined for AsyncParallelHook
16 return routesList.getRoutes();
17 });
18 }
19
20 useNavigationSystemAsync(source, target, callback) {
21 const routesList = new List();
22 this.hooks.calculateRoutes.callAsync(source, target, routesList, err => {
23 if(err) return callback(err);
24 callback(null, routesList.getRoutes());
25 });
26 }
27}
The Hook will compile a method with the most efficient way of running your plugins. It generates code depending on:
This ensures fastest possible execution.
Each hook can be tapped with one or several functions. How they are executed depends on the hook type:
Basic hook (without “Waterfall”, “Bail” or “Loop” in its name). This hook simply calls every function it tapped in a row.
Waterfall. A waterfall hook also calls each tapped function in a row. Unlike the basic hook, it passes a return value from each function to the next function.
Bail. A bail hook allows exiting early. When any of the tapped function returns anything, the bail hook will stop executing the remaining ones.
Loop. When a plugin in a loop hook returns a non-undefined value the hook will restart from the first plugin. It will loop until all plugins return undefined.
Additionally, hooks can be synchronous or asynchronous. To reflect this, there’re “Sync”, “AsyncSeries”, and “AsyncParallel” hook classes:
Sync. A sync hook can only be tapped with synchronous functions (using myHook.tap()
).
AsyncSeries. An async-series hook can be tapped with synchronous, callback-based and promise-based functions (using myHook.tap()
, myHook.tapAsync()
and myHook.tapPromise()
). They call each async method in a row.
AsyncParallel. An async-parallel hook can also be tapped with synchronous, callback-based and promise-based functions (using myHook.tap()
, myHook.tapAsync()
and myHook.tapPromise()
). However, they run each async method in parallel.
The hook type is reflected in its class name. E.g., AsyncSeriesWaterfallHook
allows asynchronous functions and runs them in series, passing each function’s return value into the next function.
All Hooks offer an additional interception API:
1myCar.hooks.calculateRoutes.intercept({ 2 call: (source, target, routesList) => { 3 console.log("Starting to calculate routes"); 4 }, 5 register: (tapInfo) => { 6 // tapInfo = { type: "promise", name: "GoogleMapsPlugin", fn: ... } 7 console.log(`${tapInfo.name} is doing its job`); 8 return tapInfo; // may return a new tapInfo object 9 } 10})
call: (...args) => void
Adding call
to your interceptor will trigger when hooks are triggered. You have access to the hooks arguments.
tap: (tap: Tap) => void
Adding tap
to your interceptor will trigger when a plugin taps into a hook. Provided is the Tap
object. Tap
object can't be changed.
loop: (...args) => void
Adding loop
to your interceptor will trigger for each loop of a looping hook.
register: (tap: Tap) => Tap | undefined
Adding register
to your interceptor will trigger for each added Tap
and allows to modify it.
Plugins and interceptors can opt-in to access an optional context
object, which can be used to pass arbitrary values to subsequent plugins and interceptors.
1myCar.hooks.accelerate.intercept({ 2 context: true, 3 tap: (context, tapInfo) => { 4 // tapInfo = { type: "sync", name: "NoisePlugin", fn: ... } 5 console.log(`${tapInfo.name} is doing it's job`); 6 7 // `context` starts as an empty object if at least one plugin uses `context: true`. 8 // If no plugins use `context: true`, then `context` is undefined. 9 if (context) { 10 // Arbitrary properties can be added to `context`, which plugins can then access. 11 context.hasMuffler = true; 12 } 13 } 14}); 15 16myCar.hooks.accelerate.tap({ 17 name: "NoisePlugin", 18 context: true 19}, (context, newSpeed) => { 20 if (context && context.hasMuffler) { 21 console.log("Silence..."); 22 } else { 23 console.log("Vroom!"); 24 } 25});
A HookMap is a helper class for a Map with Hooks
1const keyedHook = new HookMap(key => new SyncHook(["arg"]))
1keyedHook.for("some-key").tap("MyPlugin", (arg) => { /* ... */ }); 2keyedHook.for("some-key").tapAsync("MyPlugin", (arg, callback) => { /* ... */ }); 3keyedHook.for("some-key").tapPromise("MyPlugin", (arg) => { /* ... */ });
1const hook = keyedHook.get("some-key"); 2if(hook !== undefined) { 3 hook.callAsync("arg", err => { /* ... */ }); 4}
Public:
1interface Hook { 2 tap: (name: string | Tap, fn: (context?, ...args) => Result) => void, 3 tapAsync: (name: string | Tap, fn: (context?, ...args, callback: (err, result: Result) => void) => void) => void, 4 tapPromise: (name: string | Tap, fn: (context?, ...args) => Promise<Result>) => void, 5 intercept: (interceptor: HookInterceptor) => void 6} 7 8interface HookInterceptor { 9 call: (context?, ...args) => void, 10 loop: (context?, ...args) => void, 11 tap: (context?, tap: Tap) => void, 12 register: (tap: Tap) => Tap, 13 context: boolean 14} 15 16interface HookMap { 17 for: (key: any) => Hook, 18 intercept: (interceptor: HookMapInterceptor) => void 19} 20 21interface HookMapInterceptor { 22 factory: (key: any, hook: Hook) => Hook 23} 24 25interface Tap { 26 name: string, 27 type: string 28 fn: Function, 29 stage: number, 30 context: boolean, 31 before?: string | Array 32}
Protected (only for the class containing the hook):
1interface Hook { 2 isUsed: () => boolean, 3 call: (...args) => Result, 4 promise: (...args) => Promise<Result>, 5 callAsync: (...args, callback: (err, result: Result) => void) => void, 6} 7 8interface HookMap { 9 get: (key: any) => Hook | undefined, 10 for: (key: any) => Hook 11}
A helper Hook-like class to redirect taps to multiple other hooks:
1const { MultiHook } = require("tapable");
2
3this.hooks.allHooks = new MultiHook([this.hooks.hookA, this.hooks.hookB]);
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 5/18 approved changesets -- score normalized to 2
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
security policy file not detected
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
57 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More