@wabot-dev/framework 0.1.0-beta.23 → 0.1.0-beta.25

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.
@@ -0,0 +1,11 @@
1
+ import { CommandMetadataStore } from './CommandMetadataStore.js';
2
+ import { container } from '../injection/index.js';
3
+
4
+ function command(config) {
5
+ return function (target) {
6
+ const handlerContainer = container.resolve(CommandMetadataStore);
7
+ handlerContainer.registerCommand(target, config?.name ?? target.name);
8
+ };
9
+ }
10
+
11
+ export { command };
@@ -0,0 +1,12 @@
1
+ import { CommandMetadataStore } from './CommandMetadataStore.js';
2
+ import { container, injectable } from '../injection/index.js';
3
+
4
+ function commandHandler(config) {
5
+ return function (target) {
6
+ const handlerContainer = container.resolve(CommandMetadataStore);
7
+ handlerContainer.registerHandler(config.command, target);
8
+ injectable()(target);
9
+ };
10
+ }
11
+
12
+ export { commandHandler };
@@ -0,0 +1,38 @@
1
+ import { __decorate, __metadata } from 'tslib';
2
+ import { singleton } from '../injection/index.js';
3
+ import { CommandMetadataStore } from './CommandMetadataStore.js';
4
+ import { Job } from './Job.js';
5
+ import { JobRepository } from './JobRepository.js';
6
+ import { JobsEventsHub } from './JobsEventsHub.js';
7
+
8
+ let Async = class Async {
9
+ jobRepository;
10
+ handlerContainer;
11
+ jobsEventsHub;
12
+ constructor(jobRepository, handlerContainer, jobsEventsHub) {
13
+ this.jobRepository = jobRepository;
14
+ this.handlerContainer = handlerContainer;
15
+ this.jobsEventsHub = jobsEventsHub;
16
+ }
17
+ async run(command) {
18
+ const commandName = this.handlerContainer.getCommandName(command.constructor);
19
+ if (!commandName) {
20
+ throw new Error(`${command.constructor.name} is not registered as command`);
21
+ }
22
+ const job = new Job({
23
+ commandName,
24
+ commandData: command['data'],
25
+ });
26
+ await this.jobRepository.create(job);
27
+ this.jobsEventsHub.notifyJobCreated(job);
28
+ return job;
29
+ }
30
+ };
31
+ Async = __decorate([
32
+ singleton(),
33
+ __metadata("design:paramtypes", [JobRepository,
34
+ CommandMetadataStore,
35
+ JobsEventsHub])
36
+ ], Async);
37
+
38
+ export { Async };
@@ -0,0 +1,11 @@
1
+ import '../core/chat/repository/IChatRepository.js';
2
+ import { Storable } from '../core/Storable.js';
3
+ import '../core/user/IUserRepository.js';
4
+
5
+ class Command extends Storable {
6
+ getData() {
7
+ return this.data;
8
+ }
9
+ }
10
+
11
+ export { Command };
@@ -0,0 +1,38 @@
1
+ import { __decorate } from 'tslib';
2
+ import { singleton } from '../injection/index.js';
3
+
4
+ let CommandMetadataStore = class CommandMetadataStore {
5
+ handlersMap = new Map();
6
+ handlersInverseMap = new Map();
7
+ commandsMap = new Map();
8
+ commandsInverseMap = new Map();
9
+ registerCommand(command, commandName) {
10
+ this.commandsMap.set(commandName, command);
11
+ this.commandsInverseMap.set(command, commandName);
12
+ }
13
+ registerHandler(command, handlerConstructor) {
14
+ let commandName = this.commandsInverseMap.get(command);
15
+ if (!commandName) {
16
+ throw new Error(`Should use @command decorator on command class ${command.name}`);
17
+ }
18
+ this.handlersMap.set(commandName, handlerConstructor);
19
+ this.handlersInverseMap.set(handlerConstructor, commandName);
20
+ }
21
+ getHandlerForCommandName(commandName) {
22
+ return this.handlersMap.get(commandName) ?? null;
23
+ }
24
+ getCommandNameForHandler(handlerConstructor) {
25
+ return this.handlersInverseMap.get(handlerConstructor) ?? null;
26
+ }
27
+ getCommandName(command) {
28
+ return this.commandsInverseMap.get(command) ?? null;
29
+ }
30
+ getCommandForCommandName(commandName) {
31
+ return this.commandsMap.get(commandName) ?? null;
32
+ }
33
+ };
34
+ CommandMetadataStore = __decorate([
35
+ singleton()
36
+ ], CommandMetadataStore);
37
+
38
+ export { CommandMetadataStore };
@@ -0,0 +1,26 @@
1
+ import '../core/chat/repository/IChatRepository.js';
2
+ import { Entity } from '../core/Entity.js';
3
+ import '../core/user/IUserRepository.js';
4
+ import { CustomError } from '../error/CustomError.js';
5
+
6
+ class Job extends Entity {
7
+ get commandName() {
8
+ return this.data.commandName;
9
+ }
10
+ setAsStarted() {
11
+ this.data.startedAt = new Date().getTime();
12
+ }
13
+ setAsSuccess() {
14
+ this.data.successAt = new Date().getTime();
15
+ }
16
+ setAsFailed(error) {
17
+ this.data.failedAt = new Date().getTime();
18
+ this.data.error = {
19
+ message: error.message,
20
+ stack: error.stack,
21
+ info: error instanceof CustomError ? error.info : undefined,
22
+ };
23
+ }
24
+ }
25
+
26
+ export { Job };
@@ -0,0 +1,21 @@
1
+ import { __decorate, __metadata } from 'tslib';
2
+ import { Pool } from 'pg';
3
+ import { Job } from './Job.js';
4
+ import { singleton } from '../injection/index.js';
5
+ import { PgCrudRepository } from '../repository/pg/PgCrudRepository.js';
6
+
7
+ let JobRepository = class JobRepository extends PgCrudRepository {
8
+ constructor(pool) {
9
+ super(pool, {
10
+ schema: 'wabot',
11
+ table: 'job',
12
+ constructor: Job,
13
+ });
14
+ }
15
+ };
16
+ JobRepository = __decorate([
17
+ singleton(),
18
+ __metadata("design:paramtypes", [Pool])
19
+ ], JobRepository);
20
+
21
+ export { JobRepository };
@@ -0,0 +1,45 @@
1
+ import { __decorate, __metadata } from 'tslib';
2
+ import { CommandMetadataStore } from './CommandMetadataStore.js';
3
+ import { JobRepository } from './JobRepository.js';
4
+ import { singleton, container } from '../injection/index.js';
5
+
6
+ let JobRunner = class JobRunner {
7
+ jobRepository;
8
+ handlerContainer;
9
+ constructor(jobRepository, handlerContainer) {
10
+ this.jobRepository = jobRepository;
11
+ this.handlerContainer = handlerContainer;
12
+ }
13
+ async run(job) {
14
+ try {
15
+ const { commandName, commandData } = job['data'];
16
+ const handlerConstructor = this.handlerContainer.getHandlerForCommandName(commandName);
17
+ if (!handlerConstructor) {
18
+ throw new Error(`Not found handler for command '${commandName}'`);
19
+ }
20
+ const handler = container.resolve(handlerConstructor);
21
+ const commandConstructor = this.handlerContainer.getCommandForCommandName(commandName);
22
+ if (!commandConstructor) {
23
+ throw new Error(`Not found class for command name '${commandName}'`);
24
+ }
25
+ job.setAsStarted();
26
+ await this.jobRepository.update(job);
27
+ const command = new commandConstructor(commandData);
28
+ await handler.handle(command);
29
+ job.setAsSuccess();
30
+ }
31
+ catch (e) {
32
+ job.setAsFailed(e instanceof Error ? e : new Error('Invalid Job error'));
33
+ }
34
+ finally {
35
+ await this.jobRepository.update(job);
36
+ }
37
+ }
38
+ };
39
+ JobRunner = __decorate([
40
+ singleton(),
41
+ __metadata("design:paramtypes", [JobRepository,
42
+ CommandMetadataStore])
43
+ ], JobRunner);
44
+
45
+ export { JobRunner };
@@ -0,0 +1,24 @@
1
+ import { __decorate } from 'tslib';
2
+ import { singleton } from '../injection/index.js';
3
+
4
+ let JobsEventsHub = class JobsEventsHub {
5
+ jobsEventsListener = null;
6
+ notifyJobCreated(job) {
7
+ if (!this.jobsEventsListener) {
8
+ return;
9
+ }
10
+ this.jobsEventsListener({
11
+ jobId: job.id,
12
+ commandName: job.commandName,
13
+ type: 'created',
14
+ });
15
+ }
16
+ listenJobsEvents(listener) {
17
+ this.jobsEventsListener = listener;
18
+ }
19
+ };
20
+ JobsEventsHub = __decorate([
21
+ singleton()
22
+ ], JobsEventsHub);
23
+
24
+ export { JobsEventsHub };
@@ -0,0 +1,29 @@
1
+ import { JobsEventsHub } from './JobsEventsHub.js';
2
+ import { JobRunner } from './JobRunner.js';
3
+ import { CommandMetadataStore } from './CommandMetadataStore.js';
4
+ import { JobRepository } from './JobRepository.js';
5
+ import { container } from '../injection/index.js';
6
+
7
+ function runAsyncCommandHandlers(handlers) {
8
+ const eventsHub = container.resolve(JobsEventsHub);
9
+ const jobRunner = container.resolve(JobRunner);
10
+ const jobRepository = container.resolve(JobRepository);
11
+ const commandsHandlersContainer = container.resolve(CommandMetadataStore);
12
+ const handledCommands = handlers
13
+ .map((x) => commandsHandlersContainer.getCommandNameForHandler(x))
14
+ .filter((x) => x)
15
+ .map((x) => x);
16
+ eventsHub.listenJobsEvents(async (event) => {
17
+ try {
18
+ const job = await jobRepository.findOrThrow(event.jobId);
19
+ if (handledCommands.includes(job.commandName)) {
20
+ jobRunner.run(job);
21
+ }
22
+ }
23
+ catch (e) {
24
+ console.error(e);
25
+ }
26
+ });
27
+ }
28
+
29
+ export { runAsyncCommandHandlers };
@@ -0,0 +1,24 @@
1
+ import { __decorate } from 'tslib';
2
+ import { CustomError } from '../error/CustomError.js';
3
+ import { scoped, Lifecycle } from '../injection/index.js';
4
+
5
+ let Auth = class Auth {
6
+ authInfo = null;
7
+ require() {
8
+ if (!this.authInfo) {
9
+ throw new CustomError({ message: 'Unauthorized', httpCode: 401 });
10
+ }
11
+ return this.authInfo;
12
+ }
13
+ assign(authInfo) {
14
+ if (this.authInfo) {
15
+ throw new CustomError({ message: 'Authorization info already assigned', httpCode: 401 });
16
+ }
17
+ this.authInfo = authInfo;
18
+ }
19
+ };
20
+ Auth = __decorate([
21
+ scoped(Lifecycle.ContainerScoped)
22
+ ], Auth);
23
+
24
+ export { Auth };
@@ -1,14 +1,15 @@
1
1
  import InjectionToken from 'tsyringe/dist/typings/providers/injection-token';
2
2
  import DependencyContainer, { PreResolutionInterceptorCallback, PostResolutionInterceptorCallback } from 'tsyringe/dist/typings/types/dependency-container';
3
3
  import InterceptionOptions from 'tsyringe/dist/typings/types/interceptor-options';
4
+ import { Pool } from 'pg';
4
5
  import { Server } from 'http';
5
6
  import { Express, Request, Response } from 'express';
6
7
  import { Server as Server$1 } from 'socket.io';
7
- import { Pool } from 'pg';
8
8
  import { Socket } from 'socket.io-client';
9
9
  import * as tsyringe from 'tsyringe';
10
10
  import { DependencyContainer as DependencyContainer$1 } from 'tsyringe';
11
11
  export { DependencyContainer } from 'tsyringe';
12
+ import { Algorithm } from 'jsonwebtoken';
12
13
 
13
14
  interface IMindsetFunctionConfig {
14
15
  description: string;
@@ -411,6 +412,154 @@ declare class ClaudeChatBotAdapter extends ChatBotAdapter {
411
412
  private mapChatItems;
412
413
  }
413
414
 
415
+ interface ICommandConfig {
416
+ name?: string;
417
+ }
418
+ declare function command(config?: ICommandConfig): (target: IConstructor<any>) => void;
419
+
420
+ declare class Command<T extends IStorableData> extends Storable<T> {
421
+ getData(): T;
422
+ }
423
+
424
+ interface ICommandHandler<C extends Command<any>> {
425
+ handle(command: C): void | Promise<void>;
426
+ }
427
+
428
+ interface ICommandHandlerConfig<C extends Command<any>> {
429
+ command: IConstructor<C>;
430
+ }
431
+ declare function commandHandler<C extends Command<any>>(config: ICommandHandlerConfig<C>): (target: IConstructor<ICommandHandler<C>>) => void;
432
+
433
+ declare class CommandMetadataStore {
434
+ private handlersMap;
435
+ private handlersInverseMap;
436
+ private commandsMap;
437
+ private commandsInverseMap;
438
+ registerCommand(command: IConstructor<Command<any>>, commandName: string): void;
439
+ registerHandler(command: IConstructor<Command<any>>, handlerConstructor: IConstructor<ICommandHandler<any>>): void;
440
+ getHandlerForCommandName(commandName: string): IConstructor<ICommandHandler<any>> | null;
441
+ getCommandNameForHandler(handlerConstructor: IConstructor<ICommandHandler<any>>): string | null;
442
+ getCommandName(command: IConstructor<Command<any>>): string | null;
443
+ getCommandForCommandName(commandName: string): IConstructor<Command<any>> | null;
444
+ }
445
+
446
+ interface IJobData extends IEntityData {
447
+ commandName: string;
448
+ commandData: any;
449
+ startedAt?: number;
450
+ successAt?: number;
451
+ failedAt?: number;
452
+ error?: {
453
+ message: string;
454
+ stack?: string;
455
+ info?: any;
456
+ };
457
+ }
458
+ declare class Job extends Entity<IJobData> {
459
+ get commandName(): string;
460
+ setAsStarted(): void;
461
+ setAsSuccess(): void;
462
+ setAsFailed(error: Error): void;
463
+ }
464
+
465
+ interface ICrudRepository<T> {
466
+ find(id: string): Promise<T | null>;
467
+ findOrThrow(id: string): Promise<T>;
468
+ findAll(id: string): Promise<T[]>;
469
+ create(item: T): Promise<void>;
470
+ update(item: T): Promise<void>;
471
+ discard(item: T): Promise<void>;
472
+ }
473
+
474
+ type IPgRepositoryConfig<P extends Entity<IEntityData>> = {
475
+ schema?: string;
476
+ table: string;
477
+ constructor: IConstructor<P>;
478
+ add?: {
479
+ columns: {
480
+ [column: string]: {
481
+ type: string;
482
+ value: (item: P) => boolean | number | string | null | Date;
483
+ };
484
+ };
485
+ };
486
+ };
487
+
488
+ declare class PgRepositoryBase<P extends Entity<IEntityData>> {
489
+ protected pool: Pool;
490
+ protected config: IPgRepositoryConfig<any>;
491
+ private tableIsCreated;
492
+ protected schema: string;
493
+ protected table: string;
494
+ protected columnsList: string[];
495
+ protected columnsAndTypes: string;
496
+ protected columns: string;
497
+ protected vars: string;
498
+ protected updates: string;
499
+ addColumns: {
500
+ [columns: string]: {
501
+ type: string;
502
+ value: (item: P) => number | boolean | string | null | Date;
503
+ };
504
+ };
505
+ constructor(pool: Pool, config: IPgRepositoryConfig<any>);
506
+ protected values(item: P): (string | number | boolean | Date | null)[];
507
+ protected exec(sql: string, values: any[]): Promise<void>;
508
+ protected query(sql: string, values: any[]): Promise<any[]>;
509
+ protected connect(): Promise<Pool>;
510
+ protected ensureTable(): Promise<void>;
511
+ protected ensureColumns(): Promise<void>;
512
+ }
513
+
514
+ declare class PgCrudRepository<P extends Entity<IEntityData>> extends PgRepositoryBase<P> implements ICrudRepository<P> {
515
+ protected readonly config: IPgRepositoryConfig<P>;
516
+ constructor(pool: Pool, config: IPgRepositoryConfig<P>);
517
+ find(id: string): Promise<P | null>;
518
+ findOrThrow(id: string): Promise<P>;
519
+ findAll(): Promise<P[]>;
520
+ create(item: P): Promise<void>;
521
+ update(item: P): Promise<void>;
522
+ discard(item: P): Promise<void>;
523
+ }
524
+
525
+ declare class JobRepository extends PgCrudRepository<Job> {
526
+ constructor(pool: Pool);
527
+ }
528
+
529
+ interface IJobEvent extends IStorableData {
530
+ jobId: string;
531
+ type: 'created';
532
+ }
533
+ type IJobEventListener = (event: IJobEvent) => void | Promise<void>;
534
+ declare class JobsEventsHub {
535
+ private jobsEventsListener;
536
+ notifyJobCreated(job: Job): void;
537
+ listenJobsEvents(listener: IJobEventListener): void;
538
+ }
539
+
540
+ declare class Async {
541
+ private jobRepository;
542
+ private handlerContainer;
543
+ private jobsEventsHub;
544
+ constructor(jobRepository: JobRepository, handlerContainer: CommandMetadataStore, jobsEventsHub: JobsEventsHub);
545
+ run<T extends IStorableData>(command: Command<T>): Promise<Job>;
546
+ }
547
+
548
+ declare class JobRunner {
549
+ private jobRepository;
550
+ private handlerContainer;
551
+ constructor(jobRepository: JobRepository, handlerContainer: CommandMetadataStore);
552
+ run(job: Job): Promise<void>;
553
+ }
554
+
555
+ declare function runAsyncCommandHandlers(handlers: IConstructor<ICommandHandler<any>>[]): void;
556
+
557
+ declare class Auth<D extends IStorableData> {
558
+ private authInfo;
559
+ require(): D;
560
+ assign(authInfo: D): void;
561
+ }
562
+
414
563
  declare function cmd(): (target: object, propertyKey: string | symbol) => void;
415
564
 
416
565
  declare class ChatResolver {
@@ -715,66 +864,6 @@ interface IAudioMessage extends IBaseMessage {
715
864
  };
716
865
  }
717
866
 
718
- interface ICrudRepository<T> {
719
- find(id: string): Promise<T | null>;
720
- findOrThrow(id: string): Promise<T>;
721
- findAll(id: string): Promise<T[]>;
722
- create(item: T): Promise<void>;
723
- update(item: T): Promise<void>;
724
- discard(item: T): Promise<void>;
725
- }
726
-
727
- type IPgRepositoryConfig<P extends Entity<IEntityData>> = {
728
- schema?: string;
729
- table: string;
730
- constructor: IConstructor<P>;
731
- add?: {
732
- columns: {
733
- [column: string]: {
734
- type: string;
735
- value: (item: P) => boolean | number | string | null | Date;
736
- };
737
- };
738
- };
739
- };
740
-
741
- declare class PgRepositoryBase<P extends Entity<IEntityData>> {
742
- protected pool: Pool;
743
- protected config: IPgRepositoryConfig<any>;
744
- private tableIsCreated;
745
- protected schema: string;
746
- protected table: string;
747
- protected columnsList: string[];
748
- protected columnsAndTypes: string;
749
- protected columns: string;
750
- protected vars: string;
751
- protected updates: string;
752
- addColumns: {
753
- [columns: string]: {
754
- type: string;
755
- value: (item: P) => number | boolean | string | null | Date;
756
- };
757
- };
758
- constructor(pool: Pool, config: IPgRepositoryConfig<any>);
759
- protected values(item: P): (string | number | boolean | Date | null)[];
760
- protected exec(sql: string, values: any[]): Promise<void>;
761
- protected query(sql: string, values: any[]): Promise<any[]>;
762
- protected connect(): Promise<Pool>;
763
- protected ensureTable(): Promise<void>;
764
- protected ensureColumns(): Promise<void>;
765
- }
766
-
767
- declare class PgCrudRepository<P extends Entity<IEntityData>> extends PgRepositoryBase<P> implements ICrudRepository<P> {
768
- protected readonly config: IPgRepositoryConfig<P>;
769
- constructor(pool: Pool, config: IPgRepositoryConfig<P>);
770
- find(id: string): Promise<P | null>;
771
- findOrThrow(id: string): Promise<P>;
772
- findAll(): Promise<P[]>;
773
- create(item: P): Promise<void>;
774
- update(item: P): Promise<void>;
775
- discard(item: P): Promise<void>;
776
- }
777
-
778
867
  declare class PgWhatsAppRepository extends PgCrudRepository<WhatsApp> implements IWhatsAppRepository {
779
868
  constructor(pool: Pool);
780
869
  findBySlug(slug: string): Promise<WhatsApp | null>;
@@ -917,6 +1006,129 @@ declare class CustomError extends Error {
917
1006
  constructor(data: ICustomErrorData);
918
1007
  }
919
1008
 
1009
+ declare function jwtGuard(): (target: object, propertyKey: string | symbol) => void;
1010
+
1011
+ declare class JwtTokenDto {
1012
+ token?: string;
1013
+ expiration?: Date;
1014
+ }
1015
+
1016
+ declare class JwtAccessAndRefreshTokenDto {
1017
+ access?: JwtTokenDto;
1018
+ refresh?: JwtTokenDto;
1019
+ }
1020
+
1021
+ declare class JwtConfig {
1022
+ secretOrPublicKey: string;
1023
+ secretOrPrivateKey: string;
1024
+ algorithm: Algorithm;
1025
+ accessExpirationSeconds: number;
1026
+ refreshExpirationSeconds: number;
1027
+ constructor(env: Env);
1028
+ }
1029
+
1030
+ interface IJwtRefreshTokenData<A extends IStorableData> extends IEntityData {
1031
+ authInfo: A;
1032
+ }
1033
+ declare class JwtRefreshToken<A extends IStorableData> extends Entity<IJwtRefreshTokenData<A>> {
1034
+ get authInfo(): A;
1035
+ }
1036
+
1037
+ declare class Mapper {
1038
+ map<T>(data: any, ctor: IConstructor<T>): T;
1039
+ }
1040
+
1041
+ declare class JwtSigner {
1042
+ private config;
1043
+ private mapper;
1044
+ constructor(config: JwtConfig, mapper: Mapper);
1045
+ signAccessToken<D extends IStorableData>(info: D | JwtRefreshToken<any>): Promise<JwtTokenDto>;
1046
+ signRefreshToken(refreshToken: JwtRefreshToken<any>): Promise<JwtTokenDto>;
1047
+ signAccessAndRefreshToken(refreshToken: JwtRefreshToken<any>): Promise<JwtAccessAndRefreshTokenDto>;
1048
+ }
1049
+
1050
+ declare class JwtRefreshTokenRepository<D extends IStorableData> extends PgCrudRepository<JwtRefreshToken<D>> {
1051
+ constructor(pool: Pool);
1052
+ }
1053
+
1054
+ declare class Jwt {
1055
+ private auth;
1056
+ private jwtSigner;
1057
+ private jwtRefreshTokenRepository;
1058
+ constructor(auth: Auth<any>, jwtSigner: JwtSigner, jwtRefreshTokenRepository: JwtRefreshTokenRepository<any>);
1059
+ createToken(): Promise<JwtAccessAndRefreshTokenDto>;
1060
+ }
1061
+
1062
+ interface IGetConfig {
1063
+ path?: string;
1064
+ }
1065
+
1066
+ declare function get(config?: string | IGetConfig): (target: object, propertyKey: string | symbol) => void;
1067
+
1068
+ interface IMiddleware {
1069
+ handle(req: Request, res: Response, container: DependencyContainer$1): Promise<void>;
1070
+ }
1071
+
1072
+ declare function middleware(middlewareConstructor: IConstructor<IMiddleware>): (target: object, propertyKey: string | symbol) => void;
1073
+
1074
+ interface IPostConfig {
1075
+ path?: string;
1076
+ }
1077
+
1078
+ declare function post(config?: string | IPostConfig): (target: object, propertyKey: string | symbol) => void;
1079
+
1080
+ interface IRestControllerConfig {
1081
+ path: string;
1082
+ }
1083
+
1084
+ declare function restController(config: string | IRestControllerConfig): (target: IConstructor<any>) => void;
1085
+
1086
+ interface IEndPointMetadata {
1087
+ method: 'get' | 'post';
1088
+ path?: string;
1089
+ controllerConstructor: IConstructor<any>;
1090
+ functionName: string;
1091
+ paramsTypes: any[];
1092
+ }
1093
+
1094
+ interface IMiddlewareMetadata {
1095
+ controllerConstructor: IConstructor<any>;
1096
+ functionName: string;
1097
+ middlewareConstructor: IConstructor<IMiddleware>;
1098
+ }
1099
+
1100
+ interface IRestControllerMetadata {
1101
+ controllerConstructor: IConstructor<any>;
1102
+ path: string;
1103
+ }
1104
+
1105
+ declare class RestControllerMetadataStore {
1106
+ private endPoints;
1107
+ private middlewares;
1108
+ private restControllers;
1109
+ saveControllerMetadata(controllerMetadata: IRestControllerMetadata): void;
1110
+ saveEndPointMetadata(endPointMetadata: IEndPointMetadata): void;
1111
+ saveMiddlewareMetadata(middlewareMetadata: IMiddlewareMetadata): void;
1112
+ getControllerEndPointsInfo(controllerConstructor: IConstructor<any>): {
1113
+ middlewares: IMiddlewareMetadata[];
1114
+ controller: IRestControllerMetadata;
1115
+ method: "get" | "post";
1116
+ path?: string;
1117
+ controllerConstructor: IConstructor<any>;
1118
+ functionName: string;
1119
+ paramsTypes: any[];
1120
+ }[];
1121
+ }
1122
+
1123
+ declare function runRestControllers(controllers: IConstructor<any>[]): void;
1124
+
1125
+ declare class JwtGuardMiddleware implements IMiddleware {
1126
+ private config;
1127
+ private auth;
1128
+ constructor(config: JwtConfig, auth: Auth<any>);
1129
+ handle(req: Request, res: Response, container: DependencyContainer$1): Promise<void>;
1130
+ }
1131
+
920
1132
  declare class SendOneTimePasswordRequest {
921
1133
  fromEmail: string;
922
1134
  toEmail: string;
@@ -1019,69 +1231,14 @@ declare class RamChatRepository implements IChatRepository {
1019
1231
  private getMemory;
1020
1232
  }
1021
1233
 
1022
- interface IGetConfig {
1023
- path?: string;
1024
- }
1025
-
1026
- declare function get(config?: string | IGetConfig): (target: object, propertyKey: string | symbol) => void;
1027
-
1028
- interface IMiddleware {
1029
- handle(req: Request, res: Response, container: DependencyContainer$1): Promise<void>;
1030
- }
1031
-
1032
- declare function middleware(middlewareConstructor: IConstructor<IMiddleware>): (target: object, propertyKey: string | symbol) => void;
1033
-
1034
- interface IPostConfig {
1035
- path?: string;
1036
- }
1037
-
1038
- declare function post(config?: string | IPostConfig): (target: object, propertyKey: string | symbol) => void;
1039
-
1040
- interface IRestControllerConfig {
1041
- path: string;
1042
- }
1043
-
1044
- declare function restController(config: string | IRestControllerConfig): (target: IConstructor<any>) => void;
1045
-
1046
- interface IEndPointMetadata {
1047
- method: 'get' | 'post';
1048
- path?: string;
1049
- controllerConstructor: IConstructor<any>;
1050
- functionName: string;
1051
- paramsTypes: any[];
1052
- }
1053
-
1054
- interface IMiddlewareMetadata {
1055
- controllerConstructor: IConstructor<any>;
1056
- functionName: string;
1057
- middlewareConstructor: IConstructor<IMiddleware>;
1058
- }
1059
-
1060
- interface IRestControllerMetadata {
1061
- controllerConstructor: IConstructor<any>;
1062
- path: string;
1063
- }
1064
-
1065
- declare class RestControllerMetadataStore {
1066
- private endPoints;
1067
- private middlewares;
1068
- private restControllers;
1069
- saveControllerMetadata(controllerMetadata: IRestControllerMetadata): void;
1070
- saveEndPointMetadata(endPointMetadata: IEndPointMetadata): void;
1071
- saveMiddlewareMetadata(middlewareMetadata: IMiddlewareMetadata): void;
1072
- getControllerEndPointsInfo(controllerConstructor: IConstructor<any>): {
1073
- middlewares: IMiddlewareMetadata[];
1074
- controller: IRestControllerMetadata;
1075
- method: "get" | "post";
1076
- path?: string;
1077
- controllerConstructor: IConstructor<any>;
1078
- functionName: string;
1079
- paramsTypes: any[];
1080
- }[];
1234
+ declare class Random {
1235
+ static slug(name: string, options: {
1236
+ randomLength: number;
1237
+ }): string;
1238
+ static string(length: number): string;
1239
+ static numberCode(length: number): string;
1081
1240
  }
1082
1241
 
1083
- declare function runRestControllers(controllers: IConstructor<any>[]): void;
1084
-
1085
1242
  declare function prepareChatContainer(container: DependencyContainer$1, context: IMessageContext, mindsetCtor?: IConstructor<IMindset>): Promise<DependencyContainer$1>;
1086
1243
 
1087
1244
  interface IrunChannelProps {
@@ -1202,4 +1359,4 @@ declare function validateModel<V>(value: any, info: IModelValidatorsInfo<V>): IM
1202
1359
 
1203
1360
  declare function validate<V>(value: any, modelConstructor: IConstructor<V>): IModelValidationResult<V>;
1204
1361
 
1205
- export { AuthenticationModule, Chat, ChatBot, ChatBotAdapter, ChatBotMetadataStore, ChatItem, ChatMemory, ChatRepository, ChatResolver, ClaudeChatBotAdapter, CmdChannel, Container, ControllerMetadataStore, CustomError, DeepSeekChatBotAdapter, EmailService, Entity, Env, EnvWhatsAppRepository, ExpressProvider, HtmlModule, HttpServerProvider, type IChannelMetadata, type IChatBot, type IChatBotAdapter, type IChatBotMetadata, type IChatChannel, type IChatConnection, type IChatControllerMetadata, type IChatData, type IChatFunctionCall, type IChatItemData, type IChatItemType, type IChatMemory, type IChatMessage, type IChatRepository, type IChatType, type IConnectionChatMessage, type IConstructor, type ICrudRepository, type ICustomErrorData, type IEmailService, type IEndPointMetadata, type IEntityData, type IEnvType, type IGetConfig, type IGetWhatsAppTemplateRequest, type IHtmlModuleOptions, type IListenWhatsAppMessageRequest, type IMessageContext, type IMessageMetadata, type IMiddleware, type IMiddlewareMetadata, type IMindset, type IMindsetDecoration, type IMindsetFunctionConfig, type IMindsetFunctionDecoration, type IMindsetFunctionMetadata, type IMindsetFunctionParamMetadata, type IMindsetIdentity, type IMindsetMetadata, type IMindsetModuleConfig, type IMindsetModuleDecoration, type IMindsetModuleMetadata, type IModelValidationError, type IModelValidationResult, type IModelValidatorsInfo, type IOtpService, type IParamConfig, type IParamDecoration, type IPersistentData, type IPgRepositoryConfig, type IPostConfig, type IPrimitive, type IPropertyValidatorInfo, type IReceivedMessage, type IReceivedMessageItem, type IRestControllerConfig, type IRestControllerMetadata, type ISendEmailRequest, type ISendWhatsAppRequest, type ISendWhatsAppTemplateRequest, type IServerConfig, type IServerProvider, type ISocketChannelConfig, type ISocketChannelReceivedMessage, type IStorableData, type ISystemFunctionCallItem, type ISystemMessageItem, type ITelegramChannelConfig, type IUserConnection, type IUserData, type IUserRepository, type IValidateMaxOptions, type IValidateMinOptions, type IValidationError, type IValidationResult, type IValidator, type IValidatorMetadata, type IWhatsAppBusinessAccount, type IWhatsAppBusinessNumber, type IWhatsAppContact, type IWhatsAppData, type IWhatsAppMessage, type IWhatsAppMessageListener, type IWhatsAppRepository, type IWhatsAppSenderOptions, type IWhatsAppTemplate, type IWhatsAppTemplateComponent, type IWhatsAppTemplateMessage, type IWhatsAppTemplateParameter, type IWhatsAppTemplateResponse, type IWhatsAppWebhookPayload, type IWhatsappChannelConfig, type IchatControllerConfig, type IrunChannelProps, Lifecycle, Logger, MINDSET_DECORATION_MINDSET, MINDSET_FUNCTION_DECORATION_FUNCTION, MINDSET_MODULE_DECORATION_MODULE, MessageContext, Mindset, MindsetMetadataStore, MindsetOperator, OpenaiChatBotAdapter, OtpService, PARAM_DECORATION_IS_OPTIONAL, PARAM_DECORATION_PARAM, Persistent, PgChatMemory, PgChatRepository, PgCrudRepository, PgRepositoryBase, PgUserRepository, PgWhatsAppRepository, RamChatMemory, RamChatRepository, RamUserRepository, RegisterUserModule, RegisterUserWithEmailRequest, RestControllerMetadataStore, SendOneTimePasswordRequest, SocketChannel, SocketChannelConfig, SocketServerProvider, Storable, TelegramChannel, TelegramChannelConfig, User, UserRepository, UserResolver, ValidateOneTimePasswordRequest, ValidationMetadataStore, WhatsApp, WhatsAppChannel, WhatsAppReceiver, WhatsAppReceiverByDevConnection, WhatsAppReceiverByWebHook, WhatsAppRepository, WhatsAppSender, WhatsAppSenderByCloudApi, WhatsAppSenderByDevConnection, WhatsappChannelConfig, chatBot, chatController, cmd, container, get, inject, injectable, isBoolean, isDate, isModel, isNotEmpty, isNumber, isOptional, isPresent, isString, max, middleware, min, mindset, mindsetFunction, mindsetModule, param, post, prepareChatContainer, restController, runChannel, runRestControllers, runServer, scoped, singleton, socket, telegram, validate, validateIsBoolean, validateIsDate, validateIsNotEmpty, validateIsNumber, validateIsPresent, validateIsString, validateMax, validateMin, validateModel, whatsapp };
1362
+ export { Async, Auth, AuthenticationModule, Chat, ChatBot, ChatBotAdapter, ChatBotMetadataStore, ChatItem, ChatMemory, ChatRepository, ChatResolver, ClaudeChatBotAdapter, CmdChannel, Command, CommandMetadataStore, Container, ControllerMetadataStore, CustomError, DeepSeekChatBotAdapter, EmailService, Entity, Env, EnvWhatsAppRepository, ExpressProvider, HtmlModule, HttpServerProvider, type IChannelMetadata, type IChatBot, type IChatBotAdapter, type IChatBotMetadata, type IChatChannel, type IChatConnection, type IChatControllerMetadata, type IChatData, type IChatFunctionCall, type IChatItemData, type IChatItemType, type IChatMemory, type IChatMessage, type IChatRepository, type IChatType, type ICommandConfig, type ICommandHandler, type ICommandHandlerConfig, type IConnectionChatMessage, type IConstructor, type ICrudRepository, type ICustomErrorData, type IEmailService, type IEndPointMetadata, type IEntityData, type IEnvType, type IGetConfig, type IGetWhatsAppTemplateRequest, type IHtmlModuleOptions, type IJobData, type IJobEvent, type IJobEventListener, type IJwtRefreshTokenData, type IListenWhatsAppMessageRequest, type IMessageContext, type IMessageMetadata, type IMiddleware, type IMiddlewareMetadata, type IMindset, type IMindsetDecoration, type IMindsetFunctionConfig, type IMindsetFunctionDecoration, type IMindsetFunctionMetadata, type IMindsetFunctionParamMetadata, type IMindsetIdentity, type IMindsetMetadata, type IMindsetModuleConfig, type IMindsetModuleDecoration, type IMindsetModuleMetadata, type IModelValidationError, type IModelValidationResult, type IModelValidatorsInfo, type IOtpService, type IParamConfig, type IParamDecoration, type IPersistentData, type IPgRepositoryConfig, type IPostConfig, type IPrimitive, type IPropertyValidatorInfo, type IReceivedMessage, type IReceivedMessageItem, type IRestControllerConfig, type IRestControllerMetadata, type ISendEmailRequest, type ISendWhatsAppRequest, type ISendWhatsAppTemplateRequest, type IServerConfig, type IServerProvider, type ISocketChannelConfig, type ISocketChannelReceivedMessage, type IStorableData, type ISystemFunctionCallItem, type ISystemMessageItem, type ITelegramChannelConfig, type IUserConnection, type IUserData, type IUserRepository, type IValidateMaxOptions, type IValidateMinOptions, type IValidationError, type IValidationResult, type IValidator, type IValidatorMetadata, type IWhatsAppBusinessAccount, type IWhatsAppBusinessNumber, type IWhatsAppContact, type IWhatsAppData, type IWhatsAppMessage, type IWhatsAppMessageListener, type IWhatsAppRepository, type IWhatsAppSenderOptions, type IWhatsAppTemplate, type IWhatsAppTemplateComponent, type IWhatsAppTemplateMessage, type IWhatsAppTemplateParameter, type IWhatsAppTemplateResponse, type IWhatsAppWebhookPayload, type IWhatsappChannelConfig, type IchatControllerConfig, type IrunChannelProps, Job, JobRepository, JobRunner, JobsEventsHub, Jwt, JwtAccessAndRefreshTokenDto, JwtConfig, JwtGuardMiddleware, JwtRefreshToken, JwtRefreshTokenRepository, JwtSigner, JwtTokenDto, Lifecycle, Logger, MINDSET_DECORATION_MINDSET, MINDSET_FUNCTION_DECORATION_FUNCTION, MINDSET_MODULE_DECORATION_MODULE, Mapper, MessageContext, Mindset, MindsetMetadataStore, MindsetOperator, OpenaiChatBotAdapter, OtpService, PARAM_DECORATION_IS_OPTIONAL, PARAM_DECORATION_PARAM, Persistent, PgChatMemory, PgChatRepository, PgCrudRepository, PgRepositoryBase, PgUserRepository, PgWhatsAppRepository, RamChatMemory, RamChatRepository, RamUserRepository, Random, RegisterUserModule, RegisterUserWithEmailRequest, RestControllerMetadataStore, SendOneTimePasswordRequest, SocketChannel, SocketChannelConfig, SocketServerProvider, Storable, TelegramChannel, TelegramChannelConfig, User, UserRepository, UserResolver, ValidateOneTimePasswordRequest, ValidationMetadataStore, WhatsApp, WhatsAppChannel, WhatsAppReceiver, WhatsAppReceiverByDevConnection, WhatsAppReceiverByWebHook, WhatsAppRepository, WhatsAppSender, WhatsAppSenderByCloudApi, WhatsAppSenderByDevConnection, WhatsappChannelConfig, chatBot, chatController, cmd, command, commandHandler, container, get, inject, injectable, isBoolean, isDate, isModel, isNotEmpty, isNumber, isOptional, isPresent, isString, jwtGuard, max, middleware, min, mindset, mindsetFunction, mindsetModule, param, post, prepareChatContainer, restController, runAsyncCommandHandlers, runChannel, runRestControllers, runServer, scoped, singleton, socket, telegram, validate, validateIsBoolean, validateIsDate, validateIsNotEmpty, validateIsNumber, validateIsPresent, validateIsString, validateMax, validateMin, validateModel, whatsapp };
package/dist/src/index.js CHANGED
@@ -1,6 +1,17 @@
1
1
  export { DeepSeekChatBotAdapter } from './ai/deepseek/DeepSeekChatBotAdapter.js';
2
2
  export { OpenaiChatBotAdapter } from './ai/openia/OpenaiChatBotAdapter.js';
3
3
  export { ClaudeChatBotAdapter } from './ai/claude/ClaudeChatBotAdapter.js';
4
+ export { command } from './async/@command.js';
5
+ export { commandHandler } from './async/@commandHandler.js';
6
+ export { Async } from './async/Async.js';
7
+ export { Command } from './async/Command.js';
8
+ export { CommandMetadataStore } from './async/CommandMetadataStore.js';
9
+ export { Job } from './async/Job.js';
10
+ export { JobRepository } from './async/JobRepository.js';
11
+ export { JobRunner } from './async/JobRunner.js';
12
+ export { JobsEventsHub } from './async/JobsEventsHub.js';
13
+ export { runAsyncCommandHandlers } from './async/runCommandHandlers.js';
14
+ export { Auth } from './auth/Auth.js';
4
15
  export { cmd } from './channels/cmd/@cmd.js';
5
16
  export { CmdChannel } from './channels/cmd/CmdChannel.js';
6
17
  export { ExpressProvider } from './channels/express/ExpressProvider.js';
@@ -45,7 +56,17 @@ export { Storable } from './core/Storable.js';
45
56
  export { Env } from './env/Env.js';
46
57
  export { CustomError } from './error/CustomError.js';
47
58
  export { Lifecycle, container, inject, injectable, scoped, singleton } from './injection/index.js';
59
+ export { jwtGuard } from './jwt/@jwtGuard.js';
60
+ export { JwtAccessAndRefreshTokenDto } from './jwt/JwtAccessAndRefreshTokenDto.js';
61
+ export { JwtConfig } from './jwt/JwtConfig.js';
62
+ export { Jwt } from './jwt/Jwt.js';
63
+ export { JwtGuardMiddleware } from './jwt/JwtGuardMiddleware.js';
64
+ export { JwtRefreshToken } from './jwt/JwtRefreshToken.js';
65
+ export { JwtSigner } from './jwt/JwtSigner.js';
66
+ export { JwtTokenDto } from './jwt/JwtTokenDto.js';
67
+ export { JwtRefreshTokenRepository } from './jwt/JwtRefreshTokenRepository.js';
48
68
  export { Logger } from './logger/Logger.js';
69
+ export { Mapper } from './mapper/Mapper.js';
49
70
  export { mindsetFunction } from './mindset/metadata/functions/@mindsetFunction.js';
50
71
  export { MINDSET_FUNCTION_DECORATION_FUNCTION } from './mindset/metadata/functions/decoratorNames.js';
51
72
  export { mindset } from './mindset/metadata/mindsets/@mindset.js';
@@ -71,6 +92,7 @@ export { PgChatRepository } from './pre-made/repository/chat/pg/PgChatRepository
71
92
  export { PgChatMemory } from './pre-made/repository/chat/pg/PgChatMemory.js';
72
93
  export { RamChatMemory } from './pre-made/repository/chat/ram/RamChatMemory.js';
73
94
  export { RamChatRepository } from './pre-made/repository/chat/ram/RamChatRepository.js';
95
+ export { Random } from './random/Random.js';
74
96
  export { PgCrudRepository } from './repository/pg/PgCrudRepository.js';
75
97
  export { PgRepositoryBase } from './repository/pg/PgRepositoryBase.js';
76
98
  export { get } from './rest-controller/metadata/@get.js';
@@ -0,0 +1,34 @@
1
+ import '../injection/index.js';
2
+ import '../rest-controller/metadata/RestControllerMetadataStore.js';
3
+ import { middleware } from '../rest-controller/metadata/@middleware.js';
4
+ import '../controller/channel/ChatResolver.js';
5
+ import '../controller/channel/UserResolver.js';
6
+ import '../controller/metadata/ControllerMetadataStore.js';
7
+ import '../channels/cmd/CmdChannel.js';
8
+ import '../channels/express/ExpressProvider.js';
9
+ import '../channels/http/HttpServerProvider.js';
10
+ import '../channels/socket/SocketChannel.js';
11
+ import '../channels/socket/SocketChannelConfig.js';
12
+ import '../channels/socket/SocketServerProvider.js';
13
+ import '../channels/telegram/TelegramChannel.js';
14
+ import '../channels/whatsapp/WhatsAppChannel.js';
15
+ import '../channels/whatsapp/EnvWhatsAppRepository.js';
16
+ import '../channels/whatsapp/PgWhatsAppRepository.js';
17
+ import '../core/chat/repository/IChatRepository.js';
18
+ import '../core/user/IUserRepository.js';
19
+ import '../channels/whatsapp/WhatsAppReceiverByDevConnection.js';
20
+ import '../channels/whatsapp/WhatsAppReceiverByWebHook.js';
21
+ import '../channels/whatsapp/WhatsAppSenderByCloudApi.js';
22
+ import '../channels/whatsapp/WhatsAppSenderByDevConnection.js';
23
+ import 'debug';
24
+ import '../validation/metadata/ValidationMetadataStore.js';
25
+ import 'path';
26
+ import { JwtGuardMiddleware } from './JwtGuardMiddleware.js';
27
+
28
+ function jwtGuard() {
29
+ return function (target, propertyKey) {
30
+ middleware(JwtGuardMiddleware)(target, propertyKey);
31
+ };
32
+ }
33
+
34
+ export { jwtGuard };
@@ -0,0 +1,31 @@
1
+ import { __decorate, __metadata } from 'tslib';
2
+ import { Auth } from '../auth/Auth.js';
3
+ import { JwtSigner } from './JwtSigner.js';
4
+ import { JwtRefreshTokenRepository } from './JwtRefreshTokenRepository.js';
5
+ import { JwtRefreshToken } from './JwtRefreshToken.js';
6
+ import { injectable } from '../injection/index.js';
7
+
8
+ let Jwt = class Jwt {
9
+ auth;
10
+ jwtSigner;
11
+ jwtRefreshTokenRepository;
12
+ constructor(auth, jwtSigner, jwtRefreshTokenRepository) {
13
+ this.auth = auth;
14
+ this.jwtSigner = jwtSigner;
15
+ this.jwtRefreshTokenRepository = jwtRefreshTokenRepository;
16
+ }
17
+ async createToken() {
18
+ const authInfo = this.auth.require();
19
+ const refreshToken = new JwtRefreshToken({ authInfo });
20
+ await this.jwtRefreshTokenRepository.create(refreshToken);
21
+ return await this.jwtSigner.signAccessAndRefreshToken(refreshToken);
22
+ }
23
+ };
24
+ Jwt = __decorate([
25
+ injectable(),
26
+ __metadata("design:paramtypes", [Auth,
27
+ JwtSigner,
28
+ JwtRefreshTokenRepository])
29
+ ], Jwt);
30
+
31
+ export { Jwt };
@@ -0,0 +1,20 @@
1
+ import { __decorate, __metadata } from 'tslib';
2
+ import '../injection/index.js';
3
+ import '../validation/metadata/ValidationMetadataStore.js';
4
+ import { isModel } from '../validation/metadata/@isModel.js';
5
+ import { JwtTokenDto } from './JwtTokenDto.js';
6
+
7
+ class JwtAccessAndRefreshTokenDto {
8
+ access;
9
+ refresh;
10
+ }
11
+ __decorate([
12
+ isModel(JwtTokenDto),
13
+ __metadata("design:type", JwtTokenDto)
14
+ ], JwtAccessAndRefreshTokenDto.prototype, "access", void 0);
15
+ __decorate([
16
+ isModel(JwtTokenDto),
17
+ __metadata("design:type", JwtTokenDto)
18
+ ], JwtAccessAndRefreshTokenDto.prototype, "refresh", void 0);
19
+
20
+ export { JwtAccessAndRefreshTokenDto };
@@ -0,0 +1,28 @@
1
+ import { __decorate, __metadata } from 'tslib';
2
+ import { Env } from '../env/Env.js';
3
+ import { singleton } from '../injection/index.js';
4
+
5
+ let JwtConfig = class JwtConfig {
6
+ secretOrPublicKey;
7
+ secretOrPrivateKey;
8
+ algorithm;
9
+ accessExpirationSeconds;
10
+ refreshExpirationSeconds;
11
+ constructor(env) {
12
+ this.algorithm = env.requireString('JWT_ALGORITHM', { default: 'HS256' });
13
+ this.secretOrPublicKey = env.requireString('JWT_SECRET');
14
+ this.secretOrPrivateKey = env.requireString('JWT_SECRET');
15
+ this.accessExpirationSeconds = env.requireNumber('JWT_ACCESS_EXPIRATION_SECONDS', {
16
+ default: 10 * 60,
17
+ });
18
+ this.refreshExpirationSeconds = env.requireNumber('JWT_REFRESH_EXPIRATION_SECONDS', {
19
+ default: 365 * 24 * 3600,
20
+ });
21
+ }
22
+ };
23
+ JwtConfig = __decorate([
24
+ singleton(),
25
+ __metadata("design:paramtypes", [Env])
26
+ ], JwtConfig);
27
+
28
+ export { JwtConfig };
@@ -0,0 +1,45 @@
1
+ import { __decorate, __metadata } from 'tslib';
2
+ import { Auth } from '../auth/Auth.js';
3
+ import jwt from 'jsonwebtoken';
4
+ import { JwtConfig } from './JwtConfig.js';
5
+ import { injectable } from '../injection/index.js';
6
+ import { CustomError } from '../error/CustomError.js';
7
+
8
+ let JwtGuardMiddleware = class JwtGuardMiddleware {
9
+ config;
10
+ auth;
11
+ constructor(config, auth) {
12
+ this.config = config;
13
+ this.auth = auth;
14
+ }
15
+ async handle(req, res, container) {
16
+ const authorization = req.header('Authorization');
17
+ if (!authorization) {
18
+ throw new CustomError({ httpCode: 401, message: 'Authorization header not available' });
19
+ }
20
+ const [bearer, token] = authorization.split(' ');
21
+ if (bearer.toLowerCase() !== 'bearer' || !token) {
22
+ throw new CustomError({ httpCode: 401, message: 'Authorization should be a bearer token' });
23
+ }
24
+ try {
25
+ const jwtPayload = jwt.verify(token, this.config.secretOrPublicKey, {
26
+ algorithms: [this.config.algorithm],
27
+ });
28
+ this.auth.assign(jwtPayload);
29
+ }
30
+ catch (err) {
31
+ throw new CustomError({
32
+ httpCode: 401,
33
+ message: err instanceof Error ? `Invalid token: ${err.message}` : 'Invalid token',
34
+ cause: err instanceof Error ? err : undefined,
35
+ });
36
+ }
37
+ }
38
+ };
39
+ JwtGuardMiddleware = __decorate([
40
+ injectable(),
41
+ __metadata("design:paramtypes", [JwtConfig,
42
+ Auth])
43
+ ], JwtGuardMiddleware);
44
+
45
+ export { JwtGuardMiddleware };
@@ -0,0 +1,11 @@
1
+ import '../core/chat/repository/IChatRepository.js';
2
+ import { Entity } from '../core/Entity.js';
3
+ import '../core/user/IUserRepository.js';
4
+
5
+ class JwtRefreshToken extends Entity {
6
+ get authInfo() {
7
+ return this.data.authInfo;
8
+ }
9
+ }
10
+
11
+ export { JwtRefreshToken };
@@ -0,0 +1,21 @@
1
+ import { __decorate, __metadata } from 'tslib';
2
+ import { singleton } from '../injection/index.js';
3
+ import { JwtRefreshToken } from './JwtRefreshToken.js';
4
+ import { Pool } from 'pg';
5
+ import { PgCrudRepository } from '../repository/pg/PgCrudRepository.js';
6
+
7
+ let JwtRefreshTokenRepository = class JwtRefreshTokenRepository extends PgCrudRepository {
8
+ constructor(pool) {
9
+ super(pool, {
10
+ schema: 'wabot',
11
+ table: 'jwt_refresh_token',
12
+ constructor: JwtRefreshToken,
13
+ });
14
+ }
15
+ };
16
+ JwtRefreshTokenRepository = __decorate([
17
+ singleton(),
18
+ __metadata("design:paramtypes", [Pool])
19
+ ], JwtRefreshTokenRepository);
20
+
21
+ export { JwtRefreshTokenRepository };
@@ -0,0 +1,48 @@
1
+ import { __decorate, __metadata } from 'tslib';
2
+ import { JwtConfig } from './JwtConfig.js';
3
+ import jwt from 'jsonwebtoken';
4
+ import { JwtTokenDto } from './JwtTokenDto.js';
5
+ import { JwtRefreshToken } from './JwtRefreshToken.js';
6
+ import { JwtAccessAndRefreshTokenDto } from './JwtAccessAndRefreshTokenDto.js';
7
+ import { injectable } from '../injection/index.js';
8
+ import { Mapper } from '../mapper/Mapper.js';
9
+
10
+ let JwtSigner = class JwtSigner {
11
+ config;
12
+ mapper;
13
+ constructor(config, mapper) {
14
+ this.config = config;
15
+ this.mapper = mapper;
16
+ }
17
+ async signAccessToken(info) {
18
+ const _authInfo = info instanceof JwtRefreshToken
19
+ ? {
20
+ ...info.authInfo,
21
+ refreshTokenId: info.id,
22
+ }
23
+ : info;
24
+ const token = jwt.sign(_authInfo, this.config.secretOrPrivateKey, {
25
+ expiresIn: this.config.accessExpirationSeconds,
26
+ });
27
+ const expiration = new Date().getTime() + this.config.accessExpirationSeconds * 1000;
28
+ return this.mapper.map({ token, expiration }, JwtTokenDto);
29
+ }
30
+ async signRefreshToken(refreshToken) {
31
+ const token = jwt.sign({ refreshTokenId: refreshToken.id }, this.config.secretOrPrivateKey, {
32
+ expiresIn: this.config.refreshExpirationSeconds,
33
+ });
34
+ const expiration = new Date().getTime() + this.config.refreshExpirationSeconds * 1000;
35
+ return this.mapper.map({ token, expiration }, JwtTokenDto);
36
+ }
37
+ async signAccessAndRefreshToken(refreshToken) {
38
+ const access = await this.signAccessToken(refreshToken);
39
+ const refresh = await this.signRefreshToken(refreshToken);
40
+ return this.mapper.map({ access, refresh }, JwtAccessAndRefreshTokenDto);
41
+ }
42
+ };
43
+ JwtSigner = __decorate([
44
+ injectable(),
45
+ __metadata("design:paramtypes", [JwtConfig, Mapper])
46
+ ], JwtSigner);
47
+
48
+ export { JwtSigner };
@@ -0,0 +1,22 @@
1
+ import { __decorate, __metadata } from 'tslib';
2
+ import '../injection/index.js';
3
+ import '../validation/metadata/ValidationMetadataStore.js';
4
+ import { isDate } from '../validation/metadata/@isDate.js';
5
+ import { isNotEmpty } from '../validation/metadata/@isNotEmpty.js';
6
+ import { isString } from '../validation/metadata/@isString.js';
7
+
8
+ class JwtTokenDto {
9
+ token;
10
+ expiration;
11
+ }
12
+ __decorate([
13
+ isString(),
14
+ isNotEmpty(),
15
+ __metadata("design:type", String)
16
+ ], JwtTokenDto.prototype, "token", void 0);
17
+ __decorate([
18
+ isDate(),
19
+ __metadata("design:type", Date)
20
+ ], JwtTokenDto.prototype, "expiration", void 0);
21
+
22
+ export { JwtTokenDto };
@@ -0,0 +1,44 @@
1
+ import '../core/chat/repository/IChatRepository.js';
2
+ import { Storable } from '../core/Storable.js';
3
+ import '../core/user/IUserRepository.js';
4
+ import { CustomError } from '../error/CustomError.js';
5
+ import '../injection/index.js';
6
+ import '../validation/metadata/ValidationMetadataStore.js';
7
+ import { validate } from '../validation/validate.js';
8
+
9
+ function deepCopyWithStorable(obj) {
10
+ if (obj === null || typeof obj !== 'object') {
11
+ return obj;
12
+ }
13
+ if (obj instanceof Date) {
14
+ return obj.getTime();
15
+ }
16
+ if (obj instanceof Storable) {
17
+ return deepCopyWithStorable(obj['data']);
18
+ }
19
+ if (Array.isArray(obj)) {
20
+ return obj.map((item) => deepCopyWithStorable(item));
21
+ }
22
+ const copy = {};
23
+ for (const key in obj) {
24
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
25
+ copy[key] = deepCopyWithStorable(obj[key]);
26
+ }
27
+ }
28
+ return copy;
29
+ }
30
+ class Mapper {
31
+ map(data, ctor) {
32
+ const validationResult = validate(deepCopyWithStorable(data), ctor);
33
+ if (validationResult.error) {
34
+ throw new CustomError({
35
+ httpCode: 500,
36
+ message: `Cant map value to ${ctor.name}`,
37
+ info: validationResult.error,
38
+ });
39
+ }
40
+ return validationResult.value;
41
+ }
42
+ }
43
+
44
+ export { Mapper };
@@ -0,0 +1,37 @@
1
+ import { randomBytes } from 'node:crypto';
2
+
3
+ const DIGITS = '0123456789';
4
+ const CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
5
+ class Random {
6
+ static slug(name, options) {
7
+ const base = name
8
+ .toLowerCase()
9
+ .trim()
10
+ .replace(/[\s\_]+/g, '-') // spaces/underscores to hyphens
11
+ .replace(/[^a-z0-9\-]/g, '') // remove non-alphanumeric except hyphens
12
+ .replace(/\-+/g, '-') // collapse multiple hyphens
13
+ .replace(/^\-+|\-+$/g, ''); // trim hyphens from ends
14
+ const random = this.string(options.randomLength);
15
+ return `${base}-${random}`;
16
+ }
17
+ static string(length) {
18
+ const bytes = randomBytes(length);
19
+ let result = '';
20
+ for (let i = 0; i < length; i++) {
21
+ const index = bytes[i] % CHARSET.length;
22
+ result += CHARSET[index];
23
+ }
24
+ return result;
25
+ }
26
+ static numberCode(length) {
27
+ const bytes = randomBytes(length);
28
+ let result = '';
29
+ for (let i = 0; i < length; i++) {
30
+ const index = bytes[i] % 10; // 0–9
31
+ result += DIGITS[index];
32
+ }
33
+ return result;
34
+ }
35
+ }
36
+
37
+ export { Random };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wabot-dev/framework",
3
- "version": "0.1.0-beta.23",
3
+ "version": "0.1.0-beta.25",
4
4
  "description": "Framework for IA Chat Bots",
5
5
  "type": "module",
6
6
  "main": "dist/src/index.js",
@@ -38,6 +38,7 @@
38
38
  "@anthropic-ai/sdk": "^0.60.0",
39
39
  "@types/debug": "^4.1.12",
40
40
  "@types/express": "^5.0.1",
41
+ "@types/jsonwebtoken": "^9.0.10",
41
42
  "@types/pg": "^8.11.14",
42
43
  "@yucacodes/ts": "^0.0.4",
43
44
  "body-parser": "^2.2.0",
@@ -46,6 +47,7 @@
46
47
  "express": "^5.1.0",
47
48
  "grammy": "^1.36.0",
48
49
  "html-to-text": "^9.0.5",
50
+ "jsonwebtoken": "^9.0.2",
49
51
  "openai": "^4.93.0",
50
52
  "pg": "^8.15.6",
51
53
  "reflect-metadata": "^0.2.2",