@hyperttp/interceptors 1.1.5 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -1
- package/index.js +2 -3
- package/index.js.map +7 -1
- package/package.json +2 -2
- package/plugin.d.ts +4 -25
- package/plugin.d.ts.map +1 -1
- package/plugin.js +2 -56
- package/plugin.js.map +7 -1
- package/types/interceptors.d.ts +5 -31
- package/types/interceptors.d.ts.map +1 -1
- package/types/interceptors.js +2 -2
- package/types/interceptors.js.map +7 -1
- package/utils/InterceptorManager.d.ts +4 -72
- package/utils/InterceptorManager.d.ts.map +1 -1
- package/utils/InterceptorManager.js +2 -141
- package/utils/InterceptorManager.js.map +7 -1
package/README.md
CHANGED
|
@@ -1 +1,38 @@
|
|
|
1
|
-
# hyperttp
|
|
1
|
+
# @hyperttp/interceptors
|
|
2
|
+
|
|
3
|
+
> English | [Русский](https://github.com/IT-IF-OR/hyperttp-interceptors/tree/main/lang/ru)
|
|
4
|
+
|
|
5
|
+
Request and response interceptor plugin for Hyperttp.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- Runs user-defined handlers around the Core v2 request lifecycle.
|
|
10
|
+
- Supports request, response, and error interception.
|
|
11
|
+
- Uses protocol-neutral `SendRequest`, `UniversalResponse`, and `RequestContext` values.
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install @hyperttp/interceptors
|
|
17
|
+
# or
|
|
18
|
+
bun add @hyperttp/interceptors
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Usage
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { HyperClient } from "hyperttp";
|
|
25
|
+
import { withInterceptors } from "@hyperttp/interceptors";
|
|
26
|
+
|
|
27
|
+
const client = new HyperClient({
|
|
28
|
+
plugins: [withInterceptors({
|
|
29
|
+
onRequest: (request) => request,
|
|
30
|
+
})],
|
|
31
|
+
});
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
See the exported `InterceptorsOptions` type for available lifecycle callbacks.
|
|
35
|
+
|
|
36
|
+
## License
|
|
37
|
+
|
|
38
|
+
MIT © dirold2
|
package/index.js
CHANGED
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
export
|
|
2
|
-
|
|
3
|
-
//# sourceMappingURL=index.js.map
|
|
1
|
+
"use strict";export{withInterceptors}from"./plugin.js";export*from"./utils/InterceptorManager.js";
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
package/index.js.map
CHANGED
|
@@ -1 +1,7 @@
|
|
|
1
|
-
{
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/index.ts"],
|
|
4
|
+
"sourcesContent": ["export { withInterceptors } from \"./plugin.js\";\nexport * from \"./utils/InterceptorManager.js\";\nexport type * from \"./types/interceptors.js\";\n"],
|
|
5
|
+
"mappings": "aAAA,OAAS,qBAAwB,cACjC,WAAc",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hyperttp/interceptors",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "3.0.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./index.js",
|
|
6
6
|
"types": "./index.d.ts",
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
"url": "git+https://github.com/IT-IF-OR/hyperttp-interceptors.git"
|
|
23
23
|
},
|
|
24
24
|
"peerDependencies": {
|
|
25
|
-
"@hyperttp/types": "^0.
|
|
25
|
+
"@hyperttp/types": "^0.5.0"
|
|
26
26
|
},
|
|
27
27
|
"private": false
|
|
28
28
|
}
|
package/plugin.d.ts
CHANGED
|
@@ -1,34 +1,13 @@
|
|
|
1
1
|
import type { HyperPlugin } from "@hyperttp/types";
|
|
2
2
|
import { InterceptorManager } from "./utils/InterceptorManager.js";
|
|
3
3
|
import type { InterceptorOptions } from "./types/interceptors.js";
|
|
4
|
-
/**
|
|
5
|
-
* @en Extends PluginContext to include the interceptor manager instance.
|
|
6
|
-
* @ru Расширяет PluginContext, добавляя экземпляр менеджера интерцепторов.
|
|
7
|
-
*/
|
|
8
4
|
declare module "@hyperttp/types" {
|
|
5
|
+
interface HyperClientOptions {
|
|
6
|
+
interceptors?: InterceptorOptions;
|
|
7
|
+
}
|
|
9
8
|
interface PluginContext {
|
|
10
|
-
/**
|
|
11
|
-
* @en The active interceptor manager instance.
|
|
12
|
-
* @ru Активный экземпляр менеджера интерцепторов.
|
|
13
|
-
*/
|
|
14
9
|
interceptors?: InterceptorManager;
|
|
15
10
|
}
|
|
16
|
-
/**
|
|
17
|
-
* @en Extends HttpClientOptions to include interceptor configuration.
|
|
18
|
-
* @ru Расширяет HttpClientOptions, добавляя конфигурацию интерцепторов.
|
|
19
|
-
*/
|
|
20
|
-
interface HttpClientOptions {
|
|
21
|
-
/**
|
|
22
|
-
* @en Interceptor plugin configuration options.
|
|
23
|
-
* @ru Опции конфигурации плагина интерцепторов.
|
|
24
|
-
*/
|
|
25
|
-
interceptors?: InterceptorOptions;
|
|
26
|
-
}
|
|
27
11
|
}
|
|
28
|
-
|
|
29
|
-
* @en Plugin for integrating custom request and response interceptors (Axios-like Interceptors).
|
|
30
|
-
* @ru Плагин для интеграции кастомных интерцепторов запросов и ответов (Axios-like Interceptors).
|
|
31
|
-
* @returns HyperPlugin object instance.
|
|
32
|
-
*/
|
|
33
|
-
export declare function withInterceptors(): HyperPlugin;
|
|
12
|
+
export declare function withInterceptors(options?: InterceptorOptions): HyperPlugin;
|
|
34
13
|
//# sourceMappingURL=plugin.d.ts.map
|
package/plugin.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,
|
|
1
|
+
{"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EAMZ,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,KAAK,EACV,kBAAkB,EAGnB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,QAAQ,iBAAiB,CAAC;IAC/B,UAAU,kBAAkB;QAC1B,YAAY,CAAC,EAAE,kBAAkB,CAAC;KACnC;IAED,UAAU,aAAa;QACrB,YAAY,CAAC,EAAE,kBAAkB,CAAC;KACnC;CACF;AAOD,wBAAgB,gBAAgB,CAAC,OAAO,CAAC,EAAE,kBAAkB,GAAG,WAAW,CA+C1E"}
|
package/plugin.js
CHANGED
|
@@ -1,56 +1,2 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
* @en Plugin for integrating custom request and response interceptors (Axios-like Interceptors).
|
|
4
|
-
* @ru Плагин для интеграции кастомных интерцепторов запросов и ответов (Axios-like Interceptors).
|
|
5
|
-
* @returns HyperPlugin object instance.
|
|
6
|
-
*/
|
|
7
|
-
export function withInterceptors() {
|
|
8
|
-
let manager;
|
|
9
|
-
return {
|
|
10
|
-
name: "hyperttp-interceptors",
|
|
11
|
-
/**
|
|
12
|
-
* @en Evaluates plugin activation based on the provided client configuration.
|
|
13
|
-
* @ru Проверяет активацию плагина на основе переданной конфигурации.
|
|
14
|
-
* @param config - The current client configuration.
|
|
15
|
-
* @returns True if interceptors are enabled.
|
|
16
|
-
*/
|
|
17
|
-
enabled: (config) => !!config.interceptors?.enabled,
|
|
18
|
-
/**
|
|
19
|
-
* @en Initialization hook. Creates the interceptor manager and registers it within the core context.
|
|
20
|
-
* @ru Хук инициализации. Создает менеджер интерцепторов и регистрирует его в контексте ядра.
|
|
21
|
-
* @param ctx - Shared plugin orchestration context.
|
|
22
|
-
*/
|
|
23
|
-
setup(ctx) {
|
|
24
|
-
manager = new InterceptorManager();
|
|
25
|
-
ctx.interceptors = manager;
|
|
26
|
-
},
|
|
27
|
-
/**
|
|
28
|
-
* @en Request phase interceptor hook. Sequentially applies all registered interceptors to the request configuration.
|
|
29
|
-
* @ru Перехватчик фазы запроса. Последовательно применяет все зарегистрированные интерцепторы к конфигурации запроса.
|
|
30
|
-
* @param req - Contextual internal request parameters.
|
|
31
|
-
*/
|
|
32
|
-
async onRequest(req) {
|
|
33
|
-
if (!manager.hasRequest)
|
|
34
|
-
return;
|
|
35
|
-
const reqResult = await manager.applyRequest(req);
|
|
36
|
-
if (reqResult) {
|
|
37
|
-
Object.assign(req, reqResult);
|
|
38
|
-
}
|
|
39
|
-
},
|
|
40
|
-
/**
|
|
41
|
-
* @en Response phase interceptor hook. Passes the response object through the chain of custom modification interceptors.
|
|
42
|
-
* @ru Перехватчик фазы успешного ответа. Пропускает объект ответа через цепочку пользовательских интерцепторов модификации.
|
|
43
|
-
* @param res - Output HTTP client response reference.
|
|
44
|
-
* @param req - Contextual internal request parameters.
|
|
45
|
-
*/
|
|
46
|
-
async onResponse(res) {
|
|
47
|
-
if (!manager.hasResponse)
|
|
48
|
-
return;
|
|
49
|
-
const resResult = await manager.applyResponse(res);
|
|
50
|
-
if (resResult) {
|
|
51
|
-
Object.assign(res, resResult);
|
|
52
|
-
}
|
|
53
|
-
},
|
|
54
|
-
};
|
|
55
|
-
}
|
|
56
|
-
//# sourceMappingURL=plugin.js.map
|
|
1
|
+
"use strict";import{InterceptorManager as d}from"./utils/InterceptorManager.js";function o(n,a){n&&(Array.isArray(n)?n:[n]).forEach(a)}export function withInterceptors(n){let a;return{name:"hyperttp-interceptors",enabled:s=>s.interceptors?.enabled??n?.enabled??(s.interceptors!==void 0||n!==void 0),setup(s){const e=new d;a=e;const t=s.config.interceptors;o(n?.request,r=>e.addRequest(r)),o(n?.response,r=>e.addResponse(r)),o(t?.request,r=>e.addRequest(r)),o(t?.response,r=>e.addResponse(r)),s.interceptors=e},async onRequest(s,e,t){const r=e?e.interceptors:a;if(r?.hasRequest)return r.applyRequest(s,e,t)},async onResponse(s,e,t,r){const p=t?t.interceptors:a;if(p?.hasResponse)return p.applyResponse(s,e,t,r)}}}
|
|
2
|
+
//# sourceMappingURL=plugin.js.map
|
package/plugin.js.map
CHANGED
|
@@ -1 +1,7 @@
|
|
|
1
|
-
{
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/plugin.ts"],
|
|
4
|
+
"sourcesContent": ["import type {\n HyperPlugin,\n HyperClientOptions,\n UniversalResponse,\n PluginContext,\n SendRequest,\n RequestContext,\n} from \"@hyperttp/types\";\nimport { InterceptorManager } from \"./utils/InterceptorManager.js\";\nimport type {\n InterceptorOptions,\n RequestInterceptor,\n ResponseInterceptor,\n} from \"./types/interceptors.js\";\n\ndeclare module \"@hyperttp/types\" {\n interface HyperClientOptions {\n interceptors?: InterceptorOptions;\n }\n\n interface PluginContext {\n interceptors?: InterceptorManager;\n }\n}\n\nfunction register<T>(value: T | readonly T[] | undefined, add: (interceptor: T) => void): void {\n if (!value) return;\n (Array.isArray(value) ? value : [value]).forEach(add);\n}\n\nexport function withInterceptors(options?: InterceptorOptions): HyperPlugin {\n let fallbackManager: InterceptorManager | undefined;\n\n return {\n name: \"hyperttp-interceptors\",\n enabled: (config: HyperClientOptions): boolean =>\n config.interceptors?.enabled ??\n options?.enabled ??\n (config.interceptors !== undefined || options !== undefined),\n setup(ctx: PluginContext): void {\n const manager = new InterceptorManager();\n fallbackManager = manager;\n const configured = ctx.config.interceptors;\n register<RequestInterceptor>(options?.request, (interceptor) =>\n manager.addRequest(interceptor),\n );\n register<ResponseInterceptor>(options?.response, (interceptor) =>\n manager.addResponse(interceptor),\n );\n register<RequestInterceptor>(configured?.request, (interceptor) =>\n manager.addRequest(interceptor),\n );\n register<ResponseInterceptor>(configured?.response, (interceptor) =>\n manager.addResponse(interceptor),\n );\n ctx.interceptors = manager;\n },\n async onRequest(\n req: SendRequest,\n ctx?: PluginContext,\n reqCtx?: RequestContext,\n ): Promise<SendRequest | void> {\n const manager = ctx ? ctx.interceptors : fallbackManager;\n if (!manager?.hasRequest) return;\n return manager.applyRequest(req, ctx, reqCtx);\n },\n async onResponse(\n res: UniversalResponse,\n req?: SendRequest,\n ctx?: PluginContext,\n reqCtx?: RequestContext,\n ): Promise<UniversalResponse | void> {\n const manager = ctx ? ctx.interceptors : fallbackManager;\n if (!manager?.hasResponse) return;\n return manager.applyResponse(res, req, ctx, reqCtx);\n },\n };\n}\n"],
|
|
5
|
+
"mappings": "aAQA,OAAS,sBAAAA,MAA0B,gCAiBnC,SAASC,EAAYC,EAAqCC,EAA6B,CAChFD,IACJ,MAAM,QAAQA,CAAK,EAAIA,EAAQ,CAACA,CAAK,GAAG,QAAQC,CAAG,CACtD,CAEM,gBAAU,iBAAiBC,EAA4B,CAC3D,IAAIC,EAEJ,MAAO,CACL,KAAM,wBACN,QAAUC,GACRA,EAAO,cAAc,SACrBF,GAAS,UACRE,EAAO,eAAiB,QAAaF,IAAY,QACpD,MAAMG,EAAkB,CACtB,MAAMC,EAAU,IAAIR,EACpBK,EAAkBG,EAClB,MAAMC,EAAaF,EAAI,OAAO,aAC9BN,EAA6BG,GAAS,QAAUM,GAC9CF,EAAQ,WAAWE,CAAW,CAAC,EAEjCT,EAA8BG,GAAS,SAAWM,GAChDF,EAAQ,YAAYE,CAAW,CAAC,EAElCT,EAA6BQ,GAAY,QAAUC,GACjDF,EAAQ,WAAWE,CAAW,CAAC,EAEjCT,EAA8BQ,GAAY,SAAWC,GACnDF,EAAQ,YAAYE,CAAW,CAAC,EAElCH,EAAI,aAAeC,CACrB,EACA,MAAM,UACJG,EACAJ,EACAK,EAAuB,CAEvB,MAAMJ,EAAUD,EAAMA,EAAI,aAAeF,EACzC,GAAKG,GAAS,WACd,OAAOA,EAAQ,aAAaG,EAAKJ,EAAKK,CAAM,CAC9C,EACA,MAAM,WACJC,EACAF,EACAJ,EACAK,EAAuB,CAEvB,MAAMJ,EAAUD,EAAMA,EAAI,aAAeF,EACzC,GAAKG,GAAS,YACd,OAAOA,EAAQ,cAAcK,EAAKF,EAAKJ,EAAKK,CAAM,CACpD,EAEJ",
|
|
6
|
+
"names": ["InterceptorManager", "register", "value", "add", "options", "fallbackManager", "config", "ctx", "manager", "configured", "interceptor", "req", "reqCtx", "res"]
|
|
7
|
+
}
|
package/types/interceptors.d.ts
CHANGED
|
@@ -1,35 +1,9 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
/**
|
|
3
|
-
* @en Configuration options for the interceptors plugin.
|
|
4
|
-
* @ru Опции конфигурации для плагина интерцепторов.
|
|
5
|
-
*/
|
|
1
|
+
import type { PluginContext, RequestContext, SendRequest, UniversalResponse } from "@hyperttp/types";
|
|
6
2
|
export interface InterceptorOptions {
|
|
7
|
-
/**
|
|
8
|
-
* @en Enable interceptor processing for the client.
|
|
9
|
-
* @ru Включить обработку интерцепторов для клиента.
|
|
10
|
-
*/
|
|
11
3
|
enabled?: boolean;
|
|
4
|
+
request?: RequestInterceptor | readonly RequestInterceptor[];
|
|
5
|
+
response?: ResponseInterceptor | readonly ResponseInterceptor[];
|
|
12
6
|
}
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
* Accepts the core internal request object. Can return a modified configuration
|
|
16
|
-
* or `void` (if modifications are applied directly to the passed object reference).
|
|
17
|
-
* @ru Перехватчик запроса.
|
|
18
|
-
* Принимает внутренний объект запроса ядра. Может вернуть модифицированный объект
|
|
19
|
-
* или `void` (если изменения вносятся напрямую в переданный объект по ссылке).
|
|
20
|
-
* @param config - The internal request configuration.
|
|
21
|
-
* @returns A modified request object, void, or a Promise resolving to either.
|
|
22
|
-
*/
|
|
23
|
-
export type RequestInterceptor = (config: InternalRequest) => InternalRequest | void | Promise<InternalRequest | void>;
|
|
24
|
-
/**
|
|
25
|
-
* @en Response interceptor function signature.
|
|
26
|
-
* Accepts a response object with any body layout (`HttpResponse<any>`). Can return
|
|
27
|
-
* a transformed response container or `void` (if the object is mutated in-place).
|
|
28
|
-
* @ru Перехватчик ответа.
|
|
29
|
-
* Принимает объект ответа с любым типом тела (`HttpResponse<any>`). Может вернуть
|
|
30
|
-
* трансформированный объект ответа или `void` (если объект мутирует по ссылке).
|
|
31
|
-
* @param response - The HTTP response object.
|
|
32
|
-
* @returns A modified response object, void, or a Promise resolving to either.
|
|
33
|
-
*/
|
|
34
|
-
export type ResponseInterceptor = (response: HttpResponse<any>) => HttpResponse<any> | void | Promise<HttpResponse<any> | void>;
|
|
7
|
+
export type RequestInterceptor = (request: SendRequest, context?: PluginContext, requestContext?: RequestContext) => SendRequest | void | Promise<SendRequest | void>;
|
|
8
|
+
export type ResponseInterceptor = (response: UniversalResponse, request?: SendRequest, context?: PluginContext, requestContext?: RequestContext) => UniversalResponse | void | Promise<UniversalResponse | void>;
|
|
35
9
|
//# sourceMappingURL=interceptors.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interceptors.d.ts","sourceRoot":"","sources":["../../src/types/interceptors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"interceptors.d.ts","sourceRoot":"","sources":["../../src/types/interceptors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,aAAa,EACb,cAAc,EACd,WAAW,EACX,iBAAiB,EAClB,MAAM,iBAAiB,CAAC;AAEzB,MAAM,WAAW,kBAAkB;IACjC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,OAAO,CAAC,EAAE,kBAAkB,GAAG,SAAS,kBAAkB,EAAE,CAAC;IAC7D,QAAQ,CAAC,EAAE,mBAAmB,GAAG,SAAS,mBAAmB,EAAE,CAAC;CACjE;AAED,MAAM,MAAM,kBAAkB,GAAG,CAC/B,OAAO,EAAE,WAAW,EACpB,OAAO,CAAC,EAAE,aAAa,EACvB,cAAc,CAAC,EAAE,cAAc,KAC5B,WAAW,GAAG,IAAI,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CAAC;AAEtD,MAAM,MAAM,mBAAmB,GAAG,CAChC,QAAQ,EAAE,iBAAiB,EAC3B,OAAO,CAAC,EAAE,WAAW,EACrB,OAAO,CAAC,EAAE,aAAa,EACvB,cAAc,CAAC,EAAE,cAAc,KAC5B,iBAAiB,GAAG,IAAI,GAAG,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC,CAAC"}
|
package/types/interceptors.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export
|
|
2
|
-
//# sourceMappingURL=interceptors.js.map
|
|
1
|
+
"use strict";export{};
|
|
2
|
+
//# sourceMappingURL=interceptors.js.map
|
|
@@ -1 +1,7 @@
|
|
|
1
|
-
{
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["interceptors.js"],
|
|
4
|
+
"sourcesContent": ["export {};\n//# sourceMappingURL=interceptors.js.map"],
|
|
5
|
+
"mappings": "aAAA",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -1,84 +1,16 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { RequestInterceptor, ResponseInterceptor } from "../types/interceptors.js";
|
|
3
|
-
/**
|
|
4
|
-
* @en Interceptor manager for pipeline execution of requests and responses.
|
|
5
|
-
* Uses a hybrid loop (fast-path): runs synchronously until a Promise is encountered.
|
|
6
|
-
* @ru Менеджер перехватчиков (интерцепторов) для сквозной обработки запросов и ответов.
|
|
7
|
-
* Использует гибридный цикл (fast-path): выполняется синхронно до тех пор, пока не встретит Promise.
|
|
8
|
-
*/
|
|
1
|
+
import type { PluginContext, RequestContext, SendRequest, UniversalResponse } from "@hyperttp/types";
|
|
2
|
+
import type { RequestInterceptor, ResponseInterceptor } from "../types/interceptors.js";
|
|
9
3
|
export declare class InterceptorManager {
|
|
10
|
-
/**
|
|
11
|
-
* @en Array of registered request interceptors.
|
|
12
|
-
* @ru Массив зарегистрированных перехватчиков запроса.
|
|
13
|
-
* @private
|
|
14
|
-
*/
|
|
15
4
|
private requestInterceptors;
|
|
16
|
-
/**
|
|
17
|
-
* @en Array of registered response interceptors.
|
|
18
|
-
* @ru Массив зарегистрированных перехватчиков ответа.
|
|
19
|
-
* @private
|
|
20
|
-
*/
|
|
21
5
|
private responseInterceptors;
|
|
22
|
-
/**
|
|
23
|
-
* @en Flag indicating presence of active request interceptors for fast branch short-circuiting.
|
|
24
|
-
* @ru Флаг наличия активных перехватчиков запроса для быстрого ветвления.
|
|
25
|
-
*/
|
|
26
6
|
hasRequest: boolean;
|
|
27
|
-
/**
|
|
28
|
-
* @en Flag indicating presence of active response interceptors for fast branch short-circuiting.
|
|
29
|
-
* @ru Флаг наличия активных перехватчиков ответа для быстрого ветвления.
|
|
30
|
-
*/
|
|
31
7
|
hasResponse: boolean;
|
|
32
|
-
/**
|
|
33
|
-
* @en Registers a new request interceptor in the pipeline.
|
|
34
|
-
* @ru Регистрирует новый перехватчик запроса в конвейере.
|
|
35
|
-
* @param interceptor - Target request interceptor function.
|
|
36
|
-
*/
|
|
37
8
|
addRequest(interceptor: RequestInterceptor): void;
|
|
38
|
-
/**
|
|
39
|
-
* @en Registers a new response interceptor in the pipeline.
|
|
40
|
-
* @ru Регистрирует новый перехватчик ответа в конвейере.
|
|
41
|
-
* @param interceptor - Target response interceptor function.
|
|
42
|
-
*/
|
|
43
9
|
addResponse(interceptor: ResponseInterceptor): void;
|
|
44
|
-
|
|
45
|
-
* @en Sequentially applies the chain of interceptors to the request configuration.
|
|
46
|
-
* @ru Последовательно применяет цепочку перехватчиков к конфигурации запроса.
|
|
47
|
-
* @param config - Initial internal request configuration object.
|
|
48
|
-
* @returns Modified configuration or a Promise resolving to it.
|
|
49
|
-
*/
|
|
50
|
-
applyRequest(config: InternalRequest): InternalRequest | Promise<InternalRequest>;
|
|
51
|
-
/**
|
|
52
|
-
* @en Asynchronous fallback to process the remaining request chain after encountering a Promise.
|
|
53
|
-
* @ru Асинхронный фолбек для обработки оставшейся цепочки запросов после обнаружения Promise.
|
|
54
|
-
* @param startIndex - Index of the interceptor that returned a Promise.
|
|
55
|
-
* @param currentPromise - The pending Promise from the current interceptor step.
|
|
56
|
-
* @param currentResult - Cumulative configuration result before the Promise step.
|
|
57
|
-
* @private
|
|
58
|
-
*/
|
|
10
|
+
applyRequest(request: SendRequest, context?: PluginContext, requestContext?: RequestContext): SendRequest | Promise<SendRequest>;
|
|
59
11
|
private applyRequestAsync;
|
|
60
|
-
|
|
61
|
-
* @en Sequentially applies the chain of interceptors to the incoming response container.
|
|
62
|
-
* @ru Последовательно применяет цепочку перехватчиков к полученному объекту ответа.
|
|
63
|
-
* @template T - Type mapping descriptor for the expected response payload body.
|
|
64
|
-
* @param response - Target HTTP response context wrapper.
|
|
65
|
-
* @returns Transformed response context or a Promise resolving to it.
|
|
66
|
-
*/
|
|
67
|
-
applyResponse<T = unknown>(response: HttpResponse<T>): HttpResponse<T> | Promise<HttpResponse<T>>;
|
|
68
|
-
/**
|
|
69
|
-
* @en Asynchronous fallback to process the remaining response chain after encountering a Promise.
|
|
70
|
-
* @ru Асинхронный фолбек для обработки оставшейся цепочки ответов после обнаружения Promise.
|
|
71
|
-
* @template T - Type mapping descriptor for the expected response payload body.
|
|
72
|
-
* @param startIndex - Index of the interceptor that returned a Promise.
|
|
73
|
-
* @param currentPromise - The pending Promise from the current interceptor step.
|
|
74
|
-
* @param currentResult - Cumulative response result before the Promise step.
|
|
75
|
-
* @private
|
|
76
|
-
*/
|
|
12
|
+
applyResponse(response: UniversalResponse, request?: SendRequest, context?: PluginContext, requestContext?: RequestContext): UniversalResponse | Promise<UniversalResponse>;
|
|
77
13
|
private applyResponseAsync;
|
|
78
|
-
/**
|
|
79
|
-
* @en Completely flushes internal interceptor registers and resets state indicators.
|
|
80
|
-
* @ru Полностью очищает списки зарегистрированных перехватчиков и сбрасывает флаги.
|
|
81
|
-
*/
|
|
82
14
|
clear(): void;
|
|
83
15
|
}
|
|
84
16
|
//# sourceMappingURL=InterceptorManager.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"InterceptorManager.d.ts","sourceRoot":"","sources":["../../src/utils/InterceptorManager.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"InterceptorManager.d.ts","sourceRoot":"","sources":["../../src/utils/InterceptorManager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,aAAa,EACb,cAAc,EACd,WAAW,EACX,iBAAiB,EAClB,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAExF,qBAAa,kBAAkB;IAC7B,OAAO,CAAC,mBAAmB,CAA4B;IACvD,OAAO,CAAC,oBAAoB,CAA6B;IAClD,UAAU,UAAS;IACnB,WAAW,UAAS;IAE3B,UAAU,CAAC,WAAW,EAAE,kBAAkB,GAAG,IAAI,CAGhD;IAED,WAAW,CAAC,WAAW,EAAE,mBAAmB,GAAG,IAAI,CAGlD;IAED,YAAY,CACV,OAAO,EAAE,WAAW,EACpB,OAAO,CAAC,EAAE,aAAa,EACvB,cAAc,CAAC,EAAE,cAAc,GAC9B,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC,CAUpC;YAEa,iBAAiB;IAe/B,aAAa,CACX,QAAQ,EAAE,iBAAiB,EAC3B,OAAO,CAAC,EAAE,WAAW,EACrB,OAAO,CAAC,EAAE,aAAa,EACvB,cAAc,CAAC,EAAE,cAAc,GAC9B,iBAAiB,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAiBhD;YAEa,kBAAkB;IAgBhC,KAAK,IAAI,IAAI,CAKZ;CACF"}
|
|
@@ -1,141 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
* Uses a hybrid loop (fast-path): runs synchronously until a Promise is encountered.
|
|
4
|
-
* @ru Менеджер перехватчиков (интерцепторов) для сквозной обработки запросов и ответов.
|
|
5
|
-
* Использует гибридный цикл (fast-path): выполняется синхронно до тех пор, пока не встретит Promise.
|
|
6
|
-
*/
|
|
7
|
-
export class InterceptorManager {
|
|
8
|
-
/**
|
|
9
|
-
* @en Array of registered request interceptors.
|
|
10
|
-
* @ru Массив зарегистрированных перехватчиков запроса.
|
|
11
|
-
* @private
|
|
12
|
-
*/
|
|
13
|
-
requestInterceptors = [];
|
|
14
|
-
/**
|
|
15
|
-
* @en Array of registered response interceptors.
|
|
16
|
-
* @ru Массив зарегистрированных перехватчиков ответа.
|
|
17
|
-
* @private
|
|
18
|
-
*/
|
|
19
|
-
responseInterceptors = [];
|
|
20
|
-
/**
|
|
21
|
-
* @en Flag indicating presence of active request interceptors for fast branch short-circuiting.
|
|
22
|
-
* @ru Флаг наличия активных перехватчиков запроса для быстрого ветвления.
|
|
23
|
-
*/
|
|
24
|
-
hasRequest = false;
|
|
25
|
-
/**
|
|
26
|
-
* @en Flag indicating presence of active response interceptors for fast branch short-circuiting.
|
|
27
|
-
* @ru Флаг наличия активных перехватчиков ответа для быстрого ветвления.
|
|
28
|
-
*/
|
|
29
|
-
hasResponse = false;
|
|
30
|
-
/**
|
|
31
|
-
* @en Registers a new request interceptor in the pipeline.
|
|
32
|
-
* @ru Регистрирует новый перехватчик запроса в конвейере.
|
|
33
|
-
* @param interceptor - Target request interceptor function.
|
|
34
|
-
*/
|
|
35
|
-
addRequest(interceptor) {
|
|
36
|
-
this.requestInterceptors.push(interceptor);
|
|
37
|
-
this.hasRequest = true;
|
|
38
|
-
}
|
|
39
|
-
/**
|
|
40
|
-
* @en Registers a new response interceptor in the pipeline.
|
|
41
|
-
* @ru Регистрирует новый перехватчик ответа в конвейере.
|
|
42
|
-
* @param interceptor - Target response interceptor function.
|
|
43
|
-
*/
|
|
44
|
-
addResponse(interceptor) {
|
|
45
|
-
this.responseInterceptors.push(interceptor);
|
|
46
|
-
this.hasResponse = true;
|
|
47
|
-
}
|
|
48
|
-
/**
|
|
49
|
-
* @en Sequentially applies the chain of interceptors to the request configuration.
|
|
50
|
-
* @ru Последовательно применяет цепочку перехватчиков к конфигурации запроса.
|
|
51
|
-
* @param config - Initial internal request configuration object.
|
|
52
|
-
* @returns Modified configuration or a Promise resolving to it.
|
|
53
|
-
*/
|
|
54
|
-
applyRequest(config) {
|
|
55
|
-
let result = config;
|
|
56
|
-
for (let i = 0; i < this.requestInterceptors.length; i++) {
|
|
57
|
-
const next = this.requestInterceptors[i](result);
|
|
58
|
-
if (next instanceof Promise) {
|
|
59
|
-
return this.applyRequestAsync(i + 1, next, result);
|
|
60
|
-
}
|
|
61
|
-
if (next)
|
|
62
|
-
result = next;
|
|
63
|
-
}
|
|
64
|
-
return result;
|
|
65
|
-
}
|
|
66
|
-
/**
|
|
67
|
-
* @en Asynchronous fallback to process the remaining request chain after encountering a Promise.
|
|
68
|
-
* @ru Асинхронный фолбек для обработки оставшейся цепочки запросов после обнаружения Promise.
|
|
69
|
-
* @param startIndex - Index of the interceptor that returned a Promise.
|
|
70
|
-
* @param currentPromise - The pending Promise from the current interceptor step.
|
|
71
|
-
* @param currentResult - Cumulative configuration result before the Promise step.
|
|
72
|
-
* @private
|
|
73
|
-
*/
|
|
74
|
-
async applyRequestAsync(startIndex, currentPromise, currentResult) {
|
|
75
|
-
let result = (await currentPromise) ?? currentResult;
|
|
76
|
-
for (let i = startIndex; i < this.requestInterceptors.length; i++) {
|
|
77
|
-
const next = this.requestInterceptors[i](result);
|
|
78
|
-
result = (next instanceof Promise ? await next : next) ?? result;
|
|
79
|
-
}
|
|
80
|
-
return result;
|
|
81
|
-
}
|
|
82
|
-
/**
|
|
83
|
-
* @en Sequentially applies the chain of interceptors to the incoming response container.
|
|
84
|
-
* @ru Последовательно применяет цепочку перехватчиков к полученному объекту ответа.
|
|
85
|
-
* @template T - Type mapping descriptor for the expected response payload body.
|
|
86
|
-
* @param response - Target HTTP response context wrapper.
|
|
87
|
-
* @returns Transformed response context or a Promise resolving to it.
|
|
88
|
-
*/
|
|
89
|
-
applyResponse(response) {
|
|
90
|
-
let result = response;
|
|
91
|
-
const len = this.responseInterceptors.length;
|
|
92
|
-
for (let i = 0; i < len; i++) {
|
|
93
|
-
const nextResponse = this.responseInterceptors[i](result);
|
|
94
|
-
if (nextResponse instanceof Promise) {
|
|
95
|
-
return this.applyResponseAsync(i, nextResponse, result);
|
|
96
|
-
}
|
|
97
|
-
if (nextResponse)
|
|
98
|
-
result = nextResponse;
|
|
99
|
-
}
|
|
100
|
-
return result;
|
|
101
|
-
}
|
|
102
|
-
/**
|
|
103
|
-
* @en Asynchronous fallback to process the remaining response chain after encountering a Promise.
|
|
104
|
-
* @ru Асинхронный фолбек для обработки оставшейся цепочки ответов после обнаружения Promise.
|
|
105
|
-
* @template T - Type mapping descriptor for the expected response payload body.
|
|
106
|
-
* @param startIndex - Index of the interceptor that returned a Promise.
|
|
107
|
-
* @param currentPromise - The pending Promise from the current interceptor step.
|
|
108
|
-
* @param currentResult - Cumulative response result before the Promise step.
|
|
109
|
-
* @private
|
|
110
|
-
*/
|
|
111
|
-
async applyResponseAsync(startIndex, currentPromise, currentResult) {
|
|
112
|
-
let result = currentResult;
|
|
113
|
-
const resolved = await currentPromise;
|
|
114
|
-
if (resolved)
|
|
115
|
-
result = resolved;
|
|
116
|
-
const len = this.responseInterceptors.length;
|
|
117
|
-
for (let i = startIndex + 1; i < len; i++) {
|
|
118
|
-
const nextResponse = this.responseInterceptors[i](result);
|
|
119
|
-
if (nextResponse instanceof Promise) {
|
|
120
|
-
const res = await nextResponse;
|
|
121
|
-
if (res)
|
|
122
|
-
result = res;
|
|
123
|
-
}
|
|
124
|
-
else if (nextResponse) {
|
|
125
|
-
result = nextResponse;
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
return result;
|
|
129
|
-
}
|
|
130
|
-
/**
|
|
131
|
-
* @en Completely flushes internal interceptor registers and resets state indicators.
|
|
132
|
-
* @ru Полностью очищает списки зарегистрированных перехватчиков и сбрасывает флаги.
|
|
133
|
-
*/
|
|
134
|
-
clear() {
|
|
135
|
-
this.requestInterceptors = [];
|
|
136
|
-
this.responseInterceptors = [];
|
|
137
|
-
this.hasRequest = false;
|
|
138
|
-
this.hasResponse = false;
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
//# sourceMappingURL=InterceptorManager.js.map
|
|
1
|
+
"use strict";export class InterceptorManager{requestInterceptors=[];responseInterceptors=[];hasRequest=!1;hasResponse=!1;addRequest(r){this.requestInterceptors.push(r),this.hasRequest=!0}addResponse(r){this.responseInterceptors.push(r),this.hasResponse=!0}applyRequest(r,p,o){let n=r;for(let s=0;s<this.requestInterceptors.length;s++){const e=this.requestInterceptors[s](n,p,o);if(e instanceof Promise)return this.applyRequestAsync(s+1,e,n,p,o);e&&(n=e)}return n}async applyRequestAsync(r,p,o,n,s){let e=await p??o;for(let t=r;t<this.requestInterceptors.length;t++){const i=this.requestInterceptors[t](e,n,s);e=(i instanceof Promise?await i:i)??e}return e}applyResponse(r,p,o,n){let s=r;for(let e=0;e<this.responseInterceptors.length;e++){const t=this.responseInterceptors[e](s,p,o,n);if(t instanceof Promise)return this.applyResponseAsync(e+1,t,s,p,o,n);t&&(s=t)}return s}async applyResponseAsync(r,p,o,n,s,e){let t=await p??o;for(let i=r;i<this.responseInterceptors.length;i++){const a=this.responseInterceptors[i](t,n,s,e);t=(a instanceof Promise?await a:a)??t}return t}clear(){this.requestInterceptors=[],this.responseInterceptors=[],this.hasRequest=!1,this.hasResponse=!1}}
|
|
2
|
+
//# sourceMappingURL=InterceptorManager.js.map
|
|
@@ -1 +1,7 @@
|
|
|
1
|
-
{
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/utils/InterceptorManager.ts"],
|
|
4
|
+
"sourcesContent": ["import type {\n PluginContext,\n RequestContext,\n SendRequest,\n UniversalResponse,\n} from \"@hyperttp/types\";\nimport type { RequestInterceptor, ResponseInterceptor } from \"../types/interceptors.js\";\n\nexport class InterceptorManager {\n private requestInterceptors: RequestInterceptor[] = [];\n private responseInterceptors: ResponseInterceptor[] = [];\n public hasRequest = false;\n public hasResponse = false;\n\n addRequest(interceptor: RequestInterceptor): void {\n this.requestInterceptors.push(interceptor);\n this.hasRequest = true;\n }\n\n addResponse(interceptor: ResponseInterceptor): void {\n this.responseInterceptors.push(interceptor);\n this.hasResponse = true;\n }\n\n applyRequest(\n request: SendRequest,\n context?: PluginContext,\n requestContext?: RequestContext,\n ): SendRequest | Promise<SendRequest> {\n let result = request;\n for (let i = 0; i < this.requestInterceptors.length; i++) {\n const next = this.requestInterceptors[i](result, context, requestContext);\n if (next instanceof Promise) {\n return this.applyRequestAsync(i + 1, next, result, context, requestContext);\n }\n if (next) result = next;\n }\n return result;\n }\n\n private async applyRequestAsync(\n startIndex: number,\n currentPromise: Promise<SendRequest | void>,\n currentResult: SendRequest,\n context?: PluginContext,\n requestContext?: RequestContext,\n ): Promise<SendRequest> {\n let result = (await currentPromise) ?? currentResult;\n for (let i = startIndex; i < this.requestInterceptors.length; i++) {\n const next = this.requestInterceptors[i](result, context, requestContext);\n result = (next instanceof Promise ? await next : next) ?? result;\n }\n return result;\n }\n\n applyResponse(\n response: UniversalResponse,\n request?: SendRequest,\n context?: PluginContext,\n requestContext?: RequestContext,\n ): UniversalResponse | Promise<UniversalResponse> {\n let result = response;\n for (let i = 0; i < this.responseInterceptors.length; i++) {\n const nextResponse = this.responseInterceptors[i](result, request, context, requestContext);\n if (nextResponse instanceof Promise) {\n return this.applyResponseAsync(\n i + 1,\n nextResponse,\n result,\n request,\n context,\n requestContext,\n );\n }\n if (nextResponse) result = nextResponse;\n }\n return result;\n }\n\n private async applyResponseAsync(\n startIndex: number,\n currentPromise: Promise<UniversalResponse | void>,\n currentResult: UniversalResponse,\n request?: SendRequest,\n context?: PluginContext,\n requestContext?: RequestContext,\n ): Promise<UniversalResponse> {\n let result = (await currentPromise) ?? currentResult;\n for (let i = startIndex; i < this.responseInterceptors.length; i++) {\n const nextResponse = this.responseInterceptors[i](result, request, context, requestContext);\n result = (nextResponse instanceof Promise ? await nextResponse : nextResponse) ?? result;\n }\n return result;\n }\n\n clear(): void {\n this.requestInterceptors = [];\n this.responseInterceptors = [];\n this.hasRequest = false;\n this.hasResponse = false;\n }\n}\n"],
|
|
5
|
+
"mappings": "aAQM,aAAO,kBAAkB,CACrB,oBAA4C,CAAA,EAC5C,qBAA8C,CAAA,EAC/C,WAAa,GACb,YAAc,GAErB,WAAWA,EAA+B,CACxC,KAAK,oBAAoB,KAAKA,CAAW,EACzC,KAAK,WAAa,EACpB,CAEA,YAAYA,EAAgC,CAC1C,KAAK,qBAAqB,KAAKA,CAAW,EAC1C,KAAK,YAAc,EACrB,CAEA,aACEC,EACAC,EACAC,EAA+B,CAE/B,IAAIC,EAASH,EACb,QAASI,EAAI,EAAGA,EAAI,KAAK,oBAAoB,OAAQA,IAAK,CACxD,MAAMC,EAAO,KAAK,oBAAoBD,CAAC,EAAED,EAAQF,EAASC,CAAc,EACxE,GAAIG,aAAgB,QAClB,OAAO,KAAK,kBAAkBD,EAAI,EAAGC,EAAMF,EAAQF,EAASC,CAAc,EAExEG,IAAMF,EAASE,EACrB,CACA,OAAOF,CACT,CAEQ,MAAM,kBACZG,EACAC,EACAC,EACAP,EACAC,EAA+B,CAE/B,IAAIC,EAAU,MAAMI,GAAmBC,EACvC,QAASJ,EAAIE,EAAYF,EAAI,KAAK,oBAAoB,OAAQA,IAAK,CACjE,MAAMC,EAAO,KAAK,oBAAoBD,CAAC,EAAED,EAAQF,EAASC,CAAc,EACxEC,GAAUE,aAAgB,QAAU,MAAMA,EAAOA,IAASF,CAC5D,CACA,OAAOA,CACT,CAEA,cACEM,EACAT,EACAC,EACAC,EAA+B,CAE/B,IAAIC,EAASM,EACb,QAASL,EAAI,EAAGA,EAAI,KAAK,qBAAqB,OAAQA,IAAK,CACzD,MAAMM,EAAe,KAAK,qBAAqBN,CAAC,EAAED,EAAQH,EAASC,EAASC,CAAc,EAC1F,GAAIQ,aAAwB,QAC1B,OAAO,KAAK,mBACVN,EAAI,EACJM,EACAP,EACAH,EACAC,EACAC,CAAc,EAGdQ,IAAcP,EAASO,EAC7B,CACA,OAAOP,CACT,CAEQ,MAAM,mBACZG,EACAC,EACAC,EACAR,EACAC,EACAC,EAA+B,CAE/B,IAAIC,EAAU,MAAMI,GAAmBC,EACvC,QAAS,EAAIF,EAAY,EAAI,KAAK,qBAAqB,OAAQ,IAAK,CAClE,MAAMI,EAAe,KAAK,qBAAqB,CAAC,EAAEP,EAAQH,EAASC,EAASC,CAAc,EAC1FC,GAAUO,aAAwB,QAAU,MAAMA,EAAeA,IAAiBP,CACpF,CACA,OAAOA,CACT,CAEA,OAAK,CACH,KAAK,oBAAsB,CAAA,EAC3B,KAAK,qBAAuB,CAAA,EAC5B,KAAK,WAAa,GAClB,KAAK,YAAc,EACrB",
|
|
6
|
+
"names": ["interceptor", "request", "context", "requestContext", "result", "i", "next", "startIndex", "currentPromise", "currentResult", "response", "nextResponse"]
|
|
7
|
+
}
|