added tailwind back, reenabled utilities which was causing the color issue
This commit is contained in:
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License
|
||||
|
||||
Copyright JS Foundation and other contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
+715
@@ -0,0 +1,715 @@
|
||||
# Tapable
|
||||
|
||||
The tapable package exposes many Hook classes, which can be used to create hooks for plugins.
|
||||
|
||||
```javascript
|
||||
const {
|
||||
AsyncParallelBailHook,
|
||||
AsyncParallelHook,
|
||||
AsyncSeriesBailHook,
|
||||
AsyncSeriesHook,
|
||||
AsyncSeriesWaterfallHook,
|
||||
SyncBailHook,
|
||||
SyncHook,
|
||||
SyncLoopHook,
|
||||
SyncWaterfallHook
|
||||
} = require("tapable");
|
||||
```
|
||||
|
||||
## Installation
|
||||
|
||||
```shell
|
||||
npm install --save tapable
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
All Hook constructors take one optional argument, which is a list of argument names as strings.
|
||||
|
||||
```js
|
||||
const hook = new SyncHook(["arg1", "arg2", "arg3"]);
|
||||
```
|
||||
|
||||
The best practice is to expose all hooks of a class in a `hooks` property:
|
||||
|
||||
```js
|
||||
class Car {
|
||||
constructor() {
|
||||
this.hooks = {
|
||||
accelerate: new SyncHook(["newSpeed"]),
|
||||
brake: new SyncHook(),
|
||||
calculateRoutes: new AsyncParallelHook(["source", "target", "routesList"])
|
||||
};
|
||||
}
|
||||
|
||||
/* ... */
|
||||
}
|
||||
```
|
||||
|
||||
Other people can now use these hooks:
|
||||
|
||||
```js
|
||||
const myCar = new Car();
|
||||
|
||||
// Use the tap method to add a consumer (plugin)
|
||||
myCar.hooks.brake.tap("WarningLampPlugin", () => warningLamp.on());
|
||||
```
|
||||
|
||||
It's required to pass a name to identify the plugin/reason.
|
||||
|
||||
You may receive arguments:
|
||||
|
||||
```js
|
||||
myCar.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:
|
||||
|
||||
```js
|
||||
myCar.hooks.calculateRoutes.tapPromise(
|
||||
"GoogleMapsPlugin",
|
||||
(source, target, routesList) =>
|
||||
// return a promise
|
||||
google.maps.findRoute(source, target).then((route) => {
|
||||
routesList.add(route);
|
||||
})
|
||||
);
|
||||
myCar.hooks.calculateRoutes.tapAsync(
|
||||
"BingMapsPlugin",
|
||||
(source, target, routesList, callback) => {
|
||||
bing.findRoute(source, target, (err, route) => {
|
||||
if (err) return callback(err);
|
||||
routesList.add(route);
|
||||
// call the callback
|
||||
callback();
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
// You can still use sync plugins
|
||||
myCar.hooks.calculateRoutes.tap(
|
||||
"CachedRoutesPlugin",
|
||||
(source, target, routesList) => {
|
||||
const cachedRoute = cache.get(source, target);
|
||||
if (cachedRoute) routesList.add(cachedRoute);
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
The class declaring these hooks needs to call them:
|
||||
|
||||
```js
|
||||
class Car {
|
||||
/**
|
||||
* You won't get returned value from SyncHook or AsyncParallelHook,
|
||||
* to do that, use SyncWaterfallHook and AsyncSeriesWaterfallHook respectively
|
||||
*/
|
||||
|
||||
setSpeed(newSpeed) {
|
||||
// following call returns undefined even when you returned values
|
||||
this.hooks.accelerate.call(newSpeed);
|
||||
}
|
||||
|
||||
useNavigationSystemPromise(source, target) {
|
||||
const routesList = new List();
|
||||
return this.hooks.calculateRoutes
|
||||
.promise(source, target, routesList)
|
||||
.then((res) =>
|
||||
// res is undefined for AsyncParallelHook
|
||||
routesList.getRoutes()
|
||||
);
|
||||
}
|
||||
|
||||
useNavigationSystemAsync(source, target, callback) {
|
||||
const routesList = new List();
|
||||
this.hooks.calculateRoutes.callAsync(source, target, routesList, (err) => {
|
||||
if (err) return callback(err);
|
||||
callback(null, routesList.getRoutes());
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The Hook will compile a method with the most efficient way of running your plugins. It generates code depending on:
|
||||
|
||||
- The number of registered plugins (none, one, many)
|
||||
- The kind of registered plugins (sync, async, promise)
|
||||
- The used call method (sync, async, promise)
|
||||
- The number of arguments
|
||||
- Whether interception is used
|
||||
|
||||
This ensures fastest possible execution. See [Code generation](#code-generation) for more details on the runtime compilation.
|
||||
|
||||
## Plugin API
|
||||
|
||||
A plugin registers a callback on a hook using one of the `tap*` methods. The hook type determines which of these are valid (see [Hook classes](#hook-classes)):
|
||||
|
||||
- `hook.tap(nameOrOptions, fn)` — register a synchronous callback.
|
||||
- `hook.tapAsync(nameOrOptions, fn)` — register a callback-based async callback. The last argument passed to `fn` is a node-style callback `(err, result)`.
|
||||
- `hook.tapPromise(nameOrOptions, fn)` — register a promise-returning async callback. If `fn` returns something that is not thenable, the hook throws.
|
||||
|
||||
The first argument can be either a string (the plugin name) or an options object that also allows influencing the order in which taps run:
|
||||
|
||||
```js
|
||||
hook.tap(
|
||||
{
|
||||
name: "MyPlugin",
|
||||
stage: -10, // lower stages run earlier, default is 0
|
||||
before: "OtherPlugin" // run before a named tap (string or string[])
|
||||
},
|
||||
(...args) => {
|
||||
/* ... */
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
| Option | Type | Description |
|
||||
| -------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `name` | `string` | Required. Identifies the tap for debugging, interceptors, and the `before` option. |
|
||||
| `stage` | `number` | Defaults to `0`. Taps with a lower stage run before taps with a higher stage. Taps with the same stage run in registration order. |
|
||||
| `before` | `string` \| `string[]` | The tap is inserted before the named tap(s). Unknown names are ignored. Combined with `stage`, `before` wins for the taps it targets; other taps are still ordered by `stage`. |
|
||||
|
||||
The `name` is also used by some ecosystems (like webpack) for profiling and error messages. Within a single tap registration, later interceptors' `register` hooks may still replace the tap object (see [Interception](#interception)).
|
||||
|
||||
### `hook.withOptions(options)`
|
||||
|
||||
`withOptions` returns a facade around the hook whose `tap*` methods automatically merge `options` into every registration. It is useful for libraries that want to pre-configure a `stage` or `before` for all the taps they add:
|
||||
|
||||
```js
|
||||
const lateHook = myCar.hooks.accelerate.withOptions({ stage: 10 });
|
||||
lateHook.tap("LogAfterOthers", (speed) => console.log("final speed", speed));
|
||||
// equivalent to: myCar.hooks.accelerate.tap({ name: "LogAfterOthers", stage: 10 }, ...)
|
||||
```
|
||||
|
||||
The returned object does not expose the `call*` methods, so it is safe to hand out to plugins.
|
||||
|
||||
A runnable example showing how `withOptions` influences tap ordering:
|
||||
|
||||
```js
|
||||
const { SyncHook } = require("tapable");
|
||||
|
||||
const hook = new SyncHook(["value"]);
|
||||
|
||||
hook.tap("Default", (v) => console.log("default", v));
|
||||
|
||||
// Pre-configure stage: 10 so all taps registered through `late` run last.
|
||||
const late = hook.withOptions({ stage: 10 });
|
||||
late.tap("RunLast", (v) => console.log("last", v));
|
||||
|
||||
// Pre-configure stage: -10 so these taps run first. Each facade can also
|
||||
// be further narrowed via `withOptions`.
|
||||
const early = hook.withOptions({ stage: -10 });
|
||||
early.tap("RunFirst", (v) => console.log("first", v));
|
||||
|
||||
hook.call(1);
|
||||
// first 1
|
||||
// default 1
|
||||
// last 1
|
||||
```
|
||||
|
||||
Per-tap options override values from `withOptions`. For example, `late.tap({ name: "Override", stage: 0 }, fn)` ignores the facade's `stage: 10` and registers `fn` at stage `0`.
|
||||
|
||||
## Hook types
|
||||
|
||||
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.
|
||||
|
||||
## Hook classes
|
||||
|
||||
The table below summarizes the 9 built-in hook classes. For each class:
|
||||
|
||||
- **Tap methods** are the `tapX` variants that may be used to register a handler.
|
||||
- **Call methods** are the ways the owner of the hook can trigger it.
|
||||
- **Result** is the value returned from `call` (or passed to the `callAsync` callback / resolved from the `promise` call).
|
||||
- **Returned value from tap** describes whether the value returned from a tapped function has an effect.
|
||||
|
||||
| Class | Tap methods | Call methods | Result | Returned value from tap |
|
||||
| -------------------------- | ------------------------------- | ---------------------- | ----------------------------------------------- | ---------------------------------------------------- |
|
||||
| `SyncHook` | `tap` | `call` | `undefined` | ignored |
|
||||
| `SyncBailHook` | `tap` | `call` | first non-`undefined` value, or `undefined` | short-circuits the hook |
|
||||
| `SyncWaterfallHook` | `tap` | `call` | final value (first argument after the last tap) | passed as first argument to the next tap |
|
||||
| `SyncLoopHook` | `tap` | `call` | `undefined` | non-`undefined` restarts the loop from the first tap |
|
||||
| `AsyncParallelHook` | `tap`, `tapAsync`, `tapPromise` | `callAsync`, `promise` | `undefined` | ignored |
|
||||
| `AsyncParallelBailHook` | `tap`, `tapAsync`, `tapPromise` | `callAsync`, `promise` | first non-`undefined` value, or `undefined` | short-circuits the hook |
|
||||
| `AsyncSeriesHook` | `tap`, `tapAsync`, `tapPromise` | `callAsync`, `promise` | `undefined` | ignored |
|
||||
| `AsyncSeriesBailHook` | `tap`, `tapAsync`, `tapPromise` | `callAsync`, `promise` | first non-`undefined` value, or `undefined` | short-circuits the hook |
|
||||
| `AsyncSeriesLoopHook` | `tap`, `tapAsync`, `tapPromise` | `callAsync`, `promise` | `undefined` | non-`undefined` restarts the loop from the first tap |
|
||||
| `AsyncSeriesWaterfallHook` | `tap`, `tapAsync`, `tapPromise` | `callAsync`, `promise` | final value (first argument after the last tap) | passed as first argument to the next tap |
|
||||
|
||||
Detailed behavior of each class:
|
||||
|
||||
### SyncHook
|
||||
|
||||
A basic synchronous hook. Every tapped function is called in registration order with the arguments passed to `call`. Return values from tapped functions are ignored and `call` returns `undefined`.
|
||||
|
||||
- Tap methods: `tap`
|
||||
- Call methods: `call`
|
||||
- `tapAsync` and `tapPromise` throw an error.
|
||||
|
||||
```js
|
||||
const hook = new SyncHook(["name"]);
|
||||
hook.tap("A", (name) => console.log(`hello ${name}`));
|
||||
hook.tap("B", (name) => console.log(`hi ${name}`));
|
||||
hook.call("world");
|
||||
// hello world
|
||||
// hi world
|
||||
```
|
||||
|
||||
### SyncBailHook
|
||||
|
||||
A synchronous hook that allows exiting early. Every tapped function is called in order until one returns a non-`undefined` value; that value becomes the result of `call` and the remaining taps are skipped. If all taps return `undefined`, `call` returns `undefined`.
|
||||
|
||||
- Tap methods: `tap`
|
||||
- Call methods: `call`
|
||||
|
||||
```js
|
||||
const hook = new SyncBailHook(["value"]);
|
||||
hook.tap("Negative", (v) => (v < 0 ? "negative" : undefined));
|
||||
hook.tap("Zero", (v) => (v === 0 ? "zero" : undefined));
|
||||
hook.tap("Positive", (v) => "positive");
|
||||
|
||||
hook.call(-1); // "negative" (later taps skipped)
|
||||
hook.call(5); // "positive"
|
||||
```
|
||||
|
||||
### SyncWaterfallHook
|
||||
|
||||
A synchronous hook that threads a value through its tapped functions. The first argument passed to `call` is forwarded to the first tap. If a tap returns a non-`undefined` value it replaces that argument for the next tap; otherwise the previous value is kept. `call` returns the value after the last tap has run. Additional arguments (if any) are passed through unchanged.
|
||||
|
||||
- Tap methods: `tap`
|
||||
- Call methods: `call`
|
||||
|
||||
```js
|
||||
const hook = new SyncWaterfallHook(["value"]);
|
||||
hook.tap("Double", (v) => v * 2);
|
||||
hook.tap("PlusOne", (v) => v + 1);
|
||||
|
||||
hook.call(3); // 7 -> (3 * 2) + 1
|
||||
```
|
||||
|
||||
### SyncLoopHook
|
||||
|
||||
A synchronous hook that keeps re-running its taps until all of them return `undefined` for a full pass. Whenever a tap returns a non-`undefined` value the hook restarts from the first tap. `call` returns `undefined`.
|
||||
|
||||
- Tap methods: `tap`
|
||||
- Call methods: `call`
|
||||
|
||||
```js
|
||||
const hook = new SyncLoopHook(["state"]);
|
||||
let retries = 3;
|
||||
hook.tap("Retry", () => {
|
||||
if (retries-- > 0) return true; // non-undefined restarts the loop
|
||||
});
|
||||
hook.tap("Log", () => console.log("pass"));
|
||||
|
||||
hook.call({});
|
||||
// pass (runs once all taps return undefined)
|
||||
```
|
||||
|
||||
### AsyncParallelHook
|
||||
|
||||
An asynchronous hook that runs all of its tapped functions in parallel. It completes when every tap has signalled completion (sync return, callback, or promise resolution). Return values and resolution values are ignored; `callAsync`'s callback is invoked with no result and `promise()` resolves to `undefined`. If any tap errors, the error is forwarded and remaining taps still complete but their results are discarded.
|
||||
|
||||
- Tap methods: `tap`, `tapAsync`, `tapPromise`
|
||||
- Call methods: `callAsync`, `promise`
|
||||
|
||||
```js
|
||||
const hook = new AsyncParallelHook(["source"]);
|
||||
hook.tapPromise("Fetch", (src) => fetch(src));
|
||||
hook.tapAsync("Log", (src, cb) => {
|
||||
console.log("fetching", src);
|
||||
cb();
|
||||
});
|
||||
|
||||
await hook.promise("https://example.com");
|
||||
```
|
||||
|
||||
### AsyncParallelBailHook
|
||||
|
||||
Like `AsyncParallelHook`, but designed to bail out with a result. All tapped functions start in parallel; the first tap to produce a non-`undefined` value (synchronously, via its callback, or by resolving its promise) determines the hook’s result. The remaining taps continue to run but their results are ignored. Order is determined by tap registration order: an earlier tap’s value takes precedence over a later one’s, even if the later one finishes first.
|
||||
|
||||
- Tap methods: `tap`, `tapAsync`, `tapPromise`
|
||||
- Call methods: `callAsync`, `promise`
|
||||
|
||||
```js
|
||||
const hook = new AsyncParallelBailHook(["key"]);
|
||||
hook.tapPromise("Cache", async (key) => cache.get(key));
|
||||
hook.tapPromise("Db", async (key) => db.lookup(key));
|
||||
|
||||
const value = await hook.promise("user:42");
|
||||
// First non-undefined result (by registration order) wins.
|
||||
```
|
||||
|
||||
### AsyncSeriesHook
|
||||
|
||||
An asynchronous hook that runs tapped functions one after another, waiting for each to finish before starting the next. Results are ignored; `callAsync`'s callback is invoked with no result and `promise()` resolves to `undefined`. The first error aborts the series.
|
||||
|
||||
- Tap methods: `tap`, `tapAsync`, `tapPromise`
|
||||
- Call methods: `callAsync`, `promise`
|
||||
|
||||
```js
|
||||
const hook = new AsyncSeriesHook(["request"]);
|
||||
hook.tapPromise("Authenticate", async (req) => authenticate(req));
|
||||
hook.tapPromise("Log", async (req) => logger.info(req.url));
|
||||
|
||||
await hook.promise(request);
|
||||
```
|
||||
|
||||
### AsyncSeriesBailHook
|
||||
|
||||
An asynchronous series hook that allows exiting early. Tapped functions run one after another; as soon as one produces a non-`undefined` value, that value becomes the hook’s result and the remaining taps are skipped.
|
||||
|
||||
- Tap methods: `tap`, `tapAsync`, `tapPromise`
|
||||
- Call methods: `callAsync`, `promise`
|
||||
|
||||
```js
|
||||
const hook = new AsyncSeriesBailHook(["id"]);
|
||||
hook.tapPromise("Memory", async (id) => memory.get(id));
|
||||
hook.tapPromise("Disk", async (id) => disk.read(id));
|
||||
|
||||
const value = await hook.promise("doc-1");
|
||||
// Stops at the first tap that produces a value.
|
||||
```
|
||||
|
||||
### AsyncSeriesLoopHook
|
||||
|
||||
An asynchronous series hook that loops. Tapped functions run one after another; whenever a tap produces a non-`undefined` value the hook restarts from the first tap. The hook completes once a full pass yields `undefined` from every tap. The result is always `undefined`.
|
||||
|
||||
- Tap methods: `tap`, `tapAsync`, `tapPromise`
|
||||
- Call methods: `callAsync`, `promise`
|
||||
|
||||
```js
|
||||
const hook = new AsyncSeriesLoopHook(["job"]);
|
||||
hook.tapPromise("Process", async (job) => {
|
||||
const more = await job.step();
|
||||
if (more) return true; // restart the loop
|
||||
});
|
||||
|
||||
await hook.promise(job);
|
||||
```
|
||||
|
||||
### AsyncSeriesWaterfallHook
|
||||
|
||||
An asynchronous series hook that threads a value through its taps. The first argument passed to `callAsync` / `promise` is forwarded to the first tap. A tap's non-`undefined` return / callback / resolution value replaces it for the next tap; `undefined` keeps the previous value. The hook completes with the value after the last tap.
|
||||
|
||||
- Tap methods: `tap`, `tapAsync`, `tapPromise`
|
||||
- Call methods: `callAsync`, `promise`
|
||||
|
||||
```js
|
||||
const hook = new AsyncSeriesWaterfallHook(["source"]);
|
||||
hook.tapPromise("Read", async (src) => fs.readFile(src, "utf8"));
|
||||
hook.tapPromise("Trim", async (text) => text.trim());
|
||||
|
||||
const output = await hook.promise("./input.txt");
|
||||
```
|
||||
|
||||
## Interception
|
||||
|
||||
All hooks expose an `intercept(interceptor)` method. An interceptor is a plain object whose methods are invoked at specific points during the lifetime of the hook. Interceptors are invoked in registration order before the taps, and are useful for logging, tracing, profiling, or re-mapping tap options.
|
||||
|
||||
```js
|
||||
myCar.hooks.calculateRoutes.intercept({
|
||||
name: "LoggingInterceptor",
|
||||
call: (source, target, routesList) => {
|
||||
console.log("Starting to calculate routes");
|
||||
},
|
||||
tap: (tapInfo) => {
|
||||
// tapInfo = { type: "promise", name: "GoogleMapsPlugin", fn: ..., stage: 0 }
|
||||
console.log(`${tapInfo.name} is running`);
|
||||
},
|
||||
register: (tapInfo) => {
|
||||
// Called once per tap (and for each tap already registered when the
|
||||
// interceptor is added). Return a new tapInfo object to replace it.
|
||||
console.log(`${tapInfo.name} is registered`);
|
||||
|
||||
return tapInfo;
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
| Handler | Signature | When it runs |
|
||||
| ---------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `call` | `(...args) => void` | Before the hook starts executing its taps. Receives the arguments passed to `call` / `callAsync` / `promise`. |
|
||||
| `tap` | `(tap: Tap) => void` | Before each tap runs. The `tap` object is a snapshot — mutations are ignored. |
|
||||
| `loop` | `(...args) => void` | At the start of each iteration of a `SyncLoopHook` / `AsyncSeriesLoopHook`. |
|
||||
| `error` | `(err: Error) => void` | Whenever a tap throws, rejects, or calls its callback with an error. |
|
||||
| `result` | `(result: any) => void` | When a bail or waterfall hook produces a value, or when a tap produces one for a loop hook. |
|
||||
| `done` | `() => void` | When the hook finishes successfully (no error, no early bail). |
|
||||
| `register` | `(tap: Tap) => Tap \| undefined` | Once per tap at registration time (including taps that existed before the interceptor was added). Return a new `Tap` object to replace it. |
|
||||
| `name` | `string` | Optional label used by ecosystems for debugging. |
|
||||
| `context` | `boolean` | Opt into the shared `context` object. See [Context](#context). |
|
||||
|
||||
Adding an interceptor invalidates the hook's compiled call function — the next `call` / `callAsync` / `promise` recompiles it so that the new interceptor is woven in.
|
||||
|
||||
## Context
|
||||
|
||||
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.
|
||||
|
||||
```js
|
||||
myCar.hooks.accelerate.intercept({
|
||||
context: true,
|
||||
tap: (context, tapInfo) => {
|
||||
// tapInfo = { type: "sync", name: "NoisePlugin", fn: ... }
|
||||
console.log(`${tapInfo.name} is doing it's job`);
|
||||
|
||||
// `context` starts as an empty object if at least one plugin uses `context: true`.
|
||||
// If no plugins use `context: true`, then `context` is undefined.
|
||||
if (context) {
|
||||
// Arbitrary properties can be added to `context`, which plugins can then access.
|
||||
context.hasMuffler = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
myCar.hooks.accelerate.tap(
|
||||
{
|
||||
name: "NoisePlugin",
|
||||
context: true
|
||||
},
|
||||
(context, newSpeed) => {
|
||||
if (context && context.hasMuffler) {
|
||||
console.log("Silence...");
|
||||
} else {
|
||||
console.log("Vroom!");
|
||||
}
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
## HookMap
|
||||
|
||||
A `HookMap` is a helper class that lazily creates hooks per key. The constructor takes a factory function; the first time a key is requested via `for(key)`, the factory is called and the resulting hook is cached.
|
||||
|
||||
```js
|
||||
const keyedHook = new HookMap((key) => new SyncHook(["arg"]));
|
||||
```
|
||||
|
||||
Plugins use `for(key)` to obtain the hook for a specific key (creating it on demand) and then `tap` on it as usual:
|
||||
|
||||
```js
|
||||
keyedHook.for("some-key").tap("MyPlugin", (arg) => {
|
||||
/* ... */
|
||||
});
|
||||
keyedHook.for("some-key").tapAsync("MyPlugin", (arg, callback) => {
|
||||
/* ... */
|
||||
});
|
||||
keyedHook.for("some-key").tapPromise("MyPlugin", (arg) => {
|
||||
/* ... */
|
||||
});
|
||||
```
|
||||
|
||||
The owner of the `HookMap` uses `get(key)` to look up an existing hook without creating one. This is typically preferred on the calling side so that keys no plugin cares about are never materialized:
|
||||
|
||||
```js
|
||||
const hook = keyedHook.get("some-key");
|
||||
if (hook !== undefined) {
|
||||
hook.callAsync("arg", (err) => {
|
||||
/* ... */
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
A `HookMap` can also be intercepted. `intercept({ factory })` wraps the factory so you can customize or replace the hook returned for each new key.
|
||||
|
||||
## Code generation
|
||||
|
||||
Tapable does not iterate over taps at call time. Instead, the first time `call`, `callAsync` or `promise` is invoked after the hook has been modified, the hook compiles a specialized function using `new Function(...)` and caches it on the instance. This is what the README means by "evals in code": the hook's dispatch logic is generated as a string and turned into a real JavaScript function the engine can inline and optimize.
|
||||
|
||||
The generated function is tailored to:
|
||||
|
||||
- **Call type** — whether the owner called `call` (sync), `callAsync` (callback), or `promise`. Each produces a different skeleton — e.g. `promise()` wraps the body in `new Promise((_resolve, _reject) => { ... })`.
|
||||
- **Tap types** — for each tap, the generator emits the right invocation pattern: direct call for `tap`, node-style callback wrapping for `tapAsync`, and `.then(...)` chaining for `tapPromise`.
|
||||
- **Hook class** — `SyncHook` emits a straight-line sequence of calls; `SyncBailHook` emits early-return checks; `SyncWaterfallHook` threads a value through calls; loop hooks wrap the body in a re-entry loop; `AsyncParallel*` fans the taps out and counts completions; `AsyncSeries*` chains them.
|
||||
- **Interceptors** — if interceptors are attached, calls to their `call`/`tap`/`loop`/`error`/`result`/`done` handlers are spliced into the generated body; otherwise they cost nothing.
|
||||
- **Context** — a `_context` object is only created when at least one tap or interceptor opts into it with `context: true`.
|
||||
- **Arity** — the generated code hard-codes the number of arguments declared when the hook was constructed, so no `arguments`/rest handling happens at runtime.
|
||||
|
||||
The compiled function is invalidated (reset back to a one-shot "recompile then call" trampoline) whenever the hook's shape changes — i.e. on any new `tap*` or `intercept` call. Steady-state calls therefore run straight through the cached function with no per-tap branching.
|
||||
|
||||
### Why this matters
|
||||
|
||||
- You only pay for features you use. An interceptor-free, sync-only hook compiles down to a short sequence of direct function calls.
|
||||
- Debugging a hook means reading the generated source. If you need to see it, `Hook.prototype.compile` returns the `new Function(...)` result — log `hook._createCall("sync").toString()` (or `"async"` / `"promise"`) to inspect the body.
|
||||
- Because the dispatch is code-generated, a hook's behavior is fully determined at compile time. Mutating tap options after registration (for example, changing `stage` on an existing `Tap` object) will not reorder taps until you cause a recompile.
|
||||
|
||||
## Hook/HookMap interface
|
||||
|
||||
Public (callable by anyone holding a reference to the hook, i.e. the plugins):
|
||||
|
||||
```ts
|
||||
interface Hook {
|
||||
tap: (name: string | Tap, fn: (context?, ...args) => Result) => void;
|
||||
tapAsync: (
|
||||
name: string | Tap,
|
||||
fn: (
|
||||
context?,
|
||||
...args,
|
||||
callback: (err: Error | null, result: Result) => void
|
||||
) => void
|
||||
) => void;
|
||||
tapPromise: (
|
||||
name: string | Tap,
|
||||
fn: (context?, ...args) => Promise<Result>
|
||||
) => void;
|
||||
intercept: (interceptor: HookInterceptor) => void;
|
||||
withOptions: (
|
||||
options: TapOptions
|
||||
) => Omit<Hook, "call" | "callAsync" | "promise">;
|
||||
}
|
||||
|
||||
interface HookInterceptor {
|
||||
name?: string;
|
||||
call?: (context?, ...args) => void;
|
||||
loop?: (context?, ...args) => void;
|
||||
tap?: (context?, tap: Tap) => void;
|
||||
error?: (err: Error) => void;
|
||||
result?: (result: any) => void;
|
||||
done?: () => void;
|
||||
register?: (tap: Tap) => Tap | undefined;
|
||||
context?: boolean;
|
||||
}
|
||||
|
||||
interface HookMap {
|
||||
for: (key: any) => Hook;
|
||||
intercept: (interceptor: HookMapInterceptor) => void;
|
||||
}
|
||||
|
||||
interface HookMapInterceptor {
|
||||
factory: (key: any, hook: Hook) => Hook;
|
||||
}
|
||||
|
||||
interface Tap {
|
||||
name: string;
|
||||
type: "sync" | "async" | "promise";
|
||||
fn: Function;
|
||||
stage: number;
|
||||
context: boolean;
|
||||
before?: string | Array<string>;
|
||||
}
|
||||
```
|
||||
|
||||
Protected (only for the class containing the hook — it owns the right to trigger it):
|
||||
|
||||
```ts
|
||||
interface Hook {
|
||||
isUsed: () => boolean;
|
||||
call: (...args) => Result;
|
||||
promise: (...args) => Promise<Result>;
|
||||
callAsync: (
|
||||
...args,
|
||||
callback: (err: Error | null, result: Result) => void
|
||||
) => void;
|
||||
}
|
||||
|
||||
interface HookMap {
|
||||
get: (key: any) => Hook | undefined;
|
||||
for: (key: any) => Hook;
|
||||
}
|
||||
```
|
||||
|
||||
`isUsed()` returns `true` when the hook has at least one tap or interceptor registered. Hook owners can use it to skip expensive argument preparation when no plugin is listening:
|
||||
|
||||
```js
|
||||
class Car {
|
||||
// ...
|
||||
setSpeed(newSpeed) {
|
||||
if (this.hooks.accelerate.isUsed()) {
|
||||
this.hooks.accelerate.call(newSpeed);
|
||||
}
|
||||
}
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
## MultiHook
|
||||
|
||||
A `MultiHook` is a Hook-like facade that forwards `tap`, `tapAsync`, `tapPromise`, `intercept`, and `withOptions` to several underlying hooks at once. It does not expose `call*` methods — only the owners of the wrapped hooks decide when each of them runs. It is the typical way a class exposes a "happens on any of these events" listening surface without having the plugin wire itself up to every hook individually.
|
||||
|
||||
### Fan out a tap to several hooks
|
||||
|
||||
```js
|
||||
const { MultiHook, SyncHook } = require("tapable");
|
||||
|
||||
class Car {
|
||||
constructor() {
|
||||
const accelerate = new SyncHook(["newSpeed"]);
|
||||
const brake = new SyncHook();
|
||||
this.hooks = {
|
||||
accelerate,
|
||||
brake,
|
||||
// `anyMovement` is not a real hook — it simply re-registers taps
|
||||
// on both `accelerate` and `brake`.
|
||||
anyMovement: new MultiHook([accelerate, brake])
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const car = new Car();
|
||||
car.hooks.anyMovement.tap("Telemetry", () => console.log("car moved"));
|
||||
|
||||
car.hooks.accelerate.call(42); // "car moved"
|
||||
car.hooks.brake.call(); // "car moved"
|
||||
```
|
||||
|
||||
The `MultiHook` has no state of its own: the tap above ends up inside `accelerate.taps` and `brake.taps`.
|
||||
|
||||
### Forwarding async taps
|
||||
|
||||
`tapAsync` / `tapPromise` forward to every wrapped hook — it is the plugin's job to make sure they are all compatible. Registering a `tapPromise` on a `MultiHook` that wraps a `SyncHook` will throw at registration time for that hook.
|
||||
|
||||
```js
|
||||
const build = new AsyncSeriesHook(["stats"]);
|
||||
const rebuild = new AsyncSeriesHook(["stats"]);
|
||||
const anyBuild = new MultiHook([build, rebuild]);
|
||||
|
||||
anyBuild.tapPromise("Report", async (stats) => report.send(stats));
|
||||
```
|
||||
|
||||
### Shared interceptors and options
|
||||
|
||||
`intercept` and `withOptions` are also forwarded, so a `MultiHook` can be used to attach the same interceptor or pre-configured options to a group of hooks:
|
||||
|
||||
```js
|
||||
const anyBuild = new MultiHook([build, rebuild]);
|
||||
|
||||
anyBuild.intercept({
|
||||
call: () => console.log("build started"),
|
||||
done: () => console.log("build done")
|
||||
});
|
||||
|
||||
// Every tap added through `late` is staged late on both underlying hooks.
|
||||
const late = anyBuild.withOptions({ stage: 10 });
|
||||
late.tap("RunLast", () => {
|
||||
/* ... */
|
||||
});
|
||||
```
|
||||
|
||||
### `isUsed`
|
||||
|
||||
`isUsed()` returns `true` if any of the wrapped hooks has at least one tap or interceptor, which lets the owner cheaply skip work when no one is listening on any of them:
|
||||
|
||||
```js
|
||||
if (this.hooks.anyMovement.isUsed()) {
|
||||
// expensive telemetry payload is only built when a plugin actually cares
|
||||
this.hooks.accelerate.call(computeSpeed());
|
||||
}
|
||||
```
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
MIT License http://www.opensource.org/licenses/mit-license.php
|
||||
Author Tobias Koppers @sokra
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
const Hook = require("./Hook");
|
||||
const HookCodeFactory = require("./HookCodeFactory");
|
||||
|
||||
class AsyncParallelBailHookCodeFactory extends HookCodeFactory {
|
||||
content({ onError, onResult, onDone }) {
|
||||
let code = "";
|
||||
code += `var _results = new Array(${this.options.taps.length});\n`;
|
||||
code += "var _checkDone = function() {\n";
|
||||
code += "for(var i = 0; i < _results.length; i++) {\n";
|
||||
code += "var item = _results[i];\n";
|
||||
code += "if(item === undefined) return false;\n";
|
||||
code += "if(item.result !== undefined) {\n";
|
||||
code += onResult("item.result");
|
||||
code += "return true;\n";
|
||||
code += "}\n";
|
||||
code += "if(item.error) {\n";
|
||||
code += onError("item.error");
|
||||
code += "return true;\n";
|
||||
code += "}\n";
|
||||
code += "}\n";
|
||||
code += "return false;\n";
|
||||
code += "}\n";
|
||||
code += this.callTapsParallel({
|
||||
onError: (i, err, done, doneBreak) => {
|
||||
let code = "";
|
||||
code += `if(${i} < _results.length && ((_results.length = ${
|
||||
i + 1
|
||||
}), (_results[${i}] = { error: ${err} }), _checkDone())) {\n`;
|
||||
code += doneBreak(true);
|
||||
code += "} else {\n";
|
||||
code += done();
|
||||
code += "}\n";
|
||||
return code;
|
||||
},
|
||||
onResult: (i, result, done, doneBreak) => {
|
||||
let code = "";
|
||||
code += `if(${i} < _results.length && (${result} !== undefined && (_results.length = ${
|
||||
i + 1
|
||||
}), (_results[${i}] = { result: ${result} }), _checkDone())) {\n`;
|
||||
code += doneBreak(true);
|
||||
code += "} else {\n";
|
||||
code += done();
|
||||
code += "}\n";
|
||||
return code;
|
||||
},
|
||||
onTap: (i, run, done, _doneBreak) => {
|
||||
let code = "";
|
||||
if (i > 0) {
|
||||
code += `if(${i} >= _results.length) {\n`;
|
||||
code += done();
|
||||
code += "} else {\n";
|
||||
}
|
||||
code += run();
|
||||
if (i > 0) code += "}\n";
|
||||
return code;
|
||||
},
|
||||
onDone
|
||||
});
|
||||
return code;
|
||||
}
|
||||
}
|
||||
|
||||
const factory = new AsyncParallelBailHookCodeFactory();
|
||||
|
||||
function COMPILE(options) {
|
||||
factory.setup(this, options);
|
||||
return factory.create(options);
|
||||
}
|
||||
|
||||
function AsyncParallelBailHook(args = [], name = undefined) {
|
||||
const hook = new Hook(args, name);
|
||||
hook.constructor = AsyncParallelBailHook;
|
||||
hook.compile = COMPILE;
|
||||
hook._call = undefined;
|
||||
hook.call = undefined;
|
||||
return hook;
|
||||
}
|
||||
|
||||
AsyncParallelBailHook.prototype = null;
|
||||
|
||||
module.exports = AsyncParallelBailHook;
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
MIT License http://www.opensource.org/licenses/mit-license.php
|
||||
Author Tobias Koppers @sokra
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
const Hook = require("./Hook");
|
||||
const HookCodeFactory = require("./HookCodeFactory");
|
||||
|
||||
class AsyncParallelHookCodeFactory extends HookCodeFactory {
|
||||
content({ onError, onDone }) {
|
||||
return this.callTapsParallel({
|
||||
onError: (i, err, done, doneBreak) => onError(err) + doneBreak(true),
|
||||
onDone
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const factory = new AsyncParallelHookCodeFactory();
|
||||
|
||||
function COMPILE(options) {
|
||||
factory.setup(this, options);
|
||||
return factory.create(options);
|
||||
}
|
||||
|
||||
function AsyncParallelHook(args = [], name = undefined) {
|
||||
const hook = new Hook(args, name);
|
||||
hook.constructor = AsyncParallelHook;
|
||||
hook.compile = COMPILE;
|
||||
hook._call = undefined;
|
||||
hook.call = undefined;
|
||||
return hook;
|
||||
}
|
||||
|
||||
AsyncParallelHook.prototype = null;
|
||||
|
||||
module.exports = AsyncParallelHook;
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
MIT License http://www.opensource.org/licenses/mit-license.php
|
||||
Author Tobias Koppers @sokra
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
const Hook = require("./Hook");
|
||||
const HookCodeFactory = require("./HookCodeFactory");
|
||||
|
||||
class AsyncSeriesBailHookCodeFactory extends HookCodeFactory {
|
||||
content({ onError, onResult, resultReturns, onDone }) {
|
||||
return this.callTapsSeries({
|
||||
onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true),
|
||||
onResult: (i, result, next) =>
|
||||
`if(${result} !== undefined) {\n${onResult(
|
||||
result
|
||||
)}\n} else {\n${next()}}\n`,
|
||||
resultReturns,
|
||||
onDone
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const factory = new AsyncSeriesBailHookCodeFactory();
|
||||
|
||||
function COMPILE(options) {
|
||||
factory.setup(this, options);
|
||||
return factory.create(options);
|
||||
}
|
||||
|
||||
function AsyncSeriesBailHook(args = [], name = undefined) {
|
||||
const hook = new Hook(args, name);
|
||||
hook.constructor = AsyncSeriesBailHook;
|
||||
hook.compile = COMPILE;
|
||||
hook._call = undefined;
|
||||
hook.call = undefined;
|
||||
return hook;
|
||||
}
|
||||
|
||||
AsyncSeriesBailHook.prototype = null;
|
||||
|
||||
module.exports = AsyncSeriesBailHook;
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
MIT License http://www.opensource.org/licenses/mit-license.php
|
||||
Author Tobias Koppers @sokra
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
const Hook = require("./Hook");
|
||||
const HookCodeFactory = require("./HookCodeFactory");
|
||||
|
||||
class AsyncSeriesHookCodeFactory extends HookCodeFactory {
|
||||
content({ onError, onDone }) {
|
||||
return this.callTapsSeries({
|
||||
onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true),
|
||||
onDone
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const factory = new AsyncSeriesHookCodeFactory();
|
||||
|
||||
function COMPILE(options) {
|
||||
factory.setup(this, options);
|
||||
return factory.create(options);
|
||||
}
|
||||
|
||||
function AsyncSeriesHook(args = [], name = undefined) {
|
||||
const hook = new Hook(args, name);
|
||||
hook.constructor = AsyncSeriesHook;
|
||||
hook.compile = COMPILE;
|
||||
hook._call = undefined;
|
||||
hook.call = undefined;
|
||||
return hook;
|
||||
}
|
||||
|
||||
AsyncSeriesHook.prototype = null;
|
||||
|
||||
module.exports = AsyncSeriesHook;
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
MIT License http://www.opensource.org/licenses/mit-license.php
|
||||
Author Tobias Koppers @sokra
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
const Hook = require("./Hook");
|
||||
const HookCodeFactory = require("./HookCodeFactory");
|
||||
|
||||
class AsyncSeriesLoopHookCodeFactory extends HookCodeFactory {
|
||||
content({ onError, onDone }) {
|
||||
return this.callTapsLooping({
|
||||
onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true),
|
||||
onDone
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const factory = new AsyncSeriesLoopHookCodeFactory();
|
||||
|
||||
function COMPILE(options) {
|
||||
factory.setup(this, options);
|
||||
return factory.create(options);
|
||||
}
|
||||
|
||||
function AsyncSeriesLoopHook(args = [], name = undefined) {
|
||||
const hook = new Hook(args, name);
|
||||
hook.constructor = AsyncSeriesLoopHook;
|
||||
hook.compile = COMPILE;
|
||||
hook._call = undefined;
|
||||
hook.call = undefined;
|
||||
return hook;
|
||||
}
|
||||
|
||||
AsyncSeriesLoopHook.prototype = null;
|
||||
|
||||
module.exports = AsyncSeriesLoopHook;
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
MIT License http://www.opensource.org/licenses/mit-license.php
|
||||
Author Tobias Koppers @sokra
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
const Hook = require("./Hook");
|
||||
const HookCodeFactory = require("./HookCodeFactory");
|
||||
|
||||
class AsyncSeriesWaterfallHookCodeFactory extends HookCodeFactory {
|
||||
content({ onError, onResult, _onDone }) {
|
||||
return this.callTapsSeries({
|
||||
onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true),
|
||||
onResult: (i, result, next) => {
|
||||
let code = "";
|
||||
code += `if(${result} !== undefined) {\n`;
|
||||
code += `${this._args[0]} = ${result};\n`;
|
||||
code += "}\n";
|
||||
code += next();
|
||||
return code;
|
||||
},
|
||||
onDone: () => onResult(this._args[0])
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const factory = new AsyncSeriesWaterfallHookCodeFactory();
|
||||
|
||||
function COMPILE(options) {
|
||||
factory.setup(this, options);
|
||||
return factory.create(options);
|
||||
}
|
||||
|
||||
function AsyncSeriesWaterfallHook(args = [], name = undefined) {
|
||||
if (args.length < 1) {
|
||||
throw new Error("Waterfall hooks must have at least one argument");
|
||||
}
|
||||
const hook = new Hook(args, name);
|
||||
hook.constructor = AsyncSeriesWaterfallHook;
|
||||
hook.compile = COMPILE;
|
||||
hook._call = undefined;
|
||||
hook.call = undefined;
|
||||
return hook;
|
||||
}
|
||||
|
||||
AsyncSeriesWaterfallHook.prototype = null;
|
||||
|
||||
module.exports = AsyncSeriesWaterfallHook;
|
||||
+233
@@ -0,0 +1,233 @@
|
||||
/*
|
||||
MIT License http://www.opensource.org/licenses/mit-license.php
|
||||
Author Tobias Koppers @sokra
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
const util = require("util");
|
||||
|
||||
const deprecateContext = util.deprecate(
|
||||
() => {},
|
||||
"Hook.context is deprecated and will be removed"
|
||||
);
|
||||
|
||||
function CALL_DELEGATE(...args) {
|
||||
this.call = this._createCall("sync");
|
||||
return this.call(...args);
|
||||
}
|
||||
|
||||
function CALL_ASYNC_DELEGATE(...args) {
|
||||
this.callAsync = this._createCall("async");
|
||||
return this.callAsync(...args);
|
||||
}
|
||||
|
||||
function PROMISE_DELEGATE(...args) {
|
||||
this.promise = this._createCall("promise");
|
||||
return this.promise(...args);
|
||||
}
|
||||
|
||||
class Hook {
|
||||
constructor(args = [], name = undefined) {
|
||||
this._args = args;
|
||||
this.name = name;
|
||||
this.taps = [];
|
||||
this.interceptors = [];
|
||||
this._call = CALL_DELEGATE;
|
||||
this.call = CALL_DELEGATE;
|
||||
this._callAsync = CALL_ASYNC_DELEGATE;
|
||||
this.callAsync = CALL_ASYNC_DELEGATE;
|
||||
this._promise = PROMISE_DELEGATE;
|
||||
this.promise = PROMISE_DELEGATE;
|
||||
this._x = undefined;
|
||||
|
||||
// eslint-disable-next-line no-self-assign
|
||||
this.compile = this.compile;
|
||||
// eslint-disable-next-line no-self-assign
|
||||
this.tap = this.tap;
|
||||
// eslint-disable-next-line no-self-assign
|
||||
this.tapAsync = this.tapAsync;
|
||||
// eslint-disable-next-line no-self-assign
|
||||
this.tapPromise = this.tapPromise;
|
||||
}
|
||||
|
||||
compile(_options) {
|
||||
throw new Error("Abstract: should be overridden");
|
||||
}
|
||||
|
||||
_createCall(type) {
|
||||
return this.compile({
|
||||
taps: this.taps,
|
||||
interceptors: this.interceptors,
|
||||
args: this._args,
|
||||
type
|
||||
});
|
||||
}
|
||||
|
||||
_tap(type, options, fn) {
|
||||
if (typeof options === "string") {
|
||||
// Fast path: a string options ("name") is by far the most common
|
||||
// case. Build the final descriptor in a single allocation instead
|
||||
// of creating `{ name }` and then `Object.assign`ing it.
|
||||
const name = options.trim();
|
||||
if (name === "") {
|
||||
throw new Error("Missing name for tap");
|
||||
}
|
||||
options = { type, fn, name };
|
||||
} else {
|
||||
if (typeof options !== "object" || options === null) {
|
||||
throw new Error("Invalid tap options");
|
||||
}
|
||||
let { name } = options;
|
||||
if (typeof name === "string") {
|
||||
name = name.trim();
|
||||
}
|
||||
if (typeof name !== "string" || name === "") {
|
||||
throw new Error("Missing name for tap");
|
||||
}
|
||||
if (typeof options.context !== "undefined") {
|
||||
deprecateContext();
|
||||
}
|
||||
// Fast path: only `name` is set. Build the descriptor as a literal
|
||||
// so `_insert` and downstream consumers see the same hidden class
|
||||
// as the string-options path, avoiding a polymorphic call site.
|
||||
// Scan with `for...in` (cheaper than allocating `Object.keys`)
|
||||
// to verify no other user-provided properties exist - e.g.
|
||||
// webpack's `additionalAssets` - otherwise they'd be dropped.
|
||||
let onlyName = true;
|
||||
for (const key in options) {
|
||||
if (key !== "name") {
|
||||
onlyName = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (onlyName) {
|
||||
options = { type, fn, name };
|
||||
} else {
|
||||
options.name = name;
|
||||
// Preserve previous precedence: user-provided keys win over the internal `type`/`fn`.
|
||||
options = Object.assign({ type, fn }, options);
|
||||
}
|
||||
}
|
||||
options = this._runRegisterInterceptors(options);
|
||||
this._insert(options);
|
||||
}
|
||||
|
||||
tap(options, fn) {
|
||||
this._tap("sync", options, fn);
|
||||
}
|
||||
|
||||
tapAsync(options, fn) {
|
||||
this._tap("async", options, fn);
|
||||
}
|
||||
|
||||
tapPromise(options, fn) {
|
||||
this._tap("promise", options, fn);
|
||||
}
|
||||
|
||||
_runRegisterInterceptors(options) {
|
||||
const { interceptors } = this;
|
||||
const { length } = interceptors;
|
||||
// Common case: no interceptors.
|
||||
if (length === 0) return options;
|
||||
for (let i = 0; i < length; i++) {
|
||||
const interceptor = interceptors[i];
|
||||
if (interceptor.register) {
|
||||
const newOptions = interceptor.register(options);
|
||||
if (newOptions !== undefined) {
|
||||
options = newOptions;
|
||||
}
|
||||
}
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
withOptions(options) {
|
||||
const mergeOptions = (opt) =>
|
||||
Object.assign({}, options, typeof opt === "string" ? { name: opt } : opt);
|
||||
|
||||
return {
|
||||
name: this.name,
|
||||
tap: (opt, fn) => this.tap(mergeOptions(opt), fn),
|
||||
tapAsync: (opt, fn) => this.tapAsync(mergeOptions(opt), fn),
|
||||
tapPromise: (opt, fn) => this.tapPromise(mergeOptions(opt), fn),
|
||||
intercept: (interceptor) => this.intercept(interceptor),
|
||||
isUsed: () => this.isUsed(),
|
||||
withOptions: (opt) => this.withOptions(mergeOptions(opt))
|
||||
};
|
||||
}
|
||||
|
||||
isUsed() {
|
||||
return this.taps.length > 0 || this.interceptors.length > 0;
|
||||
}
|
||||
|
||||
intercept(interceptor) {
|
||||
this._resetCompilation();
|
||||
this.interceptors.push(Object.assign({}, interceptor));
|
||||
if (interceptor.register) {
|
||||
for (let i = 0; i < this.taps.length; i++) {
|
||||
this.taps[i] = interceptor.register(this.taps[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_resetCompilation() {
|
||||
this.call = this._call;
|
||||
this.callAsync = this._callAsync;
|
||||
this.promise = this._promise;
|
||||
}
|
||||
|
||||
_insert(item) {
|
||||
this._resetCompilation();
|
||||
const { taps } = this;
|
||||
const stage = typeof item.stage === "number" ? item.stage : 0;
|
||||
|
||||
// Fast path: the overwhelmingly common `hook.tap("name", fn)` case
|
||||
// has no `before` and default stage 0. If the list is empty or the
|
||||
// last tap's stage is <= the new item's stage the item belongs at
|
||||
// the end - append in O(1), skipping the Set allocation and the
|
||||
// shift loop.
|
||||
if (!(typeof item.before === "string" || Array.isArray(item.before))) {
|
||||
const n = taps.length;
|
||||
if (n === 0 || (taps[n - 1].stage || 0) <= stage) {
|
||||
taps[n] = item;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let before;
|
||||
|
||||
if (typeof item.before === "string") {
|
||||
before = new Set([item.before]);
|
||||
} else if (Array.isArray(item.before)) {
|
||||
before = new Set(item.before);
|
||||
}
|
||||
|
||||
let i = taps.length;
|
||||
|
||||
while (i > 0) {
|
||||
i--;
|
||||
const tap = taps[i];
|
||||
taps[i + 1] = tap;
|
||||
const xStage = tap.stage || 0;
|
||||
if (before) {
|
||||
if (before.has(tap.name)) {
|
||||
before.delete(tap.name);
|
||||
continue;
|
||||
}
|
||||
if (before.size > 0) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (xStage > stage) {
|
||||
continue;
|
||||
}
|
||||
i++;
|
||||
break;
|
||||
}
|
||||
taps[i] = item;
|
||||
}
|
||||
}
|
||||
|
||||
Object.setPrototypeOf(Hook.prototype, null);
|
||||
|
||||
module.exports = Hook;
|
||||
+490
@@ -0,0 +1,490 @@
|
||||
/*
|
||||
MIT License http://www.opensource.org/licenses/mit-license.php
|
||||
Author Tobias Koppers @sokra
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
class HookCodeFactory {
|
||||
constructor(config) {
|
||||
this.config = config;
|
||||
this.options = undefined;
|
||||
this._args = undefined;
|
||||
}
|
||||
|
||||
create(options) {
|
||||
this.init(options);
|
||||
let fn;
|
||||
switch (options.type) {
|
||||
case "sync":
|
||||
fn = new Function(
|
||||
this.args(),
|
||||
`"use strict";\n${this.header()}${this.contentWithInterceptors({
|
||||
onError: (err) => `throw ${err};\n`,
|
||||
onResult: (result) => `return ${result};\n`,
|
||||
resultReturns: true,
|
||||
onDone: () => "",
|
||||
rethrowIfPossible: true
|
||||
})}`
|
||||
);
|
||||
break;
|
||||
case "async":
|
||||
fn = new Function(
|
||||
this.args({
|
||||
after: "_callback"
|
||||
}),
|
||||
`"use strict";\n${this.header()}${this.contentWithInterceptors({
|
||||
onError: (err) => `_callback(${err});\n`,
|
||||
onResult: (result) => `_callback(null, ${result});\n`,
|
||||
onDone: () => "_callback();\n"
|
||||
})}`
|
||||
);
|
||||
break;
|
||||
case "promise": {
|
||||
let errorHelperUsed = false;
|
||||
const content = this.contentWithInterceptors({
|
||||
onError: (err) => {
|
||||
errorHelperUsed = true;
|
||||
return `_error(${err});\n`;
|
||||
},
|
||||
onResult: (result) => `_resolve(${result});\n`,
|
||||
onDone: () => "_resolve();\n"
|
||||
});
|
||||
let code = "";
|
||||
code += '"use strict";\n';
|
||||
code += this.header();
|
||||
code += "return new Promise((function(_resolve, _reject) {\n";
|
||||
if (errorHelperUsed) {
|
||||
code += "var _sync = true;\n";
|
||||
code += "function _error(_err) {\n";
|
||||
code += "if(_sync)\n";
|
||||
code +=
|
||||
"_resolve(Promise.resolve().then((function() { throw _err; })));\n";
|
||||
code += "else\n";
|
||||
code += "_reject(_err);\n";
|
||||
code += "};\n";
|
||||
}
|
||||
code += content;
|
||||
if (errorHelperUsed) {
|
||||
code += "_sync = false;\n";
|
||||
}
|
||||
code += "}));\n";
|
||||
fn = new Function(this.args(), code);
|
||||
break;
|
||||
}
|
||||
}
|
||||
this.deinit();
|
||||
return fn;
|
||||
}
|
||||
|
||||
setup(instance, options) {
|
||||
const { taps } = options;
|
||||
const { length } = taps;
|
||||
const fns = Array.from({ length });
|
||||
for (let i = 0; i < length; i++) {
|
||||
fns[i] = taps[i].fn;
|
||||
}
|
||||
instance._x = fns;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{ type: "sync" | "promise" | "async", taps: Array<Tap>, interceptors: Array<Interceptor> }} options
|
||||
*/
|
||||
init(options) {
|
||||
this.options = options;
|
||||
// `_args` is only read (length / join / [0]) - never mutated - so we
|
||||
// can share the caller's array directly instead of paying for a copy
|
||||
// on every compile.
|
||||
this._args = options.args;
|
||||
this._joinedArgs = undefined;
|
||||
}
|
||||
|
||||
deinit() {
|
||||
this.options = undefined;
|
||||
this._args = undefined;
|
||||
this._joinedArgs = undefined;
|
||||
}
|
||||
|
||||
contentWithInterceptors(options) {
|
||||
if (this.options.interceptors.length > 0) {
|
||||
const { onError, onResult, onDone } = options;
|
||||
let code = "";
|
||||
for (let i = 0; i < this.options.interceptors.length; i++) {
|
||||
const interceptor = this.options.interceptors[i];
|
||||
if (interceptor.call) {
|
||||
code += `${this.getInterceptor(i)}.call(${this.args({
|
||||
before: interceptor.context ? "_context" : undefined
|
||||
})});\n`;
|
||||
}
|
||||
}
|
||||
code += this.content(
|
||||
Object.assign(options, {
|
||||
onError:
|
||||
onError &&
|
||||
((err) => {
|
||||
let code = "";
|
||||
for (let i = 0; i < this.options.interceptors.length; i++) {
|
||||
const interceptor = this.options.interceptors[i];
|
||||
if (interceptor.error) {
|
||||
code += `${this.getInterceptor(i)}.error(${err});\n`;
|
||||
}
|
||||
}
|
||||
code += onError(err);
|
||||
return code;
|
||||
}),
|
||||
onResult:
|
||||
onResult &&
|
||||
((result) => {
|
||||
let code = "";
|
||||
for (let i = 0; i < this.options.interceptors.length; i++) {
|
||||
const interceptor = this.options.interceptors[i];
|
||||
if (interceptor.result) {
|
||||
code += `${this.getInterceptor(i)}.result(${result});\n`;
|
||||
}
|
||||
}
|
||||
code += onResult(result);
|
||||
return code;
|
||||
}),
|
||||
onDone:
|
||||
onDone &&
|
||||
(() => {
|
||||
let code = "";
|
||||
for (let i = 0; i < this.options.interceptors.length; i++) {
|
||||
const interceptor = this.options.interceptors[i];
|
||||
if (interceptor.done) {
|
||||
code += `${this.getInterceptor(i)}.done();\n`;
|
||||
}
|
||||
}
|
||||
code += onDone();
|
||||
return code;
|
||||
})
|
||||
})
|
||||
);
|
||||
return code;
|
||||
}
|
||||
return this.content(options);
|
||||
}
|
||||
|
||||
header() {
|
||||
let code = "";
|
||||
code += this.needContext() ? "var _context = {};\n" : "var _context;\n";
|
||||
code += "var _x = this._x;\n";
|
||||
if (this.options.interceptors.length > 0) {
|
||||
code += "var _taps = this.taps;\n";
|
||||
code += "var _interceptors = this.interceptors;\n";
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
needContext() {
|
||||
const { taps } = this.options;
|
||||
for (let i = 0; i < taps.length; i++) {
|
||||
if (taps[i].context) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
callTap(tapIndex, { onError, onResult, onDone, rethrowIfPossible }) {
|
||||
let code = "";
|
||||
let hasTapCached = false;
|
||||
for (let i = 0; i < this.options.interceptors.length; i++) {
|
||||
const interceptor = this.options.interceptors[i];
|
||||
if (interceptor.tap) {
|
||||
if (!hasTapCached) {
|
||||
code += `var _tap${tapIndex} = ${this.getTap(tapIndex)};\n`;
|
||||
hasTapCached = true;
|
||||
}
|
||||
code += `${this.getInterceptor(i)}.tap(${
|
||||
interceptor.context ? "_context, " : ""
|
||||
}_tap${tapIndex});\n`;
|
||||
}
|
||||
}
|
||||
code += `var _fn${tapIndex} = ${this.getTapFn(tapIndex)};\n`;
|
||||
const tap = this.options.taps[tapIndex];
|
||||
switch (tap.type) {
|
||||
case "sync":
|
||||
if (!rethrowIfPossible) {
|
||||
code += `var _hasError${tapIndex} = false;\n`;
|
||||
code += "try {\n";
|
||||
}
|
||||
if (onResult) {
|
||||
code += `var _result${tapIndex} = _fn${tapIndex}(${this.args({
|
||||
before: tap.context ? "_context" : undefined
|
||||
})});\n`;
|
||||
} else {
|
||||
code += `_fn${tapIndex}(${this.args({
|
||||
before: tap.context ? "_context" : undefined
|
||||
})});\n`;
|
||||
}
|
||||
if (!rethrowIfPossible) {
|
||||
code += "} catch(_err) {\n";
|
||||
code += `_hasError${tapIndex} = true;\n`;
|
||||
code += onError("_err");
|
||||
code += "}\n";
|
||||
code += `if(!_hasError${tapIndex}) {\n`;
|
||||
}
|
||||
if (onResult) {
|
||||
code += onResult(`_result${tapIndex}`);
|
||||
}
|
||||
if (onDone) {
|
||||
code += onDone();
|
||||
}
|
||||
if (!rethrowIfPossible) {
|
||||
code += "}\n";
|
||||
}
|
||||
break;
|
||||
case "async": {
|
||||
let cbCode = "";
|
||||
cbCode += onResult
|
||||
? `(function(_err${tapIndex}, _result${tapIndex}) {\n`
|
||||
: `(function(_err${tapIndex}) {\n`;
|
||||
cbCode += `if(_err${tapIndex}) {\n`;
|
||||
cbCode += onError(`_err${tapIndex}`);
|
||||
cbCode += "} else {\n";
|
||||
if (onResult) {
|
||||
cbCode += onResult(`_result${tapIndex}`);
|
||||
}
|
||||
if (onDone) {
|
||||
cbCode += onDone();
|
||||
}
|
||||
cbCode += "}\n";
|
||||
cbCode += "})";
|
||||
code += `_fn${tapIndex}(${this.args({
|
||||
before: tap.context ? "_context" : undefined,
|
||||
after: cbCode
|
||||
})});\n`;
|
||||
break;
|
||||
}
|
||||
case "promise":
|
||||
code += `var _hasResult${tapIndex} = false;\n`;
|
||||
code += `var _promise${tapIndex} = _fn${tapIndex}(${this.args({
|
||||
before: tap.context ? "_context" : undefined
|
||||
})});\n`;
|
||||
code += `if (!_promise${tapIndex} || !_promise${tapIndex}.then)\n`;
|
||||
code += ` throw new Error('Tap function (tapPromise) did not return promise (returned ' + _promise${tapIndex} + ')');\n`;
|
||||
code += `_promise${tapIndex}.then((function(_result${tapIndex}) {\n`;
|
||||
code += `_hasResult${tapIndex} = true;\n`;
|
||||
if (onResult) {
|
||||
code += onResult(`_result${tapIndex}`);
|
||||
}
|
||||
if (onDone) {
|
||||
code += onDone();
|
||||
}
|
||||
code += `}), function(_err${tapIndex}) {\n`;
|
||||
code += `if(_hasResult${tapIndex}) throw _err${tapIndex};\n`;
|
||||
code += onError(
|
||||
`!_err${tapIndex} ? new Error('Tap function (tapPromise) rejects "' + _err${tapIndex} + '" value') : _err${tapIndex}`
|
||||
);
|
||||
code += "});\n";
|
||||
break;
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
callTapsSeries({
|
||||
onError,
|
||||
onResult,
|
||||
resultReturns,
|
||||
onDone,
|
||||
doneReturns,
|
||||
rethrowIfPossible
|
||||
}) {
|
||||
const { taps } = this.options;
|
||||
const tapsLength = taps.length;
|
||||
if (tapsLength === 0) return onDone();
|
||||
// Inlined findIndex to avoid the callback allocation.
|
||||
let firstAsync = -1;
|
||||
for (let i = 0; i < tapsLength; i++) {
|
||||
if (taps[i].type !== "sync") {
|
||||
firstAsync = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const somethingReturns = resultReturns || doneReturns;
|
||||
// doneBreak doesn't depend on the loop variable - hoist to allocate once.
|
||||
const doneBreak = (skipDone) => {
|
||||
if (skipDone) return "";
|
||||
return onDone();
|
||||
};
|
||||
let code = "";
|
||||
let current = onDone;
|
||||
let unrollCounter = 0;
|
||||
for (let j = tapsLength - 1; j >= 0; j--) {
|
||||
const i = j;
|
||||
const unroll =
|
||||
current !== onDone && (taps[i].type !== "sync" || unrollCounter++ > 20);
|
||||
if (unroll) {
|
||||
unrollCounter = 0;
|
||||
code += `function _next${i}() {\n`;
|
||||
code += current();
|
||||
code += "}\n";
|
||||
current = () => `${somethingReturns ? "return " : ""}_next${i}();\n`;
|
||||
}
|
||||
const done = current;
|
||||
const content = this.callTap(i, {
|
||||
onError: (error) => onError(i, error, done, doneBreak),
|
||||
onResult:
|
||||
onResult && ((result) => onResult(i, result, done, doneBreak)),
|
||||
onDone: !onResult && done,
|
||||
rethrowIfPossible:
|
||||
rethrowIfPossible && (firstAsync < 0 || i < firstAsync)
|
||||
});
|
||||
current = () => content;
|
||||
}
|
||||
code += current();
|
||||
return code;
|
||||
}
|
||||
|
||||
callTapsLooping({ onError, onDone, rethrowIfPossible }) {
|
||||
if (this.options.taps.length === 0) return onDone();
|
||||
const syncOnly = this.options.taps.every((t) => t.type === "sync");
|
||||
let code = "";
|
||||
if (!syncOnly) {
|
||||
code += "var _looper = (function() {\n";
|
||||
code += "var _loopAsync = false;\n";
|
||||
}
|
||||
code += "var _loop;\n";
|
||||
code += "do {\n";
|
||||
code += "_loop = false;\n";
|
||||
for (let i = 0; i < this.options.interceptors.length; i++) {
|
||||
const interceptor = this.options.interceptors[i];
|
||||
if (interceptor.loop) {
|
||||
code += `${this.getInterceptor(i)}.loop(${this.args({
|
||||
before: interceptor.context ? "_context" : undefined
|
||||
})});\n`;
|
||||
}
|
||||
}
|
||||
code += this.callTapsSeries({
|
||||
onError,
|
||||
onResult: (i, result, next, doneBreak) => {
|
||||
let code = "";
|
||||
code += `if(${result} !== undefined) {\n`;
|
||||
code += "_loop = true;\n";
|
||||
if (!syncOnly) code += "if(_loopAsync) _looper();\n";
|
||||
code += doneBreak(true);
|
||||
code += "} else {\n";
|
||||
code += next();
|
||||
code += "}\n";
|
||||
return code;
|
||||
},
|
||||
onDone:
|
||||
onDone &&
|
||||
(() => {
|
||||
let code = "";
|
||||
code += "if(!_loop) {\n";
|
||||
code += onDone();
|
||||
code += "}\n";
|
||||
return code;
|
||||
}),
|
||||
rethrowIfPossible: rethrowIfPossible && syncOnly
|
||||
});
|
||||
code += "} while(_loop);\n";
|
||||
if (!syncOnly) {
|
||||
code += "_loopAsync = true;\n";
|
||||
code += "});\n";
|
||||
code += "_looper();\n";
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
callTapsParallel({
|
||||
onError,
|
||||
onResult,
|
||||
onDone,
|
||||
rethrowIfPossible,
|
||||
onTap = (i, run) => run()
|
||||
}) {
|
||||
const { taps } = this.options;
|
||||
const tapsLength = taps.length;
|
||||
if (tapsLength <= 1) {
|
||||
return this.callTapsSeries({
|
||||
onError,
|
||||
onResult,
|
||||
onDone,
|
||||
rethrowIfPossible
|
||||
});
|
||||
}
|
||||
// done and doneBreak don't depend on the loop variable - hoist them
|
||||
// so they're allocated once per compile instead of once per tap.
|
||||
const done = () => {
|
||||
if (onDone) return "if(--_counter === 0) _done();\n";
|
||||
return "--_counter;";
|
||||
};
|
||||
const doneBreak = (skipDone) => {
|
||||
if (skipDone || !onDone) return "_counter = 0;\n";
|
||||
return "_counter = 0;\n_done();\n";
|
||||
};
|
||||
let code = "";
|
||||
code += "do {\n";
|
||||
code += `var _counter = ${tapsLength};\n`;
|
||||
if (onDone) {
|
||||
code += "var _done = (function() {\n";
|
||||
code += onDone();
|
||||
code += "});\n";
|
||||
}
|
||||
for (let i = 0; i < tapsLength; i++) {
|
||||
code += "if(_counter <= 0) break;\n";
|
||||
code += onTap(
|
||||
i,
|
||||
() =>
|
||||
this.callTap(i, {
|
||||
onError: (error) => {
|
||||
let code = "";
|
||||
code += "if(_counter > 0) {\n";
|
||||
code += onError(i, error, done, doneBreak);
|
||||
code += "}\n";
|
||||
return code;
|
||||
},
|
||||
onResult:
|
||||
onResult &&
|
||||
((result) => {
|
||||
let code = "";
|
||||
code += "if(_counter > 0) {\n";
|
||||
code += onResult(i, result, done, doneBreak);
|
||||
code += "}\n";
|
||||
return code;
|
||||
}),
|
||||
onDone: !onResult && (() => done()),
|
||||
rethrowIfPossible
|
||||
}),
|
||||
done,
|
||||
doneBreak
|
||||
);
|
||||
}
|
||||
code += "} while(false);\n";
|
||||
return code;
|
||||
}
|
||||
|
||||
args({ before, after } = {}) {
|
||||
// Hot during code generation. Join `_args` once and cache the result,
|
||||
// then build the customized variants via string concat instead of
|
||||
// allocating temporary `[before, ...allArgs]` / `[...allArgs, after]`
|
||||
// arrays and re-joining.
|
||||
let joined = this._joinedArgs;
|
||||
if (joined === undefined) {
|
||||
joined = this._args.length === 0 ? "" : this._args.join(", ");
|
||||
this._joinedArgs = joined;
|
||||
}
|
||||
if (!before && !after) return joined;
|
||||
if (joined.length === 0) {
|
||||
if (before && after) return `${before}, ${after}`;
|
||||
return before || after;
|
||||
}
|
||||
if (before && after) return `${before}, ${joined}, ${after}`;
|
||||
if (before) return `${before}, ${joined}`;
|
||||
return `${joined}, ${after}`;
|
||||
}
|
||||
|
||||
getTapFn(idx) {
|
||||
return `_x[${idx}]`;
|
||||
}
|
||||
|
||||
getTap(idx) {
|
||||
return `_taps[${idx}]`;
|
||||
}
|
||||
|
||||
getInterceptor(idx) {
|
||||
return `_interceptors[${idx}]`;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = HookCodeFactory;
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
MIT License http://www.opensource.org/licenses/mit-license.php
|
||||
Author Tobias Koppers @sokra
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
const util = require("util");
|
||||
|
||||
const defaultFactory = (key, hook) => hook;
|
||||
|
||||
class HookMap {
|
||||
constructor(factory, name = undefined) {
|
||||
this._map = new Map();
|
||||
this.name = name;
|
||||
this._factory = factory;
|
||||
this._interceptors = [];
|
||||
}
|
||||
|
||||
get(key) {
|
||||
return this._map.get(key);
|
||||
}
|
||||
|
||||
for(key) {
|
||||
// Hot path: inline the map lookup to skip the `this.get(key)`
|
||||
// indirection. This gets hit on every hook access in consumers
|
||||
// like webpack.
|
||||
const map = this._map;
|
||||
const hook = map.get(key);
|
||||
if (hook !== undefined) {
|
||||
return hook;
|
||||
}
|
||||
let newHook = this._factory(key);
|
||||
const interceptors = this._interceptors;
|
||||
for (let i = 0; i < interceptors.length; i++) {
|
||||
newHook = interceptors[i].factory(key, newHook);
|
||||
}
|
||||
map.set(key, newHook);
|
||||
return newHook;
|
||||
}
|
||||
|
||||
intercept(interceptor) {
|
||||
this._interceptors.push(
|
||||
Object.assign(
|
||||
{
|
||||
factory: defaultFactory
|
||||
},
|
||||
interceptor
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
HookMap.prototype.tap = util.deprecate(function tap(key, options, fn) {
|
||||
return this.for(key).tap(options, fn);
|
||||
}, "HookMap#tap(key,…) is deprecated. Use HookMap#for(key).tap(…) instead.");
|
||||
|
||||
HookMap.prototype.tapAsync = util.deprecate(function tapAsync(
|
||||
key,
|
||||
options,
|
||||
fn
|
||||
) {
|
||||
return this.for(key).tapAsync(options, fn);
|
||||
}, "HookMap#tapAsync(key,…) is deprecated. Use HookMap#for(key).tapAsync(…) instead.");
|
||||
|
||||
HookMap.prototype.tapPromise = util.deprecate(function tapPromise(
|
||||
key,
|
||||
options,
|
||||
fn
|
||||
) {
|
||||
return this.for(key).tapPromise(options, fn);
|
||||
}, "HookMap#tapPromise(key,…) is deprecated. Use HookMap#for(key).tapPromise(…) instead.");
|
||||
|
||||
module.exports = HookMap;
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
MIT License http://www.opensource.org/licenses/mit-license.php
|
||||
Author Tobias Koppers @sokra
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
class MultiHook {
|
||||
constructor(hooks, name = undefined) {
|
||||
this.hooks = hooks;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
tap(options, fn) {
|
||||
const { hooks } = this;
|
||||
for (let i = 0; i < hooks.length; i++) {
|
||||
hooks[i].tap(options, fn);
|
||||
}
|
||||
}
|
||||
|
||||
tapAsync(options, fn) {
|
||||
const { hooks } = this;
|
||||
for (let i = 0; i < hooks.length; i++) {
|
||||
hooks[i].tapAsync(options, fn);
|
||||
}
|
||||
}
|
||||
|
||||
tapPromise(options, fn) {
|
||||
const { hooks } = this;
|
||||
for (let i = 0; i < hooks.length; i++) {
|
||||
hooks[i].tapPromise(options, fn);
|
||||
}
|
||||
}
|
||||
|
||||
isUsed() {
|
||||
const { hooks } = this;
|
||||
for (let i = 0; i < hooks.length; i++) {
|
||||
if (hooks[i].isUsed()) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
intercept(interceptor) {
|
||||
const { hooks } = this;
|
||||
for (let i = 0; i < hooks.length; i++) {
|
||||
hooks[i].intercept(interceptor);
|
||||
}
|
||||
}
|
||||
|
||||
withOptions(options) {
|
||||
return new MultiHook(
|
||||
this.hooks.map((hook) => hook.withOptions(options)),
|
||||
this.name
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = MultiHook;
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
MIT License http://www.opensource.org/licenses/mit-license.php
|
||||
Author Tobias Koppers @sokra
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
const Hook = require("./Hook");
|
||||
const HookCodeFactory = require("./HookCodeFactory");
|
||||
|
||||
class SyncBailHookCodeFactory extends HookCodeFactory {
|
||||
content({ onError, onResult, resultReturns, onDone, rethrowIfPossible }) {
|
||||
return this.callTapsSeries({
|
||||
onError: (i, err) => onError(err),
|
||||
onResult: (i, result, next) =>
|
||||
`if(${result} !== undefined) {\n${onResult(
|
||||
result
|
||||
)};\n} else {\n${next()}}\n`,
|
||||
resultReturns,
|
||||
onDone,
|
||||
rethrowIfPossible
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const factory = new SyncBailHookCodeFactory();
|
||||
|
||||
const TAP_ASYNC = () => {
|
||||
throw new Error("tapAsync is not supported on a SyncBailHook");
|
||||
};
|
||||
|
||||
const TAP_PROMISE = () => {
|
||||
throw new Error("tapPromise is not supported on a SyncBailHook");
|
||||
};
|
||||
|
||||
function COMPILE(options) {
|
||||
factory.setup(this, options);
|
||||
return factory.create(options);
|
||||
}
|
||||
|
||||
function SyncBailHook(args = [], name = undefined) {
|
||||
const hook = new Hook(args, name);
|
||||
hook.constructor = SyncBailHook;
|
||||
hook.tapAsync = TAP_ASYNC;
|
||||
hook.tapPromise = TAP_PROMISE;
|
||||
hook.compile = COMPILE;
|
||||
return hook;
|
||||
}
|
||||
|
||||
SyncBailHook.prototype = null;
|
||||
|
||||
module.exports = SyncBailHook;
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
MIT License http://www.opensource.org/licenses/mit-license.php
|
||||
Author Tobias Koppers @sokra
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
const Hook = require("./Hook");
|
||||
const HookCodeFactory = require("./HookCodeFactory");
|
||||
|
||||
class SyncHookCodeFactory extends HookCodeFactory {
|
||||
content({ onError, onDone, rethrowIfPossible }) {
|
||||
return this.callTapsSeries({
|
||||
onError: (i, err) => onError(err),
|
||||
onDone,
|
||||
rethrowIfPossible
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const factory = new SyncHookCodeFactory();
|
||||
|
||||
const TAP_ASYNC = () => {
|
||||
throw new Error("tapAsync is not supported on a SyncHook");
|
||||
};
|
||||
|
||||
const TAP_PROMISE = () => {
|
||||
throw new Error("tapPromise is not supported on a SyncHook");
|
||||
};
|
||||
|
||||
function COMPILE(options) {
|
||||
factory.setup(this, options);
|
||||
return factory.create(options);
|
||||
}
|
||||
|
||||
function SyncHook(args = [], name = undefined) {
|
||||
const hook = new Hook(args, name);
|
||||
hook.constructor = SyncHook;
|
||||
hook.tapAsync = TAP_ASYNC;
|
||||
hook.tapPromise = TAP_PROMISE;
|
||||
hook.compile = COMPILE;
|
||||
return hook;
|
||||
}
|
||||
|
||||
SyncHook.prototype = null;
|
||||
|
||||
module.exports = SyncHook;
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
MIT License http://www.opensource.org/licenses/mit-license.php
|
||||
Author Tobias Koppers @sokra
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
const Hook = require("./Hook");
|
||||
const HookCodeFactory = require("./HookCodeFactory");
|
||||
|
||||
class SyncLoopHookCodeFactory extends HookCodeFactory {
|
||||
content({ onError, onDone, rethrowIfPossible }) {
|
||||
return this.callTapsLooping({
|
||||
onError: (i, err) => onError(err),
|
||||
onDone,
|
||||
rethrowIfPossible
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const factory = new SyncLoopHookCodeFactory();
|
||||
|
||||
const TAP_ASYNC = () => {
|
||||
throw new Error("tapAsync is not supported on a SyncLoopHook");
|
||||
};
|
||||
|
||||
const TAP_PROMISE = () => {
|
||||
throw new Error("tapPromise is not supported on a SyncLoopHook");
|
||||
};
|
||||
|
||||
function COMPILE(options) {
|
||||
factory.setup(this, options);
|
||||
return factory.create(options);
|
||||
}
|
||||
|
||||
function SyncLoopHook(args = [], name = undefined) {
|
||||
const hook = new Hook(args, name);
|
||||
hook.constructor = SyncLoopHook;
|
||||
hook.tapAsync = TAP_ASYNC;
|
||||
hook.tapPromise = TAP_PROMISE;
|
||||
hook.compile = COMPILE;
|
||||
return hook;
|
||||
}
|
||||
|
||||
SyncLoopHook.prototype = null;
|
||||
|
||||
module.exports = SyncLoopHook;
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
MIT License http://www.opensource.org/licenses/mit-license.php
|
||||
Author Tobias Koppers @sokra
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
const Hook = require("./Hook");
|
||||
const HookCodeFactory = require("./HookCodeFactory");
|
||||
|
||||
class SyncWaterfallHookCodeFactory extends HookCodeFactory {
|
||||
content({ onError, onResult, resultReturns, rethrowIfPossible }) {
|
||||
return this.callTapsSeries({
|
||||
onError: (i, err) => onError(err),
|
||||
onResult: (i, result, next) => {
|
||||
let code = "";
|
||||
code += `if(${result} !== undefined) {\n`;
|
||||
code += `${this._args[0]} = ${result};\n`;
|
||||
code += "}\n";
|
||||
code += next();
|
||||
return code;
|
||||
},
|
||||
onDone: () => onResult(this._args[0]),
|
||||
doneReturns: resultReturns,
|
||||
rethrowIfPossible
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const factory = new SyncWaterfallHookCodeFactory();
|
||||
|
||||
const TAP_ASYNC = () => {
|
||||
throw new Error("tapAsync is not supported on a SyncWaterfallHook");
|
||||
};
|
||||
|
||||
const TAP_PROMISE = () => {
|
||||
throw new Error("tapPromise is not supported on a SyncWaterfallHook");
|
||||
};
|
||||
|
||||
function COMPILE(options) {
|
||||
factory.setup(this, options);
|
||||
return factory.create(options);
|
||||
}
|
||||
|
||||
function SyncWaterfallHook(args = [], name = undefined) {
|
||||
if (args.length < 1) {
|
||||
throw new Error("Waterfall hooks must have at least one argument");
|
||||
}
|
||||
const hook = new Hook(args, name);
|
||||
hook.constructor = SyncWaterfallHook;
|
||||
hook.tapAsync = TAP_ASYNC;
|
||||
hook.tapPromise = TAP_PROMISE;
|
||||
hook.compile = COMPILE;
|
||||
return hook;
|
||||
}
|
||||
|
||||
SyncWaterfallHook.prototype = null;
|
||||
|
||||
module.exports = SyncWaterfallHook;
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
/*
|
||||
MIT License http://www.opensource.org/licenses/mit-license.php
|
||||
Author Tobias Koppers @sokra
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
module.exports.AsyncParallelBailHook = require("./AsyncParallelBailHook");
|
||||
module.exports.AsyncParallelHook = require("./AsyncParallelHook");
|
||||
module.exports.AsyncSeriesBailHook = require("./AsyncSeriesBailHook");
|
||||
module.exports.AsyncSeriesHook = require("./AsyncSeriesHook");
|
||||
module.exports.AsyncSeriesLoopHook = require("./AsyncSeriesLoopHook");
|
||||
module.exports.AsyncSeriesWaterfallHook = require("./AsyncSeriesWaterfallHook");
|
||||
module.exports.HookMap = require("./HookMap");
|
||||
module.exports.MultiHook = require("./MultiHook");
|
||||
module.exports.SyncBailHook = require("./SyncBailHook");
|
||||
module.exports.SyncHook = require("./SyncHook");
|
||||
module.exports.SyncLoopHook = require("./SyncLoopHook");
|
||||
module.exports.SyncWaterfallHook = require("./SyncWaterfallHook");
|
||||
module.exports.__esModule = true;
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
/*
|
||||
MIT License http://www.opensource.org/licenses/mit-license.php
|
||||
Author Tobias Koppers @sokra
|
||||
*/
|
||||
"use strict";
|
||||
|
||||
module.exports.deprecate = (fn, msg) => {
|
||||
let once = true;
|
||||
return function deprecate() {
|
||||
if (once) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn(`DeprecationWarning: ${msg}`);
|
||||
once = false;
|
||||
}
|
||||
// eslint-disable-next-line prefer-rest-params
|
||||
return fn.apply(this, arguments);
|
||||
};
|
||||
};
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"name": "tapable",
|
||||
"version": "2.3.3",
|
||||
"description": "Just a little module for plugins.",
|
||||
"homepage": "https://github.com/webpack/tapable",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "http://github.com/webpack/tapable.git"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/webpack"
|
||||
},
|
||||
"license": "MIT",
|
||||
"author": "Tobias Koppers @sokra",
|
||||
"main": "lib/index.js",
|
||||
"browser": {
|
||||
"util": "./lib/util-browser.js"
|
||||
},
|
||||
"types": "./tapable.d.ts",
|
||||
"files": [
|
||||
"lib",
|
||||
"tapable.d.ts"
|
||||
],
|
||||
"scripts": {
|
||||
"lint": "npm run lint:code && npm run fmt:check",
|
||||
"lint:code": "eslint --cache .",
|
||||
"fmt": "npm run fmt:base -- --log-level warn --write",
|
||||
"fmt:check": "npm run fmt:base -- --check",
|
||||
"fmt:base": "node ./node_modules/prettier/bin/prettier.cjs --cache --ignore-unknown .",
|
||||
"fix": "npm run fix:code && npm run fmt",
|
||||
"fix:code": "npm run lint:code -- --fix",
|
||||
"test": "jest",
|
||||
"benchmark": "node --max-old-space-size=4096 --hash-seed=1 --random-seed=1 --no-opt --predictable --predictable-gc-schedule --interpreted-frames-native-stack --allow-natives-syntax --expose-gc --no-concurrent-sweeping ./benchmark/run.mjs",
|
||||
"version": "changeset version",
|
||||
"release": "changeset publish"
|
||||
},
|
||||
"jest": {
|
||||
"transform": {
|
||||
"test[\\\\/].+\\.js$": "babel-jest"
|
||||
},
|
||||
"snapshotFormat": {
|
||||
"escapeString": true,
|
||||
"printBasicPrototype": true
|
||||
}
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.4.4",
|
||||
"@babel/preset-env": "^7.4.4",
|
||||
"@changesets/cli": "^2.31.0",
|
||||
"@changesets/get-github-info": "^0.8.0",
|
||||
"@codspeed/core": "^5.3.0",
|
||||
"@stylistic/eslint-plugin": "^5.2.3",
|
||||
"babel-jest": "^30.3.0",
|
||||
"eslint": "^9.28.0",
|
||||
"eslint-config-webpack": "^4.6.3",
|
||||
"jest": "^30.3.0",
|
||||
"prettier": "^3.8.3",
|
||||
"prettier-1": "npm:prettier@^1",
|
||||
"tinybench": "^6.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
type FixedSizeArray<T extends number, U> = T extends 0
|
||||
? void[]
|
||||
: ReadonlyArray<U> & {
|
||||
0: U;
|
||||
length: T;
|
||||
};
|
||||
type Measure<T extends number> = T extends 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
|
||||
? T
|
||||
: never;
|
||||
type Append<T extends any[], U> = {
|
||||
0: [U];
|
||||
1: [T[0], U];
|
||||
2: [T[0], T[1], U];
|
||||
3: [T[0], T[1], T[2], U];
|
||||
4: [T[0], T[1], T[2], T[3], U];
|
||||
5: [T[0], T[1], T[2], T[3], T[4], U];
|
||||
6: [T[0], T[1], T[2], T[3], T[4], T[5], U];
|
||||
7: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], U];
|
||||
8: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], U];
|
||||
}[Measure<T["length"]>];
|
||||
type AsArray<T> = T extends any[] ? T : [T];
|
||||
|
||||
declare class UnsetAdditionalOptions {
|
||||
_UnsetAdditionalOptions: true;
|
||||
}
|
||||
type IfSet<X> = X extends UnsetAdditionalOptions ? {} : X;
|
||||
|
||||
type Callback<E, T> = (error: E | null, result?: T) => void;
|
||||
type InnerCallback<E, T> = (error?: E | null | false, result?: T) => void;
|
||||
|
||||
type FullTap = Tap & {
|
||||
type: "sync" | "async" | "promise";
|
||||
fn: Function;
|
||||
};
|
||||
|
||||
type Tap = TapOptions & {
|
||||
name: string;
|
||||
};
|
||||
|
||||
type TapOptions = {
|
||||
before?: string;
|
||||
stage?: number;
|
||||
};
|
||||
|
||||
interface HookInterceptor<T, R, AdditionalOptions = UnsetAdditionalOptions> {
|
||||
name?: string;
|
||||
tap?: (tap: FullTap & IfSet<AdditionalOptions>) => void;
|
||||
call?: (...args: any[]) => void;
|
||||
loop?: (...args: any[]) => void;
|
||||
error?: (err: Error) => void;
|
||||
result?: (result: R) => void;
|
||||
done?: () => void;
|
||||
register?: (
|
||||
tap: FullTap & IfSet<AdditionalOptions>
|
||||
) => FullTap & IfSet<AdditionalOptions>;
|
||||
}
|
||||
|
||||
type ArgumentNames<T extends any[]> = FixedSizeArray<T["length"], string>;
|
||||
|
||||
declare class Hook<T, R, AdditionalOptions = UnsetAdditionalOptions> {
|
||||
constructor(args?: ArgumentNames<AsArray<T>>, name?: string);
|
||||
name: string | undefined;
|
||||
interceptors: HookInterceptor<T, R, AdditionalOptions>[];
|
||||
taps: FullTap[];
|
||||
intercept(interceptor: HookInterceptor<T, R, AdditionalOptions>): void;
|
||||
isUsed(): boolean;
|
||||
callAsync(...args: Append<AsArray<T>, Callback<Error, R>>): void;
|
||||
promise(...args: AsArray<T>): Promise<R>;
|
||||
tap(
|
||||
options: string | (Tap & IfSet<AdditionalOptions>),
|
||||
fn: (...args: AsArray<T>) => R
|
||||
): void;
|
||||
withOptions(
|
||||
options: TapOptions & IfSet<AdditionalOptions>
|
||||
): Omit<this, "call" | "callAsync" | "promise">;
|
||||
}
|
||||
|
||||
export class SyncHook<
|
||||
T,
|
||||
R = void,
|
||||
AdditionalOptions = UnsetAdditionalOptions
|
||||
> extends Hook<T, R, AdditionalOptions> {
|
||||
call(...args: AsArray<T>): R;
|
||||
}
|
||||
|
||||
export class SyncBailHook<
|
||||
T,
|
||||
R,
|
||||
AdditionalOptions = UnsetAdditionalOptions
|
||||
> extends SyncHook<T, R, AdditionalOptions> {}
|
||||
export class SyncLoopHook<
|
||||
T,
|
||||
AdditionalOptions = UnsetAdditionalOptions
|
||||
> extends SyncHook<T, void, AdditionalOptions> {}
|
||||
export class SyncWaterfallHook<
|
||||
T,
|
||||
R = AsArray<T>[0],
|
||||
AdditionalOptions = UnsetAdditionalOptions
|
||||
> extends SyncHook<T, R, AdditionalOptions> {}
|
||||
|
||||
declare class AsyncHook<
|
||||
T,
|
||||
R,
|
||||
AdditionalOptions = UnsetAdditionalOptions
|
||||
> extends Hook<T, R, AdditionalOptions> {
|
||||
tapAsync(
|
||||
options: string | (Tap & IfSet<AdditionalOptions>),
|
||||
fn: (...args: Append<AsArray<T>, InnerCallback<Error, R>>) => void
|
||||
): void;
|
||||
tapPromise(
|
||||
options: string | (Tap & IfSet<AdditionalOptions>),
|
||||
fn: (...args: AsArray<T>) => Promise<R>
|
||||
): void;
|
||||
}
|
||||
|
||||
export class AsyncParallelHook<
|
||||
T,
|
||||
AdditionalOptions = UnsetAdditionalOptions
|
||||
> extends AsyncHook<T, void, AdditionalOptions> {}
|
||||
export class AsyncParallelBailHook<
|
||||
T,
|
||||
R,
|
||||
AdditionalOptions = UnsetAdditionalOptions
|
||||
> extends AsyncHook<T, R, AdditionalOptions> {}
|
||||
export class AsyncSeriesHook<
|
||||
T,
|
||||
AdditionalOptions = UnsetAdditionalOptions
|
||||
> extends AsyncHook<T, void, AdditionalOptions> {}
|
||||
export class AsyncSeriesBailHook<
|
||||
T,
|
||||
R,
|
||||
AdditionalOptions = UnsetAdditionalOptions
|
||||
> extends AsyncHook<T, R, AdditionalOptions> {}
|
||||
export class AsyncSeriesLoopHook<
|
||||
T,
|
||||
AdditionalOptions = UnsetAdditionalOptions
|
||||
> extends AsyncHook<T, void, AdditionalOptions> {}
|
||||
export class AsyncSeriesWaterfallHook<
|
||||
T,
|
||||
R = AsArray<T>[0],
|
||||
AdditionalOptions = UnsetAdditionalOptions
|
||||
> extends AsyncHook<T, R, AdditionalOptions> {}
|
||||
|
||||
type HookFactory<H, K = any> = (key: K) => H;
|
||||
|
||||
interface HookMapInterceptor<H, K = any> {
|
||||
factory?: (key: K, hook: H) => H;
|
||||
}
|
||||
|
||||
export class HookMap<H> {
|
||||
constructor(factory: HookFactory<H>, name?: string);
|
||||
name: string | undefined;
|
||||
get(key: any): H | undefined;
|
||||
for(key: any): H;
|
||||
intercept(interceptor: HookMapInterceptor<H>): void;
|
||||
}
|
||||
|
||||
type AnyHook = Hook<any, any>;
|
||||
|
||||
export class TypedHookMap<M extends Record<any, AnyHook>> {
|
||||
constructor(factory: HookFactory<M[keyof M], keyof M>, name?: string);
|
||||
name: string | undefined;
|
||||
get<K extends keyof M>(key: K): M[K] | undefined;
|
||||
for<K extends keyof M>(key: K): M[K];
|
||||
intercept(interceptor: HookMapInterceptor<M[keyof M], keyof M>): void;
|
||||
}
|
||||
|
||||
export class MultiHook<H> {
|
||||
constructor(hooks: H[], name?: string);
|
||||
name: string | undefined;
|
||||
tap(options: string | Tap, fn?: Function): void;
|
||||
tapAsync(options: string | Tap, fn?: Function): void;
|
||||
tapPromise(options: string | Tap, fn?: Function): void;
|
||||
}
|
||||
Reference in New Issue
Block a user