UNPKG

2.75 kBTypeScriptView Raw
1import { Context } from './context';
2import { InvocationArgs, InvocationSource } from './invocation';
3import { ResolutionSession } from './resolution-session';
4import { ValueOrPromise } from './value-promise';
5/**
6 * Create the Promise type for `T`. If `T` extends `Promise`, the type is `T`,
7 * otherwise the type is `ValueOrPromise<T>`.
8 */
9export type AsValueOrPromise<T> = T extends Promise<unknown> ? T : ValueOrPromise<T>;
10/**
11 * The intercepted variant of a function to return `ValueOrPromise<T>`.
12 * If `T` is not a function, the type is `T`.
13 */
14export type AsInterceptedFunction<T> = T extends (...args: InvocationArgs) => infer R ? (...args: Parameters<T>) => AsValueOrPromise<R> : T;
15/**
16 * The proxy type for `T`. The return type for any method of `T` with original
17 * return type `R` becomes `ValueOrPromise<R>` if `R` does not extend `Promise`.
18 * Property types stay untouched.
19 *
20 * @example
21 * ```ts
22 * class MyController {
23 * name: string;
24 *
25 * greet(name: string): string {
26 * return `Hello, ${name}`;
27 * }
28 *
29 * async hello(name: string) {
30 * return `Hello, ${name}`;
31 * }
32 * }
33 * ```
34 *
35 * `AsyncProxy<MyController>` will be:
36 * ```ts
37 * {
38 * name: string; // the same as MyController
39 * greet(name: string): ValueOrPromise<string>; // the return type becomes `ValueOrPromise<string>`
40 * hello(name: string): Promise<string>; // the same as MyController
41 * }
42 * ```
43 */
44export type AsyncProxy<T> = {
45 [P in keyof T]: AsInterceptedFunction<T[P]>;
46};
47/**
48 * Invocation source for injected proxies. It wraps a snapshot of the
49 * `ResolutionSession` that tracks the binding/injection stack.
50 */
51export declare class ProxySource implements InvocationSource<ResolutionSession> {
52 readonly value: ResolutionSession;
53 type: string;
54 constructor(value: ResolutionSession);
55 toString(): string;
56}
57/**
58 * A proxy handler that applies interceptors
59 *
60 * See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Proxy
61 */
62export declare class InterceptionHandler<T extends object> implements ProxyHandler<T> {
63 private context;
64 private session?;
65 private source?;
66 constructor(context?: Context, session?: ResolutionSession | undefined, source?: InvocationSource<unknown> | undefined);
67 get(target: T, propertyName: PropertyKey, receiver: unknown): any;
68}
69/**
70 * Create a proxy that applies interceptors for method invocations
71 * @param target - Target class or object
72 * @param context - Context object
73 * @param session - Resolution session
74 * @param source - Invocation source
75 */
76export declare function createProxyWithInterceptors<T extends object>(target: T, context?: Context, session?: ResolutionSession, source?: InvocationSource): AsyncProxy<T>;