Initial commit - Event Planner application

This commit is contained in:
mberlin
2026-03-18 14:55:56 -03:00
commit 86d779eb4d
7548 changed files with 1006324 additions and 0 deletions

3
node_modules/@nestjs/core/router/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
export * from './interfaces';
export * from './request';
export { RouterModule } from './router-module';

8
node_modules/@nestjs/core/router/index.js generated vendored Normal file
View File

@@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RouterModule = void 0;
const tslib_1 = require("tslib");
tslib_1.__exportStar(require("./interfaces"), exports);
tslib_1.__exportStar(require("./request"), exports);
var router_module_1 = require("./router-module");
Object.defineProperty(exports, "RouterModule", { enumerable: true, get: function () { return router_module_1.RouterModule; } });

View File

@@ -0,0 +1,6 @@
import { Controller } from '@nestjs/common/interfaces/controllers/controller.interface';
import { ExceptionsHandler } from '../../exceptions/exceptions-handler';
import { ContextId } from '../../injector/instance-wrapper';
export interface ExceptionsFilter {
create(instance: Controller, callback: Function, module: string, contextId?: ContextId, inquirerId?: string): ExceptionsHandler;
}

View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View File

@@ -0,0 +1,15 @@
import { RequestMethod } from '@nestjs/common';
export interface ExcludeRouteMetadata {
/**
* Route path.
*/
path: string;
/**
* Regular expression representing the route path.
*/
pathRegex: RegExp;
/**
* HTTP request method (e.g., GET, POST).
*/
requestMethod: RequestMethod;
}

View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View File

@@ -0,0 +1 @@
export * from './routes.interface';

4
node_modules/@nestjs/core/router/interfaces/index.js generated vendored Normal file
View File

@@ -0,0 +1,4 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
tslib_1.__exportStar(require("./routes.interface"), exports);

View File

@@ -0,0 +1,5 @@
export interface Resolver {
resolve(instance: any, basePath: string): void;
registerNotFoundHandler(): void;
registerExceptionHandler(): void;
}

View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View File

@@ -0,0 +1,8 @@
import { RouteParamtypes } from '@nestjs/common/enums/route-paramtypes.enum';
export interface IRouteParamsFactory {
exchangeKeyForValue<TRequest extends Record<string, any> = any, TResponse = any, TResult = any>(key: RouteParamtypes | string, data: any, { req, res, next }: {
req: TRequest;
res: TResponse;
next: Function;
}): TResult | null;
}

View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View File

@@ -0,0 +1,32 @@
import { VersioningOptions } from '@nestjs/common';
import { VersionValue } from '@nestjs/common/interfaces';
export interface RoutePathMetadata {
/**
* Controller-level path (e.g., @Controller('resource') = "resource").
*/
ctrlPath?: string;
/**
* Method-level path (e.g., @Get('resource') = "resource").
*/
methodPath?: string;
/**
* Global route prefix specified with the "NestApplication#setGlobalPrefix" method.
*/
globalPrefix?: string;
/**
* Module-level path registered through the "RouterModule".
*/
modulePath?: string;
/**
* Controller-level version (e.g., @Controller({ version: '1.0' }) = "1.0").
*/
controllerVersion?: VersionValue;
/**
* Method-level version (e.g., @Version('1.0') = "1.0").
*/
methodVersion?: VersionValue;
/**
* API versioning options object.
*/
versioningOptions?: VersioningOptions;
}

View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View File

@@ -0,0 +1,7 @@
import { Type } from '@nestjs/common';
export interface RouteTree {
path: string;
module?: Type<any>;
children?: (RouteTree | Type<any>)[];
}
export type Routes = RouteTree[];

View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View File

@@ -0,0 +1,16 @@
export declare class LegacyRouteConverter {
private static readonly logger;
/**
* Convert legacy routes to the new format (syntax).
* path-to-regexp used by Express>=v5 and @fastify/middie>=v9 no longer support unnamed wildcards.
* This method attempts to convert the old syntax to the new one, and logs an error if it fails.
* @param route The route to convert.
* @param options Options object.
* @returns The converted route, or the original route if it cannot be converted.
*/
static tryConvert(route: string, options?: {
logs?: boolean;
}): string;
static printError(route: string): void;
static printWarning(route: string): void;
}

View File

@@ -0,0 +1,61 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LegacyRouteConverter = void 0;
const common_1 = require("@nestjs/common");
const UNSUPPORTED_PATH_MESSAGE = (text, route) => `Unsupported route path: "${route}". In previous versions, the symbols ?, *, and + were used to denote optional or repeating path parameters. The latest version of "path-to-regexp" now requires the use of named parameters. For example, instead of using a route like /users/* to capture all routes starting with "/users", you should use /users/*path. For more details, refer to the migration guide.`;
class LegacyRouteConverter {
/**
* Convert legacy routes to the new format (syntax).
* path-to-regexp used by Express>=v5 and @fastify/middie>=v9 no longer support unnamed wildcards.
* This method attempts to convert the old syntax to the new one, and logs an error if it fails.
* @param route The route to convert.
* @param options Options object.
* @returns The converted route, or the original route if it cannot be converted.
*/
static tryConvert(route, options) {
// Normalize path to eliminate additional if statements.
const routeWithLeadingSlash = route.startsWith('/') ? route : `/${route}`;
const normalizedRoute = route.endsWith('/')
? routeWithLeadingSlash
: `${routeWithLeadingSlash}/`;
const loggingEnabled = options?.logs ?? true;
const printWarning = loggingEnabled
? this.printWarning.bind(this)
: () => { };
if (normalizedRoute.endsWith('/(.*)/')) {
// Skip printing warning for the "all" wildcard.
if (normalizedRoute !== '/(.*)/') {
printWarning(route);
}
return route.replace('(.*)', '{*path}');
}
if (normalizedRoute.endsWith('/*/')) {
// Skip printing warning for the "all" wildcard.
if (normalizedRoute !== '/*/') {
printWarning(route);
}
return route.replace('*', '{*path}');
}
if (normalizedRoute.endsWith('/+/')) {
printWarning(route);
return route.replace('/+', '/*path');
}
// When route includes any wildcard segments in the middle.
if (normalizedRoute.includes('/*/')) {
printWarning(route);
// Replace each /*/ segment with a named parameter using different name for each segment.
return route.replaceAll('/*/', (match, offset) => {
return `/*path${offset}/`;
});
}
return route;
}
static printError(route) {
this.logger.error(UNSUPPORTED_PATH_MESSAGE `${route}`);
}
static printWarning(route) {
this.logger.warn(UNSUPPORTED_PATH_MESSAGE `${route}` + ' Attempting to auto-convert...');
}
}
exports.LegacyRouteConverter = LegacyRouteConverter;
LegacyRouteConverter.logger = new common_1.Logger(LegacyRouteConverter.name);

18
node_modules/@nestjs/core/router/paths-explorer.d.ts generated vendored Normal file
View File

@@ -0,0 +1,18 @@
import { RequestMethod } from '@nestjs/common/enums';
import { Controller } from '@nestjs/common/interfaces/controllers/controller.interface';
import { VersionValue } from '@nestjs/common/interfaces/version-options.interface';
import { MetadataScanner } from '../metadata-scanner';
import { RouterProxyCallback } from './router-proxy';
export interface RouteDefinition {
path: string[];
requestMethod: RequestMethod;
targetCallback: RouterProxyCallback;
methodName: string;
version?: VersionValue;
}
export declare class PathsExplorer {
private readonly metadataScanner;
constructor(metadataScanner: MetadataScanner);
scanForPaths(instance: Controller, prototype?: object): RouteDefinition[];
exploreMethodMetadata(instance: Controller, prototype: object, methodName: string): RouteDefinition | null;
}

45
node_modules/@nestjs/core/router/paths-explorer.js generated vendored Normal file
View File

@@ -0,0 +1,45 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PathsExplorer = void 0;
const constants_1 = require("@nestjs/common/constants");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
class PathsExplorer {
constructor(metadataScanner) {
this.metadataScanner = metadataScanner;
}
scanForPaths(instance, prototype) {
const instancePrototype = (0, shared_utils_1.isUndefined)(prototype)
? Object.getPrototypeOf(instance)
: prototype;
return this.metadataScanner
.getAllMethodNames(instancePrototype)
.reduce((acc, method) => {
const route = this.exploreMethodMetadata(instance, instancePrototype, method);
if (route) {
acc.push(route);
}
return acc;
}, []);
}
exploreMethodMetadata(instance, prototype, methodName) {
const instanceCallback = instance[methodName];
const prototypeCallback = prototype[methodName];
const routePath = Reflect.getMetadata(constants_1.PATH_METADATA, prototypeCallback);
if ((0, shared_utils_1.isUndefined)(routePath)) {
return null;
}
const requestMethod = Reflect.getMetadata(constants_1.METHOD_METADATA, prototypeCallback);
const version = Reflect.getMetadata(constants_1.VERSION_METADATA, prototypeCallback);
const path = (0, shared_utils_1.isString)(routePath)
? [(0, shared_utils_1.addLeadingSlash)(routePath)]
: routePath.map((p) => (0, shared_utils_1.addLeadingSlash)(p));
return {
path,
requestMethod,
targetCallback: instanceCallback,
methodName,
version,
};
}
}
exports.PathsExplorer = PathsExplorer;

1
node_modules/@nestjs/core/router/request/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export { REQUEST } from './request-constants';

5
node_modules/@nestjs/core/router/request/index.js generated vendored Normal file
View File

@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.REQUEST = void 0;
var request_constants_1 = require("./request-constants");
Object.defineProperty(exports, "REQUEST", { enumerable: true, get: function () { return request_constants_1.REQUEST; } });

View File

@@ -0,0 +1,2 @@
export declare const REQUEST = "REQUEST";
export declare const REQUEST_CONTEXT_ID: unique symbol;

View File

@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.REQUEST_CONTEXT_ID = exports.REQUEST = void 0;
exports.REQUEST = 'REQUEST';
exports.REQUEST_CONTEXT_ID = Symbol('REQUEST_CONTEXT_ID');

View File

@@ -0,0 +1,2 @@
import { Provider } from '@nestjs/common';
export declare const requestProvider: Provider;

View File

@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.requestProvider = void 0;
const common_1 = require("@nestjs/common");
const request_constants_1 = require("./request-constants");
const noop = () => { };
exports.requestProvider = {
provide: request_constants_1.REQUEST,
scope: common_1.Scope.REQUEST,
useFactory: noop,
};

View File

@@ -0,0 +1,9 @@
import { RouteParamtypes } from '@nestjs/common/enums/route-paramtypes.enum';
import { IRouteParamsFactory } from './interfaces/route-params-factory.interface';
export declare class RouteParamsFactory implements IRouteParamsFactory {
exchangeKeyForValue<TRequest extends Record<string, any> = any, TResponse = any, TResult = any>(key: RouteParamtypes | string, data: string, { req, res, next }: {
req: TRequest;
res: TResponse;
next: Function;
}): TResult | null;
}

View File

@@ -0,0 +1,41 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RouteParamsFactory = void 0;
const route_paramtypes_enum_1 = require("@nestjs/common/enums/route-paramtypes.enum");
class RouteParamsFactory {
exchangeKeyForValue(key, data, { req, res, next }) {
switch (key) {
case route_paramtypes_enum_1.RouteParamtypes.NEXT:
return next;
case route_paramtypes_enum_1.RouteParamtypes.REQUEST:
return req;
case route_paramtypes_enum_1.RouteParamtypes.RESPONSE:
return res;
case route_paramtypes_enum_1.RouteParamtypes.BODY:
return data && req.body ? req.body[data] : req.body;
case route_paramtypes_enum_1.RouteParamtypes.RAW_BODY:
return req.rawBody;
case route_paramtypes_enum_1.RouteParamtypes.PARAM:
return data ? req.params[data] : req.params;
case route_paramtypes_enum_1.RouteParamtypes.HOST:
/* eslint-disable-next-line no-case-declarations */
const hosts = req.hosts || {};
return data ? hosts[data] : hosts;
case route_paramtypes_enum_1.RouteParamtypes.QUERY:
return data ? req.query[data] : req.query;
case route_paramtypes_enum_1.RouteParamtypes.HEADERS:
return data ? req.headers[data.toLowerCase()] : req.headers;
case route_paramtypes_enum_1.RouteParamtypes.SESSION:
return req.session;
case route_paramtypes_enum_1.RouteParamtypes.FILE:
return req[data || 'file'];
case route_paramtypes_enum_1.RouteParamtypes.FILES:
return req.files;
case route_paramtypes_enum_1.RouteParamtypes.IP:
return req.ip;
default:
return null;
}
}
}
exports.RouteParamsFactory = RouteParamsFactory;

View File

@@ -0,0 +1,14 @@
import { RequestMethod, VersioningOptions } from '@nestjs/common';
import { VersionValue } from '@nestjs/common/interfaces';
import { ApplicationConfig } from '../application-config';
import { RoutePathMetadata } from './interfaces/route-path-metadata.interface';
export declare class RoutePathFactory {
private readonly applicationConfig;
constructor(applicationConfig: ApplicationConfig);
create(metadata: RoutePathMetadata, requestMethod?: RequestMethod): string[];
getVersion(metadata: RoutePathMetadata): VersionValue | undefined;
getVersionPrefix(versioningOptions: VersioningOptions): string;
appendToAllIfDefined(paths: string[], fragmentToAppend: string | string[] | undefined): string[];
isExcludedFromGlobalPrefix(path: string, requestMethod?: RequestMethod, versionOrVersions?: VersionValue, versioningOptions?: VersioningOptions): boolean;
private truncateVersionPrefixFromPath;
}

101
node_modules/@nestjs/core/router/route-path-factory.js generated vendored Normal file
View File

@@ -0,0 +1,101 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RoutePathFactory = void 0;
const common_1 = require("@nestjs/common");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const utils_1 = require("./utils");
class RoutePathFactory {
constructor(applicationConfig) {
this.applicationConfig = applicationConfig;
}
create(metadata, requestMethod) {
let paths = [''];
const versionOrVersions = this.getVersion(metadata);
if (versionOrVersions &&
metadata.versioningOptions?.type === common_1.VersioningType.URI) {
const versionPrefix = this.getVersionPrefix(metadata.versioningOptions);
if (Array.isArray(versionOrVersions)) {
paths = (0, common_1.flatten)(paths.map(path => versionOrVersions.map(version =>
// Version Neutral - Do not include version in URL
version === common_1.VERSION_NEUTRAL
? path
: `${path}/${versionPrefix}${version}`)));
}
else {
// Version Neutral - Do not include version in URL
if (versionOrVersions !== common_1.VERSION_NEUTRAL) {
paths = paths.map(path => `${path}/${versionPrefix}${versionOrVersions}`);
}
}
}
paths = this.appendToAllIfDefined(paths, metadata.modulePath);
paths = this.appendToAllIfDefined(paths, metadata.ctrlPath);
paths = this.appendToAllIfDefined(paths, metadata.methodPath);
if (metadata.globalPrefix) {
paths = paths.map(path => {
if (this.isExcludedFromGlobalPrefix(path, requestMethod, versionOrVersions, metadata.versioningOptions)) {
return path;
}
return (0, shared_utils_1.stripEndSlash)(metadata.globalPrefix || '') + path;
});
}
return paths
.map(path => (0, shared_utils_1.addLeadingSlash)(path || '/'))
.map(path => (path !== '/' ? (0, shared_utils_1.stripEndSlash)(path) : path));
}
getVersion(metadata) {
// The version will be either the path version or the controller version,
// with the pathVersion taking priority.
return metadata.methodVersion || metadata.controllerVersion;
}
getVersionPrefix(versioningOptions) {
const defaultPrefix = 'v';
if (versioningOptions.type === common_1.VersioningType.URI) {
if (versioningOptions.prefix === false) {
return '';
}
else if (versioningOptions.prefix !== undefined) {
return versioningOptions.prefix;
}
}
return defaultPrefix;
}
appendToAllIfDefined(paths, fragmentToAppend) {
if (!fragmentToAppend) {
return paths;
}
const concatPaths = (a, b) => (0, shared_utils_1.stripEndSlash)(a) + (0, shared_utils_1.addLeadingSlash)(b);
if (Array.isArray(fragmentToAppend)) {
const paths2dArray = paths.map(path => fragmentToAppend.map(fragment => concatPaths(path, fragment)));
return (0, common_1.flatten)(paths2dArray);
}
return paths.map(path => concatPaths(path, fragmentToAppend));
}
isExcludedFromGlobalPrefix(path, requestMethod, versionOrVersions, versioningOptions) {
if ((0, shared_utils_1.isUndefined)(requestMethod)) {
return false;
}
const options = this.applicationConfig.getGlobalPrefixOptions();
const excludedRoutes = options.exclude;
if (versionOrVersions &&
versionOrVersions !== common_1.VERSION_NEUTRAL &&
versioningOptions?.type === common_1.VersioningType.URI) {
path = this.truncateVersionPrefixFromPath(path, versionOrVersions, versioningOptions);
}
return (Array.isArray(excludedRoutes) &&
(0, utils_1.isRouteExcluded)(excludedRoutes, path, requestMethod));
}
truncateVersionPrefixFromPath(path, versionValue, versioningOptions) {
if (typeof versionValue !== 'string') {
versionValue.forEach(version => {
if (typeof version === 'string') {
path = this.truncateVersionPrefixFromPath(path, version, versioningOptions);
}
});
return path;
}
const prefix = `/${this.getVersionPrefix(versioningOptions)}${versionValue}`;
return path.startsWith(prefix) ? path.replace(prefix, '') : path;
}
}
exports.RoutePathFactory = RoutePathFactory;

View File

@@ -0,0 +1,14 @@
import { HttpServer } from '@nestjs/common';
import { Controller } from '@nestjs/common/interfaces/controllers/controller.interface';
import { ApplicationConfig } from '../application-config';
import { BaseExceptionFilterContext } from '../exceptions/base-exception-filter-context';
import { ExceptionsHandler } from '../exceptions/exceptions-handler';
import { NestContainer } from '../injector/container';
import { RouterProxyCallback } from './router-proxy';
export declare class RouterExceptionFilters extends BaseExceptionFilterContext {
private readonly config;
private readonly applicationRef;
constructor(container: NestContainer, config: ApplicationConfig, applicationRef: HttpServer);
create(instance: Controller, callback: RouterProxyCallback, moduleKey: string | undefined, contextId?: import("../injector/instance-wrapper").ContextId, inquirerId?: string): ExceptionsHandler;
getGlobalMetadata<T extends unknown[]>(contextId?: import("../injector/instance-wrapper").ContextId, inquirerId?: string): T;
}

View File

@@ -0,0 +1,40 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RouterExceptionFilters = void 0;
const constants_1 = require("@nestjs/common/constants");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const iterare_1 = require("iterare");
const base_exception_filter_context_1 = require("../exceptions/base-exception-filter-context");
const exceptions_handler_1 = require("../exceptions/exceptions-handler");
const constants_2 = require("../injector/constants");
class RouterExceptionFilters extends base_exception_filter_context_1.BaseExceptionFilterContext {
constructor(container, config, applicationRef) {
super(container);
this.config = config;
this.applicationRef = applicationRef;
}
create(instance, callback, moduleKey, contextId = constants_2.STATIC_CONTEXT, inquirerId) {
this.moduleContext = moduleKey;
const exceptionHandler = new exceptions_handler_1.ExceptionsHandler(this.applicationRef);
const filters = this.createContext(instance, callback, constants_1.EXCEPTION_FILTERS_METADATA, contextId, inquirerId);
if ((0, shared_utils_1.isEmpty)(filters)) {
return exceptionHandler;
}
exceptionHandler.setCustomFilters(filters.reverse());
return exceptionHandler;
}
getGlobalMetadata(contextId = constants_2.STATIC_CONTEXT, inquirerId) {
const globalFilters = this.config.getGlobalFilters();
if (contextId === constants_2.STATIC_CONTEXT && !inquirerId) {
return globalFilters;
}
const scopedFilterWrappers = this.config.getGlobalRequestFilters();
const scopedFilters = (0, iterare_1.iterate)(scopedFilterWrappers)
.map(wrapper => wrapper.getInstanceByContextId(contextId, inquirerId))
.filter(host => !!host)
.map(host => host.instance)
.toArray();
return globalFilters.concat(scopedFilters);
}
}
exports.RouterExceptionFilters = RouterExceptionFilters;

View File

@@ -0,0 +1,54 @@
import { CanActivate, HttpServer, ParamData, PipeTransform, RequestMethod } from '@nestjs/common';
import { RouteParamMetadata } from '@nestjs/common/decorators';
import { RouteParamtypes } from '@nestjs/common/enums/route-paramtypes.enum';
import { ContextType, Controller } from '@nestjs/common/interfaces';
import { GuardsConsumer, GuardsContextCreator } from '../guards';
import { ExecutionContextHost } from '../helpers/execution-context-host';
import { HandleResponseFn, HandlerMetadata } from '../helpers/handler-metadata-storage';
import { InterceptorsConsumer } from '../interceptors/interceptors-consumer';
import { InterceptorsContextCreator } from '../interceptors/interceptors-context-creator';
import { PipesConsumer } from '../pipes/pipes-consumer';
import { PipesContextCreator } from '../pipes/pipes-context-creator';
import { IRouteParamsFactory } from './interfaces/route-params-factory.interface';
import { CustomHeader, RedirectResponse } from './router-response-controller';
export interface ParamProperties {
index: number;
type: RouteParamtypes | string;
data: ParamData;
pipes: PipeTransform[];
extractValue: <TRequest, TResponse>(req: TRequest, res: TResponse, next: Function) => any;
}
export declare class RouterExecutionContext {
private readonly paramsFactory;
private readonly pipesContextCreator;
private readonly pipesConsumer;
private readonly guardsContextCreator;
private readonly guardsConsumer;
private readonly interceptorsContextCreator;
private readonly interceptorsConsumer;
readonly applicationRef: HttpServer;
private readonly handlerMetadataStorage;
private readonly contextUtils;
private readonly responseController;
constructor(paramsFactory: IRouteParamsFactory, pipesContextCreator: PipesContextCreator, pipesConsumer: PipesConsumer, guardsContextCreator: GuardsContextCreator, guardsConsumer: GuardsConsumer, interceptorsContextCreator: InterceptorsContextCreator, interceptorsConsumer: InterceptorsConsumer, applicationRef: HttpServer);
create(instance: Controller, callback: (...args: any[]) => unknown, methodName: string, moduleKey: string, requestMethod: RequestMethod, contextId?: import("..").ContextId, inquirerId?: string): <TRequest, TResponse>(req: TRequest, res: TResponse, next: Function) => Promise<void>;
getMetadata<TContext extends ContextType = ContextType>(instance: Controller, callback: (...args: any[]) => any, methodName: string, moduleKey: string, requestMethod: RequestMethod, contextType: TContext): HandlerMetadata;
reflectRedirect(callback: (...args: unknown[]) => unknown): RedirectResponse;
reflectHttpStatusCode(callback: (...args: unknown[]) => unknown): number;
reflectRenderTemplate(callback: (...args: unknown[]) => unknown): string;
reflectResponseHeaders(callback: (...args: unknown[]) => unknown): CustomHeader[];
reflectSse(callback: (...args: unknown[]) => unknown): string;
exchangeKeysForValues(keys: string[], metadata: Record<number, RouteParamMetadata>, moduleContext: string, contextId?: import("..").ContextId, inquirerId?: string, contextFactory?: (args: unknown[]) => ExecutionContextHost): ParamProperties[];
getParamValue<T>(value: T, { metatype, type, data, }: {
metatype: unknown;
type: RouteParamtypes;
data: unknown;
}, pipes: PipeTransform[]): Promise<unknown>;
isPipeable(type: number | string): boolean;
createGuardsFn<TContext extends string = ContextType>(guards: CanActivate[], instance: Controller, callback: (...args: any[]) => any, contextType?: TContext): ((args: any[]) => Promise<void>) | null;
createPipesFn(pipes: PipeTransform[], paramsOptions: (ParamProperties & {
metatype?: any;
})[]): (<TRequest, TResponse>(args: any[], req: TRequest, res: TResponse, next: Function) => Promise<void>) | null;
createHandleResponseFn(callback: (...args: unknown[]) => unknown, isResponseHandled: boolean, redirectResponse?: RedirectResponse, httpStatusCode?: number): HandleResponseFn;
private isResponseHandled;
}

View File

@@ -0,0 +1,186 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RouterExecutionContext = void 0;
const common_1 = require("@nestjs/common");
const constants_1 = require("@nestjs/common/constants");
const route_paramtypes_enum_1 = require("@nestjs/common/enums/route-paramtypes.enum");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const guards_1 = require("../guards");
const context_utils_1 = require("../helpers/context-utils");
const handler_metadata_storage_1 = require("../helpers/handler-metadata-storage");
const constants_2 = require("../injector/constants");
const router_response_controller_1 = require("./router-response-controller");
class RouterExecutionContext {
constructor(paramsFactory, pipesContextCreator, pipesConsumer, guardsContextCreator, guardsConsumer, interceptorsContextCreator, interceptorsConsumer, applicationRef) {
this.paramsFactory = paramsFactory;
this.pipesContextCreator = pipesContextCreator;
this.pipesConsumer = pipesConsumer;
this.guardsContextCreator = guardsContextCreator;
this.guardsConsumer = guardsConsumer;
this.interceptorsContextCreator = interceptorsContextCreator;
this.interceptorsConsumer = interceptorsConsumer;
this.applicationRef = applicationRef;
this.handlerMetadataStorage = new handler_metadata_storage_1.HandlerMetadataStorage();
this.contextUtils = new context_utils_1.ContextUtils();
this.responseController = new router_response_controller_1.RouterResponseController(applicationRef);
}
create(instance, callback, methodName, moduleKey, requestMethod, contextId = constants_2.STATIC_CONTEXT, inquirerId) {
const contextType = 'http';
const { argsLength, fnHandleResponse, paramtypes, getParamsMetadata, httpStatusCode, responseHeaders, hasCustomHeaders, } = this.getMetadata(instance, callback, methodName, moduleKey, requestMethod, contextType);
const paramsOptions = this.contextUtils.mergeParamsMetatypes(getParamsMetadata(moduleKey, contextId, inquirerId), paramtypes);
const pipes = this.pipesContextCreator.create(instance, callback, moduleKey, contextId, inquirerId);
const guards = this.guardsContextCreator.create(instance, callback, moduleKey, contextId, inquirerId);
const interceptors = this.interceptorsContextCreator.create(instance, callback, moduleKey, contextId, inquirerId);
const fnCanActivate = this.createGuardsFn(guards, instance, callback, contextType);
const fnApplyPipes = this.createPipesFn(pipes, paramsOptions);
const handler = (args, req, res, next) => async () => {
fnApplyPipes && (await fnApplyPipes(args, req, res, next));
return callback.apply(instance, args);
};
return async (req, res, next) => {
const args = this.contextUtils.createNullArray(argsLength);
fnCanActivate && (await fnCanActivate([req, res, next]));
this.responseController.setStatus(res, httpStatusCode);
hasCustomHeaders &&
this.responseController.setHeaders(res, responseHeaders);
const result = await this.interceptorsConsumer.intercept(interceptors, [req, res, next], instance, callback, handler(args, req, res, next), contextType);
await fnHandleResponse(result, res, req);
};
}
getMetadata(instance, callback, methodName, moduleKey, requestMethod, contextType) {
const cacheMetadata = this.handlerMetadataStorage.get(instance, methodName);
if (cacheMetadata) {
return cacheMetadata;
}
const metadata = this.contextUtils.reflectCallbackMetadata(instance, methodName, constants_1.ROUTE_ARGS_METADATA) || {};
const keys = Object.keys(metadata);
const argsLength = this.contextUtils.getArgumentsLength(keys, metadata);
const paramtypes = this.contextUtils.reflectCallbackParamtypes(instance, methodName);
const contextFactory = this.contextUtils.getContextFactory(contextType, instance, callback);
const getParamsMetadata = (moduleKey, contextId = constants_2.STATIC_CONTEXT, inquirerId) => this.exchangeKeysForValues(keys, metadata, moduleKey, contextId, inquirerId, contextFactory);
const paramsMetadata = getParamsMetadata(moduleKey);
const isResponseHandled = this.isResponseHandled(instance, methodName, paramsMetadata);
const httpRedirectResponse = this.reflectRedirect(callback);
const fnHandleResponse = this.createHandleResponseFn(callback, isResponseHandled, httpRedirectResponse);
const httpCode = this.reflectHttpStatusCode(callback);
const httpStatusCode = httpCode
? httpCode
: this.responseController.getStatusByMethod(requestMethod);
const responseHeaders = this.reflectResponseHeaders(callback);
const hasCustomHeaders = !(0, shared_utils_1.isEmpty)(responseHeaders);
const handlerMetadata = {
argsLength,
fnHandleResponse,
paramtypes,
getParamsMetadata,
httpStatusCode,
hasCustomHeaders,
responseHeaders,
};
this.handlerMetadataStorage.set(instance, methodName, handlerMetadata);
return handlerMetadata;
}
reflectRedirect(callback) {
return Reflect.getMetadata(constants_1.REDIRECT_METADATA, callback);
}
reflectHttpStatusCode(callback) {
return Reflect.getMetadata(constants_1.HTTP_CODE_METADATA, callback);
}
reflectRenderTemplate(callback) {
return Reflect.getMetadata(constants_1.RENDER_METADATA, callback);
}
reflectResponseHeaders(callback) {
return Reflect.getMetadata(constants_1.HEADERS_METADATA, callback) || [];
}
reflectSse(callback) {
return Reflect.getMetadata(constants_1.SSE_METADATA, callback);
}
exchangeKeysForValues(keys, metadata, moduleContext, contextId = constants_2.STATIC_CONTEXT, inquirerId, contextFactory) {
this.pipesContextCreator.setModuleContext(moduleContext);
return keys.map(key => {
const { index, data, pipes: pipesCollection } = metadata[key];
const pipes = this.pipesContextCreator.createConcreteContext(pipesCollection, contextId, inquirerId);
const type = this.contextUtils.mapParamType(key);
if (key.includes(constants_1.CUSTOM_ROUTE_ARGS_METADATA)) {
const { factory } = metadata[key];
const customExtractValue = this.contextUtils.getCustomFactory(factory, data, contextFactory);
return { index, extractValue: customExtractValue, type, data, pipes };
}
const numericType = Number(type);
const extractValue = (req, res, next) => this.paramsFactory.exchangeKeyForValue(numericType, data, {
req: req,
res,
next,
});
return { index, extractValue, type: numericType, data, pipes };
});
}
async getParamValue(value, { metatype, type, data, }, pipes) {
if (!(0, shared_utils_1.isEmpty)(pipes)) {
return this.pipesConsumer.apply(value, { metatype, type, data }, pipes);
}
return value;
}
isPipeable(type) {
return (type === route_paramtypes_enum_1.RouteParamtypes.BODY ||
type === route_paramtypes_enum_1.RouteParamtypes.RAW_BODY ||
type === route_paramtypes_enum_1.RouteParamtypes.QUERY ||
type === route_paramtypes_enum_1.RouteParamtypes.PARAM ||
type === route_paramtypes_enum_1.RouteParamtypes.FILE ||
type === route_paramtypes_enum_1.RouteParamtypes.FILES ||
(0, shared_utils_1.isString)(type));
}
createGuardsFn(guards, instance, callback, contextType) {
const canActivateFn = async (args) => {
const canActivate = await this.guardsConsumer.tryActivate(guards, args, instance, callback, contextType);
if (!canActivate) {
throw new common_1.ForbiddenException(guards_1.FORBIDDEN_MESSAGE);
}
};
return guards.length ? canActivateFn : null;
}
createPipesFn(pipes, paramsOptions) {
const pipesFn = async (args, req, res, next) => {
const resolveParamValue = async (param) => {
const { index, extractValue, type, data, metatype, pipes: paramPipes, } = param;
const value = extractValue(req, res, next);
args[index] = this.isPipeable(type)
? await this.getParamValue(value, { metatype, type, data }, pipes.concat(paramPipes))
: value;
};
await Promise.all(paramsOptions.map(resolveParamValue));
};
return paramsOptions.length ? pipesFn : null;
}
createHandleResponseFn(callback, isResponseHandled, redirectResponse, httpStatusCode) {
const renderTemplate = this.reflectRenderTemplate(callback);
if (renderTemplate) {
return async (result, res) => {
return await this.responseController.render(result, res, renderTemplate);
};
}
if (redirectResponse && (0, shared_utils_1.isString)(redirectResponse.url)) {
return async (result, res) => {
await this.responseController.redirect(result, res, redirectResponse);
};
}
const isSseHandler = !!this.reflectSse(callback);
if (isSseHandler) {
return async (result, res, req) => {
await this.responseController.sse(result, res.raw || res, req.raw || req, { additionalHeaders: res.getHeaders?.() });
};
}
return async (result, res) => {
result = await this.responseController.transformToResult(result);
!isResponseHandled &&
(await this.responseController.apply(result, res, httpStatusCode));
return res;
};
}
isResponseHandled(instance, methodName, paramsMetadata) {
const hasResponseOrNextDecorator = paramsMetadata.some(({ type }) => type === route_paramtypes_enum_1.RouteParamtypes.RESPONSE || type === route_paramtypes_enum_1.RouteParamtypes.NEXT);
const isPassthroughEnabled = this.contextUtils.reflectPassthrough(instance, methodName);
return hasResponseOrNextDecorator && !isPassthroughEnabled;
}
}
exports.RouterExecutionContext = RouterExecutionContext;

47
node_modules/@nestjs/core/router/router-explorer.d.ts generated vendored Normal file
View File

@@ -0,0 +1,47 @@
import { HttpServer } from '@nestjs/common';
import { RequestMethod } from '@nestjs/common/enums';
import { Controller } from '@nestjs/common/interfaces/controllers/controller.interface';
import { Type } from '@nestjs/common/interfaces/type.interface';
import { VersionValue } from '@nestjs/common/interfaces/version-options.interface';
import { ApplicationConfig } from '../application-config';
import { NestContainer } from '../injector/container';
import { Injector } from '../injector/injector';
import { InstanceWrapper } from '../injector/instance-wrapper';
import { Module } from '../injector/module';
import { GraphInspector } from '../inspector/graph-inspector';
import { MetadataScanner } from '../metadata-scanner';
import { ExceptionsFilter } from './interfaces/exceptions-filter.interface';
import { RoutePathMetadata } from './interfaces/route-path-metadata.interface';
import { RoutePathFactory } from './route-path-factory';
import { RouterProxy, RouterProxyCallback } from './router-proxy';
export interface RouteDefinition {
path: string[];
requestMethod: RequestMethod;
targetCallback: RouterProxyCallback;
methodName: string;
version?: VersionValue;
}
export declare class RouterExplorer {
private readonly container;
private readonly injector;
private readonly routerProxy;
private readonly exceptionsFilter;
private readonly routePathFactory;
private readonly graphInspector;
private readonly executionContextCreator;
private readonly pathsExplorer;
private readonly routerMethodFactory;
private readonly logger;
private readonly exceptionFiltersCache;
constructor(metadataScanner: MetadataScanner, container: NestContainer, injector: Injector, routerProxy: RouterProxy, exceptionsFilter: ExceptionsFilter, config: ApplicationConfig, routePathFactory: RoutePathFactory, graphInspector: GraphInspector);
explore<T extends HttpServer = any>(instanceWrapper: InstanceWrapper, moduleKey: string, httpAdapterRef: T, host: string | RegExp | Array<string | RegExp>, routePathMetadata: RoutePathMetadata): void;
extractRouterPath(metatype: Type<Controller>): string[];
applyPathsToRouterProxy<T extends HttpServer>(router: T, routeDefinitions: RouteDefinition[], instanceWrapper: InstanceWrapper, moduleKey: string, routePathMetadata: RoutePathMetadata, host: string | RegExp | Array<string | RegExp>): void;
private applyCallbackToRouter;
private applyHostFilter;
private applyVersionFilter;
private createCallbackProxy;
createRequestScopedHandler(instanceWrapper: InstanceWrapper, requestMethod: RequestMethod, moduleRef: Module, moduleKey: string, methodName: string): <TRequest extends Record<any, any>, TResponse>(req: TRequest, res: TResponse, next: () => void) => Promise<void>;
private getContextId;
private copyMetadataToCallback;
}

234
node_modules/@nestjs/core/router/router-explorer.js generated vendored Normal file
View File

@@ -0,0 +1,234 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RouterExplorer = void 0;
const constants_1 = require("@nestjs/common/constants");
const enums_1 = require("@nestjs/common/enums");
const exceptions_1 = require("@nestjs/common/exceptions");
const logger_service_1 = require("@nestjs/common/services/logger.service");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const path_to_regexp_1 = require("path-to-regexp");
const unknown_request_mapping_exception_1 = require("../errors/exceptions/unknown-request-mapping.exception");
const guards_1 = require("../guards");
const context_id_factory_1 = require("../helpers/context-id-factory");
const execution_context_host_1 = require("../helpers/execution-context-host");
const messages_1 = require("../helpers/messages");
const router_method_factory_1 = require("../helpers/router-method-factory");
const constants_2 = require("../injector/constants");
const interceptors_1 = require("../interceptors");
const pipes_1 = require("../pipes");
const paths_explorer_1 = require("./paths-explorer");
const request_constants_1 = require("./request/request-constants");
const route_params_factory_1 = require("./route-params-factory");
const router_execution_context_1 = require("./router-execution-context");
class RouterExplorer {
constructor(metadataScanner, container, injector, routerProxy, exceptionsFilter, config, routePathFactory, graphInspector) {
this.container = container;
this.injector = injector;
this.routerProxy = routerProxy;
this.exceptionsFilter = exceptionsFilter;
this.routePathFactory = routePathFactory;
this.graphInspector = graphInspector;
this.routerMethodFactory = new router_method_factory_1.RouterMethodFactory();
this.logger = new logger_service_1.Logger(RouterExplorer.name, {
timestamp: true,
});
this.exceptionFiltersCache = new WeakMap();
this.pathsExplorer = new paths_explorer_1.PathsExplorer(metadataScanner);
const routeParamsFactory = new route_params_factory_1.RouteParamsFactory();
const pipesContextCreator = new pipes_1.PipesContextCreator(container, config);
const pipesConsumer = new pipes_1.PipesConsumer();
const guardsContextCreator = new guards_1.GuardsContextCreator(container, config);
const guardsConsumer = new guards_1.GuardsConsumer();
const interceptorsContextCreator = new interceptors_1.InterceptorsContextCreator(container, config);
const interceptorsConsumer = new interceptors_1.InterceptorsConsumer();
this.executionContextCreator = new router_execution_context_1.RouterExecutionContext(routeParamsFactory, pipesContextCreator, pipesConsumer, guardsContextCreator, guardsConsumer, interceptorsContextCreator, interceptorsConsumer, container.getHttpAdapterRef());
}
explore(instanceWrapper, moduleKey, httpAdapterRef, host, routePathMetadata) {
const { instance } = instanceWrapper;
const routerPaths = this.pathsExplorer.scanForPaths(instance);
this.applyPathsToRouterProxy(httpAdapterRef, routerPaths, instanceWrapper, moduleKey, routePathMetadata, host);
}
extractRouterPath(metatype) {
const path = Reflect.getMetadata(constants_1.PATH_METADATA, metatype);
if ((0, shared_utils_1.isUndefined)(path)) {
throw new unknown_request_mapping_exception_1.UnknownRequestMappingException(metatype);
}
if (Array.isArray(path)) {
return path.map(p => (0, shared_utils_1.addLeadingSlash)(p));
}
return [(0, shared_utils_1.addLeadingSlash)(path)];
}
applyPathsToRouterProxy(router, routeDefinitions, instanceWrapper, moduleKey, routePathMetadata, host) {
(routeDefinitions || []).forEach(routeDefinition => {
const { version: methodVersion } = routeDefinition;
routePathMetadata.methodVersion = methodVersion;
this.applyCallbackToRouter(router, routeDefinition, instanceWrapper, moduleKey, routePathMetadata, host);
});
}
applyCallbackToRouter(router, routeDefinition, instanceWrapper, moduleKey, routePathMetadata, host) {
const { path: paths, requestMethod, targetCallback, methodName, } = routeDefinition;
const { instance } = instanceWrapper;
const routerMethodRef = this.routerMethodFactory
.get(router, requestMethod)
.bind(router);
const isRequestScoped = !instanceWrapper.isDependencyTreeStatic();
const proxy = isRequestScoped
? this.createRequestScopedHandler(instanceWrapper, requestMethod, this.container.getModuleByKey(moduleKey), moduleKey, methodName)
: this.createCallbackProxy(instance, targetCallback, methodName, moduleKey, requestMethod);
const isVersioned = (routePathMetadata.methodVersion ||
routePathMetadata.controllerVersion) &&
routePathMetadata.versioningOptions;
let routeHandler = this.applyHostFilter(host, proxy);
paths.forEach(path => {
if (isVersioned &&
routePathMetadata.versioningOptions.type !== enums_1.VersioningType.URI) {
// All versioning (except for URI Versioning) is done via the "Version Filter"
routeHandler = this.applyVersionFilter(router, routePathMetadata, routeHandler);
}
routePathMetadata.methodPath = path;
const pathsToRegister = this.routePathFactory.create(routePathMetadata, requestMethod);
pathsToRegister.forEach(path => {
const entrypointDefinition = {
type: 'http-endpoint',
methodName,
className: instanceWrapper.name,
classNodeId: instanceWrapper.id,
metadata: {
key: path,
path,
requestMethod: enums_1.RequestMethod[requestMethod],
methodVersion: routePathMetadata.methodVersion,
controllerVersion: routePathMetadata.controllerVersion,
},
};
this.copyMetadataToCallback(targetCallback, routeHandler);
const normalizedPath = router.normalizePath
? router.normalizePath(path)
: path;
const httpAdapter = this.container.getHttpAdapterRef();
const onRouteTriggered = httpAdapter.getOnRouteTriggered?.();
if (onRouteTriggered) {
routerMethodRef(normalizedPath, (...args) => {
onRouteTriggered(requestMethod, path);
return routeHandler(...args);
});
}
else {
routerMethodRef(normalizedPath, routeHandler);
}
this.graphInspector.insertEntrypointDefinition(entrypointDefinition, instanceWrapper.id);
});
const pathsToLog = this.routePathFactory.create({
...routePathMetadata,
versioningOptions: undefined,
}, requestMethod);
pathsToLog.forEach(path => {
if (isVersioned) {
const version = this.routePathFactory.getVersion(routePathMetadata);
this.logger.log((0, messages_1.VERSIONED_ROUTE_MAPPED_MESSAGE)(path, requestMethod, version));
}
else {
this.logger.log((0, messages_1.ROUTE_MAPPED_MESSAGE)(path, requestMethod));
}
});
});
}
applyHostFilter(host, handler) {
if (!host) {
return handler;
}
const httpAdapterRef = this.container.getHttpAdapterRef();
const hosts = Array.isArray(host) ? host : [host];
const hostRegExps = hosts.map((host) => {
if (typeof host === 'string') {
try {
return (0, path_to_regexp_1.pathToRegexp)(host);
}
catch (e) {
if (e instanceof TypeError) {
this.logger.error(`Unsupported host "${host}" syntax. In past releases, ?, *, and + were used to denote optional or repeating path parameters. The latest version of "path-to-regexp" now requires the use of named parameters. For example, instead of using a route like /users/* to capture all routes starting with "/users", you should use /users/*path. Please see the migration guide for more information.`);
}
throw e;
}
}
return { regexp: host, keys: [] };
});
const unsupportedFilteringErrorMessage = Array.isArray(host)
? `HTTP adapter does not support filtering on hosts: ["${host.join('", "')}"]`
: `HTTP adapter does not support filtering on host: "${host}"`;
return (req, res, next) => {
req.hosts = {};
const hostname = httpAdapterRef.getRequestHostname(req) || '';
for (const exp of hostRegExps) {
const match = hostname.match(exp.regexp);
if (match) {
if (exp.keys.length > 0) {
exp.keys.forEach((key, i) => (req.hosts[key.name] = match[i + 1]));
}
else if (exp.regexp && match.groups) {
for (const groupName in match.groups) {
req.hosts[groupName] = match.groups[groupName];
}
}
return handler(req, res, next);
}
}
if (!next) {
throw new exceptions_1.InternalServerErrorException(unsupportedFilteringErrorMessage);
}
return next();
};
}
applyVersionFilter(router, routePathMetadata, handler) {
const version = this.routePathFactory.getVersion(routePathMetadata);
return router.applyVersionFilter(handler, version, routePathMetadata.versioningOptions);
}
createCallbackProxy(instance, callback, methodName, moduleRef, requestMethod, contextId = constants_2.STATIC_CONTEXT, inquirerId) {
const executionContext = this.executionContextCreator.create(instance, callback, methodName, moduleRef, requestMethod, contextId, inquirerId);
const exceptionFilter = this.exceptionsFilter.create(instance, callback, moduleRef, contextId, inquirerId);
return this.routerProxy.createProxy(executionContext, exceptionFilter);
}
createRequestScopedHandler(instanceWrapper, requestMethod, moduleRef, moduleKey, methodName) {
const { instance } = instanceWrapper;
const collection = moduleRef.controllers;
const isTreeDurable = instanceWrapper.isDependencyTreeDurable();
return async (req, res, next) => {
try {
const contextId = this.getContextId(req, isTreeDurable);
const contextInstance = await this.injector.loadPerContext(instance, moduleRef, collection, contextId);
await this.createCallbackProxy(contextInstance, contextInstance[methodName], methodName, moduleKey, requestMethod, contextId, instanceWrapper.id)(req, res, next);
}
catch (err) {
let exceptionFilter = this.exceptionFiltersCache.get(instance[methodName]);
if (!exceptionFilter) {
exceptionFilter = this.exceptionsFilter.create(instance, instance[methodName], moduleKey);
this.exceptionFiltersCache.set(instance[methodName], exceptionFilter);
}
const host = new execution_context_host_1.ExecutionContextHost([req, res, next]);
exceptionFilter.next(err, host);
}
};
}
getContextId(request, isTreeDurable) {
const contextId = context_id_factory_1.ContextIdFactory.getByRequest(request);
if (!request[request_constants_1.REQUEST_CONTEXT_ID]) {
Object.defineProperty(request, request_constants_1.REQUEST_CONTEXT_ID, {
value: contextId,
enumerable: false,
writable: false,
configurable: false,
});
const requestProviderValue = isTreeDurable
? contextId.payload
: Object.assign(request, contextId.payload);
this.container.registerRequestProvider(requestProviderValue, contextId);
}
return contextId;
}
copyMetadataToCallback(originalCallback, targetCallback) {
for (const key of Reflect.getMetadataKeys(originalCallback)) {
Reflect.defineMetadata(key, Reflect.getMetadata(key, originalCallback), targetCallback);
}
}
}
exports.RouterExplorer = RouterExplorer;

19
node_modules/@nestjs/core/router/router-module.d.ts generated vendored Normal file
View File

@@ -0,0 +1,19 @@
import { DynamicModule } from '@nestjs/common';
import { Module as ModuleClass } from '../injector/module';
import { ModulesContainer } from '../injector/modules-container';
import { Routes } from './interfaces';
export declare const ROUTES: unique symbol;
export declare const targetModulesByContainer: WeakMap<ModulesContainer, WeakSet<ModuleClass>>;
/**
* @publicApi
*/
export declare class RouterModule {
private readonly modulesContainer;
private readonly routes;
constructor(modulesContainer: ModulesContainer, routes: Routes);
static register(routes: Routes): DynamicModule;
private deepCloneRoutes;
private initialize;
private registerModulePathMetadata;
private updateTargetModulesCache;
}

80
node_modules/@nestjs/core/router/router-module.js generated vendored Normal file
View File

@@ -0,0 +1,80 @@
"use strict";
var RouterModule_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.RouterModule = exports.targetModulesByContainer = exports.ROUTES = void 0;
const tslib_1 = require("tslib");
const common_1 = require("@nestjs/common");
const constants_1 = require("@nestjs/common/constants");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const modules_container_1 = require("../injector/modules-container");
const utils_1 = require("./utils");
exports.ROUTES = Symbol('ROUTES');
exports.targetModulesByContainer = new WeakMap();
/**
* @publicApi
*/
let RouterModule = RouterModule_1 = class RouterModule {
constructor(modulesContainer, routes) {
this.modulesContainer = modulesContainer;
this.routes = routes;
this.routes = this.deepCloneRoutes(routes);
this.initialize();
}
static register(routes) {
return {
module: RouterModule_1,
providers: [
{
provide: exports.ROUTES,
useValue: routes,
},
],
};
}
deepCloneRoutes(routes) {
return routes.map((routeOrType) => {
if (typeof routeOrType === 'function') {
return routeOrType;
}
if (routeOrType.children) {
return {
...routeOrType,
children: this.deepCloneRoutes(routeOrType.children),
};
}
return { ...routeOrType };
});
}
initialize() {
const flattenedRoutes = (0, utils_1.flattenRoutePaths)(this.routes);
flattenedRoutes.forEach(route => {
const modulePath = (0, shared_utils_1.normalizePath)(route.path);
this.registerModulePathMetadata(route.module, modulePath);
this.updateTargetModulesCache(route.module);
});
}
registerModulePathMetadata(moduleCtor, modulePath) {
Reflect.defineMetadata(constants_1.MODULE_PATH + this.modulesContainer.applicationId, modulePath, moduleCtor);
}
updateTargetModulesCache(moduleCtor) {
let moduleClassSet;
if (exports.targetModulesByContainer.has(this.modulesContainer)) {
moduleClassSet = exports.targetModulesByContainer.get(this.modulesContainer);
}
else {
moduleClassSet = new WeakSet();
exports.targetModulesByContainer.set(this.modulesContainer, moduleClassSet);
}
const moduleRef = Array.from(this.modulesContainer.values()).find(item => item?.metatype === moduleCtor);
if (!moduleRef) {
return;
}
moduleClassSet.add(moduleRef);
}
};
exports.RouterModule = RouterModule;
exports.RouterModule = RouterModule = RouterModule_1 = tslib_1.__decorate([
(0, common_1.Module)({}),
tslib_1.__param(1, (0, common_1.Inject)(exports.ROUTES)),
tslib_1.__metadata("design:paramtypes", [modules_container_1.ModulesContainer, Array])
], RouterModule);

6
node_modules/@nestjs/core/router/router-proxy.d.ts generated vendored Normal file
View File

@@ -0,0 +1,6 @@
import { ExceptionsHandler } from '../exceptions/exceptions-handler';
export type RouterProxyCallback = <TRequest, TResponse>(req: TRequest, res: TResponse, next: () => void) => void | Promise<void>;
export declare class RouterProxy {
createProxy(targetCallback: RouterProxyCallback, exceptionsHandler: ExceptionsHandler): <TRequest, TResponse>(req: TRequest, res: TResponse, next: () => void) => Promise<TResponse | undefined>;
createExceptionLayerProxy(targetCallback: <TError, TRequest, TResponse>(err: TError, req: TRequest, res: TResponse, next: () => void) => void | Promise<void>, exceptionsHandler: ExceptionsHandler): <TError, TRequest, TResponse>(err: TError, req: TRequest, res: TResponse, next: () => void) => Promise<TResponse | undefined>;
}

31
node_modules/@nestjs/core/router/router-proxy.js generated vendored Normal file
View File

@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RouterProxy = void 0;
const execution_context_host_1 = require("../helpers/execution-context-host");
class RouterProxy {
createProxy(targetCallback, exceptionsHandler) {
return async (req, res, next) => {
try {
await targetCallback(req, res, next);
}
catch (e) {
const host = new execution_context_host_1.ExecutionContextHost([req, res, next]);
exceptionsHandler.next(e, host);
return res;
}
};
}
createExceptionLayerProxy(targetCallback, exceptionsHandler) {
return async (err, req, res, next) => {
try {
await targetCallback(err, req, res, next);
}
catch (e) {
const host = new execution_context_host_1.ExecutionContextHost([req, res, next]);
exceptionsHandler.next(e, host);
return res;
}
};
}
}
exports.RouterProxy = RouterProxy;

View File

@@ -0,0 +1,28 @@
import { HttpServer, RequestMethod } from '@nestjs/common';
import { IncomingMessage } from 'http';
import { Observable } from 'rxjs';
import { AdditionalHeaders, WritableHeaderStream } from './sse-stream';
export interface CustomHeader {
name: string;
value: string | (() => string);
}
export interface RedirectResponse {
url: string;
statusCode?: number;
}
export declare class RouterResponseController {
private readonly applicationRef;
private readonly logger;
constructor(applicationRef: HttpServer);
apply<TInput = any, TResponse = any>(result: TInput, response: TResponse, httpStatusCode?: number): Promise<any>;
redirect<TInput = any, TResponse = any>(resultOrDeferred: TInput, response: TResponse, redirectResponse: RedirectResponse): Promise<void>;
render<TInput = unknown, TResponse = unknown>(resultOrDeferred: TInput, response: TResponse, template: string): Promise<any>;
transformToResult(resultOrDeferred: any): Promise<any>;
getStatusByMethod(requestMethod: RequestMethod): number;
setHeaders<TResponse = unknown>(response: TResponse, headers: CustomHeader[]): void;
setStatus<TResponse = unknown>(response: TResponse, statusCode: number): void;
sse<TInput extends Observable<unknown> = any, TResponse extends WritableHeaderStream = any, TRequest extends IncomingMessage = any>(result: TInput | Promise<TInput>, response: TResponse, request: TRequest, options?: {
additionalHeaders: AdditionalHeaders;
}): Promise<void>;
private assertObservable;
}

View File

@@ -0,0 +1,98 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RouterResponseController = void 0;
const common_1 = require("@nestjs/common");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const rxjs_1 = require("rxjs");
const operators_1 = require("rxjs/operators");
const sse_stream_1 = require("./sse-stream");
class RouterResponseController {
constructor(applicationRef) {
this.applicationRef = applicationRef;
this.logger = new common_1.Logger(RouterResponseController.name);
}
async apply(result, response, httpStatusCode) {
return this.applicationRef.reply(response, result, httpStatusCode);
}
async redirect(resultOrDeferred, response, redirectResponse) {
const result = await this.transformToResult(resultOrDeferred);
const statusCode = result && result.statusCode
? result.statusCode
: redirectResponse.statusCode
? redirectResponse.statusCode
: common_1.HttpStatus.FOUND;
const url = result && result.url ? result.url : redirectResponse.url;
this.applicationRef.redirect(response, statusCode, url);
}
async render(resultOrDeferred, response, template) {
const result = await this.transformToResult(resultOrDeferred);
return this.applicationRef.render(response, template, result);
}
async transformToResult(resultOrDeferred) {
if ((0, rxjs_1.isObservable)(resultOrDeferred)) {
return (0, rxjs_1.lastValueFrom)(resultOrDeferred);
}
return resultOrDeferred;
}
getStatusByMethod(requestMethod) {
switch (requestMethod) {
case common_1.RequestMethod.POST:
return common_1.HttpStatus.CREATED;
default:
return common_1.HttpStatus.OK;
}
}
setHeaders(response, headers) {
headers.forEach(({ name, value }) => this.applicationRef.setHeader(response, name, typeof value === 'function' ? value() : value));
}
setStatus(response, statusCode) {
this.applicationRef.status(response, statusCode);
}
async sse(result, response, request, options) {
// It's possible that we sent headers already so don't use a stream
if (response.writableEnded) {
return;
}
const observableResult = await Promise.resolve(result);
this.assertObservable(observableResult);
const stream = new sse_stream_1.SseStream(request);
// Extract custom status code from response if it was set
const customStatusCode = response.statusCode;
const pipeOptions = typeof customStatusCode !== 'undefined'
? { ...options, statusCode: customStatusCode }
: options;
stream.pipe(response, pipeOptions);
const subscription = observableResult
.pipe((0, operators_1.map)((message) => {
if ((0, shared_utils_1.isObject)(message)) {
return message;
}
return { data: message };
}), (0, operators_1.concatMap)(message => new Promise(resolve => stream.writeMessage(message, () => resolve()))), (0, operators_1.catchError)(err => {
const data = err instanceof Error ? err.message : err;
stream.writeMessage({ type: 'error', data }, writeError => {
if (writeError) {
this.logger.error(writeError);
}
});
return rxjs_1.EMPTY;
}))
.subscribe({
complete: () => {
response.end();
},
});
request.on('close', () => {
subscription.unsubscribe();
if (!stream.writableEnded) {
stream.end();
}
});
}
assertObservable(value) {
if (!(0, rxjs_1.isObservable)(value)) {
throw new ReferenceError('You must return an Observable stream to use Server-Sent Events (SSE).');
}
}
}
exports.RouterResponseController = RouterResponseController;

27
node_modules/@nestjs/core/router/routes-resolver.d.ts generated vendored Normal file
View File

@@ -0,0 +1,27 @@
import { Controller, HttpServer } from '@nestjs/common/interfaces';
import { ApplicationConfig } from '../application-config';
import { NestContainer } from '../injector/container';
import { Injector } from '../injector/injector';
import { InstanceWrapper } from '../injector/instance-wrapper';
import { GraphInspector } from '../inspector/graph-inspector';
import { Resolver } from './interfaces/resolver.interface';
export declare class RoutesResolver implements Resolver {
private readonly container;
private readonly applicationConfig;
private readonly injector;
private readonly logger;
private readonly routerProxy;
private readonly routePathFactory;
private readonly routerExceptionsFilter;
private readonly routerExplorer;
constructor(container: NestContainer, applicationConfig: ApplicationConfig, injector: Injector, graphInspector: GraphInspector);
resolve<T extends HttpServer>(applicationRef: T, globalPrefix: string): void;
registerRouters(routes: Map<string | symbol | Function, InstanceWrapper<Controller>>, moduleName: string, globalPrefix: string, modulePath: string, applicationRef: HttpServer): void;
registerNotFoundHandler(): void;
registerExceptionHandler(): void;
mapExternalException(err: any): any;
private isHttpFastifyError;
private getModulePathMetadata;
private getHostMetadata;
private getVersionMetadata;
}

129
node_modules/@nestjs/core/router/routes-resolver.js generated vendored Normal file
View File

@@ -0,0 +1,129 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RoutesResolver = void 0;
const common_1 = require("@nestjs/common");
const constants_1 = require("@nestjs/common/constants");
const logger_service_1 = require("@nestjs/common/services/logger.service");
const messages_1 = require("../helpers/messages");
const metadata_scanner_1 = require("../metadata-scanner");
const route_path_factory_1 = require("./route-path-factory");
const router_exception_filters_1 = require("./router-exception-filters");
const router_explorer_1 = require("./router-explorer");
const router_proxy_1 = require("./router-proxy");
class RoutesResolver {
constructor(container, applicationConfig, injector, graphInspector) {
this.container = container;
this.applicationConfig = applicationConfig;
this.injector = injector;
this.logger = new logger_service_1.Logger(RoutesResolver.name, {
timestamp: true,
});
this.routerProxy = new router_proxy_1.RouterProxy();
const httpAdapterRef = container.getHttpAdapterRef();
this.routerExceptionsFilter = new router_exception_filters_1.RouterExceptionFilters(container, applicationConfig, httpAdapterRef);
this.routePathFactory = new route_path_factory_1.RoutePathFactory(this.applicationConfig);
const metadataScanner = new metadata_scanner_1.MetadataScanner();
this.routerExplorer = new router_explorer_1.RouterExplorer(metadataScanner, this.container, this.injector, this.routerProxy, this.routerExceptionsFilter, this.applicationConfig, this.routePathFactory, graphInspector);
}
resolve(applicationRef, globalPrefix) {
const modules = this.container.getModules();
modules.forEach(({ controllers, metatype }, moduleName) => {
const modulePath = this.getModulePathMetadata(metatype);
this.registerRouters(controllers, moduleName, globalPrefix, modulePath, applicationRef);
});
}
registerRouters(routes, moduleName, globalPrefix, modulePath, applicationRef) {
routes.forEach(instanceWrapper => {
const { metatype } = instanceWrapper;
const host = this.getHostMetadata(metatype);
const routerPaths = this.routerExplorer.extractRouterPath(metatype);
const controllerVersion = this.getVersionMetadata(metatype);
const controllerName = metatype.name;
routerPaths.forEach(path => {
const pathsToLog = this.routePathFactory.create({
ctrlPath: path,
modulePath,
globalPrefix,
});
if (!controllerVersion) {
pathsToLog.forEach(path => {
const logMessage = (0, messages_1.CONTROLLER_MAPPING_MESSAGE)(controllerName, path);
this.logger.log(logMessage);
});
}
else {
pathsToLog.forEach(path => {
const logMessage = (0, messages_1.VERSIONED_CONTROLLER_MAPPING_MESSAGE)(controllerName, path, controllerVersion);
this.logger.log(logMessage);
});
}
const versioningOptions = this.applicationConfig.getVersioning();
const routePathMetadata = {
ctrlPath: path,
modulePath,
globalPrefix,
controllerVersion,
versioningOptions,
};
this.routerExplorer.explore(instanceWrapper, moduleName, applicationRef, host, routePathMetadata);
});
});
}
registerNotFoundHandler() {
const applicationRef = this.container.getHttpAdapterRef();
const callback = (req, res) => {
const method = applicationRef.getRequestMethod(req);
const url = applicationRef.getRequestUrl(req);
throw new common_1.NotFoundException(`Cannot ${method} ${url}`);
};
const handler = this.routerExceptionsFilter.create({}, callback, undefined);
const proxy = this.routerProxy.createProxy(callback, handler);
applicationRef.setNotFoundHandler &&
applicationRef.setNotFoundHandler(proxy, this.applicationConfig.getGlobalPrefix());
}
registerExceptionHandler() {
const callback = (err, req, res, next) => {
throw this.mapExternalException(err);
};
const handler = this.routerExceptionsFilter.create({}, callback, undefined);
const proxy = this.routerProxy.createExceptionLayerProxy(callback, handler);
const applicationRef = this.container.getHttpAdapterRef();
applicationRef.setErrorHandler &&
applicationRef.setErrorHandler(proxy, this.applicationConfig.getGlobalPrefix());
}
mapExternalException(err) {
switch (true) {
// SyntaxError is thrown by Express body-parser when given invalid JSON (#422, #430)
// URIError is thrown by Express when given a path parameter with an invalid percentage
// encoding, e.g. '%FF' (#8915)
case err instanceof SyntaxError || err instanceof URIError:
return new common_1.BadRequestException(err.message);
case this.isHttpFastifyError(err):
return new common_1.HttpException(err.message, err.statusCode);
default:
return err;
}
}
isHttpFastifyError(error) {
// condition based on this code - https://github.com/fastify/fastify-error/blob/d669b150a82968322f9f7be992b2f6b463272de3/index.js#L22
return (error.statusCode !== undefined &&
error instanceof Error &&
error.name === 'FastifyError');
}
getModulePathMetadata(metatype) {
const modulesContainer = this.container.getModules();
const modulePath = Reflect.getMetadata(constants_1.MODULE_PATH + modulesContainer.applicationId, metatype);
return modulePath ?? Reflect.getMetadata(constants_1.MODULE_PATH, metatype);
}
getHostMetadata(metatype) {
return Reflect.getMetadata(constants_1.HOST_METADATA, metatype);
}
getVersionMetadata(metatype) {
const versioningConfig = this.applicationConfig.getVersioning();
if (versioningConfig) {
return (Reflect.getMetadata(constants_1.VERSION_METADATA, metatype) ??
versioningConfig.defaultVersion);
}
}
}
exports.RoutesResolver = RoutesResolver;

43
node_modules/@nestjs/core/router/sse-stream.d.ts generated vendored Normal file
View File

@@ -0,0 +1,43 @@
import { MessageEvent } from '@nestjs/common/interfaces';
import { IncomingMessage, OutgoingHttpHeaders } from 'http';
import { Transform } from 'stream';
export type AdditionalHeaders = Record<string, string[] | string | number | undefined>;
interface ReadHeaders {
getHeaders?(): AdditionalHeaders;
}
interface WriteHeaders {
writableEnded?: boolean;
writeHead?(statusCode: number, reasonPhrase?: string, headers?: OutgoingHttpHeaders): void;
writeHead?(statusCode: number, headers?: OutgoingHttpHeaders): void;
flushHeaders?(): void;
}
export type WritableHeaderStream = NodeJS.WritableStream & WriteHeaders;
export type HeaderStream = WritableHeaderStream & ReadHeaders;
/**
* Adapted from https://raw.githubusercontent.com/EventSource/node-ssestream
* Transforms "messages" to W3C event stream content.
* See https://html.spec.whatwg.org/multipage/server-sent-events.html
* A message is an object with one or more of the following properties:
* - data (String or object, which gets turned into JSON)
* - type
* - id
* - retry
*
* If constructed with a HTTP Request, it will optimise the socket for streaming.
* If this stream is piped to an HTTP Response, it will set appropriate headers.
*/
export declare class SseStream extends Transform {
private lastEventId;
constructor(req?: IncomingMessage);
pipe<T extends WritableHeaderStream>(destination: T, options?: {
additionalHeaders?: AdditionalHeaders;
statusCode?: number;
end?: boolean;
}): T;
_transform(message: MessageEvent, encoding: string, callback: (error?: Error | null, data?: any) => void): void;
/**
* Calls `.write` but handles the drain if needed
*/
writeMessage(message: MessageEvent, cb: (error: Error | null | undefined) => void): void;
}
export {};

83
node_modules/@nestjs/core/router/sse-stream.js generated vendored Normal file
View File

@@ -0,0 +1,83 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SseStream = void 0;
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const stream_1 = require("stream");
function toDataString(data) {
if ((0, shared_utils_1.isObject)(data)) {
return toDataString(JSON.stringify(data));
}
return data
.split(/\r\n|\r|\n/)
.map(line => `data: ${line}\n`)
.join('');
}
/**
* Adapted from https://raw.githubusercontent.com/EventSource/node-ssestream
* Transforms "messages" to W3C event stream content.
* See https://html.spec.whatwg.org/multipage/server-sent-events.html
* A message is an object with one or more of the following properties:
* - data (String or object, which gets turned into JSON)
* - type
* - id
* - retry
*
* If constructed with a HTTP Request, it will optimise the socket for streaming.
* If this stream is piped to an HTTP Response, it will set appropriate headers.
*/
class SseStream extends stream_1.Transform {
constructor(req) {
super({ objectMode: true });
this.lastEventId = null;
if (req && req.socket) {
req.socket.setKeepAlive(true);
req.socket.setNoDelay(true);
req.socket.setTimeout(0);
}
}
pipe(destination, options) {
if (destination.writeHead) {
const statusCode = options?.statusCode ?? 200;
destination.writeHead(statusCode, {
...options?.additionalHeaders,
// See https://github.com/dunglas/mercure/blob/master/hub/subscribe.go#L124-L130
'Content-Type': 'text/event-stream',
Connection: 'keep-alive',
// Disable cache, even for old browsers and proxies
'Cache-Control': 'private, no-cache, no-store, must-revalidate, max-age=0, no-transform',
Pragma: 'no-cache',
Expire: '0',
// NGINX support https://www.nginx.com/resources/wiki/start/topics/examples/x-accel/#x-accel-buffering
'X-Accel-Buffering': 'no',
});
destination.flushHeaders?.();
}
destination.write('\n');
return super.pipe(destination, options);
}
_transform(message, encoding, callback) {
let data = message.type ? `event: ${message.type}\n` : '';
data += message.id ? `id: ${message.id}\n` : '';
data += message.retry ? `retry: ${message.retry}\n` : '';
data += message.data ? toDataString(message.data) : '';
data += '\n';
this.push(data);
callback();
}
/**
* Calls `.write` but handles the drain if needed
*/
writeMessage(message, cb) {
if (!message.id) {
this.lastEventId++;
message.id = this.lastEventId.toString();
}
if (!this.write(message, 'utf-8')) {
this.once('drain', cb);
}
else {
process.nextTick(cb);
}
}
}
exports.SseStream = SseStream;

View File

@@ -0,0 +1,4 @@
import { RequestMethod } from '@nestjs/common';
import { ExcludeRouteMetadata } from '../interfaces/exclude-route-metadata.interface';
export declare const isRequestMethodAll: (method: RequestMethod) => boolean;
export declare function isRouteExcluded(excludedRoutes: ExcludeRouteMetadata[], path: string, requestMethod?: RequestMethod): boolean;

View File

@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isRequestMethodAll = void 0;
exports.isRouteExcluded = isRouteExcluded;
const common_1 = require("@nestjs/common");
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
const isRequestMethodAll = (method) => {
return common_1.RequestMethod.ALL === method || method === -1;
};
exports.isRequestMethodAll = isRequestMethodAll;
function isRouteExcluded(excludedRoutes, path, requestMethod) {
return excludedRoutes.some(route => {
if ((0, exports.isRequestMethodAll)(route.requestMethod) ||
route.requestMethod === requestMethod) {
return route.pathRegex.exec((0, shared_utils_1.addLeadingSlash)(path));
}
return false;
});
}

View File

@@ -0,0 +1,6 @@
import { Type } from '@nestjs/common';
import { Routes } from '../interfaces/routes.interface';
export declare function flattenRoutePaths(routes: Routes): {
module: Type;
path: string;
}[];

View File

@@ -0,0 +1,25 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.flattenRoutePaths = flattenRoutePaths;
const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
function flattenRoutePaths(routes) {
const result = [];
routes.forEach(item => {
if (item.module && item.path) {
result.push({ module: item.module, path: item.path });
}
if (item.children) {
const childrenRef = item.children;
childrenRef.forEach(child => {
if (!(0, shared_utils_1.isString)(child) && (0, shared_utils_1.isString)(child.path)) {
child.path = (0, shared_utils_1.normalizePath)((0, shared_utils_1.normalizePath)(item.path) + (0, shared_utils_1.normalizePath)(child.path));
}
else {
result.push({ path: item.path, module: child });
}
});
result.push(...flattenRoutePaths(childrenRef));
}
});
return result;
}

2
node_modules/@nestjs/core/router/utils/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
export * from './exclude-route.util';
export * from './flatten-route-paths.util';

5
node_modules/@nestjs/core/router/utils/index.js generated vendored Normal file
View File

@@ -0,0 +1,5 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
tslib_1.__exportStar(require("./exclude-route.util"), exports);
tslib_1.__exportStar(require("./flatten-route-paths.util"), exports);