This commit is contained in:
2026-11-25 18:18:22 +08:00
parent eb2ea93f4c
commit 5c2f3daeee
697 changed files with 200872 additions and 641 deletions
+21
View File
@@ -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
View File
@@ -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());
}
```
+140
View File
@@ -0,0 +1,140 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Hook = require("./Hook");
const HookCodeFactory = require("./HookCodeFactory");
/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */
/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */
/** @typedef {import("./Hook").UnsetAdditionalOptions} UnsetAdditionalOptions */
/** @typedef {import("./Hook").CompileOptions<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>} CompileOptions */
/** @typedef {import("./HookCodeFactory").ContentOptions} ContentOptions */
/**
* @template {EXPECTED_ANY[]} T
* @typedef {import("./Hook").ArgumentNames<T>} ArgumentNames
*/
/**
* @template T
* @typedef {import("./Hook").AsArray<T>} AsArray
*/
/**
* Mirror of the `AsyncParallelBailHook` class declared in `tapable.d.ts` for
* use as the factory function's return type, so `new AsyncParallelBailHook(...)`
* resolves to the specific subclass type instead of the generic `Hook`.
* @template T
* @template R
* @template [AdditionalOptions=UnsetAdditionalOptions]
* @typedef {import("../tapable").AsyncParallelBailHook<T, R, AdditionalOptions>} AsyncParallelBailHookType
*/
class AsyncParallelBailHookCodeFactory extends HookCodeFactory {
/**
* @param {ContentOptions} options content generation options
* @returns {string} generated body code
*/
content({ onError, onResult, onDone }) {
const opts = /** @type {CompileOptions} */ (this.options);
let code = "";
code += `var _results = new Array(${opts.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();
/**
* @template T
* @template R
* @template [AdditionalOptions=UnsetAdditionalOptions]
* @this {Hook<T, R, AdditionalOptions>}
* @param {CompileOptions} options compile options
* @returns {EXPECTED_FUNCTION} the compiled call function
*/
function COMPILE(options) {
factory.setup(this, options);
return factory.create(options);
}
/**
* @constructor
* @template T
* @template R
* @template [AdditionalOptions=UnsetAdditionalOptions]
* @param {ArgumentNames<AsArray<T>>=} args argument names of the hook
* @param {string=} name name of the hook
* @returns {AsyncParallelBailHookType<T, R, AdditionalOptions>} a new AsyncParallelBailHook instance
*/
function AsyncParallelBailHook(
args = /** @type {ArgumentNames<AsArray<T>>} */ (/** @type {unknown} */ ([])),
name = undefined
) {
const hook = new Hook(args, name);
hook.constructor = AsyncParallelBailHook;
hook.compile = COMPILE;
// @ts-expect-error for performance reasons
hook._call = undefined;
hook.call = undefined;
return /** @type {AsyncParallelBailHookType<T, R, AdditionalOptions>} */ (
/** @type {unknown} */ (hook)
);
}
/** @type {EXPECTED_ANY} */
AsyncParallelBailHook.prototype = null;
module.exports = AsyncParallelBailHook;
+84
View File
@@ -0,0 +1,84 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Hook = require("./Hook");
const HookCodeFactory = require("./HookCodeFactory");
/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */
/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */
/** @typedef {import("./Hook").CompileOptions<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>} CompileOptions */
/** @typedef {import("./Hook").UnsetAdditionalOptions} UnsetAdditionalOptions */
/** @typedef {import("./HookCodeFactory").ContentOptions} ContentOptions */
/**
* @template {EXPECTED_ANY[]} T
* @typedef {import("./Hook").ArgumentNames<T>} ArgumentNames
*/
/**
* @template T
* @typedef {import("./Hook").AsArray<T>} AsArray
*/
/**
* Mirror of the `AsyncParallelHook` class declared in `tapable.d.ts` for use
* as the factory function's return type, so `new AsyncParallelHook(...)`
* resolves to the specific subclass type instead of the generic `Hook`.
* @template T
* @template [AdditionalOptions=UnsetAdditionalOptions]
* @typedef {import("../tapable").AsyncParallelHook<T, AdditionalOptions>} AsyncParallelHookType
*/
class AsyncParallelHookCodeFactory extends HookCodeFactory {
/**
* @param {ContentOptions} options content generation options
* @returns {string} generated body code
*/
content({ onError, onDone }) {
return this.callTapsParallel({
onError: (i, err, done, doneBreak) => onError(err) + doneBreak(true),
onDone
});
}
}
const factory = new AsyncParallelHookCodeFactory();
/**
* @this {Hook<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>}
* @param {CompileOptions} options compile options
* @returns {EXPECTED_FUNCTION} the compiled call function
*/
function COMPILE(options) {
factory.setup(this, options);
return factory.create(options);
}
/**
* @constructor
* @template T
* @template [AdditionalOptions=UnsetAdditionalOptions]
* @param {ArgumentNames<AsArray<T>>=} args argument names of the hook
* @param {string=} name name of the hook
* @returns {AsyncParallelHookType<T, AdditionalOptions>} a new AsyncParallelHook instance
*/
function AsyncParallelHook(
args = /** @type {ArgumentNames<AsArray<T>>} */ (/** @type {unknown} */ ([])),
name = undefined
) {
const hook = new Hook(args, name);
hook.constructor = AsyncParallelHook;
hook.compile = COMPILE;
// @ts-expect-error for performance reasons
hook._call = undefined;
hook.call = undefined;
return /** @type {AsyncParallelHookType<T, AdditionalOptions>} */ (
/** @type {unknown} */ (hook)
);
}
/** @type {EXPECTED_ANY} */
AsyncParallelHook.prototype = null;
module.exports = AsyncParallelHook;
+91
View File
@@ -0,0 +1,91 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Hook = require("./Hook");
const HookCodeFactory = require("./HookCodeFactory");
/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */
/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */
/** @typedef {import("./Hook").CompileOptions<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>} CompileOptions */
/** @typedef {import("./Hook").UnsetAdditionalOptions} UnsetAdditionalOptions */
/** @typedef {import("./HookCodeFactory").ContentOptions} ContentOptions */
/**
* @template {EXPECTED_ANY[]} T
* @typedef {import("./Hook").ArgumentNames<T>} ArgumentNames
*/
/**
* @template T
* @typedef {import("./Hook").AsArray<T>} AsArray
*/
/**
* Mirror of the `AsyncSeriesBailHook` class declared in `tapable.d.ts` for
* use as the factory function's return type, so `new AsyncSeriesBailHook(...)`
* resolves to the specific subclass type instead of the generic `Hook`.
* @template T
* @template R
* @template [AdditionalOptions=UnsetAdditionalOptions]
* @typedef {import("../tapable").AsyncSeriesBailHook<T, R, AdditionalOptions>} AsyncSeriesBailHookType
*/
class AsyncSeriesBailHookCodeFactory extends HookCodeFactory {
/**
* @param {ContentOptions} options content generation options
* @returns {string} generated body code
*/
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();
/**
* @this {Hook<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>}
* @param {CompileOptions} options compile options
* @returns {EXPECTED_FUNCTION} the compiled call function
*/
function COMPILE(options) {
factory.setup(this, options);
return factory.create(options);
}
/**
* @constructor
* @template T
* @template R
* @template [AdditionalOptions=UnsetAdditionalOptions]
* @param {ArgumentNames<AsArray<T>>=} args argument names of the hook
* @param {string=} name name of the hook
* @returns {AsyncSeriesBailHookType<T, R, AdditionalOptions>} a new AsyncSeriesBailHook instance
*/
function AsyncSeriesBailHook(
args = /** @type {ArgumentNames<AsArray<T>>} */ (/** @type {unknown} */ ([])),
name = undefined
) {
const hook = new Hook(args, name);
hook.constructor = AsyncSeriesBailHook;
hook.compile = COMPILE;
// @ts-expect-error for performance reasons
hook._call = undefined;
hook.call = undefined;
return /** @type {AsyncSeriesBailHookType<T, R, AdditionalOptions>} */ (
/** @type {unknown} */ (hook)
);
}
/** @type {EXPECTED_ANY} */
AsyncSeriesBailHook.prototype = null;
module.exports = AsyncSeriesBailHook;
+84
View File
@@ -0,0 +1,84 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Hook = require("./Hook");
const HookCodeFactory = require("./HookCodeFactory");
/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */
/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */
/** @typedef {import("./Hook").CompileOptions<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>} CompileOptions */
/** @typedef {import("./Hook").UnsetAdditionalOptions} UnsetAdditionalOptions */
/** @typedef {import("./HookCodeFactory").ContentOptions} ContentOptions */
/**
* @template {EXPECTED_ANY[]} T
* @typedef {import("./Hook").ArgumentNames<T>} ArgumentNames
*/
/**
* @template T
* @typedef {import("./Hook").AsArray<T>} AsArray
*/
/**
* Mirror of the `AsyncSeriesHook` class declared in `tapable.d.ts` for use
* as the factory function's return type, so `new AsyncSeriesHook(...)`
* resolves to the specific subclass type instead of the generic `Hook`.
* @template T
* @template [AdditionalOptions=UnsetAdditionalOptions]
* @typedef {import("../tapable").AsyncSeriesHook<T, AdditionalOptions>} AsyncSeriesHookType
*/
class AsyncSeriesHookCodeFactory extends HookCodeFactory {
/**
* @param {ContentOptions} options content generation options
* @returns {string} generated body code
*/
content({ onError, onDone }) {
return this.callTapsSeries({
onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true),
onDone
});
}
}
const factory = new AsyncSeriesHookCodeFactory();
/**
* @this {Hook<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>}
* @param {CompileOptions} options compile options
* @returns {EXPECTED_FUNCTION} the compiled call function
*/
function COMPILE(options) {
factory.setup(this, options);
return factory.create(options);
}
/**
* @constructor
* @template T
* @template [AdditionalOptions=UnsetAdditionalOptions]
* @param {ArgumentNames<AsArray<T>>=} args argument names of the hook
* @param {string=} name name of the hook
* @returns {AsyncSeriesHookType<T, AdditionalOptions>} a new AsyncSeriesHook instance
*/
function AsyncSeriesHook(
args = /** @type {ArgumentNames<AsArray<T>>} */ (/** @type {unknown} */ ([])),
name = undefined
) {
const hook = new Hook(args, name);
hook.constructor = AsyncSeriesHook;
hook.compile = COMPILE;
// @ts-expect-error for performance reasons
hook._call = undefined;
hook.call = undefined;
return /** @type {AsyncSeriesHookType<T, AdditionalOptions>} */ (
/** @type {unknown} */ (hook)
);
}
/** @type {EXPECTED_ANY} */
AsyncSeriesHook.prototype = null;
module.exports = AsyncSeriesHook;
+84
View File
@@ -0,0 +1,84 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Hook = require("./Hook");
const HookCodeFactory = require("./HookCodeFactory");
/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */
/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */
/** @typedef {import("./Hook").CompileOptions<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>} CompileOptions */
/** @typedef {import("./Hook").UnsetAdditionalOptions} UnsetAdditionalOptions */
/** @typedef {import("./HookCodeFactory").ContentOptions} ContentOptions */
/**
* @template {EXPECTED_ANY[]} T
* @typedef {import("./Hook").ArgumentNames<T>} ArgumentNames
*/
/**
* @template T
* @typedef {import("./Hook").AsArray<T>} AsArray
*/
/**
* Mirror of the `AsyncSeriesLoopHook` class declared in `tapable.d.ts` for
* use as the factory function's return type, so `new AsyncSeriesLoopHook(...)`
* resolves to the specific subclass type instead of the generic `Hook`.
* @template T
* @template [AdditionalOptions=UnsetAdditionalOptions]
* @typedef {import("../tapable").AsyncSeriesLoopHook<T, AdditionalOptions>} AsyncSeriesLoopHookType
*/
class AsyncSeriesLoopHookCodeFactory extends HookCodeFactory {
/**
* @param {ContentOptions} options content generation options
* @returns {string} generated body code
*/
content({ onError, onDone }) {
return this.callTapsLooping({
onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true),
onDone
});
}
}
const factory = new AsyncSeriesLoopHookCodeFactory();
/**
* @this {Hook<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>}
* @param {CompileOptions} options compile options
* @returns {EXPECTED_FUNCTION} the compiled call function
*/
function COMPILE(options) {
factory.setup(this, options);
return factory.create(options);
}
/**
* @constructor
* @template T
* @template [AdditionalOptions=UnsetAdditionalOptions]
* @param {ArgumentNames<AsArray<T>>=} args argument names of the hook
* @param {string=} name name of the hook
* @returns {AsyncSeriesLoopHookType<T, AdditionalOptions>} a new AsyncSeriesLoopHook instance
*/
function AsyncSeriesLoopHook(
args = /** @type {ArgumentNames<AsArray<T>>} */ (/** @type {unknown} */ ([])),
name = undefined
) {
const hook = new Hook(args, name);
hook.constructor = AsyncSeriesLoopHook;
hook.compile = COMPILE;
// @ts-expect-error for performance reasons
hook._call = undefined;
hook.call = undefined;
return /** @type {AsyncSeriesLoopHookType<T, AdditionalOptions>} */ (
/** @type {unknown} */ (hook)
);
}
/** @type {EXPECTED_ANY} */
AsyncSeriesLoopHook.prototype = null;
module.exports = AsyncSeriesLoopHook;
+98
View File
@@ -0,0 +1,98 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Hook = require("./Hook");
const HookCodeFactory = require("./HookCodeFactory");
/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */
/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */
/** @typedef {import("./Hook").CompileOptions<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>} CompileOptions */
/** @typedef {import("./Hook").UnsetAdditionalOptions} UnsetAdditionalOptions */
/** @typedef {import("./HookCodeFactory").ContentOptions} ContentOptions */
/**
* @template {EXPECTED_ANY[]} T
* @typedef {import("./Hook").ArgumentNames<T>} ArgumentNames
*/
/**
* @template T
* @typedef {import("./Hook").AsArray<T>} AsArray
*/
/**
* Mirror of the `AsyncSeriesWaterfallHook` class declared in `tapable.d.ts`
* for use as the factory function's return type, so
* `new AsyncSeriesWaterfallHook(...)` resolves to the specific subclass type
* instead of the generic `Hook`.
* @template T
* @template [R=AsArray<T>[0]]
* @template [AdditionalOptions=UnsetAdditionalOptions]
* @typedef {import("../tapable").AsyncSeriesWaterfallHook<T, R, AdditionalOptions>} AsyncSeriesWaterfallHookType
*/
class AsyncSeriesWaterfallHookCodeFactory extends HookCodeFactory {
/**
* @param {ContentOptions} options content generation options
* @returns {string} generated body code
*/
content({ onError, onResult }) {
return this.callTapsSeries({
onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true),
onResult: (i, result, next) => {
let code = "";
code += `if(${result} !== undefined) {\n`;
code += `${/** @type {string[]} */ (this._args)[0]} = ${result};\n`;
code += "}\n";
code += next();
return code;
},
onDone: () => onResult(/** @type {string[]} */ (this._args)[0])
});
}
}
const factory = new AsyncSeriesWaterfallHookCodeFactory();
/**
* @this {Hook<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>}
* @param {CompileOptions} options compile options
* @returns {EXPECTED_FUNCTION} the compiled call function
*/
function COMPILE(options) {
factory.setup(this, options);
return factory.create(options);
}
/**
* @constructor
* @template T
* @template [R=AsArray<T>[0]]
* @template [AdditionalOptions=UnsetAdditionalOptions]
* @param {ArgumentNames<AsArray<T>>=} args argument names of the hook
* @param {string=} name name of the hook
* @returns {AsyncSeriesWaterfallHookType<T, R, AdditionalOptions>} a new AsyncSeriesWaterfallHook instance
*/
function AsyncSeriesWaterfallHook(
args = /** @type {ArgumentNames<AsArray<T>>} */ (/** @type {unknown} */ ([])),
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;
// @ts-expect-error for performance reasons
hook._call = undefined;
hook.call = undefined;
return /** @type {AsyncSeriesWaterfallHookType<T, R, AdditionalOptions>} */ (
/** @type {unknown} */ (hook)
);
}
/** @type {EXPECTED_ANY} */
AsyncSeriesWaterfallHook.prototype = null;
module.exports = AsyncSeriesWaterfallHook;
+500
View File
@@ -0,0 +1,500 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const util = require("util");
// eslint-disable-next-line jsdoc/reject-function-type
/** @typedef {Function} EXPECTED_FUNCTION */
// eslint-disable-next-line jsdoc/reject-any-type
/** @typedef {any} EXPECTED_ANY */
/** @typedef {Record<string, EXPECTED_ANY>} EXPECTED_OBJECT */
/**
* @template T
* @typedef {T extends EXPECTED_ANY[] ? T : [T]} AsArray
*/
/**
* @template {number} T
* @typedef {T extends 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 ? T : never} Measure
*/
/**
* @template {EXPECTED_ANY[]} T
* @template U
* @typedef {{
* 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"]>]} Append
*/
/* eslint-disable jsdoc/ts-no-empty-object-type */
/**
* @template X
* @typedef {X extends UnsetAdditionalOptions ? { } : X} IfSet
*/
/* eslint-enable jsdoc/ts-no-empty-object-type */
/**
* @template {number} T
* @template U
* @typedef {T extends 0 ? void[] : ReadonlyArray<U> & { 0: U, length: T }} FixedSizeArray
*/
/**
* @template {EXPECTED_ANY[]} T
* @typedef {FixedSizeArray<T["length"], string>} ArgumentNames
*/
/**
* @typedef {object} TapOptions
* @property {string=} before name of an earlier tap to insert this tap before
* @property {number=} stage stage to schedule the tap in (lower runs earlier)
*/
/**
* @typedef {TapOptions & { name: string }} Tap
*/
/**
* @typedef {Tap & { type: "sync" | "async" | "promise", fn: EXPECTED_FUNCTION }} FullTap
*/
/**
* @template E, T
* @typedef {(error: E | null, result?: T) => void} Callback
*/
/**
* @template E, T
* @typedef {(error?: E | null | false, result?: T) => void} InnerCallback
*/
// TODO remove context in the next major release, deprecated
/**
* @template T
* @template R
* @template [AdditionalOptions=UnsetAdditionalOptions]
* @typedef {object} HookInterceptor
* @property {string=} name optional name of the interceptor
* @property {((tap: FullTap & IfSet<AdditionalOptions>) => void)=} tap called for each tap before it runs
* @property {((...args: EXPECTED_ANY[]) => void)=} call called when the hook is called
* @property {((...args: EXPECTED_ANY[]) => void)=} loop called for each loop iteration of looping hooks
* @property {((err: Error) => void)=} error called when an error occurs
* @property {((result: R) => void)=} result called with the hook's result
* @property {(() => void)=} done called when the hook is fully done
* @property {((tap: FullTap & IfSet<AdditionalOptions>) => FullTap & IfSet<AdditionalOptions>)=} register called whenever a tap is registered
* @property {boolean=} context true to pass a `_context` argument to interceptor callbacks
*/
/**
* @typedef {object} UnsetAdditionalOptions
* @property {true} _UnsetAdditionalOptions unset
*/
/**
* @template T
* @template R
* @template [AdditionalOptions=UnsetAdditionalOptions]
* @typedef {object} CompileOptions
* @property {FullTap[]} taps the registered taps
* @property {HookInterceptor<T, R, AdditionalOptions>[]} interceptors the registered interceptors
* @property {ArgumentNames<AsArray<T>>} args names of the hook arguments (used for code generation)
* @property {"sync" | "async" | "promise"} type call type
*/
const deprecateContext = util.deprecate(
() => {},
"Hook.context is deprecated and will be removed"
);
/**
* @template T, R
* @callback CallDelegate
* @param {...AsArray<T>} args
* @returns {R}
*/
/**
* @template T, R
* @type {CallDelegate<EXPECTED_ANY, EXPECTED_ANY>}
* @this {Hook<T, R>}
*/
function CALL_DELEGATE(...args) {
// @ts-expect-error for performance reasons
this.call = this._createCall("sync");
// @ts-expect-error for performance reasons
return this.call(...args);
}
/**
* @template T, R
* @callback CallAsyncDelegate
* @param {...Append<AsArray<T>, Callback<Error, R>>} args
* @returns void
*/
/**
* @template T, R
* @type {CallAsyncDelegate<EXPECTED_ANY, EXPECTED_ANY>}
* @this {Hook<T, R>}
*/
function CALL_ASYNC_DELEGATE(...args) {
// @ts-expect-error for performance reasons
this.callAsync = this._createCall("async");
return this.callAsync(...args);
}
/**
* @template T, R
* @callback PromiseDeledate
* @param {...AsArray<T>} args
* @returns {Promise<R>}
*/
/**
* @template T, R
* @type {PromiseDeledate<EXPECTED_ANY, EXPECTED_ANY>}
* @this {Hook<T, R>}
*/
function PROMISE_DELEGATE(...args) {
// @ts-expect-error for performance reasons
this.promise = this._createCall("promise");
return this.promise(...args);
}
/**
* @template T
* @template R
* @template [AdditionalOptions=UnsetAdditionalOptions]
*/
class Hook {
/**
* @param {ArgumentNames<AsArray<T>>=} args argument names of the hook (used for code generation)
* @param {string=} name name of the hook
*/
constructor(
args = /** @type {ArgumentNames<AsArray<T>>} */ (
/** @type {unknown} */ ([])
),
name = undefined
) {
/**
* @private
* @type {ArgumentNames<AsArray<T>>}
*/
this._args = args;
/** @type {string | undefined} */
this.name = name;
/** @type {FullTap[]} */
this.taps = [];
/** @type {HookInterceptor<T, R, AdditionalOptions>[]} */
this.interceptors = [];
/**
* @private
* @type {CallDelegate<T, R> | undefined}
*/
this._call = CALL_DELEGATE;
/** @type {CallDelegate<T, R> | undefined} */
this.call = CALL_DELEGATE;
/**
* @private
* @type {CallAsyncDelegate<T, R>}
*/
this._callAsync = CALL_ASYNC_DELEGATE;
/** @type {CallAsyncDelegate<T, R>} */
this.callAsync = CALL_ASYNC_DELEGATE;
/**
* @private
* @type {PromiseDeledate<T, R>}
*/
this._promise = PROMISE_DELEGATE;
/** @type {PromiseDeledate<T, R>} */
this.promise = PROMISE_DELEGATE;
/** @type {EXPECTED_FUNCTION[] | undefined} */
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;
}
/**
* @abstract
* @param {CompileOptions<T, R, AdditionalOptions>} _options compile options
* @returns {EXPECTED_FUNCTION} the compiled call function
*/
compile(_options) {
throw new Error("Abstract: should be overridden");
}
/**
* @private
* @param {"sync" | "async" | "promise"} type the call type
* @returns {EXPECTED_FUNCTION} the compiled call function
*/
_createCall(type) {
return this.compile({
taps: this.taps,
interceptors: this.interceptors,
args: this._args,
type
});
}
/**
* @private
* @param {"sync" | "async" | "promise"} type the tap type
* @param {string | (Tap & IfSet<AdditionalOptions>)} options name or full tap options
* @param {EXPECTED_FUNCTION} fn callback registered with the tap
* @returns {void}
*/
_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 {FullTap & IfSet<AdditionalOptions>} */
({ 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 (/** @type {{ context?: unknown }} */ (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 {FullTap & IfSet<AdditionalOptions>} */
({ 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(
/** @type {FullTap & IfSet<AdditionalOptions>} */
(options)
);
this._insert(
/** @type {FullTap & IfSet<AdditionalOptions>} */
(options)
);
}
/**
* @param {string | (Tap & IfSet<AdditionalOptions>)} options tap name or full tap options
* @param {(...args: AsArray<T>) => R} fn the function to register
* @returns {void}
*/
tap(options, fn) {
this._tap("sync", options, fn);
}
/**
* @param {string | (Tap & IfSet<AdditionalOptions>)} options tap name or full tap options
* @param {(...args: Append<AsArray<T>, InnerCallback<Error, R>>) => void} fn the function to register
* @returns {void}
*/
tapAsync(options, fn) {
this._tap("async", options, fn);
}
/**
* @param {string | (Tap & IfSet<AdditionalOptions>)} options tap name or full tap options
* @param {(...args: AsArray<T>) => Promise<R>} fn the function to register
* @returns {void}
*/
tapPromise(options, fn) {
this._tap("promise", options, fn);
}
/**
* @private
* @param {FullTap & IfSet<AdditionalOptions>} options the tap descriptor
* @returns {FullTap & IfSet<AdditionalOptions>} possibly transformed options
*/
_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;
}
/**
* @param {TapOptions & IfSet<AdditionalOptions>} options the options to merge into each tap
* @returns {Omit<this, "call" | "callAsync" | "promise">} a wrapper that pre-applies the options
*/
withOptions(options) {
/**
* @param {string | (TapOptions & IfSet<AdditionalOptions>)} opt options
* @returns {Tap & IfSet<AdditionalOptions>} merged options
*/
const mergeOptions = (opt) =>
/** @type {Tap & IfSet<AdditionalOptions>} */ (
Object.assign(
{},
options,
typeof opt === "string" ? { name: opt } : opt
)
);
return /** @type {Omit<this, "call" | "callAsync" | "promise">} */ ({
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))
});
}
/**
* @returns {boolean} true if the hook has any taps or interceptors registered
*/
isUsed() {
return this.taps.length > 0 || this.interceptors.length > 0;
}
/**
* @param {HookInterceptor<T, R, AdditionalOptions>} interceptor the interceptor to register
* @returns {void}
*/
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(
/** @type {FullTap & IfSet<AdditionalOptions>} */ (this.taps[i])
);
}
}
}
/**
* @private
* @returns {void}
*/
_resetCompilation() {
this.call = this._call;
this.callAsync = this._callAsync;
this.promise = this._promise;
}
/**
* @private
* @param {FullTap & IfSet<AdditionalOptions>} item the tap to insert into the ordered taps list
* @returns {void}
*/
_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;
}
}
/** @type {Set<string> | undefined} */
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;
+649
View File
@@ -0,0 +1,649 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */
/** @typedef {import("./Hook").EXPECTED_OBJECT} EXPECTED_OBJECT */
/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */
/** @typedef {import("./Hook").FullTap} FullTap */
/** @typedef {import("./Hook").CompileOptions<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>} CompileOptions */
/**
* @template T, R, AdditionalOptions
* @typedef {import("./Hook").HookInterceptor<T, R, AdditionalOptions>} HookInterceptor
*/
/**
* @template T, R, AdditionalOptions
* @typedef {import("./Hook")<T, R, AdditionalOptions>} Hook
*/
/**
* @typedef {(error: string) => string} OnErrorCallback
*/
/**
* @typedef {(result: string) => string} OnResultCallback
*/
/**
* @typedef {() => string} OnDoneCallback
*/
/**
* @typedef {object} ContentOptions
* @property {OnErrorCallback} onError generates code for handling an error
* @property {OnResultCallback} onResult generates code for handling a result
* @property {OnDoneCallback} onDone generates code for completion
* @property {boolean=} resultReturns true if the generated function returns a result
* @property {boolean=} doneReturns true if the generated function returns when done
* @property {boolean=} rethrowIfPossible true to rethrow errors when safe
*/
/**
* @typedef {object} CallTapOptions
* @property {OnErrorCallback} onError generates code for handling an error
* @property {OnResultCallback=} onResult generates code for handling a result
* @property {OnDoneCallback=} onDone generates code for completion
* @property {boolean=} rethrowIfPossible true to rethrow errors when safe
*/
/**
* @typedef {object} CallTapsOptions
* @property {((tapIndex: number, error: string, next: () => string, doneBreak: (skipDone: boolean) => string) => string)} onError generates code for handling an error
* @property {((tapIndex: number, result: string, next: () => string, doneBreak: (skipDone: boolean) => string) => string)=} onResult generates code for handling a result
* @property {OnDoneCallback} onDone generates code for completion
* @property {boolean=} rethrowIfPossible true to rethrow errors when safe
* @property {boolean=} doneReturns true if the generated function returns when done
* @property {boolean=} resultReturns true if the generated function returns a result
*/
/**
* @typedef {object} CallTapsParallelOptions
* @property {((tapIndex: number, error: string, next: () => string, doneBreak: (skipDone: boolean) => string) => string)} onError generates code for handling an error
* @property {((tapIndex: number, result: string, next: () => string, doneBreak: (skipDone: boolean) => string) => string)=} onResult generates code for handling a result
* @property {(tapIndex: number, run: () => string, done: () => string, doneBreak: (skipDone: boolean) => string) => string=} onTap options
* @property {OnDoneCallback=} onDone generates code for completion
* @property {boolean=} rethrowIfPossible true to rethrow errors when safe
*/
class HookCodeFactory {
constructor() {
/** @type {CompileOptions | undefined} */
this.options = undefined;
/** @type {string[] | undefined} */
this._args = undefined;
}
/**
* @param {CompileOptions} options compile options
* @returns {EXPECTED_FUNCTION} the compiled hook function
*/
create(options) {
this.init(options);
/** @type {EXPECTED_FUNCTION} */
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`,
onDone: () => "",
resultReturns: true,
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;
}
/**
* @param {Hook<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>} instance the hook instance to attach the resolved tap function array to
* @param {CompileOptions} options compile options containing the taps
* @returns {void}
*/
setup(instance, options) {
const { taps } = options;
const { length } = taps;
/** @type {EXPECTED_FUNCTION[]}} */
const fns = Array.from({ length });
for (let i = 0; i < length; i++) {
fns[i] = taps[i].fn;
}
instance._x = fns;
}
/**
* @param {CompileOptions} options compile options
* @returns {void}
*/
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 = /** @type {string[]} */ (
/** @type {unknown} */ (options.args)
);
/** @type {string | undefined} */
this._joinedArgs = undefined;
}
/**
* @returns {void}
*/
deinit() {
this.options = undefined;
this._args = undefined;
this._joinedArgs = undefined;
}
/**
* @param {ContentOptions} options content generation options
* @returns {string} generated code with interceptor calls wrapped around content
*/
contentWithInterceptors(options) {
if (/** @type {CompileOptions} */ (this.options).interceptors.length > 0) {
const { onError, onResult, onDone } = options;
let code = "";
const opts = /** @type {CompileOptions} */ (this.options);
for (let i = 0; i < opts.interceptors.length; i++) {
const interceptor = opts.interceptors[i];
if (interceptor.call) {
code += `${this.getInterceptor(i)}.call(${this.args({
before: interceptor.context ? "_context" : undefined
})});\n`;
}
}
// `content` is intentionally not declared on the base class - it's
// abstract and provided by every subclass. Skipping the runtime
// stub keeps the prototype chain mononomorphic on the hot compile
// path: subclass `content` is the only one V8 sees, no shadowing.
// @ts-expect-error abstract method, provided by subclasses for performance reasons
code += this.content(
Object.assign(options, {
onError:
onError &&
/** @type {OnErrorCallback} */
(
(err) => {
let code = "";
for (let i = 0; i < opts.interceptors.length; i++) {
const interceptor = opts.interceptors[i];
if (interceptor.error) {
code += `${this.getInterceptor(i)}.error(${err});\n`;
}
}
code += onError(err);
return code;
}
),
onResult:
onResult &&
/** @type {OnResultCallback} */
(
(result) => {
let code = "";
for (let i = 0; i < opts.interceptors.length; i++) {
const interceptor = opts.interceptors[i];
if (interceptor.result) {
code += `${this.getInterceptor(i)}.result(${result});\n`;
}
}
code += onResult(result);
return code;
}
),
onDone:
onDone &&
/** @type {OnDoneCallback} */
(
() => {
let code = "";
for (let i = 0; i < opts.interceptors.length; i++) {
const interceptor = opts.interceptors[i];
if (interceptor.done) {
code += `${this.getInterceptor(i)}.done();\n`;
}
}
code += onDone();
return code;
}
)
})
);
return code;
}
// @ts-expect-error abstract method, provided by subclasses for performance reasons
return this.content(options);
}
/**
* @returns {string} generated header preamble shared across all call types
*/
header() {
let code = "";
code += this.needContext() ? "var _context = {};\n" : "var _context;\n";
code += "var _x = this._x;\n";
if (/** @type {CompileOptions} */ (this.options).interceptors.length > 0) {
code += "var _taps = this.taps;\n";
code += "var _interceptors = this.interceptors;\n";
}
return code;
}
/**
* @returns {boolean} true if any tap requested a `_context`
*/
needContext() {
const { taps } = /** @type {CompileOptions} */ (this.options);
for (let i = 0; i < taps.length; i++) {
if (/** @type {{ context?: boolean }} */ (taps[i]).context) return true;
}
return false;
}
/**
* @param {number} tapIndex index of the tap to call
* @param {CallTapOptions} options content generation options
* @returns {string} generated code that invokes the tap
*/
callTap(tapIndex, { onError, onResult, onDone, rethrowIfPossible }) {
let code = "";
let hasTapCached = false;
const opts = /** @type {CompileOptions} */ (this.options);
for (let i = 0; i < opts.interceptors.length; i++) {
const interceptor = opts.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 =
/** @type {FullTap & { context?: boolean }} */
(opts.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;
}
/**
* @param {CallTapsOptions} options series-call options
* @returns {string} generated code calling all taps in series
*/
callTapsSeries({
onError,
onResult,
resultReturns,
onDone,
doneReturns,
rethrowIfPossible
}) {
const { taps } = /** @type {CompileOptions} */ (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.
/**
* @param {boolean} skipDone true when need to skip done, otherwise false
* @returns {string} code
*/
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 : undefined,
rethrowIfPossible:
rethrowIfPossible && (firstAsync < 0 || i < firstAsync)
});
current = () => content;
}
code += current();
return code;
}
/**
* @param {CallTapsOptions} options looping-call options
* @returns {string} generated code that calls taps in a loop
*/
callTapsLooping({ onError, onDone, rethrowIfPossible }) {
const opts = /** @type {CompileOptions} */ (this.options);
if (opts.taps.length === 0) return onDone();
const syncOnly = opts.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 < opts.interceptors.length; i++) {
const interceptor = opts.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;
}
/**
* @param {CallTapsParallelOptions} options parallel-call options
* @returns {string} generated code that calls all taps in parallel
*/
callTapsParallel({
onError,
onResult,
onDone,
rethrowIfPossible,
onTap = (i, run) => run()
}) {
const { taps } = /** @type {CompileOptions} */ (this.options);
const tapsLength = taps.length;
if (tapsLength <= 1) {
return this.callTapsSeries({
onError,
onResult,
// @ts-expect-error is it a bug?
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;";
};
/**
* @param {boolean} skipDone true when need to skip done, otherwise false
* @returns {string} code
*/
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() : undefined,
rethrowIfPossible
}),
done,
doneBreak
);
}
code += "} while(false);\n";
return code;
}
/**
* @param {{ before?: string, after?: string }=} options optional arguments to prepend or append
* @returns {string} comma-separated argument list as JS source
*/
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 =
/** @type {string[]} */ (this._args).length === 0
? ""
: /** @type {string[]} */ (this._args).join(", ");
this._joinedArgs = joined;
}
if (!before && !after) return joined;
if (joined.length === 0) {
if (before && after) return `${before}, ${after}`;
return /** @type {string} */ (before || after);
}
if (before && after) return `${before}, ${joined}, ${after}`;
if (before) return `${before}, ${joined}`;
return `${joined}, ${after}`;
}
/**
* @param {number} idx tap index
* @returns {string} JS expression that resolves to the registered tap function at index `idx`
*/
getTapFn(idx) {
return `_x[${idx}]`;
}
/**
* @param {number} idx tap index
* @returns {string} JS expression that resolves to the tap descriptor at index `idx`
*/
getTap(idx) {
return `_taps[${idx}]`;
}
/**
* @param {number} idx interceptor index
* @returns {string} JS expression that resolves to the interceptor at index `idx`
*/
getInterceptor(idx) {
return `_interceptors[${idx}]`;
}
}
module.exports = HookCodeFactory;
+120
View File
@@ -0,0 +1,120 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const util = require("util");
/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */
/**
* @template H
* @template [K=EXPECTED_ANY]
* @typedef {(key: K) => H} HookFactory
*/
/**
* @template H
* @template [K=EXPECTED_ANY]
* @typedef {object} HookMapInterceptor
* @property {((key: K, hook: H) => H)=} factory called when a hook is created for a new key
*/
/**
* @template H, K
* @param {K} key key passed through unchanged
* @param {H} hook hook returned unchanged
* @returns {H} the hook unchanged
*/
const defaultFactory = (key, hook) => hook;
/**
* @template H
*/
class HookMap {
/**
* @param {HookFactory<H>} factory factory creating new hooks for unknown keys
* @param {string=} name name of the hook map
*/
constructor(factory, name = undefined) {
/** @type {Map<EXPECTED_ANY, H>} */
this._map = new Map();
/** @type {string | undefined} */
this.name = name;
/** @type {HookFactory<H>} */
this._factory = factory;
/** @type {HookMapInterceptor<H>[]} */
this._interceptors = [];
}
/**
* @param {EXPECTED_ANY} key the key to look up
* @returns {H | undefined} the hook stored for `key`, if any
*/
get(key) {
return this._map.get(key);
}
/**
* @param {EXPECTED_ANY} key the key to look up or create
* @returns {H} the hook stored for `key`, creating one via the factory if missing
*/
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 =
/** @type {NonNullable<HookMapInterceptor<H>["factory"]>} */
(interceptors[i].factory)(key, newHook);
}
map.set(key, newHook);
return newHook;
}
/**
* @param {HookMapInterceptor<H>} interceptor the interceptor to register
* @returns {void}
*/
intercept(interceptor) {
this._interceptors.push(
Object.assign(
{
factory: defaultFactory
},
interceptor
)
);
}
}
HookMap.prototype.tap =
// @ts-expect-error deprecated
util.deprecate(function tap(key, options, fn) {
// @ts-expect-error deprecated
return this.for(key).tap(options, fn);
}, "HookMap#tap(key,…) is deprecated. Use HookMap#for(key).tap(…) instead.");
HookMap.prototype.tapAsync =
// @ts-expect-error deprecated
util.deprecate(function tapAsync(key, options, fn) {
// @ts-expect-error deprecated
return this.for(key).tapAsync(options, fn);
}, "HookMap#tapAsync(key,…) is deprecated. Use HookMap#for(key).tapAsync(…) instead.");
HookMap.prototype.tapPromise =
// @ts-expect-error deprecated
util.deprecate(function tapPromise(key, options, fn) {
// @ts-expect-error deprecated
return this.for(key).tapPromise(options, fn);
}, "HookMap#tapPromise(key,…) is deprecated. Use HookMap#for(key).tapPromise(…) instead.");
module.exports = HookMap;
+137
View File
@@ -0,0 +1,137 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */
/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */
/** @typedef {import("./Hook").Tap} Tap */
/** @typedef {import("./Hook").TapOptions} TapOptions */
/**
* @template T
* @typedef {import("./Hook").AsArray<T>} AsArray
*/
/**
* @template {EXPECTED_ANY[]} T
* @template U
* @typedef {import("./Hook").Append<T, U>} Append
*/
/**
* @template E, T
* @typedef {import("./Hook").InnerCallback<E, T>} InnerCallback
*/
/**
* @template T
* @template [R=void]
* @template [AdditionalOptions=object]
* @typedef {import("./Hook")<T, R, AdditionalOptions>} Hook
*/
/**
* @template T, R, AdditionalOptions
* @typedef {import("./Hook").HookInterceptor<T, R, AdditionalOptions>} HookInterceptor
*/
/**
* @template {Hook<EXPECTED_ANY>} H
*/
class MultiHook {
/**
* @param {H[]} hooks the underlying hooks to multiplex tap calls across
* @param {string=} name name of the multi hook
*/
constructor(hooks, name = undefined) {
/** @type {H[]} */
this.hooks = hooks;
/** @type {string | undefined} */
this.name = name;
}
/**
* @template T, R
* @param {string | Tap} options tap name or full tap options
* @param {(...args: AsArray<T>) => R} fn the function to register
* @returns {void}
*/
tap(options, fn) {
const { hooks } = this;
for (let i = 0; i < hooks.length; i++) {
hooks[i].tap(options, fn);
}
}
/**
* @template T, R
* @param {string | Tap} options tap name or full tap options
* @param {(...args: Append<AsArray<T>, InnerCallback<Error, R>>) => void} fn the function to register
* @returns {void}
*/
tapAsync(options, fn) {
const { hooks } = this;
for (let i = 0; i < hooks.length; i++) {
hooks[i].tapAsync(options, fn);
}
}
/**
* @template T, R
* @param {string | Tap} options tap name or full tap options
* @param {(...args: AsArray<T>) => Promise<R>} fn the function to register
* @returns {void}
*/
tapPromise(options, fn) {
const { hooks } = this;
for (let i = 0; i < hooks.length; i++) {
hooks[i].tapPromise(options, /** @type {EXPECTED_ANY} */ (fn));
}
}
/**
* @returns {boolean} true if any of the underlying hooks reports usage
*/
isUsed() {
const { hooks } = this;
for (let i = 0; i < hooks.length; i++) {
if (hooks[i].isUsed()) {
return true;
}
}
return false;
}
/**
* @param {HookInterceptor<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>} interceptor the interceptor to register
* @returns {void}
*/
intercept(interceptor) {
const { hooks } = this;
for (let i = 0; i < hooks.length; i++) {
hooks[i].intercept(interceptor);
}
}
/**
* @param {TapOptions} options the options to merge into each tap
* @returns {MultiHook<H>} a new MultiHook wrapping each underlying hook with the options
*/
withOptions(options) {
return /** @type {MultiHook<H>} */ (
new MultiHook(
this.hooks.map(
(hook) =>
/** @type {H} */ (
/** @type {unknown} */ (hook.withOptions(options))
)
),
this.name
)
);
}
}
module.exports = MultiHook;
+100
View File
@@ -0,0 +1,100 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Hook = require("./Hook");
const HookCodeFactory = require("./HookCodeFactory");
/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */
/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */
/** @typedef {import("./Hook").UnsetAdditionalOptions} UnsetAdditionalOptions */
/** @typedef {import("./Hook").CompileOptions<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>} CompileOptions */
/** @typedef {import("./HookCodeFactory").ContentOptions} ContentOptions */
/**
* @template T
* @typedef {import("./Hook").AsArray<T>} AsArray
*/
/**
* @template {EXPECTED_ANY[]} T
* @typedef {import("./Hook").ArgumentNames<T>} ArgumentNames
*/
/**
* Mirror of the `SyncBailHook` class declared in `tapable.d.ts` for use as
* the factory function's return type, so `new SyncBailHook(...)` resolves to
* the specific subclass type instead of the generic `Hook`.
* @template T
* @template R
* @template [AdditionalOptions=UnsetAdditionalOptions]
* @typedef {import("../tapable").SyncBailHook<T, R, AdditionalOptions>} SyncBailHookType
*/
class SyncBailHookCodeFactory extends HookCodeFactory {
/**
* @param {ContentOptions} options content generation options
* @returns {string} generated body code
*/
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");
};
/**
* @this {Hook<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>}
* @param {CompileOptions} options compile options
* @returns {EXPECTED_FUNCTION} the compiled call function
*/
function COMPILE(options) {
factory.setup(this, options);
return factory.create(options);
}
/**
* @constructor
* @template T
* @template R
* @template [AdditionalOptions=UnsetAdditionalOptions]
* @param {ArgumentNames<AsArray<T>>=} args argument names of the hook
* @param {string=} name name of the hook
* @returns {SyncBailHookType<T, R, AdditionalOptions>} a new SyncBailHook instance
*/
function SyncBailHook(
args = /** @type {ArgumentNames<AsArray<T>>} */ (/** @type {unknown} */ ([])),
name = undefined
) {
const hook = new Hook(args, name);
hook.constructor = SyncBailHook;
hook.tapAsync = TAP_ASYNC;
hook.tapPromise = TAP_PROMISE;
hook.compile = COMPILE;
return /** @type {SyncBailHookType<T, R, AdditionalOptions>} */ (
/** @type {unknown} */ (hook)
);
}
/** @type {EXPECTED_ANY} */
SyncBailHook.prototype = null;
module.exports = SyncBailHook;
+95
View File
@@ -0,0 +1,95 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Hook = require("./Hook");
const HookCodeFactory = require("./HookCodeFactory");
/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */
/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */
/** @typedef {import("./Hook").UnsetAdditionalOptions} UnsetAdditionalOptions */
/** @typedef {import("./Hook").CompileOptions<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>} CompileOptions */
/** @typedef {import("./HookCodeFactory").ContentOptions} ContentOptions */
/**
* @template T
* @typedef {import("./Hook").AsArray<T>} AsArray
*/
/**
* @template {EXPECTED_ANY[]} T
* @typedef {import("./Hook").ArgumentNames<T>} ArgumentNames
*/
/**
* Mirror of the `SyncHook` class declared in `tapable.d.ts` for use as the
* factory function's return type, so `new SyncHook(...)` resolves to the
* specific subclass type instead of the generic `Hook`.
* @template T
* @template [R=void]
* @template [AdditionalOptions=UnsetAdditionalOptions]
* @typedef {import("../tapable").SyncHook<T, R, AdditionalOptions>} SyncHookType
*/
class SyncHookCodeFactory extends HookCodeFactory {
/**
* @param {ContentOptions} options content generation options
* @returns {string} generated body code
*/
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");
};
/**
* @this {Hook<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>}
* @param {CompileOptions} options compile options
* @returns {EXPECTED_FUNCTION} the compiled call function
*/
function COMPILE(options) {
factory.setup(this, options);
return factory.create(options);
}
/**
* @constructor
* @template T
* @template [R=void]
* @template [AdditionalOptions=UnsetAdditionalOptions]
* @param {ArgumentNames<AsArray<T>>=} args argument names of the hook
* @param {string=} name name of the hook
* @returns {SyncHookType<T, R, AdditionalOptions>} a new SyncHook instance
*/
function SyncHook(
args = /** @type {ArgumentNames<AsArray<T>>} */ (/** @type {unknown} */ ([])),
name = undefined
) {
const hook = new Hook(args, name);
hook.constructor = SyncHook;
hook.tapAsync = TAP_ASYNC;
hook.tapPromise = TAP_PROMISE;
hook.compile = COMPILE;
return /** @type {SyncHookType<T, R, AdditionalOptions>} */ (
/** @type {unknown} */ (hook)
);
}
/** @type {EXPECTED_ANY} */
SyncHook.prototype = null;
module.exports = SyncHook;
+92
View File
@@ -0,0 +1,92 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Hook = require("./Hook");
const HookCodeFactory = require("./HookCodeFactory");
/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */
/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */
/** @typedef {import("./Hook").CompileOptions<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>} CompileOptions */
/** @typedef {import("./Hook").UnsetAdditionalOptions} UnsetAdditionalOptions */
/** @typedef {import("./HookCodeFactory").ContentOptions} ContentOptions */
/**
* @template T
* @typedef {import("./Hook").AsArray<T>} AsArray
*/
/**
* @template {EXPECTED_ANY[]} T
* @typedef {import("./Hook").ArgumentNames<T>} ArgumentNames
*/
/**
* Mirror of the `SyncLoopHook` class declared in `tapable.d.ts` for use as
* the factory function's return type, so `new SyncLoopHook(...)` resolves
* to the specific subclass type instead of the generic `Hook`.
* @template T
* @template [AdditionalOptions=UnsetAdditionalOptions]
* @typedef {import("../tapable").SyncLoopHook<T, AdditionalOptions>} SyncLoopHookType
*/
class SyncLoopHookCodeFactory extends HookCodeFactory {
/**
* @param {ContentOptions} options content generation options
* @returns {string} generated body code
*/
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");
};
/**
* @this {Hook<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>}
* @param {CompileOptions} options compile options
* @returns {EXPECTED_FUNCTION} the compiled call function
*/
function COMPILE(options) {
factory.setup(this, options);
return factory.create(options);
}
/**
* @constructor
* @template T
* @template [AdditionalOptions=UnsetAdditionalOptions]
* @param {ArgumentNames<AsArray<T>>=} args argument names of the hook
* @param {string=} name name of the hook
* @returns {SyncLoopHookType<T, AdditionalOptions>} a new SyncLoopHook instance
*/
function SyncLoopHook(
args = /** @type {ArgumentNames<AsArray<T>>} */ (/** @type {unknown} */ ([])),
name = undefined
) {
const hook = new Hook(args, name);
hook.constructor = SyncLoopHook;
hook.tapAsync = TAP_ASYNC;
hook.tapPromise = TAP_PROMISE;
hook.compile = COMPILE;
return /** @type {SyncLoopHookType<T, AdditionalOptions>} */ (
/** @type {unknown} */ (hook)
);
}
/** @type {EXPECTED_ANY} */
SyncLoopHook.prototype = null;
module.exports = SyncLoopHook;
+106
View File
@@ -0,0 +1,106 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Hook = require("./Hook");
const HookCodeFactory = require("./HookCodeFactory");
/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */
/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */
/** @typedef {import("./Hook").CompileOptions<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>} CompileOptions */
/** @typedef {import("./Hook").UnsetAdditionalOptions} UnsetAdditionalOptions */
/** @typedef {import("./HookCodeFactory").ContentOptions} ContentOptions */
/**
* @template T
* @typedef {import("./Hook").AsArray<T>} AsArray
*/
/**
* @template {EXPECTED_ANY[]} T
* @typedef {import("./Hook").ArgumentNames<T>} ArgumentNames
*/
/**
* Mirror of the `SyncWaterfallHook` class declared in `tapable.d.ts` for use
* as the factory function's return type, so `new SyncWaterfallHook(...)`
* resolves to the specific subclass type instead of the generic `Hook`.
* @template T
* @template [R=AsArray<T>[0]]
* @template [AdditionalOptions=UnsetAdditionalOptions]
* @typedef {import("../tapable").SyncWaterfallHook<T, R, AdditionalOptions>} SyncWaterfallHookType
*/
class SyncWaterfallHookCodeFactory extends HookCodeFactory {
/**
* @param {ContentOptions} options content generation options
* @returns {string} generated body code
*/
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 += `${/** @type {string[]} */ (this._args)[0]} = ${result};\n`;
code += "}\n";
code += next();
return code;
},
onDone: () => onResult(/** @type {string[]} */ (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");
};
/**
* @this {Hook<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>}
* @param {CompileOptions} options compile options
* @returns {EXPECTED_FUNCTION} the compiled call function
*/
function COMPILE(options) {
factory.setup(this, options);
return factory.create(options);
}
/**
* @constructor
* @template T
* @template [R=AsArray<T>[0]]
* @template [AdditionalOptions=UnsetAdditionalOptions]
* @param {ArgumentNames<AsArray<T>>=} args argument names of the hook
* @param {string=} name name of the hook
* @returns {SyncWaterfallHookType<T, R, AdditionalOptions>} a new SyncWaterfallHook instance
*/
function SyncWaterfallHook(
args = /** @type {ArgumentNames<AsArray<T>>} */ (/** @type {unknown} */ ([])),
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 /** @type {SyncWaterfallHookType<T, R, AdditionalOptions>} */ (
/** @type {unknown} */ (hook)
);
}
/** @type {EXPECTED_ANY} */
SyncWaterfallHook.prototype = null;
module.exports = SyncWaterfallHook;
+19
View File
@@ -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;
+28
View File
@@ -0,0 +1,28 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */
/**
* Browser shim for `util.deprecate`. Logs the deprecation message once on the
* first call, then forwards arguments to `fn`.
* @param {EXPECTED_FUNCTION} fn the function to wrap
* @param {string} msg the deprecation message
* @returns {EXPECTED_FUNCTION} the wrapped function
*/
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;
}
// @ts-expect-error expected
// eslint-disable-next-line prefer-rest-params
return fn.apply(this, arguments);
};
};
+67
View File
@@ -0,0 +1,67 @@
{
"name": "tapable",
"version": "2.3.4",
"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 lint:types && npm run fmt:check",
"lint:types": "tsc --pretty --noEmit",
"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": "^3.0.3",
"@changesets/get-github-info": "^1.0.1",
"@codspeed/core": "^6.1.1",
"@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",
"typescript": "^6.0.3"
},
"engines": {
"node": ">=6"
}
}
+175
View File
@@ -0,0 +1,175 @@
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: AsArray<T>) => void;
loop?: (...args: AsArray<T>) => 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;
}
/**
* A `HookMap` whose keys are typed: each key `K` of `M` maps to the hook `M[K]`.
* It is a type only, for annotating a `HookMap`; create one with `new HookMap()`.
*/
export interface TypedHookMap<M extends object> {
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;
}