truxie 0.1.0-test.12 → 0.1.0-test.13

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.
Files changed (3) hide show
  1. package/dist/index.d.ts +1 -155
  2. package/dist/index.js +3 -3
  3. package/package.json +104 -104
package/dist/index.d.ts CHANGED
@@ -3,7 +3,6 @@ import { T as Token, I as InjectableOptions, a as Type, F as ForwardRef, M as Mo
3
3
  export { C as ClassProvider, E as ExistingProvider, d as FactoryProvider, e as ModuleOptionsFactory, S as Scope, V as ValueProvider } from './types-D-An5cXP.js';
4
4
  import { E as ExecutionContext, I as ICanActivateGuard } from './interfaces-zvtMSS9r.js';
5
5
  export { B as BaseExecutionContext, F as FormDataPart } from './interfaces-zvtMSS9r.js';
6
- import { ZodSchema } from 'zod';
7
6
  import { E as EventBusOptions, a as EventEmitter2 } from './event-bus-BKPUV8M9.js';
8
7
  export { D as DomainEvent, b as EventHandler } from './event-bus-BKPUV8M9.js';
9
8
  import { W as WsPeer, a as WsMessage } from './types-G2NQp5Jb.js';
@@ -365,53 +364,6 @@ declare class UnitOfWorkInterceptor implements Interceptor {
365
364
  intercept(ctx: ExecutionContext, next: () => Promise<unknown>): Promise<unknown>;
366
365
  }
367
366
 
368
- /**
369
- * Interceptor that transforms the handler response through a Zod schema.
370
- *
371
- * Applied automatically by the `@Serialize` decorator.
372
- * Strips any fields not declared in the schema — preventing accidental
373
- * data leaks (passwords, internal IDs, etc.).
374
- *
375
- * Arrays are parsed element-wise via `z.array(schema)`.
376
- *
377
- * @internal
378
- */
379
- declare class SerializeInterceptor implements Interceptor {
380
- intercept(ctx: ExecutionContext, next: () => Promise<unknown>): Promise<unknown>;
381
- }
382
- /**
383
- * Decorator that applies response serialization via a Zod schema.
384
- *
385
- * Works as both a method and class decorator:
386
- * - Method: serializes only that route's response
387
- * - Class: serializes all routes in the controller
388
- *
389
- * The schema acts as an allow-list — only declared fields pass through.
390
- * Undeclared fields are stripped, preventing accidental data leaks.
391
- *
392
- * @example
393
- * ```ts
394
- * const userResponse = z.object({
395
- * id: z.string(),
396
- * email: z.string(),
397
- * name: z.string(),
398
- * // password NOT included → auto-stripped
399
- * })
400
- *
401
- * @Serialize(userResponse)
402
- * @Get('/:id')
403
- * async getUser(@Param('id') id: string) {
404
- * return this.userService.findById(id) // password field auto-stripped
405
- * }
406
- * ```
407
- */
408
- declare function Serialize<T extends ZodSchema>(schema: T): any;
409
- /**
410
- * Read the serialize schema from a handler function.
411
- * Used by the SerializeInterceptor to check if serialization is needed.
412
- */
413
- declare function getSerializeSchema(fn: Function): ZodSchema | undefined;
414
-
415
367
  type MiddlewareRef = Type<Middleware> | Middleware;
416
368
  /**
417
369
  * Attach middleware to a controller class or a specific route method.
@@ -441,25 +393,6 @@ declare function getEffectiveMiddlewares(target: Function, methodName: string):
441
393
 
442
394
  declare function UsePipes(...pipes: PipeRef[]): ClassDecorator & MethodDecorator;
443
395
 
444
- interface ZodLikeSchema {
445
- parse(data: unknown): unknown;
446
- safeParse(data: unknown): {
447
- success: boolean;
448
- data?: unknown;
449
- error?: {
450
- issues: Array<{
451
- path: (string | number)[];
452
- message: string;
453
- }>;
454
- };
455
- };
456
- }
457
- declare class ZodValidationPipe implements PipeTransform {
458
- private readonly schema;
459
- constructor(schema: ZodLikeSchema);
460
- transform(ctx: ExecutionContext): void;
461
- }
462
-
463
396
  declare class ParseIdPipe implements PipeTransform {
464
397
  private readonly paramName;
465
398
  constructor(paramName?: string);
@@ -470,25 +403,6 @@ declare class ParseIntPipe implements ParamPipe {
470
403
  transform(value: unknown): number;
471
404
  }
472
405
 
473
- /**
474
- * Param-level Zod pipe. Validates (and coerces) a single extracted parameter
475
- * value against a Zod schema.
476
- *
477
- * @example
478
- * const ExportQuerySchema = z.object({
479
- * email: z.string().email().optional(),
480
- * page: z.coerce.number().int().positive().default(1),
481
- * })
482
- *
483
- * @Get('export')
484
- * async export(@Query(undefined, new ZodParamPipe(ExportQuerySchema)) query: ExportQuery) {}
485
- */
486
- declare class ZodParamPipe<T> implements ParamPipe {
487
- private readonly schema;
488
- constructor(schema: ZodSchema<T>);
489
- transform(value: unknown): T;
490
- }
491
-
492
406
  /**
493
407
  * Factory that returns a pipe replacing `null` or `undefined` with a default value.
494
408
  * Designed to be placed before type-coercion pipes in a chain.
@@ -499,74 +413,6 @@ declare class ZodParamPipe<T> implements ParamPipe {
499
413
  */
500
414
  declare function DefaultValuePipe(defaultValue: unknown): ParamPipe;
501
415
 
502
- /**
503
- * Factory that creates a typed `@Body()` parameter decorator which
504
- * validates the request body against a Zod schema.
505
- *
506
- * @example
507
- * ```ts
508
- * const createUserSchema = z.object({
509
- * email: z.string().email(),
510
- * name: z.string().min(1),
511
- * })
512
- *
513
- * const CreateUserDTO = ZodValidatedBody(createUserSchema)
514
- *
515
- * @Post('/')
516
- * async create(@CreateUserDTO() body) {
517
- * // body is parsed & validated — z.infer<typeof createUserSchema>
518
- * }
519
- * ```
520
- */
521
- declare function ZodValidatedBody<T extends ZodSchema>(schema: T): () => ParameterDecorator;
522
-
523
- /**
524
- * Factory that creates a typed `@Query()` parameter decorator which
525
- * validates and coerces query parameters against a Zod schema.
526
- *
527
- * Query params arrive as strings — use `z.coerce` for numeric/boolean fields.
528
- *
529
- * @example
530
- * ```ts
531
- * const listUsersQuery = z.object({
532
- * search: z.string().optional(),
533
- * page: z.coerce.number().int().positive().default(1),
534
- * limit: z.coerce.number().int().max(100).default(20),
535
- * role: z.enum(['admin', 'user']).optional(),
536
- * })
537
- *
538
- * const ListUsersQuery = ZodValidatedQuery(listUsersQuery)
539
- *
540
- * @Get('/')
541
- * async list(@ListUsersQuery() query) {
542
- * // query is parsed & validated — z.infer<typeof listUsersQuery>
543
- * }
544
- * ```
545
- */
546
- declare function ZodValidatedQuery<T extends ZodSchema>(schema: T): () => ParameterDecorator;
547
-
548
- /**
549
- * Factory that creates a typed `@Params()` parameter decorator which
550
- * validates URL path parameters against a Zod schema.
551
- *
552
- * URL params are always strings — use `z.coerce` for numeric fields.
553
- *
554
- * @example
555
- * ```ts
556
- * const productParams = z.object({
557
- * id: z.string().min(1),
558
- * })
559
- *
560
- * const ProductParams = ZodValidatedParams(productParams)
561
- *
562
- * @Get('/:id')
563
- * async getById(@ProductParams() params) {
564
- * // params.id is validated
565
- * }
566
- * ```
567
- */
568
- declare function ZodValidatedParams<T extends ZodSchema>(schema: T): () => ParameterDecorator;
569
-
570
416
  declare function UseFilters(...filters: FilterRef[]): ClassDecorator & MethodDecorator;
571
417
  declare function Catch(...exceptions: Type<Error>[]): ClassDecorator;
572
418
 
@@ -1026,4 +872,4 @@ declare class TruxieFactory {
1026
872
  static create(rootModule: Type | DynamicModule, options?: ApplicationOptions): Promise<TruxieApplication>;
1027
873
  }
1028
874
 
1029
- export { AppError, type ApplicationOptions, Auth, type AuthExtractorFn, Body, Catch, type CompiledRoute, ConfigurableModuleBuilder, type ConfigurableModuleBuilderResult, type ConfigurableModuleClass, ConflictError, Container, Controller, ControllerRouter, Cookie, type CreatePipelineOptions, DefaultValuePipe, Delete, DiscoveryService, DynamicModule, EventBusOptions, EventEmitter2, type ExceptionFilter, ExecutionContext, type ExtraOptions, type FeatureConfig, type FilterRef, ForbiddenError, FormData, ForwardRef, Get, Global, type GuardClass, type GuardInstance, type GuardRef, type HandlerFn, Headers, type HttpDispatchResult, type HttpMethod, ICanActivateGuard, type IUseCase, Inject, Injectable, InjectableOptions, type Interceptor, type InterceptorRef, Ip, type Middleware, type MiddlewareRef, Module, ModuleAsyncOptions, ModuleMetadata, ModuleRegistry, NoGuard, NotFoundError, type OnApplicationBootstrap, type OnApplicationShutdown, OnEvent, type OnModuleDestroy, type OnModuleInit, Optional, Param, type ParamPipe, type ParamPipeRef, ParseIdPipe, ParseIntPipe, Patch, type PipeRef, type PipeTransform, type PipelineOptions, Post, Provider, Put, Query, REDIRECT_BRAND, RawBody, type RedirectResult, RequestAbortedError, RouteGuards, type RouteMatch, type RouteMetadata, type RouteParamMetadata, type RouteParamType, Serialize, SerializeInterceptor, Token, TruxieApplication, TruxieFactory, Type, UOW_INSTANCE_KEY, UOW_SESSION_KEY, UnauthorizedError, type UnitOfWork, type UnitOfWorkFactory, UnitOfWorkInterceptor, UseFilters, UseInterceptors, UseMiddleware, UsePipes, UserAgent, ValidationError, type WsHooks, type WsHooksAdapters, ZodParamPipe, ZodValidatedBody, ZodValidatedParams, ZodValidatedQuery, ZodValidationPipe, createParamDecorator, createPipeline, defineAuth, forwardRef, getControllerGuards, getControllerPath, getEffectiveInterceptors, getEffectiveMiddlewares, getInterceptorsMetadata, getMethodGuards, getMethodInterceptors, getMethodMiddlewares, getMiddlewaresMetadata, getModuleMetadata, getRouteMetadata, getRouteParams, getSerializeSchema, isGlobalModule, isRedirect, isServerless, redirect, resolveForwardRef, resolveParamArgs };
875
+ export { AppError, type ApplicationOptions, Auth, type AuthExtractorFn, Body, Catch, type CompiledRoute, ConfigurableModuleBuilder, type ConfigurableModuleBuilderResult, type ConfigurableModuleClass, ConflictError, Container, Controller, ControllerRouter, Cookie, type CreatePipelineOptions, DefaultValuePipe, Delete, DiscoveryService, DynamicModule, EventBusOptions, EventEmitter2, type ExceptionFilter, ExecutionContext, type ExtraOptions, type FeatureConfig, type FilterRef, ForbiddenError, FormData, ForwardRef, Get, Global, type GuardClass, type GuardInstance, type GuardRef, type HandlerFn, Headers, type HttpDispatchResult, type HttpMethod, ICanActivateGuard, type IUseCase, Inject, Injectable, InjectableOptions, type Interceptor, type InterceptorRef, Ip, type Middleware, type MiddlewareRef, Module, ModuleAsyncOptions, ModuleMetadata, ModuleRegistry, NoGuard, NotFoundError, type OnApplicationBootstrap, type OnApplicationShutdown, OnEvent, type OnModuleDestroy, type OnModuleInit, Optional, Param, type ParamPipe, type ParamPipeRef, ParseIdPipe, ParseIntPipe, Patch, type PipeRef, type PipeTransform, type PipelineOptions, Post, Provider, Put, Query, REDIRECT_BRAND, RawBody, type RedirectResult, RequestAbortedError, RouteGuards, type RouteMatch, type RouteMetadata, type RouteParamMetadata, type RouteParamType, Token, TruxieApplication, TruxieFactory, Type, UOW_INSTANCE_KEY, UOW_SESSION_KEY, UnauthorizedError, type UnitOfWork, type UnitOfWorkFactory, UnitOfWorkInterceptor, UseFilters, UseInterceptors, UseMiddleware, UsePipes, UserAgent, ValidationError, type WsHooks, type WsHooksAdapters, createParamDecorator, createPipeline, defineAuth, forwardRef, getControllerGuards, getControllerPath, getEffectiveInterceptors, getEffectiveMiddlewares, getInterceptorsMetadata, getMethodGuards, getMethodInterceptors, getMethodMiddlewares, getMiddlewaresMetadata, getModuleMetadata, getRouteMetadata, getRouteParams, isGlobalModule, isRedirect, isServerless, redirect, resolveForwardRef, resolveParamArgs };
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import {l,n,o,c as c$1,p,q as q$1,s}from'./chunk-IEQXYYZJ.js';export{c as Container,d as Controller,h as Delete,q as EventEmitter2,e as Get,p as ModuleRegistry,k as NoGuard,r as OnEvent,i as Patch,f as Post,g as Put,j as RouteGuards,a as forwardRef,m as getControllerGuards,l as getControllerPath,o as getMethodGuards,n as getRouteMetadata,b as resolveForwardRef}from'./chunk-IEQXYYZJ.js';import {a as a$1}from'./chunk-2ACNLLXS.js';export{a as DiscoveryService}from'./chunk-2ACNLLXS.js';import {c,e,g as g$1}from'./chunk-PT5RXFB5.js';export{a as AppError,f as ConflictError,e as ForbiddenError,b as NotFoundError,g as RequestAbortedError,d as UnauthorizedError,c as ValidationError}from'./chunk-PT5RXFB5.js';import {b}from'./chunk-MF2CCNPQ.js';export{k as Global,d as Inject,c as Injectable,j as Module,e as Optional,a as Scope,l as getModuleMetadata,m as isGlobalModule}from'./chunk-MF2CCNPQ.js';import {n as n$1,i,j as j$1,k as k$1,m}from'./chunk-RLQ7JJW6.js';import {a}from'./chunk-EI7MMDWY.js';import'reflect-metadata';function gt(o,e){if("useFactory"in e&&e.useFactory){let r=e.useFactory;return [{provide:o,useFactory:r,inject:e.inject??[]}]}if("useClass"in e&&e.useClass){let r=e.useClass;return [{provide:o,useFactory:a(async t=>t.createModuleOptions(),"useFactory"),inject:[r]},r]}if("useExisting"in e&&e.useExisting){let r=e.useExisting;return [{provide:o,useFactory:a(async t=>t.createModuleOptions(),"useFactory"),inject:[r]}]}throw new Error("ModuleAsyncOptions must specify one of: useFactory, useClass, or useExisting")}a(gt,"createAsyncProviders");var F=class{static{a(this,"ConfigurableModuleBuilder");}description;featureDescription;onForRoot;onForFeature;constructor(e="MODULE_OPTIONS"){this.description=e,this.featureDescription=e+"_FEATURE";}setTokenDescription(e){return this.description=e,this}transformDynamicModule(e){return this.onForRoot=e,this}transformFeatureModule(e){return this.onForFeature=e,this}build(){let e=new b(this.description),r=new b(this.featureDescription),t=this.onForRoot,n=this.onForFeature;return {ConfigurableModuleClass:class{static{a(this,"ConfigurableModuleClassImpl");}static forRoot(c,d={}){let u={module:this,global:d.global??false,providers:[{provide:e,useValue:c}],exports:[e]};return t&&(u=t(u,c)),u}static forRootAsync(c){let d=gt(e,c);return {module:this,imports:c.imports??[],providers:d,exports:[e]}}static forFeature(c,d={}){let u={module:this,global:d.global??false,providers:[{provide:r,useValue:c}],exports:[r]};return n&&(u=n(u,c)),u}},MODULE_OPTIONS_TOKEN:e,MODULE_FEATURE_TOKEN:r}}};var T=class{static{a(this,"BaseExecutionContext");}nativeRequest;handler;container;query;params;body;rawBody;formData;auth;data=new Map;metadata=new Map;abortController;constructor(e,r,t,n={},i={},a){this.nativeRequest=e,this.handler=r,this.container=t,this.query=n,this.params=i,this.abortController=a??new AbortController;}getNativeRequest(){return this.nativeRequest}getHandler(){return this.handler}getBody(){return this.body}setBody(e){this.body=e;}getRawBody(){return this.rawBody}setRawBody(e){this.rawBody=e;}getFormData(){return this.formData}setFormData(e){this.formData=e;}getQuery(){return this.query}getParams(){return this.params}getAuth(){return this.auth}setAuth(e){this.auth=e;}getMetadata(e){return this.metadata.get(e)}setMetadata(e,r){this.metadata.set(e,r);}getData(e){return this.data.get(e)}setData(e,r){this.data.set(e,r);}getContainer(){return this.container}getSignal(){return this.abortController.signal}abort(e){this.abortController.abort(e);}};var Ve=Symbol("filters"),qe=Symbol("catch");function We(...o){return (e,r,t)=>{let n=r?e.constructor:e,i=Reflect.getOwnMetadata(Ve,n)??[];Reflect.defineMetadata(Ve,[...i,...o],n);}}a(We,"UseFilters");function je(...o){return e=>{Reflect.defineMetadata(qe,o,e);}}a(je,"Catch");function J(o){return Reflect.getOwnMetadata(qe,o)??[]}a(J,"getCatchMetadata");function k(o,e$1,r){return async t=>{let n=[...e$1.middlewares??[],...r.middlewares??[]],i=[...e$1.guards??[],...r.guards??[]],a$1=[...e$1.interceptors??[],...r.interceptors??[]],c=[...e$1.pipes??[],...r.pipes??[]],d=[...e$1.filters??[],...r.filters??[]],u=await A(o,d);try{y(t);let l=await A(o,n);return await yt(t,l,async()=>{y(t);let f=await A(o,i);for(let R of f)if(y(t),!await R.canActivate(t))throw new e("Access denied by guard");y(t);let m=await A(o,c);for(let R of m)y(t),await R.transform(t);y(t);let h=await A(o,a$1),le=a(async()=>(y(t),r.handler(t)),"handlerCall");return h.length===0?le():h.reduceRight((R,de)=>async()=>(y(t),de.intercept(t,R)),le)()})}catch(l){return wt(l,t,u)}}}a(k,"createPipeline");async function yt(o,e,r){return e.length===0?r():e.reduceRight((n,i)=>()=>i.use(o,n),r)()}a(yt,"runMiddlewareChain");function y(o){if(o.getSignal().aborted)throw new g$1}a(y,"checkAborted");async function wt(o,e,r){for(let t of r){let n=J(t.constructor);if(n.length===0||o instanceof Error&&n.some(a=>o instanceof a))return t.catch(o,e)}throw o}a(wt,"handleError");async function A(o,e){let r=[];for(let t of e)typeof t=="function"?r.push(await o.resolve(t)):r.push(t);return r}a(A,"resolveRefs");var X=Symbol("interceptors"),ee=Symbol("method:interceptors");function He(...o){return (e,r,t)=>{if(r!==void 0){let i=t?.value??e,a=i[ee]??[];return i[ee]=[...a,...o],t}let n=Reflect.getOwnMetadata(X,e)??[];Reflect.defineMetadata(X,[...n,...o],e);}}a(He,"UseInterceptors");function te(o){return Reflect.getOwnMetadata(X,o)??[]}a(te,"getInterceptorsMetadata");function re(o,e){let t=o.prototype?.[e];return typeof t=="function"&&t[ee]||[]}a(re,"getMethodInterceptors");function z(o,e){return [...te(o),...re(o,e)]}a(z,"getEffectiveInterceptors");var oe="uow:session",se="uow:instance",U=class{static{a(this,"UnitOfWorkInterceptor");}factory;constructor(e){this.factory=e;}async intercept(e,r){let t=this.factory();await t.start(),e.setData(oe,t.getContext()),e.setData(se,t);try{let n=await r();return await t.commit(),n}catch(n){throw await t.rollback(),n}}};var B=Symbol("serialize:schema"),$=class{static{a(this,"SerializeInterceptor");}async intercept(e,r){let t=await r();if(t==null)return t;let i=e.getHandler()[B];if(!i)return t;if(Array.isArray(t)){let{z:a}=await import('zod');return a.array(i).parse(t)}return i.parse(t)}};function Le(o){return (e,r,t)=>{if(r!==void 0&&t){let a=t.value;return typeof a=="function"&&(a[B]=o),t}let n=e.prototype,i=Object.getOwnPropertyNames(n).filter(a=>a!=="constructor"&&typeof n[a]=="function");for(let a of i)n[a][B]=o;}}a(Le,"Serialize");function Ze(o){return o[B]}a(Ze,"getSerializeSchema");var ne=Symbol("middlewares"),ae=Symbol("method:middlewares");function Qe(...o){return (e,r,t)=>{if(r!==void 0){let i=t?.value??e,a=i[ae]??[];return i[ae]=[...a,...o],t}let n=Reflect.getOwnMetadata(ne,e)??[];Reflect.defineMetadata(ne,[...n,...o],e);}}a(Qe,"UseMiddleware");function ie(o){return Reflect.getOwnMetadata(ne,o)??[]}a(ie,"getMiddlewaresMetadata");function ce(o,e){let t=o.prototype?.[e];return typeof t=="function"&&t[ae]||[]}a(ce,"getMethodMiddlewares");function G(o,e){return [...ie(o),...ce(o,e)]}a(G,"getEffectiveMiddlewares");var Ke=Symbol("pipes");function Ye(...o){return (e,r,t)=>{let n=r?e.constructor:e,i=Reflect.getOwnMetadata(Ke,n)??[];Reflect.defineMetadata(Ke,[...i,...o],n);}}a(Ye,"UsePipes");var O=class{static{a(this,"ZodValidationPipe");}schema;constructor(e){this.schema=e;}transform(e){let r=e.getBody(),t=this.schema.safeParse(r);if(!t.success){let n={};for(let i of t.error.issues){let a=i.path.join(".")||"_root";n[a]||(n[a]=[]),n[a].push(i.message);}throw new c("Validation failed",n)}e.setBody(t.data);}};var xt=/^[0-9a-fA-F]{24}$/,V=class{static{a(this,"ParseIdPipe");}paramName;constructor(e="id"){this.paramName=e;}transform(e){let t=e.getParams()[this.paramName];if(!t||!xt.test(t))throw new c(`Invalid ${this.paramName}: must be a valid ObjectId`)}};var q=class{static{a(this,"ParseIntPipe");}transform(e){let r=Number(e);if(!Number.isInteger(r)||e===""||e===null||e===void 0)throw new c(`Expected an integer, received: ${JSON.stringify(e)}`);return r}};var W=class{static{a(this,"ZodParamPipe");}schema;constructor(e){this.schema=e;}transform(e){let r=this.schema.safeParse(e);if(!r.success){let t=r.error.errors.map(n=>`${n.path.join(".")}: ${n.message}`).join(", ");throw new c(t)}return r.data}};function Je(o){return {transform(e){return e??o}}}a(Je,"DefaultValuePipe");var x=Symbol("route:params");function Et(o){return o==null?false:typeof o=="function"||typeof o=="object"&&typeof o.transform=="function"}a(Et,"isParamPipeRef");function j(o,e){return Et(o)?{key:void 0,pipes:[o,...e??[]]}:{key:o,pipes:e??[]}}a(j,"resolveArgs");function g(o,e,r=[]){return (t,n,i)=>{if(n===void 0)return;let a=t[n];if(typeof a!="function")return;let c=a[x]??[];a[x]=[...c,{index:i,type:o,key:e,pipes:r.length>0?r:void 0}];}}a(g,"buildBuiltinDecorator");function Mt(o){return typeof o=="function"?new o:o}a(Mt,"resolveParamPipe");function Xe(o,...e){let{key:r,pipes:t}=j(o,e);return g("query",r,t)}a(Xe,"Query");function et(o,...e){let{key:r,pipes:t}=j(o,e);return g("param",r,t)}a(et,"Param");function tt(o,...e){let{key:r,pipes:t}=j(o,e);return g("body",r,t)}a(tt,"Body");var rt=a(()=>g("rawBody"),"RawBody"),ot=a(()=>g("formData"),"FormData"),st=a(()=>g("ip"),"Ip"),nt=a(()=>g("userAgent"),"UserAgent"),at=a(o=>g("cookie",o),"Cookie");function it(o,...e){let{key:r,pipes:t}=j(o,e);return g("headers",r,t)}a(it,"Headers");function ue(o){return ()=>(e,r,t)=>{if(r===void 0)return;let n=e[r];if(typeof n!="function")return;let i=n[x]??[];n[x]=[...i,{index:t,type:"auth",extractor:o}];}}a(ue,"defineAuth");var ct=ue();function w(o){return ()=>(e,r,t)=>{if(r===void 0)return;let n=e[r];if(typeof n!="function")return;let i=n[x]??[];n[x]=[...i,{index:t,type:"custom",extractor:o}];}}a(w,"createParamDecorator");function H(o,e){let r=o.prototype[e];if(typeof r!="function")return null;let t=r[x];return t&&t.length>0?t:null}a(H,"getRouteParams");async function L(o,e){let r=Math.max(...o.map(n=>n.index)),t=new Array(r+1).fill(void 0);for(let{index:n,type:i,key:a,pipes:c,extractor:d}of o){let u;switch(i){case "query":{let l=e.getQuery();u=a!==void 0?l[a]:l;break}case "param":{let l=e.getParams();u=a!==void 0?l[a]:l;break}case "body":{let l=e.getBody()??{};u=a!==void 0?l[a]:l;break}case "rawBody":{u=e.getRawBody();break}case "formData":{u=e.getFormData();break}case "headers":{let l=e.getNativeRequest(),f=l?.node?.req?.headers??l?.headers??{};u=a!==void 0?f[a.toLowerCase()]:f;break}case "cookie":{let l=e.getNativeRequest(),f=l?.node?.req?.headers?.cookie??l?.headers?.cookie??"";if(a&&f){let m=f.split(";").map(h=>h.trim()).find(h=>h.startsWith(a+"="));u=m?decodeURIComponent(m.slice(a.length+1)):void 0;}else u=void 0;break}case "ip":{let l=e.getNativeRequest(),f=l?.node?.req?.headers??{},m=f["cf-connecting-ip"];if(m){u=m.trim();break}let h=f["x-forwarded-for"];if(h){u=(String(h).split(",")[0]??"").trim();break}u=l?.node?.req?.socket?.remoteAddress??"";break}case "userAgent":{u=(e.getNativeRequest()?.node?.req?.headers??{})["user-agent"]??"";break}case "auth":{u=d?await d(e):e.getAuth();break}case "custom":{u=d?await d(e):void 0;break}}if(c&&c.length>0)for(let l of c)u=Mt(l).transform(u);t[n]=u;}return t}a(L,"resolveParamArgs");function ut(o){return w(e=>{let r=e.getBody(),t=o.safeParse(r);if(!t.success){let n={};for(let i of t.error.issues){let a=i.path.join(".")||"_root";(n[a]??=[]).push(i.message);}throw new c("Validation failed",n)}return t.data})}a(ut,"ZodValidatedBody");function lt(o){return w(e=>{let r=e.getQuery(),t=o.safeParse(r);if(!t.success){let n={};for(let i of t.error.issues){let a=i.path.join(".")||"_root";(n[a]??=[]).push(i.message);}throw new c("Query validation failed",n)}return t.data})}a(lt,"ZodValidatedQuery");function dt(o){return w(e=>{let r=e.getParams(),t=o.safeParse(r);if(!t.success){let n={};for(let i of t.error.issues){let a=i.path.join(".")||"_root";(n[a]??=[]).push(i.message);}throw new c("Params validation failed",n)}return t.data})}a(dt,"ZodValidatedParams");var Z=class{static{a(this,"DomainEvent");}payload;timestamp;constructor(e){this.payload=e,this.timestamp=Date.now();}};var E=class{static{a(this,"ControllerRouter");}routes=[];globalPrefix;constructor(e=""){this.globalPrefix=e;}register(...e){for(let r of e){let t=l(r)??"",n$1=n(r);for(let i of n$1){let a=Rt(`${this.globalPrefix}/${t}/${i.path}`);At(a,r.name,i.methodName),this.checkDuplicate(a,i.method,r.name,i.methodName);let{pattern:c,paramNames:d}=Pt(a),u=o(r,i.methodName),l=z(r,i.methodName),f=G(r,i.methodName);this.routes.push({method:i.method,pattern:c,paramNames:d,controllerClass:r,methodName:i.methodName,guardClasses:u,interceptorRefs:l,middlewareRefs:f,rawPath:a});}}this.routes.sort((r,t)=>ft(r.rawPath)-ft(t.rawPath));}checkDuplicate(e,r,t,n){let i=this.routes.find(a=>a.method===r&&a.rawPath===e);if(i)throw new Error(`Duplicate route: ${r} ${e}
2
- Already registered by: ${i.controllerClass.name}.${i.methodName}
3
- Conflicting with: ${t}.${n}`)}match(e,r){let t=e.toUpperCase();for(let n of this.routes){if(n.method!==t)continue;let i=n.pattern.exec(r);if(!i)continue;let a={};for(let c=0;c<n.paramNames.length;c++)a[n.paramNames[c]]=i[c+1]??"";return {route:n,params:a}}return null}getRoutes(){return this.routes}};function Rt(o){return "/"+o.replace(/\/+/g,"/").replace(/^\/|\/$/g,"")}a(Rt,"normalizePath");function Pt(o){let e=[],r=o.split("/").map(t=>t.startsWith(":")?(e.push(t.slice(1)),"([^/]+)"):vt(t)).join("/");return {pattern:new RegExp(`^${r}$`),paramNames:e}}a(Pt,"compilePath");function vt(o){return o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(vt,"escapeRegex");function ft(o){return o.split("/").filter(Boolean).reduce((e,r)=>e+(r.startsWith(":")?1:0),0)}a(ft,"routePriority");function At(o,e,r){let t=`Invalid path "${o}" on ${e}.${r}:`;if(!o.startsWith("/"))throw new Error(`${t} must start with /`);let n=o.split("/").filter((a,c)=>c>0),i=new Set;for(let a of n){if(a==="")throw new Error(`${t} contains empty segment (double slash)`);if(a.startsWith(":")){let c=a.slice(1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(c))throw new Error(`${t} invalid param name ":${c}" \u2014 must be a valid identifier`);if(i.has(c))throw new Error(`${t} duplicate param name ":${c}"`);i.add(c);}}}a(At,"validatePath");var pt="__redirect";function ht(o,e=302){return {__redirect:true,url:o,statusCode:e}}a(ht,"redirect");function Q(o){return o!==null&&typeof o=="object"&&o.__redirect===true}a(Q,"isRedirect");function mt(){return !!(process.env.VERCEL||process.env.AWS_LAMBDA_FUNCTION_NAME||process.env.LAMBDA_TASK_ROOT||process.env.FUNCTIONS_WORKER_RUNTIME||process.env.K_SERVICE||process.env.NETLIFY)}a(mt,"isServerless");var C=class{static{a(this,"TruxieApplication");}container;registry;initialized=false;rootModule;options;eventEmitter;prefix="";router;filters=[];gateways=new Map;wsInitialized=false;constructor(e,r={}){this.rootModule=e,this.options=r,this.container=new c$1,this.registry=new p;}async init(){if(this.initialized)return;this.eventEmitter=new q$1,this.options.eventBus&&this.eventEmitter.setOptions(this.options.eventBus),this.container.register({provide:q$1,useValue:this.eventEmitter});let e=new a$1;this.container.register({provide:a$1,useValue:e}),this.registry.scan(this.rootModule),this.registry.registerAll(this.container);let r=this.registry.getAllProviders();e._init(this.container,r),await this.registry.callLifecycleHooks(this.container,"onModuleInit"),await s(this.container,r),await this.registry.callLifecycleHooks(this.container,"onApplicationBootstrap"),this.router=new E(this.prefix),this.router.register(...this.registry.getAllControllers()),this.filters=this.options.globalFilters??[],this.initialized=true;}setGlobalPrefix(e){return this.prefix=e,this.initialized&&(this.router=new E(this.prefix),this.router.register(...this.registry.getAllControllers())),this}getGlobalPrefix(){return this.prefix}async resolve(e){return this.ensureInitialized(),this.container.resolve(e)}has(e){return this.container.has(e)}getContainer(){return this.container}matchRoute(e,r){return this.ensureInitialized(),this.router.match(e,r)??null}async handleRequest(e$1,r){this.ensureInitialized();let{container:t,dispose:n}=this.createRequestContext();try{let i=await t.resolve(e$1.controllerClass),a=i[e$1.methodName].bind(i),c=H(e$1.controllerClass,e$1.methodName);try{for(let u of e$1.guardClasses)if(!await(t.has(u)?await t.resolve(u):new u).canActivate(r))throw new e("Access denied by guard");let d=c?await a(...await L(c,r)):await a(r);if(Q(d)){let u=d;return {value:d,isRedirect:!0,redirectUrl:u.url,redirectStatus:u.statusCode}}return {value:d,isRedirect:!1}}catch(d){for(let u of this.filters)try{return {value:await u.catch(d,r),isRedirect:!1}}catch{continue}throw d}}finally{await n();}}hasGateways(){return this.ensureInitialized(),this.registry.getAllGateways().length>0}async createWebSocketHooks(e){this.ensureInitialized(),await this.initGateways();let r=this;return {async open(t){let i="/"+(e.getUrl(t).split("?")[0]??"/").replace(/^\/+|\/+$/g,""),a=r.matchGatewayPath(i);if(!a)return;let c=t.context;c&&(c._gatewayPath=a);let d=r.gateways.get(a),u=e.adaptPeer(t);for(let l of d.serverProps)d.instance[l]={peers:e.getPeers(t)??new Set};if(d.hasConnection)try{await d.instance.handleConnection(u);}catch(l){console.error(`[WS] ${d.className}.handleConnection error:`,l);}},async message(t,n){let a=t.context?._gatewayPath;if(!a)return;let c=r.gateways.get(a);if(!c)return;let d=e.adaptPeer(t),u=e.adaptMessage(n),l;try{l=u.json();}catch{return}if(!l.event||typeof l.event!="string")return;let f=c.messageHandlers.get(l.event);if(f)try{let m=n$1(f.paramMeta,d,u,l.data),h=await f.method(...m);h!=null&&d.send(h);}catch(m){console.error(`[WS] ${c.className}.${l.event} error:`,m);}},async close(t,n){let a=t.context?._gatewayPath;if(!a)return;let c=r.gateways.get(a);if(!c?.hasDisconnect)return;let d=e.adaptPeer(t);try{await c.instance.handleDisconnect(d,n);}catch(u){console.error(`[WS] ${c.className}.handleDisconnect error:`,u);}},async error(t,n){let i=t?.id??"unknown";console.error(`[WS] Peer ${String(i)} error:`,n);}}}getControllers(){return this.ensureInitialized(),this.registry.getAllControllers()}getGateways(){return this.ensureInitialized(),this.registry.getAllGateways()}getProviders(){return this.ensureInitialized(),this.registry.getAllProviders()}getEventEmitter(){return this.ensureInitialized(),this.eventEmitter}getRouter(){return this.ensureInitialized(),this.router}createHandler(e){return this.ensureInitialized(),k(this.container,this.getGlobalOptions(),e)}async shutdown(){this.initialized&&(await this.registry.callLifecycleHooks(this.container,"onModuleDestroy"),await this.registry.callLifecycleHooks(this.container,"onApplicationShutdown"),this.eventEmitter.clear(),await this.container.dispose(),this.initialized=false);}createRequestContext(){if(!this.container.hasRequestScoped())return {container:this.container,dispose:a(async()=>{},"dispose")};let e=this.container.createChild();return {container:e,dispose:a(()=>e.dispose(),"dispose")}}matchGatewayPath(e){if(this.gateways.has(e))return e;for(let r of this.gateways.keys())if(e.endsWith(r))return r;if(this.gateways.has("/"))return "/"}async initGateways(){if(!this.wsInitialized){for(let e of this.registry.getAllGateways()){let r=i(e);if(!r)continue;let t=await this.container.resolve(e),n=new Map;for(let i of j$1(e)){let a=t[i.methodName];typeof a=="function"&&n.set(i.event,{method:a.bind(t),paramMeta:k$1(e.prototype[i.methodName])});}if(this.gateways.set(r.path,{instance:t,className:e.name,messageHandlers:n,hasConnection:typeof t.handleConnection=="function",hasDisconnect:typeof t.handleDisconnect=="function",serverProps:m(e)}),typeof t.afterInit=="function")try{await t.afterInit();}catch{}}this.wsInitialized=true;}}getGlobalOptions(){return {guards:this.options.globalGuards,interceptors:this.options.globalInterceptors,pipes:this.options.globalPipes,filters:this.options.globalFilters}}ensureInitialized(){if(!this.initialized)throw new Error("TruxieApplication not initialized. Call TruxieFactory.create() or app.init().")}},K=class{static{a(this,"TruxieFactory");}static async create(e,r){let t=new C(e,r);return await t.init(),t}};export{ct as Auth,T as BaseExecutionContext,tt as Body,je as Catch,F as ConfigurableModuleBuilder,E as ControllerRouter,at as Cookie,Je as DefaultValuePipe,Z as DomainEvent,ot as FormData,it as Headers,st as Ip,et as Param,V as ParseIdPipe,q as ParseIntPipe,Xe as Query,pt as REDIRECT_BRAND,rt as RawBody,Le as Serialize,$ as SerializeInterceptor,C as TruxieApplication,K as TruxieFactory,se as UOW_INSTANCE_KEY,oe as UOW_SESSION_KEY,U as UnitOfWorkInterceptor,We as UseFilters,He as UseInterceptors,Qe as UseMiddleware,Ye as UsePipes,nt as UserAgent,W as ZodParamPipe,ut as ZodValidatedBody,dt as ZodValidatedParams,lt as ZodValidatedQuery,O as ZodValidationPipe,w as createParamDecorator,k as createPipeline,ue as defineAuth,z as getEffectiveInterceptors,G as getEffectiveMiddlewares,te as getInterceptorsMetadata,re as getMethodInterceptors,ce as getMethodMiddlewares,ie as getMiddlewaresMetadata,H as getRouteParams,Ze as getSerializeSchema,Q as isRedirect,mt as isServerless,ht as redirect,L as resolveParamArgs};
1
+ import {l,n,o,c as c$1,p,q as q$1,s}from'./chunk-IEQXYYZJ.js';export{c as Container,d as Controller,h as Delete,q as EventEmitter2,e as Get,p as ModuleRegistry,k as NoGuard,r as OnEvent,i as Patch,f as Post,g as Put,j as RouteGuards,a as forwardRef,m as getControllerGuards,l as getControllerPath,o as getMethodGuards,n as getRouteMetadata,b as resolveForwardRef}from'./chunk-IEQXYYZJ.js';import {a as a$1}from'./chunk-2ACNLLXS.js';export{a as DiscoveryService}from'./chunk-2ACNLLXS.js';import {c,e,g as g$1}from'./chunk-PT5RXFB5.js';export{a as AppError,f as ConflictError,e as ForbiddenError,b as NotFoundError,g as RequestAbortedError,d as UnauthorizedError,c as ValidationError}from'./chunk-PT5RXFB5.js';import {b}from'./chunk-MF2CCNPQ.js';export{k as Global,d as Inject,c as Injectable,j as Module,e as Optional,a as Scope,l as getModuleMetadata,m as isGlobalModule}from'./chunk-MF2CCNPQ.js';import {n as n$1,i,j,k as k$1,m as m$1}from'./chunk-RLQ7JJW6.js';import {a}from'./chunk-EI7MMDWY.js';import'reflect-metadata';function it(o,e){if("useFactory"in e&&e.useFactory){let r=e.useFactory;return [{provide:o,useFactory:r,inject:e.inject??[]}]}if("useClass"in e&&e.useClass){let r=e.useClass;return [{provide:o,useFactory:a(async t=>t.createModuleOptions(),"useFactory"),inject:[r]},r]}if("useExisting"in e&&e.useExisting){let r=e.useExisting;return [{provide:o,useFactory:a(async t=>t.createModuleOptions(),"useFactory"),inject:[r]}]}throw new Error("ModuleAsyncOptions must specify one of: useFactory, useClass, or useExisting")}a(it,"createAsyncProviders");var F=class{static{a(this,"ConfigurableModuleBuilder");}description;featureDescription;onForRoot;onForFeature;constructor(e="MODULE_OPTIONS"){this.description=e,this.featureDescription=e+"_FEATURE";}setTokenDescription(e){return this.description=e,this}transformDynamicModule(e){return this.onForRoot=e,this}transformFeatureModule(e){return this.onForFeature=e,this}build(){let e=new b(this.description),r=new b(this.featureDescription),t=this.onForRoot,s=this.onForFeature;return {ConfigurableModuleClass:class{static{a(this,"ConfigurableModuleClassImpl");}static forRoot(u,d={}){let c={module:this,global:d.global??false,providers:[{provide:e,useValue:u}],exports:[e]};return t&&(c=t(c,u)),c}static forRootAsync(u){let d=it(e,u);return {module:this,imports:u.imports??[],providers:d,exports:[e]}}static forFeature(u,d={}){let c={module:this,global:d.global??false,providers:[{provide:r,useValue:u}],exports:[r]};return s&&(c=s(c,u)),c}},MODULE_OPTIONS_TOKEN:e,MODULE_FEATURE_TOKEN:r}}};var _=class{static{a(this,"BaseExecutionContext");}nativeRequest;handler;container;query;params;body;rawBody;formData;auth;data=new Map;metadata=new Map;abortController;constructor(e,r,t,s={},a={},i){this.nativeRequest=e,this.handler=r,this.container=t,this.query=s,this.params=a,this.abortController=i??new AbortController;}getNativeRequest(){return this.nativeRequest}getHandler(){return this.handler}getBody(){return this.body}setBody(e){this.body=e;}getRawBody(){return this.rawBody}setRawBody(e){this.rawBody=e;}getFormData(){return this.formData}setFormData(e){this.formData=e;}getQuery(){return this.query}getParams(){return this.params}getAuth(){return this.auth}setAuth(e){this.auth=e;}getMetadata(e){return this.metadata.get(e)}setMetadata(e,r){this.metadata.set(e,r);}getData(e){return this.data.get(e)}setData(e,r){this.data.set(e,r);}getContainer(){return this.container}getSignal(){return this.abortController.signal}abort(e){this.abortController.abort(e);}};var Ge=Symbol("filters"),$e=Symbol("catch");function Be(...o){return (e,r,t)=>{let s=r?e.constructor:e,a=Reflect.getOwnMetadata(Ge,s)??[];Reflect.defineMetadata(Ge,[...a,...o],s);}}a(Be,"UseFilters");function Oe(...o){return e=>{Reflect.defineMetadata($e,o,e);}}a(Oe,"Catch");function V(o){return Reflect.getOwnMetadata($e,o)??[]}a(V,"getCatchMetadata");function T(o,e$1,r){return async t=>{let s=[...e$1.middlewares??[],...r.middlewares??[]],a$1=[...e$1.guards??[],...r.guards??[]],i=[...e$1.interceptors??[],...r.interceptors??[]],u=[...e$1.pipes??[],...r.pipes??[]],d=[...e$1.filters??[],...r.filters??[]],c=await C(o,d);try{g(t);let l=await C(o,s);return await ct(t,l,async()=>{g(t);let f=await C(o,a$1);for(let M of f)if(g(t),!await M.canActivate(t))throw new e("Access denied by guard");g(t);let h=await C(o,u);for(let M of h)g(t),await M.transform(t);g(t);let p=await C(o,i),se=a(async()=>(g(t),r.handler(t)),"handlerCall");return p.length===0?se():p.reduceRight((M,ae)=>async()=>(g(t),ae.intercept(t,M)),se)()})}catch(l){return ut(l,t,c)}}}a(T,"createPipeline");async function ct(o,e,r){return e.length===0?r():e.reduceRight((s,a)=>()=>a.use(o,s),r)()}a(ct,"runMiddlewareChain");function g(o){if(o.getSignal().aborted)throw new g$1}a(g,"checkAborted");async function ut(o,e,r){for(let t of r){let s=V(t.constructor);if(s.length===0||o instanceof Error&&s.some(i=>o instanceof i))return t.catch(o,e)}throw o}a(ut,"handleError");async function C(o,e){let r=[];for(let t of e)typeof t=="function"?r.push(await o.resolve(t)):r.push(t);return r}a(C,"resolveRefs");var K=Symbol("interceptors"),Y=Symbol("method:interceptors");function ze(...o){return (e,r,t)=>{if(r!==void 0){let a=t?.value??e,i=a[Y]??[];return a[Y]=[...i,...o],t}let s=Reflect.getOwnMetadata(K,e)??[];Reflect.defineMetadata(K,[...s,...o],e);}}a(ze,"UseInterceptors");function Q(o){return Reflect.getOwnMetadata(K,o)??[]}a(Q,"getInterceptorsMetadata");function J(o,e){let t=o.prototype?.[e];return typeof t=="function"&&t[Y]||[]}a(J,"getMethodInterceptors");function k(o,e){return [...Q(o),...J(o,e)]}a(k,"getEffectiveInterceptors");var Z="uow:session",X="uow:instance",U=class{static{a(this,"UnitOfWorkInterceptor");}factory;constructor(e){this.factory=e;}async intercept(e,r){let t=this.factory();await t.start(),e.setData(Z,t.getContext()),e.setData(X,t);try{let s=await r();return await t.commit(),s}catch(s){throw await t.rollback(),s}}};var ee=Symbol("middlewares"),te=Symbol("method:middlewares");function qe(...o){return (e,r,t)=>{if(r!==void 0){let a=t?.value??e,i=a[te]??[];return a[te]=[...i,...o],t}let s=Reflect.getOwnMetadata(ee,e)??[];Reflect.defineMetadata(ee,[...s,...o],e);}}a(qe,"UseMiddleware");function re(o){return Reflect.getOwnMetadata(ee,o)??[]}a(re,"getMiddlewaresMetadata");function oe(o,e){let t=o.prototype?.[e];return typeof t=="function"&&t[te]||[]}a(oe,"getMethodMiddlewares");function G(o,e){return [...re(o),...oe(o,e)]}a(G,"getEffectiveMiddlewares");var We=Symbol("pipes");function He(...o){return (e,r,t)=>{let s=r?e.constructor:e,a=Reflect.getOwnMetadata(We,s)??[];Reflect.defineMetadata(We,[...a,...o],s);}}a(He,"UsePipes");var lt=/^[0-9a-fA-F]{24}$/,$=class{static{a(this,"ParseIdPipe");}paramName;constructor(e="id"){this.paramName=e;}transform(e){let t=e.getParams()[this.paramName];if(!t||!lt.test(t))throw new c(`Invalid ${this.paramName}: must be a valid ObjectId`)}};var B=class{static{a(this,"ParseIntPipe");}transform(e){let r=Number(e);if(!Number.isInteger(r)||e===""||e===null||e===void 0)throw new c(`Expected an integer, received: ${JSON.stringify(e)}`);return r}};function Le(o){return {transform(e){return e??o}}}a(Le,"DefaultValuePipe");var O=class{static{a(this,"DomainEvent");}payload;timestamp;constructor(e){this.payload=e,this.timestamp=Date.now();}};var E=class{static{a(this,"ControllerRouter");}routes=[];globalPrefix;constructor(e=""){this.globalPrefix=e;}register(...e){for(let r of e){let t=l(r)??"",s=n(r);for(let a of s){let i=dt(`${this.globalPrefix}/${t}/${a.path}`);ht(i,r.name,a.methodName),this.checkDuplicate(i,a.method,r.name,a.methodName);let{pattern:u,paramNames:d}=ft(i),c=o(r,a.methodName),l=k(r,a.methodName),f=G(r,a.methodName);this.routes.push({method:a.method,pattern:u,paramNames:d,controllerClass:r,methodName:a.methodName,guardClasses:c,interceptorRefs:l,middlewareRefs:f,rawPath:i});}}this.routes.sort((r,t)=>je(r.rawPath)-je(t.rawPath));}checkDuplicate(e,r,t,s){let a=this.routes.find(i=>i.method===r&&i.rawPath===e);if(a)throw new Error(`Duplicate route: ${r} ${e}
2
+ Already registered by: ${a.controllerClass.name}.${a.methodName}
3
+ Conflicting with: ${t}.${s}`)}match(e,r){let t=e.toUpperCase();for(let s of this.routes){if(s.method!==t)continue;let a=s.pattern.exec(r);if(!a)continue;let i={};for(let u=0;u<s.paramNames.length;u++)i[s.paramNames[u]]=a[u+1]??"";return {route:s,params:i}}return null}getRoutes(){return this.routes}};function dt(o){return "/"+o.replace(/\/+/g,"/").replace(/^\/|\/$/g,"")}a(dt,"normalizePath");function ft(o){let e=[],r=o.split("/").map(t=>t.startsWith(":")?(e.push(t.slice(1)),"([^/]+)"):pt(t)).join("/");return {pattern:new RegExp(`^${r}$`),paramNames:e}}a(ft,"compilePath");function pt(o){return o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(pt,"escapeRegex");function je(o){return o.split("/").filter(Boolean).reduce((e,r)=>e+(r.startsWith(":")?1:0),0)}a(je,"routePriority");function ht(o,e,r){let t=`Invalid path "${o}" on ${e}.${r}:`;if(!o.startsWith("/"))throw new Error(`${t} must start with /`);let s=o.split("/").filter((i,u)=>u>0),a=new Set;for(let i of s){if(i==="")throw new Error(`${t} contains empty segment (double slash)`);if(i.startsWith(":")){let u=i.slice(1);if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(u))throw new Error(`${t} invalid param name ":${u}" \u2014 must be a valid identifier`);if(a.has(u))throw new Error(`${t} duplicate param name ":${u}"`);a.add(u);}}}a(ht,"validatePath");var w=Symbol("route:params");function mt(o){return o==null?false:typeof o=="function"||typeof o=="object"&&typeof o.transform=="function"}a(mt,"isParamPipeRef");function z(o,e){return mt(o)?{key:void 0,pipes:[o,...e??[]]}:{key:o,pipes:e??[]}}a(z,"resolveArgs");function m(o,e,r=[]){return (t,s,a)=>{if(s===void 0)return;let i=t[s];if(typeof i!="function")return;let u=i[w]??[];i[w]=[...u,{index:a,type:o,key:e,pipes:r.length>0?r:void 0}];}}a(m,"buildBuiltinDecorator");function gt(o){return typeof o=="function"?new o:o}a(gt,"resolveParamPipe");function Ve(o,...e){let{key:r,pipes:t}=z(o,e);return m("query",r,t)}a(Ve,"Query");function Ke(o,...e){let{key:r,pipes:t}=z(o,e);return m("param",r,t)}a(Ke,"Param");function Ye(o,...e){let{key:r,pipes:t}=z(o,e);return m("body",r,t)}a(Ye,"Body");var Qe=a(()=>m("rawBody"),"RawBody"),Je=a(()=>m("formData"),"FormData"),Ze=a(()=>m("ip"),"Ip"),Xe=a(()=>m("userAgent"),"UserAgent"),et=a(o=>m("cookie",o),"Cookie");function tt(o,...e){let{key:r,pipes:t}=z(o,e);return m("headers",r,t)}a(tt,"Headers");function ne(o){return ()=>(e,r,t)=>{if(r===void 0)return;let s=e[r];if(typeof s!="function")return;let a=s[w]??[];s[w]=[...a,{index:t,type:"auth",extractor:o}];}}a(ne,"defineAuth");var rt=ne();function ot(o){return ()=>(e,r,t)=>{if(r===void 0)return;let s=e[r];if(typeof s!="function")return;let a=s[w]??[];s[w]=[...a,{index:t,type:"custom",extractor:o}];}}a(ot,"createParamDecorator");function q(o,e){let r=o.prototype[e];if(typeof r!="function")return null;let t=r[w];return t&&t.length>0?t:null}a(q,"getRouteParams");async function W(o,e){let r=Math.max(...o.map(s=>s.index)),t=new Array(r+1).fill(void 0);for(let{index:s,type:a,key:i,pipes:u,extractor:d}of o){let c;switch(a){case "query":{let l=e.getQuery();c=i!==void 0?l[i]:l;break}case "param":{let l=e.getParams();c=i!==void 0?l[i]:l;break}case "body":{let l=e.getBody()??{};c=i!==void 0?l[i]:l;break}case "rawBody":{c=e.getRawBody();break}case "formData":{c=e.getFormData();break}case "headers":{let l=e.getNativeRequest(),f=l?.node?.req?.headers??l?.headers??{};c=i!==void 0?f[i.toLowerCase()]:f;break}case "cookie":{let l=e.getNativeRequest(),f=l?.node?.req?.headers?.cookie??l?.headers?.cookie??"";if(i&&f){let h=f.split(";").map(p=>p.trim()).find(p=>p.startsWith(i+"="));c=h?decodeURIComponent(h.slice(i.length+1)):void 0;}else c=void 0;break}case "ip":{let l=e.getNativeRequest(),f=l?.node?.req?.headers??{},h=f["cf-connecting-ip"];if(h){c=h.trim();break}let p=f["x-forwarded-for"];if(p){c=(String(p).split(",")[0]??"").trim();break}c=l?.node?.req?.socket?.remoteAddress??"";break}case "userAgent":{c=(e.getNativeRequest()?.node?.req?.headers??{})["user-agent"]??"";break}case "auth":{c=d?await d(e):e.getAuth();break}case "custom":{c=d?await d(e):void 0;break}}if(u&&u.length>0)for(let l of u)c=gt(l).transform(c);t[s]=c;}return t}a(W,"resolveParamArgs");var nt="__redirect";function st(o,e=302){return {__redirect:true,url:o,statusCode:e}}a(st,"redirect");function H(o){return o!==null&&typeof o=="object"&&o.__redirect===true}a(H,"isRedirect");function at(){return !!(process.env.VERCEL||process.env.AWS_LAMBDA_FUNCTION_NAME||process.env.LAMBDA_TASK_ROOT||process.env.FUNCTIONS_WORKER_RUNTIME||process.env.K_SERVICE||process.env.NETLIFY)}a(at,"isServerless");var A=class{static{a(this,"TruxieApplication");}container;registry;initialized=false;rootModule;options;eventEmitter;prefix="";router;filters=[];gateways=new Map;wsInitialized=false;constructor(e,r={}){this.rootModule=e,this.options=r,this.container=new c$1,this.registry=new p;}async init(){if(this.initialized)return;this.eventEmitter=new q$1,this.options.eventBus&&this.eventEmitter.setOptions(this.options.eventBus),this.container.register({provide:q$1,useValue:this.eventEmitter});let e=new a$1;this.container.register({provide:a$1,useValue:e}),this.registry.scan(this.rootModule),this.registry.registerAll(this.container);let r=this.registry.getAllProviders();e._init(this.container,r),await this.registry.callLifecycleHooks(this.container,"onModuleInit"),await s(this.container,r),await this.registry.callLifecycleHooks(this.container,"onApplicationBootstrap"),this.router=new E(this.prefix),this.router.register(...this.registry.getAllControllers()),this.filters=this.options.globalFilters??[],this.initialized=true;}setGlobalPrefix(e){return this.prefix=e,this}getGlobalPrefix(){return this.prefix}async resolve(e){return this.ensureInitialized(),this.container.resolve(e)}has(e){return this.container.has(e)}getContainer(){return this.container}matchRoute(e,r){return this.ensureInitialized(),this.router.match(e,r)??null}async handleRequest(e$1,r){this.ensureInitialized();let{container:t,dispose:s}=this.createRequestContext();try{let a=await t.resolve(e$1.controllerClass),i=a[e$1.methodName].bind(a),u=q(e$1.controllerClass,e$1.methodName);try{for(let c of e$1.guardClasses)if(!await(t.has(c)?await t.resolve(c):new c).canActivate(r))throw new e("Access denied by guard");let d=u?await i(...await W(u,r)):await i(r);if(H(d)){let c=d;return {value:d,isRedirect:!0,redirectUrl:c.url,redirectStatus:c.statusCode}}return {value:d,isRedirect:!1}}catch(d){for(let c of this.filters)try{return {value:await c.catch(d,r),isRedirect:!1}}catch{continue}throw d}}finally{await s();}}hasGateways(){return this.ensureInitialized(),this.registry.getAllGateways().length>0}async createWebSocketHooks(e){this.ensureInitialized(),await this.initGateways();let r=this;return {async open(t){let a="/"+(e.getUrl(t).split("?")[0]??"/").replace(/^\/+|\/+$/g,""),i=r.matchGatewayPath(a);if(!i)return;let u=t.context;u&&(u._gatewayPath=i);let d=r.gateways.get(i),c=e.adaptPeer(t);for(let l of d.serverProps)d.instance[l]={peers:e.getPeers(t)??new Set};if(d.hasConnection)try{await d.instance.handleConnection(c);}catch(l){console.error(`[WS] ${d.className}.handleConnection error:`,l);}},async message(t,s){let i=t.context?._gatewayPath;if(!i)return;let u=r.gateways.get(i);if(!u)return;let d=e.adaptPeer(t),c=e.adaptMessage(s),l;try{l=c.json();}catch{return}if(!l.event||typeof l.event!="string")return;let f=u.messageHandlers.get(l.event);if(f)try{let h=n$1(f.paramMeta,d,c,l.data),p=await f.method(...h);p!=null&&d.send(p);}catch(h){console.error(`[WS] ${u.className}.${l.event} error:`,h);}},async close(t,s){let i=t.context?._gatewayPath;if(!i)return;let u=r.gateways.get(i);if(!u?.hasDisconnect)return;let d=e.adaptPeer(t);try{await u.instance.handleDisconnect(d,s);}catch(c){console.error(`[WS] ${u.className}.handleDisconnect error:`,c);}},async error(t,s){let a=t?.id??"unknown";console.error(`[WS] Peer ${String(a)} error:`,s);}}}getControllers(){return this.ensureInitialized(),this.registry.getAllControllers()}getGateways(){return this.ensureInitialized(),this.registry.getAllGateways()}getProviders(){return this.ensureInitialized(),this.registry.getAllProviders()}getEventEmitter(){return this.ensureInitialized(),this.eventEmitter}getRouter(){return this.ensureInitialized(),this.router}createHandler(e){return this.ensureInitialized(),T(this.container,this.getGlobalOptions(),e)}async shutdown(){this.initialized&&(await this.registry.callLifecycleHooks(this.container,"onModuleDestroy"),await this.registry.callLifecycleHooks(this.container,"onApplicationShutdown"),this.eventEmitter.clear(),await this.container.dispose(),this.initialized=false);}createRequestContext(){if(!this.container.hasRequestScoped())return {container:this.container,dispose:a(async()=>{},"dispose")};let e=this.container.createChild();return {container:e,dispose:a(()=>e.dispose(),"dispose")}}matchGatewayPath(e){if(this.gateways.has(e))return e;for(let r of this.gateways.keys())if(e.endsWith(r))return r;if(this.gateways.has("/"))return "/"}async initGateways(){if(!this.wsInitialized){for(let e of this.registry.getAllGateways()){let r=i(e);if(!r)continue;let t=await this.container.resolve(e),s=new Map;for(let a of j(e)){let i=t[a.methodName];typeof i=="function"&&s.set(a.event,{method:i.bind(t),paramMeta:k$1(e.prototype[a.methodName])});}if(this.gateways.set(r.path,{instance:t,className:e.name,messageHandlers:s,hasConnection:typeof t.handleConnection=="function",hasDisconnect:typeof t.handleDisconnect=="function",serverProps:m$1(e)}),typeof t.afterInit=="function")try{await t.afterInit();}catch{}}this.wsInitialized=true;}}getGlobalOptions(){return {guards:this.options.globalGuards,interceptors:this.options.globalInterceptors,pipes:this.options.globalPipes,filters:this.options.globalFilters}}ensureInitialized(){if(!this.initialized)throw new Error("TruxieApplication not initialized. Call TruxieFactory.create() or app.init().")}},L=class{static{a(this,"TruxieFactory");}static async create(e,r){let t=new A(e,r);return await t.init(),t}};export{rt as Auth,_ as BaseExecutionContext,Ye as Body,Oe as Catch,F as ConfigurableModuleBuilder,E as ControllerRouter,et as Cookie,Le as DefaultValuePipe,O as DomainEvent,Je as FormData,tt as Headers,Ze as Ip,Ke as Param,$ as ParseIdPipe,B as ParseIntPipe,Ve as Query,nt as REDIRECT_BRAND,Qe as RawBody,A as TruxieApplication,L as TruxieFactory,X as UOW_INSTANCE_KEY,Z as UOW_SESSION_KEY,U as UnitOfWorkInterceptor,Be as UseFilters,ze as UseInterceptors,qe as UseMiddleware,He as UsePipes,Xe as UserAgent,ot as createParamDecorator,T as createPipeline,ne as defineAuth,k as getEffectiveInterceptors,G as getEffectiveMiddlewares,Q as getInterceptorsMetadata,J as getMethodInterceptors,oe as getMethodMiddlewares,re as getMiddlewaresMetadata,q as getRouteParams,H as isRedirect,at as isServerless,st as redirect,W as resolveParamArgs};
package/package.json CHANGED
@@ -1,104 +1,104 @@
1
- {
2
- "name": "truxie",
3
- "version": "0.1.0-test.12",
4
- "description": "NestJS-like structural backend library with DI, modules, guards, interceptors, pipes, and exception filters",
5
- "type": "module",
6
- "main": "dist/index.js",
7
- "module": "dist/index.js",
8
- "types": "dist/index.d.ts",
9
- "exports": {
10
- ".": {
11
- "types": "./dist/index.d.ts",
12
- "import": "./dist/index.js",
13
- "default": "./dist/index.js"
14
- },
15
- "./schedule": {
16
- "types": "./dist/schedule.d.ts",
17
- "import": "./dist/schedule.js",
18
- "default": "./dist/schedule.js"
19
- },
20
- "./testing": {
21
- "types": "./dist/testing.d.ts",
22
- "import": "./dist/testing.js",
23
- "default": "./dist/testing.js"
24
- },
25
- "./cache": {
26
- "types": "./dist/cache.d.ts",
27
- "import": "./dist/cache.js",
28
- "default": "./dist/cache.js"
29
- },
30
- "./throttle": {
31
- "types": "./dist/throttle.d.ts",
32
- "import": "./dist/throttle.js",
33
- "default": "./dist/throttle.js"
34
- },
35
- "./logger": {
36
- "types": "./dist/logger.d.ts",
37
- "import": "./dist/logger.js",
38
- "default": "./dist/logger.js"
39
- },
40
- "./health": {
41
- "types": "./dist/health.d.ts",
42
- "import": "./dist/health.js",
43
- "default": "./dist/health.js"
44
- },
45
- "./ws": {
46
- "types": "./dist/ws.d.ts",
47
- "import": "./dist/ws.js",
48
- "default": "./dist/ws.js"
49
- },
50
- "./cqrs": {
51
- "types": "./dist/cqrs.d.ts",
52
- "import": "./dist/cqrs.js",
53
- "default": "./dist/cqrs.js"
54
- }
55
- },
56
- "files": [
57
- "dist",
58
- "README.md"
59
- ],
60
- "dependencies": {
61
- "reflect-metadata": "^0.2.2"
62
- },
63
- "peerDependencies": {
64
- "croner": "^9.0.0",
65
- "zod": "^3.22.0"
66
- },
67
- "peerDependenciesMeta": {
68
- "croner": {
69
- "optional": true
70
- },
71
- "zod": {
72
- "optional": true
73
- }
74
- },
75
- "devDependencies": {
76
- "@swc/core": "^1.15.18",
77
- "@types/node": "^22.10.5",
78
- "croner": "^9.1.0",
79
- "tsup": "^8.0.0",
80
- "typescript": "^5.0.0",
81
- "vitest": "^4.0.18",
82
- "zod": "^3.22.0"
83
- },
84
- "keywords": [
85
- "nestjs",
86
- "di",
87
- "dependency-injection",
88
- "backend",
89
- "modules",
90
- "guards",
91
- "interceptors",
92
- "pipes"
93
- ],
94
- "license": "MIT",
95
- "engines": {
96
- "node": ">=18.0.0"
97
- },
98
- "scripts": {
99
- "build": "tsup",
100
- "dev": "tsup --watch",
101
- "typecheck": "tsc --noEmit",
102
- "clean": "rm -rf dist"
103
- }
104
- }
1
+ {
2
+ "name": "truxie",
3
+ "version": "0.1.0-test.13",
4
+ "description": "NestJS-like structural backend library with DI, modules, guards, interceptors, pipes, and exception filters",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "module": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "./schedule": {
16
+ "types": "./dist/schedule.d.ts",
17
+ "import": "./dist/schedule.js",
18
+ "default": "./dist/schedule.js"
19
+ },
20
+ "./testing": {
21
+ "types": "./dist/testing.d.ts",
22
+ "import": "./dist/testing.js",
23
+ "default": "./dist/testing.js"
24
+ },
25
+ "./cache": {
26
+ "types": "./dist/cache.d.ts",
27
+ "import": "./dist/cache.js",
28
+ "default": "./dist/cache.js"
29
+ },
30
+ "./throttle": {
31
+ "types": "./dist/throttle.d.ts",
32
+ "import": "./dist/throttle.js",
33
+ "default": "./dist/throttle.js"
34
+ },
35
+ "./logger": {
36
+ "types": "./dist/logger.d.ts",
37
+ "import": "./dist/logger.js",
38
+ "default": "./dist/logger.js"
39
+ },
40
+ "./health": {
41
+ "types": "./dist/health.d.ts",
42
+ "import": "./dist/health.js",
43
+ "default": "./dist/health.js"
44
+ },
45
+ "./ws": {
46
+ "types": "./dist/ws.d.ts",
47
+ "import": "./dist/ws.js",
48
+ "default": "./dist/ws.js"
49
+ },
50
+ "./cqrs": {
51
+ "types": "./dist/cqrs.d.ts",
52
+ "import": "./dist/cqrs.js",
53
+ "default": "./dist/cqrs.js"
54
+ }
55
+ },
56
+ "files": [
57
+ "dist",
58
+ "README.md"
59
+ ],
60
+ "scripts": {
61
+ "build": "tsup",
62
+ "dev": "tsup --watch",
63
+ "typecheck": "tsc --noEmit",
64
+ "clean": "rm -rf dist"
65
+ },
66
+ "dependencies": {
67
+ "reflect-metadata": "^0.2.2"
68
+ },
69
+ "peerDependencies": {
70
+ "croner": "^9.0.0",
71
+ "zod": "^3.22.0"
72
+ },
73
+ "peerDependenciesMeta": {
74
+ "croner": {
75
+ "optional": true
76
+ },
77
+ "zod": {
78
+ "optional": true
79
+ }
80
+ },
81
+ "devDependencies": {
82
+ "@swc/core": "^1.15.18",
83
+ "@types/node": "^22.10.5",
84
+ "croner": "^9.1.0",
85
+ "tsup": "^8.0.0",
86
+ "typescript": "^5.0.0",
87
+ "vitest": "^4.0.18",
88
+ "zod": "^3.22.0"
89
+ },
90
+ "keywords": [
91
+ "nestjs",
92
+ "di",
93
+ "dependency-injection",
94
+ "backend",
95
+ "modules",
96
+ "guards",
97
+ "interceptors",
98
+ "pipes"
99
+ ],
100
+ "license": "MIT",
101
+ "engines": {
102
+ "node": ">=18.0.0"
103
+ }
104
+ }