truxie 0.1.0-test.1 → 0.1.0-test.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-M2ZPR3DR.js +1 -0
- package/dist/index.d.ts +266 -85
- package/dist/index.js +3 -3
- package/dist/saga.d.ts +82 -0
- package/dist/saga.js +1 -0
- package/package.json +7 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import'reflect-metadata';var R=Object.defineProperty;var n=(t,e)=>R(t,"name",{value:e,configurable:true});var u=(function(t){return t.SINGLETON="singleton",t.REQUEST="request",t.TRANSIENT="transient",t})({}),p=class{static{n(this,"InjectionToken");}description;constructor(e){this.description=e;}toString(){return `InjectionToken(${this.description})`}};var l=Symbol("injectable"),c=Symbol("inject:param"),f=Symbol("inject:deps"),a=Symbol("optional");function I(t){return e=>{Reflect.defineMetadata(l,{scope:t?.scope??u.SINGLETON},e);}}n(I,"Injectable");function N(...t){return (e,s,r)=>{if(typeof r=="number"){let i=Reflect.getOwnMetadata(c,e)??new Map;i.set(r,t[0]),Reflect.defineMetadata(c,i,e);}else Reflect.defineMetadata(f,t,e);}}n(N,"Inject");function h(){return (t,e,s)=>{let r=Reflect.getOwnMetadata(a,t)??new Set;r.add(s),Reflect.defineMetadata(a,r,t);}}n(h,"Optional");function m(t){return Reflect.getOwnMetadata(l,t)}n(m,"getInjectableMetadata");function E(t){return Reflect.getOwnMetadata(f,t)??[]}n(E,"getClassDeps");function j(t){return Reflect.getOwnMetadata(c,t)??new Map}n(j,"getInjectTokens");function _(t){return Reflect.getOwnMetadata(a,t)??new Set}n(_,"getOptionalParams");var o=class extends Error{static{n(this,"AppError");}statusCode;status;isOperational;constructor(e,s){super(e),this.statusCode=s,this.status=s>=400&&s<500?"fail":"error",this.isOperational=true,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace(this,this.constructor);}},d=class extends o{static{n(this,"NotFoundError");}constructor(e="Resource not found"){super(e,404);}},x=class extends o{static{n(this,"ValidationError");}errors;constructor(e="Validation failed",s){super(e,400),this.errors=s;}},T=class extends o{static{n(this,"UnauthorizedError");}constructor(e="Not authorized"){super(e,401);}},M=class extends o{static{n(this,"ForbiddenError");}constructor(e="Access forbidden"){super(e,403);}},A=class extends o{static{n(this,"ConflictError");}constructor(e="Resource conflict"){super(e,409);}},O=class extends o{static{n(this,"RequestAbortedError");}constructor(e="Request aborted by client"){super(e,499);}};export{n as a,u as b,p as c,I as d,N as e,h as f,m as g,E as h,j as i,_ as j,o as k,d as l,x as m,T as n,M as o,A as p,O as q};
|
package/dist/index.d.ts
CHANGED
|
@@ -24,6 +24,7 @@ interface FactoryProvider<T = unknown> {
|
|
|
24
24
|
provide: Token<T>;
|
|
25
25
|
useFactory: (...args: any[]) => T | Promise<T>;
|
|
26
26
|
inject?: Token[];
|
|
27
|
+
scope?: Scope;
|
|
27
28
|
}
|
|
28
29
|
interface ExistingProvider<T = unknown> {
|
|
29
30
|
provide: Token<T>;
|
|
@@ -91,10 +92,60 @@ interface DynamicModule {
|
|
|
91
92
|
exports?: Token[];
|
|
92
93
|
global?: boolean;
|
|
93
94
|
}
|
|
95
|
+
/**
|
|
96
|
+
* Factory class interface for `useClass` / `useExisting` async options.
|
|
97
|
+
* Implement this on a class to provide module options asynchronously.
|
|
98
|
+
*/
|
|
99
|
+
interface ModuleOptionsFactory<T> {
|
|
100
|
+
createModuleOptions(): T | Promise<T>;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Async options accepted by `forRootAsync()`.
|
|
104
|
+
*
|
|
105
|
+
* Exactly one of `useFactory`, `useClass`, or `useExisting` must be provided.
|
|
106
|
+
*/
|
|
107
|
+
type ModuleAsyncOptions<T> = {
|
|
108
|
+
imports?: Array<Type | DynamicModule>;
|
|
109
|
+
useFactory: (...args: any[]) => T | Promise<T>;
|
|
110
|
+
inject?: Token[];
|
|
111
|
+
useClass?: never;
|
|
112
|
+
useExisting?: never;
|
|
113
|
+
} | {
|
|
114
|
+
imports?: Array<Type | DynamicModule>;
|
|
115
|
+
useClass: Type<ModuleOptionsFactory<T>>;
|
|
116
|
+
useFactory?: never;
|
|
117
|
+
inject?: never;
|
|
118
|
+
useExisting?: never;
|
|
119
|
+
} | {
|
|
120
|
+
imports?: Array<Type | DynamicModule>;
|
|
121
|
+
useExisting: Type<ModuleOptionsFactory<T>>;
|
|
122
|
+
useFactory?: never;
|
|
123
|
+
inject?: never;
|
|
124
|
+
useClass?: never;
|
|
125
|
+
};
|
|
94
126
|
|
|
95
127
|
declare function Module(metadata: ModuleMetadata): ClassDecorator;
|
|
128
|
+
/**
|
|
129
|
+
* Marks a module as global so its exported providers are visible to all
|
|
130
|
+
* modules without needing to import it explicitly.
|
|
131
|
+
*
|
|
132
|
+
* @example
|
|
133
|
+
* @Global()
|
|
134
|
+
* @Module({ providers: [ConfigService], exports: [ConfigService] })
|
|
135
|
+
* export class CoreModule {}
|
|
136
|
+
*/
|
|
137
|
+
declare function Global(): ClassDecorator;
|
|
96
138
|
declare function getModuleMetadata(target: Function): ModuleMetadata | undefined;
|
|
139
|
+
declare function isGlobalModule(target: Function): boolean;
|
|
97
140
|
|
|
141
|
+
interface ResolvedModule {
|
|
142
|
+
type: Type;
|
|
143
|
+
metadata: ModuleMetadata;
|
|
144
|
+
controllers: Type[];
|
|
145
|
+
providers: Provider[];
|
|
146
|
+
exports: Set<Token>;
|
|
147
|
+
global: boolean;
|
|
148
|
+
}
|
|
98
149
|
declare class ModuleRegistry {
|
|
99
150
|
private resolved;
|
|
100
151
|
private sortedModules;
|
|
@@ -113,10 +164,146 @@ declare class ModuleRegistry {
|
|
|
113
164
|
getAllControllers(): Type[];
|
|
114
165
|
callLifecycleHooks(container: Container, hook: string, signal?: string): Promise<void>;
|
|
115
166
|
private resolveModule;
|
|
167
|
+
/**
|
|
168
|
+
* Build the set of tokens visible to a module:
|
|
169
|
+
* own providers + exported tokens from imported modules + global module providers.
|
|
170
|
+
*/
|
|
171
|
+
getVisibleTokens(mod: ResolvedModule): Set<Token>;
|
|
172
|
+
/**
|
|
173
|
+
* Validate that every module's exports are resolvable:
|
|
174
|
+
* each exported token must be in the module's own providers
|
|
175
|
+
* or in an imported module's exports (re-export).
|
|
176
|
+
*/
|
|
177
|
+
private validateExports;
|
|
178
|
+
/**
|
|
179
|
+
* Validate that all @Inject dependencies of a module's providers
|
|
180
|
+
* are visible (own providers + imported exports + globals).
|
|
181
|
+
* Call after scan() for strict visibility enforcement.
|
|
182
|
+
*/
|
|
183
|
+
validateVisibility(): void;
|
|
184
|
+
private getProviderToken;
|
|
185
|
+
private collectImportedExports;
|
|
186
|
+
/**
|
|
187
|
+
* Find a provider by token in a module's own providers.
|
|
188
|
+
*/
|
|
189
|
+
private findProvider;
|
|
190
|
+
/**
|
|
191
|
+
* Find a provider from an imported module's exports (for re-export support).
|
|
192
|
+
* Walks the import chain to find the original provider definition.
|
|
193
|
+
*/
|
|
194
|
+
private findReExportedProvider;
|
|
116
195
|
private getModuleType;
|
|
117
196
|
private topologicalSort;
|
|
118
197
|
}
|
|
119
198
|
|
|
199
|
+
/**
|
|
200
|
+
* The class generated by `ConfigurableModuleBuilder.build()`.
|
|
201
|
+
*
|
|
202
|
+
* Extend it in your module class to inherit `forRoot`, `forRootAsync`,
|
|
203
|
+
* and `forFeature` as static methods.
|
|
204
|
+
*/
|
|
205
|
+
interface ConfigurableModuleClass<TOptions extends object> {
|
|
206
|
+
new (...args: any[]): {};
|
|
207
|
+
/**
|
|
208
|
+
* Synchronous configuration — use when options are known at module load time.
|
|
209
|
+
*
|
|
210
|
+
* @example
|
|
211
|
+
* @Module({ imports: [NotionModule.forRoot({ apiKey: '...' })] })
|
|
212
|
+
* class AppModule {}
|
|
213
|
+
*/
|
|
214
|
+
forRoot(options: TOptions, extras?: ExtraOptions): DynamicModule;
|
|
215
|
+
/**
|
|
216
|
+
* Asynchronous configuration — use when options come from config service,
|
|
217
|
+
* environment, or another provider.
|
|
218
|
+
*
|
|
219
|
+
* @example
|
|
220
|
+
* @Module({
|
|
221
|
+
* imports: [NotionModule.forRootAsync({
|
|
222
|
+
* imports: [ConfigModule],
|
|
223
|
+
* useFactory: (cfg: ConfigService) => ({ apiKey: cfg.get('NOTION_KEY') }),
|
|
224
|
+
* inject: [ConfigService],
|
|
225
|
+
* })]
|
|
226
|
+
* })
|
|
227
|
+
* class AppModule {}
|
|
228
|
+
*/
|
|
229
|
+
forRootAsync(asyncOptions: ModuleAsyncOptions<TOptions>): DynamicModule;
|
|
230
|
+
/**
|
|
231
|
+
* Feature-level configuration — use inside feature modules to configure
|
|
232
|
+
* a subset of the module's behaviour (e.g. register specific entities/schemas).
|
|
233
|
+
*
|
|
234
|
+
* @example
|
|
235
|
+
* @Module({ imports: [TypeOrmModule.forFeature([User, Post])] })
|
|
236
|
+
* class UserModule {}
|
|
237
|
+
*/
|
|
238
|
+
forFeature(config: FeatureConfig, extras?: ExtraOptions): DynamicModule;
|
|
239
|
+
}
|
|
240
|
+
/** Extra options available on every `forRoot` / `forFeature` call. */
|
|
241
|
+
interface ExtraOptions {
|
|
242
|
+
/** When true, providers exported by this module are available everywhere. */
|
|
243
|
+
global?: boolean;
|
|
244
|
+
}
|
|
245
|
+
/** Configuration accepted by `forFeature`. */
|
|
246
|
+
type FeatureConfig = object;
|
|
247
|
+
interface ConfigurableModuleBuilderResult<TOptions extends object, TFeature extends FeatureConfig> {
|
|
248
|
+
/**
|
|
249
|
+
* Base class to extend in your `@Module` class.
|
|
250
|
+
* Provides `forRoot`, `forRootAsync`, and `forFeature` as static methods.
|
|
251
|
+
*/
|
|
252
|
+
ConfigurableModuleClass: ConfigurableModuleClass<TOptions>;
|
|
253
|
+
/**
|
|
254
|
+
* Injection token for the module options.
|
|
255
|
+
* Use with `@Inject(MODULE_OPTIONS_TOKEN)` in your service.
|
|
256
|
+
*/
|
|
257
|
+
MODULE_OPTIONS_TOKEN: InjectionToken<TOptions>;
|
|
258
|
+
/**
|
|
259
|
+
* Injection token for the feature config (only if `forFeature` is used).
|
|
260
|
+
* Use with `@Inject(MODULE_FEATURE_TOKEN)` in your service.
|
|
261
|
+
*/
|
|
262
|
+
MODULE_FEATURE_TOKEN: InjectionToken<TFeature[]>;
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Builds a reusable configurable module base class with `forRoot`,
|
|
266
|
+
* `forRootAsync`, and `forFeature` static methods — identical to the
|
|
267
|
+
* NestJS `ConfigurableModuleBuilder` pattern.
|
|
268
|
+
*
|
|
269
|
+
* @example
|
|
270
|
+
* const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } =
|
|
271
|
+
* new ConfigurableModuleBuilder<NotionOptions>().build()
|
|
272
|
+
*
|
|
273
|
+
* @Global()
|
|
274
|
+
* @Module({ providers: [NotionService], exports: [NotionService] })
|
|
275
|
+
* export class NotionModule extends ConfigurableModuleClass {}
|
|
276
|
+
*/
|
|
277
|
+
declare class ConfigurableModuleBuilder<TOptions extends object, TFeature extends FeatureConfig = FeatureConfig> {
|
|
278
|
+
private description;
|
|
279
|
+
private featureDescription;
|
|
280
|
+
private onForRoot?;
|
|
281
|
+
private onForFeature?;
|
|
282
|
+
constructor(description?: string);
|
|
283
|
+
/**
|
|
284
|
+
* Custom token description (used in error messages).
|
|
285
|
+
* Default: `'MODULE_OPTIONS'`.
|
|
286
|
+
*/
|
|
287
|
+
setTokenDescription(description: string): this;
|
|
288
|
+
/**
|
|
289
|
+
* Hook called after every `forRoot` / `forRootAsync` to let you augment
|
|
290
|
+
* the returned `DynamicModule` (e.g. add extra providers, change exports).
|
|
291
|
+
*
|
|
292
|
+
* @example
|
|
293
|
+
* builder.transformDynamicModule((mod, opts) => ({
|
|
294
|
+
* ...mod,
|
|
295
|
+
* providers: [...(mod.providers ?? []), createCacheProvider(opts)],
|
|
296
|
+
* }))
|
|
297
|
+
*/
|
|
298
|
+
transformDynamicModule(fn: (module: DynamicModule, options: TOptions) => DynamicModule): this;
|
|
299
|
+
/**
|
|
300
|
+
* Hook called after every `forFeature` to let you augment the
|
|
301
|
+
* returned `DynamicModule`.
|
|
302
|
+
*/
|
|
303
|
+
transformFeatureModule(fn: (module: DynamicModule, config: TFeature) => DynamicModule): this;
|
|
304
|
+
build(): ConfigurableModuleBuilderResult<TOptions, TFeature>;
|
|
305
|
+
}
|
|
306
|
+
|
|
120
307
|
/** Framework-agnostic representation of a multipart form field or file. */
|
|
121
308
|
interface FormDataPart {
|
|
122
309
|
name: string;
|
|
@@ -188,6 +375,24 @@ interface Interceptor {
|
|
|
188
375
|
intercept(ctx: ExecutionContext, next: () => Promise<unknown>): Promise<unknown>;
|
|
189
376
|
}
|
|
190
377
|
|
|
378
|
+
/**
|
|
379
|
+
* Middleware runs before guards, pipes, and interceptors.
|
|
380
|
+
* Suitable for: logging, CORS, rate limiting, request transformation.
|
|
381
|
+
*
|
|
382
|
+
* @example
|
|
383
|
+
* class LogMiddleware implements Middleware {
|
|
384
|
+
* async use(ctx: ExecutionContext, next: () => Promise<unknown>) {
|
|
385
|
+
* console.log('→', ctx.getNativeRequest())
|
|
386
|
+
* const result = await next()
|
|
387
|
+
* console.log('←', result)
|
|
388
|
+
* return result
|
|
389
|
+
* }
|
|
390
|
+
* }
|
|
391
|
+
*/
|
|
392
|
+
interface Middleware {
|
|
393
|
+
use(ctx: ExecutionContext, next: () => Promise<unknown>): Promise<unknown>;
|
|
394
|
+
}
|
|
395
|
+
|
|
191
396
|
interface PipeTransform {
|
|
192
397
|
transform(ctx: ExecutionContext): void | Promise<void>;
|
|
193
398
|
}
|
|
@@ -204,9 +409,11 @@ interface ExceptionFilter {
|
|
|
204
409
|
|
|
205
410
|
type GuardRef = Type<ICanActivateGuard> | ICanActivateGuard;
|
|
206
411
|
type InterceptorRef = Type<Interceptor> | Interceptor;
|
|
412
|
+
type MiddlewareRef$1 = Type<Middleware> | Middleware;
|
|
207
413
|
type PipeRef = Type<PipeTransform> | PipeTransform;
|
|
208
414
|
type FilterRef = Type<ExceptionFilter> | ExceptionFilter;
|
|
209
415
|
interface PipelineOptions {
|
|
416
|
+
middlewares?: MiddlewareRef$1[];
|
|
210
417
|
guards?: GuardRef[];
|
|
211
418
|
interceptors?: InterceptorRef[];
|
|
212
419
|
pipes?: PipeRef[];
|
|
@@ -219,7 +426,16 @@ interface CreatePipelineOptions extends PipelineOptions {
|
|
|
219
426
|
}
|
|
220
427
|
declare function createPipeline(container: Container, globalOptions: PipelineOptions, localOptions: CreatePipelineOptions): (ctx: ExecutionContext) => Promise<unknown>;
|
|
221
428
|
|
|
222
|
-
declare function UseInterceptors(...interceptors: InterceptorRef[]):
|
|
429
|
+
declare function UseInterceptors(...interceptors: InterceptorRef[]): any;
|
|
430
|
+
/** Class-level interceptors set via @UseInterceptors on the class. */
|
|
431
|
+
declare function getInterceptorsMetadata(target: Function): InterceptorRef[];
|
|
432
|
+
/** Method-level interceptors set via @UseInterceptors on a specific method. */
|
|
433
|
+
declare function getMethodInterceptors(target: Function, methodName: string): InterceptorRef[];
|
|
434
|
+
/**
|
|
435
|
+
* Effective interceptors for a route = class-level + method-level, in that order.
|
|
436
|
+
* Class interceptors run first (outermost), method interceptors run last (innermost).
|
|
437
|
+
*/
|
|
438
|
+
declare function getEffectiveInterceptors(target: Function, methodName: string): InterceptorRef[];
|
|
223
439
|
|
|
224
440
|
/**
|
|
225
441
|
* Framework-agnostic transaction context.
|
|
@@ -306,6 +522,33 @@ declare class UnitOfWorkInterceptor implements Interceptor {
|
|
|
306
522
|
intercept(ctx: ExecutionContext, next: () => Promise<unknown>): Promise<unknown>;
|
|
307
523
|
}
|
|
308
524
|
|
|
525
|
+
type MiddlewareRef = Type<Middleware> | Middleware;
|
|
526
|
+
/**
|
|
527
|
+
* Attach middleware to a controller class or a specific route method.
|
|
528
|
+
*
|
|
529
|
+
* Class-level: runs for every route in the controller.
|
|
530
|
+
* Method-level: runs only for that route, after class-level middleware.
|
|
531
|
+
*
|
|
532
|
+
* @example
|
|
533
|
+
* @UseMiddleware(LogMiddleware)
|
|
534
|
+
* @Controller('users')
|
|
535
|
+
* class UserController {
|
|
536
|
+
* @UseMiddleware(RateLimitMiddleware)
|
|
537
|
+
* @Post('/')
|
|
538
|
+
* create() { ... }
|
|
539
|
+
* }
|
|
540
|
+
*/
|
|
541
|
+
declare function UseMiddleware(...middlewares: MiddlewareRef[]): any;
|
|
542
|
+
/** Class-level middlewares set via @UseMiddleware on the class. */
|
|
543
|
+
declare function getMiddlewaresMetadata(target: Function): MiddlewareRef[];
|
|
544
|
+
/** Method-level middlewares set via @UseMiddleware on a specific method. */
|
|
545
|
+
declare function getMethodMiddlewares(target: Function, methodName: string): MiddlewareRef[];
|
|
546
|
+
/**
|
|
547
|
+
* Effective middlewares for a route = class-level + method-level, in that order.
|
|
548
|
+
* Class middlewares run first (outermost), method middlewares run next.
|
|
549
|
+
*/
|
|
550
|
+
declare function getEffectiveMiddlewares(target: Function, methodName: string): MiddlewareRef[];
|
|
551
|
+
|
|
309
552
|
declare function UsePipes(...pipes: PipeRef[]): ClassDecorator & MethodDecorator;
|
|
310
553
|
|
|
311
554
|
interface ZodLikeSchema {
|
|
@@ -516,88 +759,6 @@ declare class EventBus {
|
|
|
516
759
|
*/
|
|
517
760
|
declare function OnEvent(eventType: string): MethodDecorator;
|
|
518
761
|
|
|
519
|
-
/**
|
|
520
|
-
* A single step in a saga.
|
|
521
|
-
*
|
|
522
|
-
* @template T - The return type of the execute function
|
|
523
|
-
*/
|
|
524
|
-
interface SagaStep<T = unknown> {
|
|
525
|
-
/** Human-readable name for logging/debugging. */
|
|
526
|
-
name: string;
|
|
527
|
-
/** The forward action. Returns a result that is passed to compensate on failure. */
|
|
528
|
-
execute: (signal?: AbortSignal) => T | Promise<T>;
|
|
529
|
-
/**
|
|
530
|
-
* The compensating action. Called with the result of execute() if a LATER step fails.
|
|
531
|
-
* Should undo the effect of execute().
|
|
532
|
-
* If not provided, the step is considered non-compensatable (e.g., the last step).
|
|
533
|
-
*/
|
|
534
|
-
compensate?: (result: T) => void | Promise<void>;
|
|
535
|
-
}
|
|
536
|
-
interface SagaResult<T = unknown> {
|
|
537
|
-
/** Whether all steps completed successfully. */
|
|
538
|
-
success: boolean;
|
|
539
|
-
/** Results of each completed step, keyed by step name. */
|
|
540
|
-
results: Record<string, unknown>;
|
|
541
|
-
/** The result of the last step (convenience). */
|
|
542
|
-
value?: T;
|
|
543
|
-
/** If failed, the error that caused the failure. */
|
|
544
|
-
error?: unknown;
|
|
545
|
-
/** Name of the step that failed. */
|
|
546
|
-
failedStep?: string;
|
|
547
|
-
/** Names of steps that were successfully compensated. */
|
|
548
|
-
compensated: string[];
|
|
549
|
-
/** Compensation errors, if any. Keyed by step name. */
|
|
550
|
-
compensationErrors: Record<string, unknown>;
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
interface SagaOrchestratorOptions {
|
|
554
|
-
/** Called when a compensation step fails. Defaults to console.error. */
|
|
555
|
-
onCompensationError?: (stepName: string, error: unknown) => void;
|
|
556
|
-
}
|
|
557
|
-
/**
|
|
558
|
-
* Executes a sequence of steps with automatic compensation on failure.
|
|
559
|
-
*
|
|
560
|
-
* If step N fails, steps N-1..0 are compensated in reverse order.
|
|
561
|
-
* Compensation errors are captured but do NOT prevent other compensations.
|
|
562
|
-
*
|
|
563
|
-
* @example
|
|
564
|
-
* ```typescript
|
|
565
|
-
* @UseCase()
|
|
566
|
-
* class CreateOrderUseCase {
|
|
567
|
-
* constructor(private saga: SagaOrchestrator) {}
|
|
568
|
-
*
|
|
569
|
-
* async execute(input: CreateOrderInput) {
|
|
570
|
-
* const result = await this.saga.execute([
|
|
571
|
-
* {
|
|
572
|
-
* name: 'reserve-inventory',
|
|
573
|
-
* execute: () => inventoryService.reserve(input.items),
|
|
574
|
-
* compensate: (res) => inventoryService.release(res.reservationId),
|
|
575
|
-
* },
|
|
576
|
-
* {
|
|
577
|
-
* name: 'charge-payment',
|
|
578
|
-
* execute: () => paymentService.charge(input.amount),
|
|
579
|
-
* compensate: (res) => paymentService.refund(res.chargeId),
|
|
580
|
-
* },
|
|
581
|
-
* {
|
|
582
|
-
* name: 'create-order',
|
|
583
|
-
* execute: () => orderService.create(input),
|
|
584
|
-
* },
|
|
585
|
-
* ])
|
|
586
|
-
*
|
|
587
|
-
* if (!result.success) throw result.error
|
|
588
|
-
* return result.value
|
|
589
|
-
* }
|
|
590
|
-
* }
|
|
591
|
-
* ```
|
|
592
|
-
*/
|
|
593
|
-
declare class SagaOrchestrator {
|
|
594
|
-
private onCompensationError;
|
|
595
|
-
constructor();
|
|
596
|
-
setOptions(options: SagaOrchestratorOptions): void;
|
|
597
|
-
execute<T = unknown>(steps: SagaStep[], signal?: AbortSignal): Promise<SagaResult<T>>;
|
|
598
|
-
private buildFailure;
|
|
599
|
-
}
|
|
600
|
-
|
|
601
762
|
declare class AppError extends Error {
|
|
602
763
|
readonly statusCode: number;
|
|
603
764
|
readonly status: 'fail' | 'error';
|
|
@@ -667,6 +828,8 @@ interface CompiledRoute {
|
|
|
667
828
|
controllerClass: any;
|
|
668
829
|
methodName: string;
|
|
669
830
|
guardClasses: GuardClass[];
|
|
831
|
+
interceptorRefs: InterceptorRef[];
|
|
832
|
+
middlewareRefs: MiddlewareRef$1[];
|
|
670
833
|
rawPath: string;
|
|
671
834
|
}
|
|
672
835
|
interface RouteMatch {
|
|
@@ -695,7 +858,7 @@ declare class ControllerRouter {
|
|
|
695
858
|
|
|
696
859
|
/** Async-capable function that extracts the auth payload from the execution context. */
|
|
697
860
|
type AuthExtractorFn<T = unknown> = (ctx: ExecutionContext) => T | Promise<T>;
|
|
698
|
-
type RouteParamType = 'query' | 'param' | 'body' | 'rawBody' | 'formData' | 'headers' | 'cookie' | 'ip' | 'userAgent' | 'auth';
|
|
861
|
+
type RouteParamType = 'query' | 'param' | 'body' | 'rawBody' | 'formData' | 'headers' | 'cookie' | 'ip' | 'userAgent' | 'auth' | 'custom';
|
|
699
862
|
interface RouteParamMetadata {
|
|
700
863
|
index: number;
|
|
701
864
|
type: RouteParamType;
|
|
@@ -808,6 +971,24 @@ declare function defineAuth<_T = unknown>(extractor?: AuthExtractorFn<_T>): () =
|
|
|
808
971
|
* Use `defineAuth<YourPayload>()` in your project to get a typed version.
|
|
809
972
|
*/
|
|
810
973
|
declare const Auth: () => ParameterDecorator;
|
|
974
|
+
/**
|
|
975
|
+
* Factory for custom parameter decorators with a user-supplied async extractor.
|
|
976
|
+
*
|
|
977
|
+
* The returned function is a zero-argument decorator factory — call it with `()` at the use site.
|
|
978
|
+
*
|
|
979
|
+
* @example
|
|
980
|
+
* // Define once:
|
|
981
|
+
* const CurrentUser = createParamDecorator<IUser>(async (ctx) => {
|
|
982
|
+
* const payload = ctx.getAuth<{ id: string }>()
|
|
983
|
+
* if (!payload) throw new UnauthorizedError()
|
|
984
|
+
* return userService.findById(payload.id)
|
|
985
|
+
* })
|
|
986
|
+
*
|
|
987
|
+
* // Use in a controller:
|
|
988
|
+
* @Get('/profile')
|
|
989
|
+
* getProfile(@CurrentUser() user: IUser) {}
|
|
990
|
+
*/
|
|
991
|
+
declare function createParamDecorator<T = unknown>(extractor: (ctx: ExecutionContext) => T | Promise<T>): () => ParameterDecorator;
|
|
811
992
|
declare function getRouteParams(controllerClass: Function, methodName: string): RouteParamMetadata[] | null;
|
|
812
993
|
declare function resolveParamArgs(meta: RouteParamMetadata[], ctx: ExecutionContext): Promise<unknown[]>;
|
|
813
994
|
|
|
@@ -853,4 +1034,4 @@ declare class BackendApplication {
|
|
|
853
1034
|
private ensureInitialized;
|
|
854
1035
|
}
|
|
855
1036
|
|
|
856
|
-
export { AppError, type ApplicationOptions, Auth, type AuthExtractorFn, BackendApplication, BaseExecutionContext, Body, Catch, type ClassProvider, type CompiledRoute, ConflictError, Container, Controller, ControllerRouter, Cookie, type CreatePipelineOptions, DefaultValuePipe, Delete, DomainEvent, type DynamicModule, EventBus, type EventBusOptions, type EventHandler, type ExceptionFilter, type ExecutionContext, type ExistingProvider, type FactoryProvider, type FilterRef, ForbiddenError, FormData, type FormDataPart, type ForwardRef, Get, type GuardClass, type GuardInstance, type GuardRef, type HandlerFn, Headers, type HttpMethod, type ICanActivateGuard, type IUseCase, Inject, Injectable, type InjectableOptions, type Interceptor, type InterceptorRef, Ip, Module, type 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, type Provider, Put, Query, RawBody, RequestAbortedError, RouteGuards, type RouteMatch, type RouteMetadata, type RouteParamMetadata, type RouteParamType,
|
|
1037
|
+
export { AppError, type ApplicationOptions, Auth, type AuthExtractorFn, BackendApplication, BaseExecutionContext, Body, Catch, type ClassProvider, type CompiledRoute, ConfigurableModuleBuilder, type ConfigurableModuleBuilderResult, type ConfigurableModuleClass, ConflictError, Container, Controller, ControllerRouter, Cookie, type CreatePipelineOptions, DefaultValuePipe, Delete, DomainEvent, type DynamicModule, EventBus, type EventBusOptions, type EventHandler, type ExceptionFilter, type ExecutionContext, type ExistingProvider, type ExtraOptions, type FactoryProvider, type FeatureConfig, type FilterRef, ForbiddenError, FormData, type FormDataPart, type ForwardRef, Get, Global, type GuardClass, type GuardInstance, type GuardRef, type HandlerFn, Headers, type HttpMethod, type ICanActivateGuard, type IUseCase, Inject, Injectable, type InjectableOptions, type Interceptor, type InterceptorRef, Ip, type Middleware, type MiddlewareRef, Module, type ModuleAsyncOptions, type ModuleMetadata, type ModuleOptionsFactory, 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, type Provider, Put, Query, RawBody, RequestAbortedError, RouteGuards, type RouteMatch, type RouteMetadata, type RouteParamMetadata, type RouteParamType, Scope, type Token, type Type, UOW_INSTANCE_KEY, UOW_SESSION_KEY, UnauthorizedError, type UnitOfWork, type UnitOfWorkFactory, UnitOfWorkInterceptor, UseFilters, UseInterceptors, UseMiddleware, UsePipes, UserAgent, ValidationError, type ValueProvider, ZodParamPipe, ZodValidationPipe, createParamDecorator, createPipeline, defineAuth, forwardRef, getControllerGuards, getControllerPath, getEffectiveInterceptors, getEffectiveMiddlewares, getInterceptorsMetadata, getMethodGuards, getMethodInterceptors, getMethodMiddlewares, getMiddlewaresMetadata, getModuleMetadata, getRouteMetadata, getRouteParams, isGlobalModule, resolveForwardRef, resolveParamArgs };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import'reflect-metadata';var ne=Object.defineProperty;var s=(e,t)=>ne(e,"name",{value:t,configurable:true});var d=(function(e){return e.SINGLETON="singleton",e.REQUEST="request",e.TRANSIENT="transient",e})({}),_=class{static{s(this,"InjectionToken");}description;constructor(t){this.description=t;}toString(){return `InjectionToken(${this.description})`}};var pt=Symbol("injectable"),X=Symbol("inject:param"),ht=Symbol("inject:deps"),tt=Symbol("optional");function M(e){return t=>{Reflect.defineMetadata(pt,{scope:e?.scope??d.SINGLETON},t);}}s(M,"Injectable");function mt(...e){return (t,r,o)=>{if(typeof o=="number"){let n=Reflect.getOwnMetadata(X,t)??new Map;n.set(o,e[0]),Reflect.defineMetadata(X,n,t);}else Reflect.defineMetadata(ht,e,t);}}s(mt,"Inject");function gt(){return (e,t,r)=>{let o=Reflect.getOwnMetadata(tt,e)??new Set;o.add(r),Reflect.defineMetadata(tt,o,e);}}s(gt,"Optional");function N(e){return Reflect.getOwnMetadata(pt,e)}s(N,"getInjectableMetadata");function yt(e){return Reflect.getOwnMetadata(ht,e)??[]}s(yt,"getClassDeps");function wt(e){return Reflect.getOwnMetadata(X,e)??new Map}s(wt,"getInjectTokens");function xt(e){return Reflect.getOwnMetadata(tt,e)??new Set}s(xt,"getOptionalParams");function Et(e){return {forwardRef:e}}s(Et,"forwardRef");function D(e){return typeof e=="object"&&"forwardRef"in e?e.forwardRef():e}s(D,"resolveForwardRef");var b=class e{static{s(this,"Container");}registrations=new Map;resolving=new Set;parent=null;children=[];register(...t){for(let r of t)this.registerOne(r);}registerOne(t){if(typeof t=="function"){let a=N(t)?.scope??d.SINGLETON;this.registrations.set(t,{provider:t,scope:a});return}let r=t.provide,o=d.SINGLETON;if("useClass"in t){let n=N(t.useClass);o=t.scope??n?.scope??d.SINGLETON;}else "useFactory"in t&&(o=d.SINGLETON);this.registrations.set(r,{provider:t,scope:o});}async resolve(t){let r=D(t),o=r!==t?r:t,n=this.registrations.get(o)??this.parent?.findRegistration(o);if(!n)throw new Error(`No provider found for ${et(o)}`);if(n.scope===d.SINGLETON&&n.instance!==void 0||n.scope===d.REQUEST&&this.parent&&n.instance!==void 0)return n.instance;if(this.resolving.has(o))throw new Error(`Circular dependency detected for ${et(o)}`);this.resolving.add(o);try{let a=await this.createInstance(n);return (n.scope===d.SINGLETON||n.scope===d.REQUEST)&&(n.instance=a),a}finally{this.resolving.delete(o);}}has(t){return this.registrations.has(t)||(this.parent?.has(t)??false)}findRegistration(t){return this.registrations.get(t)??this.parent?.findRegistration(t)}createChild(){let t=new e;t.parent=this;for(let[r,o]of this.registrations)o.scope===d.REQUEST&&t.registrations.set(r,{provider:o.provider,scope:d.REQUEST,instance:void 0});return this.children.push(t),t}async dispose(){for(let t of this.children)await t.dispose();this.children=[];for(let[,t]of this.registrations)if(t.instance&&typeof t.instance=="object"&&t.instance!==null){let r=t.instance;typeof r.onModuleDestroy=="function"&&await r.onModuleDestroy();}this.registrations.clear(),this.resolving.clear();}async createInstance(t){let{provider:r}=t;if(typeof r=="function")return this.instantiateClass(r);if("useValue"in r)return r.useValue;if("useClass"in r)return this.instantiateClass(r.useClass);if("useFactory"in r){let o=r,n=[];if(o.inject)for(let a of o.inject)n.push(await this.resolve(a));return o.useFactory(...n)}if("useExisting"in r)return this.resolve(r.useExisting);throw new Error("Unknown provider type")}async instantiateClass(t){let r=Reflect.getMetadata("design:paramtypes",t)??[],o=yt(t),n=wt(t),a=xt(t),i=n.size>0?Math.max(...n.keys())+1:0,c=Math.max(r.length,i,o.length),u=[];for(let f=0;f<c;f++){let l=n.get(f)??o[f]??r[f],p=a.has(f);try{u.push(await this.resolve(l));}catch{if(p)u.push(void 0);else throw new Error(`Cannot resolve parameter at index ${f} (${et(l)}) of ${t.name}`)}}return new t(...u)}};function et(e){return typeof e=="string"?e:typeof e=="symbol"||e instanceof _?e.toString():typeof e=="function"?e.name:String(e)}s(et,"tokenToString");var Rt=Symbol("module");function Mt(e){return t=>{Reflect.defineMetadata(Rt,e,t);}}s(Mt,"Module");function j(e){return Reflect.getOwnMetadata(Rt,e)}s(j,"getModuleMetadata");var bt=Symbol("controller:path"),rt=Symbol("controller:guards"),ot=Symbol("route:metadata"),nt=Symbol("method:route"),T=Symbol("method:guards"),st=Symbol("method:noguard");function vt(e){return t=>{Reflect.defineMetadata(bt,e,t);}}s(vt,"Controller");function O(e){return (t="")=>(r,o,n)=>{let a=n!==void 0,i=String(a?o:o?.name??o),c=a?n?.value:r;if(typeof c=="function"&&(c[nt]={method:e,path:t,methodName:i}),a){let u=Reflect.getOwnMetadata(ot,r.constructor)??[];return u.push({method:e,path:t,methodName:i}),Reflect.defineMetadata(ot,u,r.constructor),n}return r}}s(O,"createMethodDecorator");var At=O("GET"),Pt=O("POST"),St=O("PUT"),Ct=O("DELETE"),Nt=O("PATCH");function Tt(...e){return (t,r,o)=>{if(r==null){Reflect.defineMetadata(rt,e,t);return}if(o!==void 0){if(o?.value){let n=o.value[T]??[];o.value[T]=[...n,...e];}return o}if(typeof t=="function"){let n=t[T]??[];t[T]=[...n,...e];}return typeof t=="function"&&r?.kind==="class"&&Reflect.defineMetadata(rt,e,t),t}}s(Tt,"RouteGuards");function Ot(){return (e,t,r)=>r!==void 0?(r?.value&&(r.value[st]=true),r):(typeof e=="function"&&(e[st]=true),e)}s(Ot,"NoGuard");function v(e){return Reflect.getOwnMetadata(bt,e)}s(v,"getControllerPath");function at(e){return Reflect.getOwnMetadata(rt,e)??[]}s(at,"getControllerGuards");function $(e){let t=[],r=e.prototype;if(r){let o=Object.getOwnPropertyNames(r);for(let n of o){if(n==="constructor")continue;let a=r[n];typeof a=="function"&&a[nt]&&t.push(a[nt]);}}return t.length>0?t:Reflect.getOwnMetadata(ot,e)??[]}s($,"getRouteMetadata");function G(e,t){let o=e.prototype?.[t],n=typeof o=="function"&&o[st]===true,a=typeof o=="function"&&o[T]||[];return n?a:[...at(e),...a]}s(G,"getMethodGuards");var A=class{static{s(this,"ModuleRegistry");}resolved=new Map;sortedModules=[];scan(t){this.resolveModule(t),this.sortedModules=this.topologicalSort();}registerAll(t){let r=new Set;for(let o of this.sortedModules)if(o.global)for(let n of o.providers)r.add(n);r.size>0&&t.register(...r);for(let o of this.sortedModules)if(t.register(...o.providers),o.metadata.imports)for(let n of o.metadata.imports){let a=this.getModuleType(n),i=this.resolved.get(a);if(i)for(let c of i.exports){let u=i.providers.find(f=>typeof f=="function"?f===c:f.provide===c);u&&t.register(u);}}}getAllProviders(){let t=[];for(let r of this.sortedModules)t.push(...r.providers);return t}getAllControllers(){let t=new Set,r=[];for(let o of this.sortedModules){for(let n of o.controllers)t.has(n)||(t.add(n),r.push(n));for(let n of o.metadata.providers??[])typeof n=="function"&&v(n)!==void 0&&!t.has(n)&&(t.add(n),r.push(n));}return r}async callLifecycleHooks(t,r,o){for(let n of this.sortedModules)for(let a of n.providers){let i=typeof a=="function"?a:a.provide;if(t.has(i))try{let c=await t.resolve(i);c&&typeof c=="object"&&typeof c[r]=="function"&&await c[r](o);}catch{}}}resolveModule(t){let r=typeof t=="object"&&"module"in t,o=r?t.module:t;if(this.resolved.has(o))return this.resolved.get(o);let n=j(o)??{},a=r?t:{},i=[...n.controllers??[],...a.controllers??[]],c={imports:[...n.imports??[],...a.imports??[]],controllers:i,providers:[...n.providers??[],...a.providers??[]],exports:[...n.exports??[],...a.exports??[]]},u={type:o,metadata:c,controllers:i,providers:[...i,...c.providers??[]],exports:new Set(c.exports??[]),global:r?t.global??false:false};this.resolved.set(o,u);for(let f of c.imports??[])this.resolveModule(f);return u}getModuleType(t){return typeof t=="object"&&"module"in t?t.module:t}topologicalSort(){let t=new Set,r=new Set,o=[],n=s(a=>{if(t.has(a))return;if(r.has(a))throw new Error(`Circular module dependency detected: ${a.name}`);r.add(a);let i=this.resolved.get(a);if(i){for(let c of i.metadata.imports??[])n(this.getModuleType(c));r.delete(a),t.add(a),o.push(i);}},"visit");for(let[a]of this.resolved)n(a);return o}};var B=class{static{s(this,"BaseExecutionContext");}nativeRequest;handler;container;query;params;body;rawBody;formData;auth;data=new Map;metadata=new Map;abortController;constructor(t,r,o,n={},a={},i){this.nativeRequest=t,this.handler=r,this.container=o,this.query=n,this.params=a,this.abortController=i??new AbortController;}getNativeRequest(){return this.nativeRequest}getHandler(){return this.handler}getBody(){return this.body}setBody(t){this.body=t;}getRawBody(){return this.rawBody}setRawBody(t){this.rawBody=t;}getFormData(){return this.formData}setFormData(t){this.formData=t;}getQuery(){return this.query}getParams(){return this.params}getAuth(){return this.auth}setAuth(t){this.auth=t;}getMetadata(t){return this.metadata.get(t)}setMetadata(t,r){this.metadata.set(t,r);}getData(t){return this.data.get(t)}setData(t,r){this.data.set(t,r);}getContainer(){return this.container}getSignal(){return this.abortController.signal}abort(t){this.abortController.abort(t);}};var It=Symbol("filters"),_t=Symbol("catch");function Dt(...e){return (t,r,o)=>{let n=r?t.constructor:t,a=Reflect.getOwnMetadata(It,n)??[];Reflect.defineMetadata(It,[...a,...e],n);}}s(Dt,"UseFilters");function jt(...e){return t=>{Reflect.defineMetadata(_t,e,t);}}s(jt,"Catch");function it(e){return Reflect.getOwnMetadata(_t,e)??[]}s(it,"getCatchMetadata");var g=class extends Error{static{s(this,"AppError");}statusCode;status;isOperational;constructor(t,r){super(t),this.statusCode=r,this.status=r>=400&&r<500?"fail":"error",this.isOperational=true,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace(this,this.constructor);}},U=class extends g{static{s(this,"NotFoundError");}constructor(t="Resource not found"){super(t,404);}},h=class extends g{static{s(this,"ValidationError");}errors;constructor(t="Validation failed",r){super(t,400),this.errors=r;}},k=class extends g{static{s(this,"UnauthorizedError");}constructor(t="Not authorized"){super(t,401);}},P=class extends g{static{s(this,"ForbiddenError");}constructor(t="Access forbidden"){super(t,403);}},F=class extends g{static{s(this,"ConflictError");}constructor(t="Resource conflict"){super(t,409);}},x=class extends g{static{s(this,"RequestAbortedError");}constructor(t="Request aborted by client"){super(t,499);}};function q(e,t,r){return async o=>{let n=[...t.guards??[],...r.guards??[]],a=[...t.interceptors??[],...r.interceptors??[]],i=[...t.pipes??[],...r.pipes??[]],c=[...t.filters??[],...r.filters??[]],u=await H(e,c);try{R(o);let f=await H(e,n);for(let C of f)if(R(o),!await C.canActivate(o))throw new P("Access denied by guard");R(o);let l=await H(e,i);for(let C of l)R(o),await C.transform(o);R(o);let p=await H(e,a),w=s(async()=>(R(o),r.handler(o)),"handlerCall");return p.length===0?await w():await p.reduceRight((C,dt)=>async()=>(R(o),dt.intercept(o,C)),w)()}catch(f){return se(f,o,u)}}}s(q,"createPipeline");function R(e){if(e.getSignal().aborted)throw new x}s(R,"checkAborted");async function se(e,t,r){for(let o of r){let n=it(o.constructor);if(n.length===0||e instanceof Error&&n.some(i=>e instanceof i))return o.catch(e,t)}throw e}s(se,"handleError");async function H(e,t){let r=[];for(let o of t)typeof o=="function"?r.push(await e.resolve(o)):r.push(o);return r}s(H,"resolveRefs");var $t=Symbol("interceptors");function Gt(...e){return (t,r,o)=>{let n=r?t.constructor:t,a=Reflect.getOwnMetadata($t,n)??[];Reflect.defineMetadata($t,[...a,...e],n);}}s(Gt,"UseInterceptors");var ct="uow:session",ft="uow:instance",L=class{static{s(this,"UnitOfWorkInterceptor");}factory;constructor(t){this.factory=t;}async intercept(t,r){let o=this.factory();await o.start(),t.setData(ct,o.getContext()),t.setData(ft,o);try{let n=await r();return await o.commit(),n}catch(n){throw await o.rollback(),n}}};var Bt=Symbol("pipes");function Ut(...e){return (t,r,o)=>{let n=r?t.constructor:t,a=Reflect.getOwnMetadata(Bt,n)??[];Reflect.defineMetadata(Bt,[...a,...e],n);}}s(Ut,"UsePipes");var z=class{static{s(this,"ZodValidationPipe");}schema;constructor(t){this.schema=t;}transform(t){let r=t.getBody(),o=this.schema.safeParse(r);if(!o.success){let n={};for(let a of o.error.issues){let i=a.path.join(".")||"_root";n[i]||(n[i]=[]),n[i].push(a.message);}throw new h("Validation failed",n)}t.setBody(o.data);}};var ae=/^[0-9a-fA-F]{24}$/,V=class{static{s(this,"ParseIdPipe");}paramName;constructor(t="id"){this.paramName=t;}transform(t){let o=t.getParams()[this.paramName];if(!o||!ae.test(o))throw new h(`Invalid ${this.paramName}: must be a valid ObjectId`)}};var W=class{static{s(this,"ParseIntPipe");}transform(t){let r=Number(t);if(!Number.isInteger(r)||t===""||t===null||t===void 0)throw new h(`Expected an integer, received: ${JSON.stringify(t)}`);return r}};var Q=class{static{s(this,"ZodParamPipe");}schema;constructor(t){this.schema=t;}transform(t){let r=this.schema.safeParse(t);if(!r.success){let o=r.error.errors.map(n=>`${n.path.join(".")}: ${n.message}`).join(", ");throw new h(o)}return r.data}};function kt(e){return {transform(t){return t??e}}}s(kt,"DefaultValuePipe");var Y=class{static{s(this,"DomainEvent");}payload;timestamp;constructor(t){this.payload=t,this.timestamp=Date.now();}};function ie(e,t,r,o){var n=arguments.length,a=n<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,r):o,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(e,t,r,o);else for(var c=e.length-1;c>=0;c--)(i=e[c])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a}s(ie,"_ts_decorate");function Ft(e,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(e,t)}s(Ft,"_ts_metadata");var m=class{static{s(this,"EventBus");}handlers=new Map;onError;constructor(){this.onError=ce;}setOptions(t){t.onError&&(this.onError=t.onError);}subscribe(t,r,o){let n=this.handlers.get(t)??[];n.push({instance:o?.instance??{},methodName:o?.methodName??"anonymous",handler:r}),this.handlers.set(t,n);}registerHandler(t,r,o){let n=r[o].bind(r);this.subscribe(t,n,{instance:r,methodName:o});}async emit(t){let r=this.handlers.get(t.type);if(!r||r.length===0)return;let o=await Promise.allSettled(r.map(n=>n.handler(t)));for(let n=0;n<o.length;n++){let a=o[n];if(a.status==="rejected"){let i=r[n],c=`${i.instance.constructor?.name??"Unknown"}.${i.methodName}`;this.onError(a.reason,t.type,c);}}}emitAsync(t){this.emit(t).catch(()=>{});}hasHandlers(t){let r=this.handlers.get(t);return r!==void 0&&r.length>0}handlerCount(t){return this.handlers.get(t)?.length??0}clear(){this.handlers.clear();}};m=ie([M(),Ft("design:type",Function),Ft("design:paramtypes",[])],m);function ce(e,t,r){console.error(`[EventBus] Handler "${r}" failed for event "${t}":`,e);}s(ce,"defaultErrorHandler");var ut=Symbol("on-event");function Ht(e){return (t,r,o)=>{let n=Reflect.getOwnMetadata(ut,t.constructor)??[];n.push({eventType:e,methodName:String(r)}),Reflect.defineMetadata(ut,n,t.constructor);}}s(Ht,"OnEvent");function qt(e){return Reflect.getOwnMetadata(ut,e)??[]}s(qt,"getOnEventMetadata");function fe(e,t,r,o){var n=arguments.length,a=n<3?t:o===null?o=Object.getOwnPropertyDescriptor(t,r):o,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(e,t,r,o);else for(var c=e.length-1;c>=0;c--)(i=e[c])&&(a=(n<3?i(a):n>3?i(t,r,a):i(t,r))||a);return n>3&&a&&Object.defineProperty(t,r,a),a}s(fe,"_ts_decorate");function Lt(e,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(e,t)}s(Lt,"_ts_metadata");var S=class{static{s(this,"SagaOrchestrator");}onCompensationError;constructor(){this.onCompensationError=ue;}setOptions(t){t.onCompensationError&&(this.onCompensationError=t.onCompensationError);}async execute(t,r){let o=[],n={};for(let i of t){if(r?.aborted)return this.buildFailure(new x,i.name,o,n);try{let c=await i.execute(r);o.push({step:i,result:c}),n[i.name]=c;}catch(c){return this.buildFailure(c,i.name,o,n)}}let a=o.length>0?o[o.length-1].result:void 0;return {success:true,results:n,value:a,compensated:[],compensationErrors:{}}}async buildFailure(t,r,o,n){let a=[],i={};for(let c=o.length-1;c>=0;c--){let{step:u,result:f}=o[c];if(u.compensate)try{await u.compensate(f),a.push(u.name);}catch(l){i[u.name]=l,this.onCompensationError(u.name,l);}}return {success:false,results:n,error:t,failedStep:r,compensated:a,compensationErrors:i}}};S=fe([M(),Lt("design:type",Function),Lt("design:paramtypes",[])],S);function ue(e,t){console.error(`[Saga] Compensation failed for step "${e}":`,t);}s(ue,"defaultCompensationErrorHandler");var J=class{static{s(this,"ControllerRouter");}routes=[];globalPrefix;constructor(t=""){this.globalPrefix=t;}register(...t){for(let r of t){let o=v(r)??"",n=$(r);for(let a of n){let i=le(`${this.globalPrefix}/${o}/${a.path}`);he(i,r.name,a.methodName),this.checkDuplicate(i,a.method,r.name,a.methodName);let{pattern:c,paramNames:u}=de(i),f=G(r,a.methodName);this.routes.push({method:a.method,pattern:c,paramNames:u,controllerClass:r,methodName:a.methodName,guardClasses:f,rawPath:i});}}}checkDuplicate(t,r,o,n){let a=this.routes.find(i=>i.method===r&&i.rawPath===t);if(a)throw new Error(`Duplicate route: ${r} ${t}
|
|
2
|
-
Already registered by: ${
|
|
3
|
-
Conflicting with: ${
|
|
1
|
+
import {a,g,b as b$1,h as h$1,i,j as j$1,c,m,d,o,q as q$1}from'./chunk-M2ZPR3DR.js';export{k as AppError,p as ConflictError,o as ForbiddenError,e as Inject,d as Injectable,l as NotFoundError,f as Optional,q as RequestAbortedError,b as Scope,n as UnauthorizedError,m as ValidationError}from'./chunk-M2ZPR3DR.js';import'reflect-metadata';function Ce(o){return {forwardRef:o}}a(Ce,"forwardRef");function _(o){return typeof o=="object"&&"forwardRef"in o?o.forwardRef():o}a(_,"resolveForwardRef");var E=class o{static{a(this,"Container");}registrations=new Map;resolving=new Set;parent=null;children=[];register(...e){for(let t of e)this.registerOne(t);}registerOne(e){if(typeof e=="function"){let s=g(e)?.scope??b$1.SINGLETON;this.registrations.set(e,{provider:e,scope:s});return}let t=e.provide,r=b$1.SINGLETON;if("useClass"in e){let n=g(e.useClass);r=e.scope??n?.scope??b$1.SINGLETON;}else "useFactory"in e&&(r=e.scope??b$1.SINGLETON);this.registrations.set(t,{provider:e,scope:r});}async resolve(e){let t=_(e),r=t!==e?t:e,n=this.registrations.get(r)??this.parent?.findRegistration(r);if(!n)throw new Error(`No provider found for ${X(r)}`);if(n.scope===b$1.SINGLETON&&n.instance!==void 0||n.scope===b$1.REQUEST&&this.parent!==null&&n.instance!==void 0)return n.instance;if(this.resolving.has(r))throw new Error(`Circular dependency detected for ${X(r)}`);this.resolving.add(r);try{let s=await this.createInstance(n);return (n.scope===b$1.SINGLETON||n.scope===b$1.REQUEST&&this.parent!==null)&&(n.instance=s),s}finally{this.resolving.delete(r);}}has(e){return this.registrations.has(e)||(this.parent?.has(e)??false)}findRegistration(e){return this.registrations.get(e)??this.parent?.findRegistration(e)}createChild(){let e=new o;e.parent=this;for(let[t,r]of this.registrations)r.scope===b$1.REQUEST&&e.registrations.set(t,{provider:r.provider,scope:b$1.REQUEST,instance:void 0});return this.children.push(e),e}async dispose(){for(let e of this.children)await e.dispose();this.children=[];for(let[,e]of this.registrations)if(e.instance&&typeof e.instance=="object"&&e.instance!==null){let t=e.instance;typeof t.onModuleDestroy=="function"&&await t.onModuleDestroy();}this.registrations.clear(),this.resolving.clear();}async createInstance(e){let{provider:t}=e;if(typeof t=="function")return this.instantiateClass(t);if("useValue"in t)return t.useValue;if("useClass"in t)return this.instantiateClass(t.useClass);if("useFactory"in t){let r=t,n=[];if(r.inject)for(let s of r.inject)n.push(await this.resolve(s));return r.useFactory(...n)}if("useExisting"in t)return this.resolve(t.useExisting);throw new Error("Unknown provider type")}async instantiateClass(e){let t=Reflect.getMetadata("design:paramtypes",e)??[],r=h$1(e),n=i(e),s=j$1(e),a=n.size>0?Math.max(...n.keys())+1:0,c=Math.max(t.length,a,r.length),f=[];for(let d=0;d<c;d++){let u=n.get(d)??r[d]??t[d],l=s.has(d);try{f.push(await this.resolve(u));}catch{if(l)f.push(void 0);else throw new Error(`Cannot resolve parameter at index ${d} (${X(u)}) of ${e.name}`)}}return new e(...f)}};function X(o){return typeof o=="string"?o:typeof o=="symbol"||o instanceof c?o.toString():typeof o=="function"?o.name:String(o)}a(X,"tokenToString");var Se=Symbol("module"),Ie=Symbol("module:global");function Ne(o){return e=>{Reflect.defineMetadata(Se,o,e);}}a(Ne,"Module");function De(){return o=>{Reflect.defineMetadata(Ie,true,o);}}a(De,"Global");function k(o){return Reflect.getOwnMetadata(Se,o)}a(k,"getModuleMetadata");function T(o){return Reflect.getOwnMetadata(Ie,o)===true}a(T,"isGlobalModule");var Oe=Symbol("controller:path"),ee=Symbol("controller:guards"),te=Symbol("route:metadata"),re=Symbol("method:route"),C=Symbol("method:guards"),oe=Symbol("method:noguard");function Fe(o){return e=>{Reflect.defineMetadata(Oe,o,e);}}a(Fe,"Controller");function S(o){return (e="")=>(t,r,n)=>{let s=n!==void 0,a=String(s?r:r?.name??r),c=s?n?.value:t;if(typeof c=="function"&&(c[re]={method:o,path:e,methodName:a}),s){let f=Reflect.getOwnMetadata(te,t.constructor)??[];return f.push({method:o,path:e,methodName:a}),Reflect.defineMetadata(te,f,t.constructor),n}return t}}a(S,"createMethodDecorator");var _e=S("GET"),ke=S("POST"),Ge=S("PUT"),Ue=S("DELETE"),$e=S("PATCH");function Be(...o){return (e,t,r)=>{if(t==null){Reflect.defineMetadata(ee,o,e);return}if(r!==void 0){if(r?.value){let n=r.value[C]??[];r.value[C]=[...n,...o];}return r}if(typeof e=="function"){let n=e[C]??[];e[C]=[...n,...o];}return typeof e=="function"&&t?.kind==="class"&&Reflect.defineMetadata(ee,o,e),e}}a(Be,"RouteGuards");function je(){return (o,e,t)=>t!==void 0?(t?.value&&(t.value[oe]=true),t):(typeof o=="function"&&(o[oe]=true),o)}a(je,"NoGuard");function x(o){return Reflect.getOwnMetadata(Oe,o)}a(x,"getControllerPath");function ne(o){return Reflect.getOwnMetadata(ee,o)??[]}a(ne,"getControllerGuards");function G(o){let e=[],t=o.prototype;if(t){let r=Object.getOwnPropertyNames(t);for(let n of r){if(n==="constructor")continue;let s=t[n];typeof s=="function"&&s[re]&&e.push(s[re]);}}return e.length>0?e:Reflect.getOwnMetadata(te,o)??[]}a(G,"getRouteMetadata");function U(o,e){let r=o.prototype?.[e],n=typeof r=="function"&&r[oe]===true,s=typeof r=="function"&&r[C]||[];return n?s:[...ne(o),...s]}a(U,"getMethodGuards");var b=class{static{a(this,"ModuleRegistry");}resolved=new Map;sortedModules=[];scan(e){this.resolveModule(e),this.sortedModules=this.topologicalSort(),this.validateExports();}registerAll(e){let t=new Set;for(let r of this.sortedModules)if(r.global)for(let n of r.providers)t.add(n);t.size>0&&e.register(...t);for(let r of this.sortedModules){e.register(...r.providers);for(let n of r.metadata.imports??[]){let s=this.getModuleType(n),a=this.resolved.get(s);if(a)for(let c of a.exports){let f=this.findProvider(a,c)??this.findReExportedProvider(a,c);f&&e.register(f);}}}}getAllProviders(){let e=[];for(let t of this.sortedModules)e.push(...t.providers);return e}getAllControllers(){let e=new Set,t=[];for(let r of this.sortedModules){for(let n of r.controllers)e.has(n)||(e.add(n),t.push(n));for(let n of r.metadata.providers??[])typeof n=="function"&&x(n)!==void 0&&!e.has(n)&&(e.add(n),t.push(n));}return t}async callLifecycleHooks(e,t,r){for(let n of this.sortedModules)for(let s of n.providers){let a=typeof s=="function"?s:s.provide;if(e.has(a))try{let c=await e.resolve(a);c&&typeof c=="object"&&typeof c[t]=="function"&&await c[t](r);}catch{}}}resolveModule(e){let t=typeof e=="object"&&"module"in e,r=t?e.module:e;if(this.resolved.has(r))return this.resolved.get(r);let n=k(r)??{},s=t?e:{},a=[...n.controllers??[],...s.controllers??[]],c={imports:[...n.imports??[],...s.imports??[]],controllers:a,providers:[...n.providers??[],...s.providers??[]],exports:[...n.exports??[],...s.exports??[]]},f={type:r,metadata:c,controllers:a,providers:[...a,...c.providers??[]],exports:new Set(c.exports??[]),global:t?e.global??T(r):T(r)};this.resolved.set(r,f);for(let d of c.imports??[])this.resolveModule(d);return f}getVisibleTokens(e){let t=new Set;for(let r of e.providers)t.add(this.getProviderToken(r));for(let r of e.metadata.imports??[]){let n=this.getModuleType(r),s=this.resolved.get(n);if(s)for(let a of s.exports)t.add(a);}for(let r of this.sortedModules)if(r.global)for(let n of r.providers)t.add(this.getProviderToken(n));return t}validateExports(){for(let e of this.sortedModules){let t=new Set(e.providers.map(n=>this.getProviderToken(n))),r=this.collectImportedExports(e);for(let n of e.exports)if(!t.has(n)&&!r.has(n)){let s=typeof n=="function"?n.name:String(n);throw new Error(`${e.type.name} exports ${s} but it is not in its providers and is not re-exported from an imported module`)}}}validateVisibility(){for(let e of this.sortedModules){let t=this.getVisibleTokens(e);for(let r of e.providers){if(typeof r!="function")continue;let n=h$1(r);for(let s of n)if(!t.has(s)){let a=typeof s=="function"?s.name:String(s);throw new Error(`${e.type.name}: ${r.name} depends on ${a}, but it is not provided in this module and not exported by any imported module`)}}}}getProviderToken(e){return typeof e=="function"?e:e.provide}collectImportedExports(e){let t=new Set;for(let r of e.metadata.imports??[]){let n=this.getModuleType(r),s=this.resolved.get(n);if(s)for(let a of s.exports)t.add(a);}return t}findProvider(e,t){return e.providers.find(r=>typeof r=="function"?r===t:r.provide===t)}findReExportedProvider(e,t){for(let r of e.metadata.imports??[]){let n=this.getModuleType(r),s=this.resolved.get(n);if(!s||!s.exports.has(t))continue;let a=this.findProvider(s,t);if(a)return a;let c=this.findReExportedProvider(s,t);if(c)return c}}getModuleType(e){return typeof e=="object"&&"module"in e?e.module:e}topologicalSort(){let e=new Set,t=new Set,r=[],n=a(s=>{if(e.has(s))return;if(t.has(s))throw new Error(`Circular module dependency detected: ${s.name}`);t.add(s);let a=this.resolved.get(s);if(a){for(let c of a.metadata.imports??[])n(this.getModuleType(c));t.delete(s),e.add(s),r.push(a);}},"visit");for(let[s]of this.resolved)n(s);return r}};function ht(o,e){if("useFactory"in e&&e.useFactory){let t=e.useFactory;return [{provide:o,useFactory:t,inject:e.inject??[]}]}if("useClass"in e&&e.useClass){let t=e.useClass;return [{provide:o,useFactory:a(async r=>r.createModuleOptions(),"useFactory"),inject:[t]},t]}if("useExisting"in e&&e.useExisting){let t=e.useExisting;return [{provide:o,useFactory:a(async r=>r.createModuleOptions(),"useFactory"),inject:[t]}]}throw new Error("ModuleAsyncOptions must specify one of: useFactory, useClass, or useExisting")}a(ht,"createAsyncProviders");var $=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 c(this.description),t=new c(this.featureDescription),r=this.onForRoot,n=this.onForFeature;return {ConfigurableModuleClass:class{static{a(this,"ConfigurableModuleClassImpl");}static forRoot(c,f={}){let d={module:this,global:f.global??false,providers:[{provide:e,useValue:c}],exports:[e]};return r&&(d=r(d,c)),d}static forRootAsync(c){let f=ht(e,c);return {module:this,imports:c.imports??[],providers:f,exports:[e]}}static forFeature(c,f={}){let d={module:this,global:f.global??false,providers:[{provide:t,useValue:c}],exports:[t]};return n&&(d=n(d,c)),d}},MODULE_OPTIONS_TOKEN:e,MODULE_FEATURE_TOKEN:t}}};var B=class{static{a(this,"BaseExecutionContext");}nativeRequest;handler;container;query;params;body;rawBody;formData;auth;data=new Map;metadata=new Map;abortController;constructor(e,t,r,n={},s={},a){this.nativeRequest=e,this.handler=t,this.container=r,this.query=n,this.params=s,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,t){this.metadata.set(e,t);}getData(e){return this.data.get(e)}setData(e,t){this.data.set(e,t);}getContainer(){return this.container}getSignal(){return this.abortController.signal}abort(e){this.abortController.abort(e);}};var Le=Symbol("filters"),He=Symbol("catch");function qe(...o){return (e,t,r)=>{let n=t?e.constructor:e,s=Reflect.getOwnMetadata(Le,n)??[];Reflect.defineMetadata(Le,[...s,...o],n);}}a(qe,"UseFilters");function Ve(...o){return e=>{Reflect.defineMetadata(He,o,e);}}a(Ve,"Catch");function se(o){return Reflect.getOwnMetadata(He,o)??[]}a(se,"getCatchMetadata");function j(o$1,e,t){return async r=>{let n=[...e.middlewares??[],...t.middlewares??[]],s=[...e.guards??[],...t.guards??[]],a$1=[...e.interceptors??[],...t.interceptors??[]],c=[...e.pipes??[],...t.pipes??[]],f=[...e.filters??[],...t.filters??[]],d=await I(o$1,f);try{w(r);let u=await I(o$1,n);return await mt(r,u,async()=>{w(r);let l=await I(o$1,s);for(let R of l)if(w(r),!await R.canActivate(r))throw new o("Access denied by guard");w(r);let M=await I(o$1,c);for(let R of M)w(r),await R.transform(r);w(r);let g=await I(o$1,a$1),we=a(async()=>(w(r),t.handler(r)),"handlerCall");return g.length===0?we():g.reduceRight((R,Me)=>async()=>(w(r),Me.intercept(r,R)),we)()})}catch(u){return gt(u,r,d)}}}a(j,"createPipeline");async function mt(o,e,t){return e.length===0?t():e.reduceRight((n,s)=>()=>s.use(o,n),t)()}a(mt,"runMiddlewareChain");function w(o){if(o.getSignal().aborted)throw new q$1}a(w,"checkAborted");async function gt(o,e,t){for(let r of t){let n=se(r.constructor);if(n.length===0||o instanceof Error&&n.some(a=>o instanceof a))return r.catch(o,e)}throw o}a(gt,"handleError");async function I(o,e){let t=[];for(let r of e)typeof r=="function"?t.push(await o.resolve(r)):t.push(r);return t}a(I,"resolveRefs");var ie=Symbol("interceptors"),ae=Symbol("method:interceptors");function ze(...o){return (e,t,r)=>{if(t!==void 0){let s=r?.value??e,a=s[ae]??[];return s[ae]=[...a,...o],r}let n=Reflect.getOwnMetadata(ie,e)??[];Reflect.defineMetadata(ie,[...n,...o],e);}}a(ze,"UseInterceptors");function ce(o){return Reflect.getOwnMetadata(ie,o)??[]}a(ce,"getInterceptorsMetadata");function de(o,e){let r=o.prototype?.[e];return typeof r=="function"&&r[ae]||[]}a(de,"getMethodInterceptors");function L(o,e){return [...ce(o),...de(o,e)]}a(L,"getEffectiveInterceptors");var fe="uow:session",ue="uow:instance",H=class{static{a(this,"UnitOfWorkInterceptor");}factory;constructor(e){this.factory=e;}async intercept(e,t){let r=this.factory();await r.start(),e.setData(fe,r.getContext()),e.setData(ue,r);try{let n=await t();return await r.commit(),n}catch(n){throw await r.rollback(),n}}};var le=Symbol("middlewares"),pe=Symbol("method:middlewares");function We(...o){return (e,t,r)=>{if(t!==void 0){let s=r?.value??e,a=s[pe]??[];return s[pe]=[...a,...o],r}let n=Reflect.getOwnMetadata(le,e)??[];Reflect.defineMetadata(le,[...n,...o],e);}}a(We,"UseMiddleware");function he(o){return Reflect.getOwnMetadata(le,o)??[]}a(he,"getMiddlewaresMetadata");function me(o,e){let r=o.prototype?.[e];return typeof r=="function"&&r[pe]||[]}a(me,"getMethodMiddlewares");function q(o,e){return [...he(o),...me(o,e)]}a(q,"getEffectiveMiddlewares");var Qe=Symbol("pipes");function Ye(...o){return (e,t,r)=>{let n=t?e.constructor:e,s=Reflect.getOwnMetadata(Qe,n)??[];Reflect.defineMetadata(Qe,[...s,...o],n);}}a(Ye,"UsePipes");var V=class{static{a(this,"ZodValidationPipe");}schema;constructor(e){this.schema=e;}transform(e){let t=e.getBody(),r=this.schema.safeParse(t);if(!r.success){let n={};for(let s of r.error.issues){let a=s.path.join(".")||"_root";n[a]||(n[a]=[]),n[a].push(s.message);}throw new m("Validation failed",n)}e.setBody(r.data);}};var yt=/^[0-9a-fA-F]{24}$/,z=class{static{a(this,"ParseIdPipe");}paramName;constructor(e="id"){this.paramName=e;}transform(e){let r=e.getParams()[this.paramName];if(!r||!yt.test(r))throw new m(`Invalid ${this.paramName}: must be a valid ObjectId`)}};var W=class{static{a(this,"ParseIntPipe");}transform(e){let t=Number(e);if(!Number.isInteger(t)||e===""||e===null||e===void 0)throw new m(`Expected an integer, received: ${JSON.stringify(e)}`);return t}};var Q=class{static{a(this,"ZodParamPipe");}schema;constructor(e){this.schema=e;}transform(e){let t=this.schema.safeParse(e);if(!t.success){let r=t.error.errors.map(n=>`${n.path.join(".")}: ${n.message}`).join(", ");throw new m(r)}return t.data}};function Ze(o){return {transform(e){return e??o}}}a(Ze,"DefaultValuePipe");var Y=class{static{a(this,"DomainEvent");}payload;timestamp;constructor(e){this.payload=e,this.timestamp=Date.now();}};function wt(o,e,t,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,e,t,r);else for(var c=o.length-1;c>=0;c--)(a=o[c])&&(s=(n<3?a(s):n>3?a(e,t,s):a(e,t))||s);return n>3&&s&&Object.defineProperty(e,t,s),s}a(wt,"_ts_decorate");function Je(o,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,e)}a(Je,"_ts_metadata");var h=class{static{a(this,"EventBus");}handlers=new Map;onError;constructor(){this.onError=Mt;}setOptions(e){e.onError&&(this.onError=e.onError);}subscribe(e,t,r){let n=this.handlers.get(e)??[];n.push({instance:r?.instance??{},methodName:r?.methodName??"anonymous",handler:t}),this.handlers.set(e,n);}registerHandler(e,t,r){let n=t[r].bind(t);this.subscribe(e,n,{instance:t,methodName:r});}async emit(e){let t=this.handlers.get(e.type);if(!t||t.length===0)return;let r=await Promise.allSettled(t.map(n=>n.handler(e)));for(let n=0;n<r.length;n++){let s=r[n];if(s.status==="rejected"){let a=t[n],c=`${a.instance.constructor?.name??"Unknown"}.${a.methodName}`;this.onError(s.reason,e.type,c);}}}emitAsync(e){this.emit(e).catch(()=>{});}hasHandlers(e){let t=this.handlers.get(e);return t!==void 0&&t.length>0}handlerCount(e){return this.handlers.get(e)?.length??0}clear(){this.handlers.clear();}};h=wt([d(),Je("design:type",Function),Je("design:paramtypes",[])],h);function Mt(o,e,t){console.error(`[EventBus] Handler "${t}" failed for event "${e}":`,o);}a(Mt,"defaultErrorHandler");var ge=Symbol("on-event");function Ke(o){return (e,t,r)=>{let n=Reflect.getOwnMetadata(ge,e.constructor)??[];n.push({eventType:o,methodName:String(t)}),Reflect.defineMetadata(ge,n,e.constructor);}}a(Ke,"OnEvent");function Xe(o){return Reflect.getOwnMetadata(ge,o)??[]}a(Xe,"getOnEventMetadata");var Z=class{static{a(this,"ControllerRouter");}routes=[];globalPrefix;constructor(e=""){this.globalPrefix=e;}register(...e){for(let t of e){let r=x(t)??"",n=G(t);for(let s of n){let a=vt(`${this.globalPrefix}/${r}/${s.path}`);bt(a,t.name,s.methodName),this.checkDuplicate(a,s.method,t.name,s.methodName);let{pattern:c,paramNames:f}=Et(a),d=U(t,s.methodName),u=L(t,s.methodName),l=q(t,s.methodName);this.routes.push({method:s.method,pattern:c,paramNames:f,controllerClass:t,methodName:s.methodName,guardClasses:d,interceptorRefs:u,middlewareRefs:l,rawPath:a});}}}checkDuplicate(e,t,r,n){let s=this.routes.find(a=>a.method===t&&a.rawPath===e);if(s)throw new Error(`Duplicate route: ${t} ${e}
|
|
2
|
+
Already registered by: ${s.controllerClass.name}.${s.methodName}
|
|
3
|
+
Conflicting with: ${r}.${n}`)}match(e,t){let r=e.toUpperCase();for(let n of this.routes){if(n.method!==r)continue;let s=n.pattern.exec(t);if(!s)continue;let a={};for(let c=0;c<n.paramNames.length;c++)a[n.paramNames[c]]=s[c+1]??"";return {route:n,params:a}}return null}getRoutes(){return this.routes}};function vt(o){return "/"+o.replace(/\/+/g,"/").replace(/^\/|\/$/g,"")}a(vt,"normalizePath");function Et(o){let e=[],t=o.split("/").map(r=>r.startsWith(":")?(e.push(r.slice(1)),"([^/]+)"):xt(r)).join("/");return {pattern:new RegExp(`^${t}$`),paramNames:e}}a(Et,"compilePath");function xt(o){return o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}a(xt,"escapeRegex");function bt(o,e,t){let r=`Invalid path "${o}" on ${e}.${t}:`;if(!o.startsWith("/"))throw new Error(`${r} must start with /`);let n=o.split("/").filter((a,c)=>c>0),s=new Set;for(let a of n){if(a==="")throw new Error(`${r} 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(`${r} invalid param name ":${c}" \u2014 must be a valid identifier`);if(s.has(c))throw new Error(`${r} duplicate param name ":${c}"`);s.add(c);}}}a(bt,"validatePath");var v=Symbol("route:params");function Rt(o){return o==null?false:typeof o=="function"||typeof o=="object"&&typeof o.transform=="function"}a(Rt,"isParamPipeRef");function J(o,e){return Rt(o)?{key:void 0,pipes:[o,...e??[]]}:{key:o,pipes:e??[]}}a(J,"resolveArgs");function y(o,e,t=[]){return (r,n,s)=>{if(n===void 0)return;let a=r[n];if(typeof a!="function")return;let c=a[v]??[];a[v]=[...c,{index:s,type:o,key:e,pipes:t.length>0?t:void 0}];}}a(y,"buildBuiltinDecorator");function Pt(o){return typeof o=="function"?new o:o}a(Pt,"resolveParamPipe");function et(o,...e){let{key:t,pipes:r}=J(o,e);return y("query",t,r)}a(et,"Query");function tt(o,...e){let{key:t,pipes:r}=J(o,e);return y("param",t,r)}a(tt,"Param");function rt(o,...e){let{key:t,pipes:r}=J(o,e);return y("body",t,r)}a(rt,"Body");var ot=a(()=>y("rawBody"),"RawBody"),nt=a(()=>y("formData"),"FormData"),st=a(()=>y("ip"),"Ip"),it=a(()=>y("userAgent"),"UserAgent"),at=a(o=>y("cookie",o),"Cookie");function ct(o,...e){let{key:t,pipes:r}=J(o,e);return y("headers",t,r)}a(ct,"Headers");function ye(o){return ()=>(e,t,r)=>{if(t===void 0)return;let n=e[t];if(typeof n!="function")return;let s=n[v]??[];n[v]=[...s,{index:r,type:"auth",extractor:o}];}}a(ye,"defineAuth");var dt=ye();function ft(o){return ()=>(e,t,r)=>{if(t===void 0)return;let n=e[t];if(typeof n!="function")return;let s=n[v]??[];n[v]=[...s,{index:r,type:"custom",extractor:o}];}}a(ft,"createParamDecorator");function ut(o,e){let t=o.prototype[e];if(typeof t!="function")return null;let r=t[v];return r&&r.length>0?r:null}a(ut,"getRouteParams");async function lt(o,e){let t=Math.max(...o.map(n=>n.index)),r=new Array(t+1).fill(void 0);for(let{index:n,type:s,key:a,pipes:c,extractor:f}of o){let d;switch(s){case "query":{let u=e.getQuery();d=a!==void 0?u[a]:u;break}case "param":{let u=e.getParams();d=a!==void 0?u[a]:u;break}case "body":{let u=e.getBody()??{};d=a!==void 0?u[a]:u;break}case "rawBody":{d=e.getRawBody();break}case "formData":{d=e.getFormData();break}case "headers":{let u=e.getNativeRequest(),l=u?.node?.req?.headers??u?.headers??{};d=a!==void 0?l[a.toLowerCase()]:l;break}case "cookie":{let u=e.getNativeRequest(),l=u?.node?.req?.headers?.cookie??u?.headers?.cookie??"";if(a&&l){let M=l.split(";").map(g=>g.trim()).find(g=>g.startsWith(a+"="));d=M?decodeURIComponent(M.slice(a.length+1)):void 0;}else d=void 0;break}case "ip":{let u=e.getNativeRequest(),l=u?.node?.req?.headers??{},M=l["cf-connecting-ip"];if(M){d=M.trim();break}let g=l["x-forwarded-for"];if(g){d=(String(g).split(",")[0]??"").trim();break}d=u?.node?.req?.socket?.remoteAddress??"";break}case "userAgent":{d=(e.getNativeRequest()?.node?.req?.headers??{})["user-agent"]??"";break}case "auth":{d=f?await f(e):e.getAuth();break}case "custom":{d=f?await f(e):void 0;break}}if(c&&c.length>0)for(let u of c)d=Pt(u).transform(d);r[n]=d;}return r}a(lt,"resolveParamArgs");async function pt(o,e){let t=await o.resolve(h);for(let r of e){let n=At(r);if(!n)continue;let s=Xe(n);if(s.length===0)continue;let a=typeof r=="function"?r:r.provide,c;try{c=await o.resolve(a);}catch{continue}for(let f of s)typeof c[f.methodName]=="function"&&t.registerHandler(f.eventType,c,f.methodName);}}a(pt,"scanEventHandlers");function At(o){return typeof o=="function"?g(o)?o:null:"useClass"in o?o.useClass:null}a(At,"getProviderClass");var K=class{static{a(this,"BackendApplication");}container;registry;initialized=false;options;eventBus;prefix="";constructor(e){this.options=e,this.container=new E,this.registry=new b;}async init(){if(this.initialized)return;this.eventBus=new h,this.options.eventBus&&this.eventBus.setOptions(this.options.eventBus),this.container.register({provide:h,useValue:this.eventBus}),this.registry.scan(this.options.rootModule),this.registry.registerAll(this.container),await this.registry.callLifecycleHooks(this.container,"onModuleInit");let e=this.registry.getAllProviders();await pt(this.container,e),await this.registry.callLifecycleHooks(this.container,"onApplicationBootstrap"),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}getControllers(){return this.ensureInitialized(),this.registry.getAllControllers()}getEventBus(){return this.ensureInitialized(),this.eventBus}createHandler(e){return this.ensureInitialized(),j(this.container,this.getGlobalOptions(),e)}async shutdown(){this.initialized&&(await this.registry.callLifecycleHooks(this.container,"onModuleDestroy"),await this.registry.callLifecycleHooks(this.container,"onApplicationShutdown"),this.eventBus.clear(),await this.container.dispose(),this.initialized=false);}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("BackendApplication not initialized. Call init() first.")}};export{dt as Auth,K as BackendApplication,B as BaseExecutionContext,rt as Body,Ve as Catch,$ as ConfigurableModuleBuilder,E as Container,Fe as Controller,Z as ControllerRouter,at as Cookie,Ze as DefaultValuePipe,Ue as Delete,Y as DomainEvent,h as EventBus,nt as FormData,_e as Get,De as Global,ct as Headers,st as Ip,Ne as Module,b as ModuleRegistry,je as NoGuard,Ke as OnEvent,tt as Param,z as ParseIdPipe,W as ParseIntPipe,$e as Patch,ke as Post,Ge as Put,et as Query,ot as RawBody,Be as RouteGuards,ue as UOW_INSTANCE_KEY,fe as UOW_SESSION_KEY,H as UnitOfWorkInterceptor,qe as UseFilters,ze as UseInterceptors,We as UseMiddleware,Ye as UsePipes,it as UserAgent,Q as ZodParamPipe,V as ZodValidationPipe,ft as createParamDecorator,j as createPipeline,ye as defineAuth,Ce as forwardRef,ne as getControllerGuards,x as getControllerPath,L as getEffectiveInterceptors,q as getEffectiveMiddlewares,ce as getInterceptorsMetadata,U as getMethodGuards,de as getMethodInterceptors,me as getMethodMiddlewares,he as getMiddlewaresMetadata,k as getModuleMetadata,G as getRouteMetadata,ut as getRouteParams,T as isGlobalModule,_ as resolveForwardRef,lt as resolveParamArgs};
|
package/dist/saga.d.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A single step in a saga.
|
|
3
|
+
*
|
|
4
|
+
* @template T - The return type of the execute function
|
|
5
|
+
*/
|
|
6
|
+
interface SagaStep<T = unknown> {
|
|
7
|
+
/** Human-readable name for logging/debugging. */
|
|
8
|
+
name: string;
|
|
9
|
+
/** The forward action. Returns a result that is passed to compensate on failure. */
|
|
10
|
+
execute: (signal?: AbortSignal) => T | Promise<T>;
|
|
11
|
+
/**
|
|
12
|
+
* The compensating action. Called with the result of execute() if a LATER step fails.
|
|
13
|
+
* Should undo the effect of execute().
|
|
14
|
+
* If not provided, the step is considered non-compensatable (e.g., the last step).
|
|
15
|
+
*/
|
|
16
|
+
compensate?: (result: T) => void | Promise<void>;
|
|
17
|
+
}
|
|
18
|
+
interface SagaResult<T = unknown> {
|
|
19
|
+
/** Whether all steps completed successfully. */
|
|
20
|
+
success: boolean;
|
|
21
|
+
/** Results of each completed step, keyed by step name. */
|
|
22
|
+
results: Record<string, unknown>;
|
|
23
|
+
/** The result of the last step (convenience). */
|
|
24
|
+
value?: T;
|
|
25
|
+
/** If failed, the error that caused the failure. */
|
|
26
|
+
error?: unknown;
|
|
27
|
+
/** Name of the step that failed. */
|
|
28
|
+
failedStep?: string;
|
|
29
|
+
/** Names of steps that were successfully compensated. */
|
|
30
|
+
compensated: string[];
|
|
31
|
+
/** Compensation errors, if any. Keyed by step name. */
|
|
32
|
+
compensationErrors: Record<string, unknown>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
interface SagaExecuteOptions {
|
|
36
|
+
/** AbortSignal that cancels pending steps and triggers compensation. */
|
|
37
|
+
signal?: AbortSignal;
|
|
38
|
+
/** Called when a compensation step throws. Defaults to a no-op. */
|
|
39
|
+
onCompensationError?: (stepName: string, error: unknown) => void;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Executes a sequence of steps with automatic compensation on failure.
|
|
43
|
+
*
|
|
44
|
+
* If step N fails, steps N-1..0 are compensated in reverse order.
|
|
45
|
+
* Compensation errors are captured but do NOT prevent other compensations.
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```typescript
|
|
49
|
+
* @UseCase()
|
|
50
|
+
* class CreateOrderUseCase {
|
|
51
|
+
* constructor(private saga: SagaOrchestrator) {}
|
|
52
|
+
*
|
|
53
|
+
* async execute(input: CreateOrderInput) {
|
|
54
|
+
* const result = await this.saga.execute([
|
|
55
|
+
* {
|
|
56
|
+
* name: 'reserve-inventory',
|
|
57
|
+
* execute: () => inventoryService.reserve(input.items),
|
|
58
|
+
* compensate: (res) => inventoryService.release(res.reservationId),
|
|
59
|
+
* },
|
|
60
|
+
* {
|
|
61
|
+
* name: 'charge-payment',
|
|
62
|
+
* execute: () => paymentService.charge(input.amount),
|
|
63
|
+
* compensate: (res) => paymentService.refund(res.chargeId),
|
|
64
|
+
* },
|
|
65
|
+
* {
|
|
66
|
+
* name: 'create-order',
|
|
67
|
+
* execute: () => orderService.create(input),
|
|
68
|
+
* },
|
|
69
|
+
* ])
|
|
70
|
+
*
|
|
71
|
+
* if (!result.success) throw result.error
|
|
72
|
+
* return result.value
|
|
73
|
+
* }
|
|
74
|
+
* }
|
|
75
|
+
* ```
|
|
76
|
+
*/
|
|
77
|
+
declare class SagaOrchestrator {
|
|
78
|
+
execute<T = unknown>(steps: SagaStep[], options?: SagaExecuteOptions): Promise<SagaResult<T>>;
|
|
79
|
+
private buildFailure;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export { type SagaExecuteOptions, SagaOrchestrator, type SagaResult, type SagaStep };
|
package/dist/saga.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {a,q,d as d$1}from'./chunk-M2ZPR3DR.js';function d(i,n,r,o){var c=arguments.length,e=c<3?n:o===null?o=Object.getOwnPropertyDescriptor(n,r):o,t;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")e=Reflect.decorate(i,n,r,o);else for(var u=i.length-1;u>=0;u--)(t=i[u])&&(e=(c<3?t(e):c>3?t(n,r,e):t(n,r))||e);return c>3&&e&&Object.defineProperty(n,r,e),e}a(d,"_ts_decorate");var l=class{static{a(this,"SagaOrchestrator");}async execute(n,r){let o=r?.signal,c=r?.onCompensationError??(()=>{}),e=[],t={};for(let a of n){if(o?.aborted)return this.buildFailure(new q,a.name,e,t,c);try{let s=await a.execute(o);e.push({step:a,result:s}),t[a.name]=s;}catch(s){return this.buildFailure(s,a.name,e,t,c)}}let u=e.length>0?e[e.length-1].result:void 0;return {success:true,results:t,value:u,compensated:[],compensationErrors:{}}}async buildFailure(n,r,o,c,e){let t=[],u={};for(let a=o.length-1;a>=0;a--){let{step:s,result:b}=o[a];if(s.compensate)try{await s.compensate(b),t.push(s.name);}catch(m){u[s.name]=m,e(s.name,m);}}return {success:false,results:c,error:n,failedStep:r,compensated:t,compensationErrors:u}}};l=d([d$1()],l);export{l as SagaOrchestrator};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "truxie",
|
|
3
|
-
"version": "0.1.0-test.
|
|
3
|
+
"version": "0.1.0-test.3",
|
|
4
4
|
"description": "NestJS-like structural backend library with DI, modules, guards, interceptors, pipes, and exception filters",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -11,6 +11,11 @@
|
|
|
11
11
|
"types": "./dist/index.d.ts",
|
|
12
12
|
"import": "./dist/index.js",
|
|
13
13
|
"default": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./saga": {
|
|
16
|
+
"types": "./dist/saga.d.ts",
|
|
17
|
+
"import": "./dist/saga.js",
|
|
18
|
+
"default": "./dist/saga.js"
|
|
14
19
|
}
|
|
15
20
|
},
|
|
16
21
|
"files": [
|
|
@@ -39,6 +44,7 @@
|
|
|
39
44
|
"@types/node": "^22.10.5",
|
|
40
45
|
"tsup": "^8.0.0",
|
|
41
46
|
"typescript": "^5.0.0",
|
|
47
|
+
"vitest": "^4.0.18",
|
|
42
48
|
"zod": "^3.22.0"
|
|
43
49
|
},
|
|
44
50
|
"keywords": [
|