@avleon/core 0.0.46 → 0.0.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/License +21 -21
  2. package/README.md +666 -666
  3. package/dist/chunk-9hOWP6kD.cjs +64 -0
  4. package/dist/chunk-DORXReHP.js +37 -0
  5. package/dist/index-CWUcfHYp.d.ts +1283 -0
  6. package/dist/index-CzAzauXZ.d.cts +1282 -0
  7. package/dist/index.cjs +3194 -0
  8. package/dist/index.cjs.map +1 -0
  9. package/dist/index.js +3022 -79
  10. package/dist/index.js.map +1 -0
  11. package/dist/lib-Bk8hUm06.cjs +7847 -0
  12. package/dist/lib-Bk8hUm06.cjs.map +1 -0
  13. package/dist/lib-CvDxBMkR.js +7843 -0
  14. package/dist/lib-CvDxBMkR.js.map +1 -0
  15. package/package.json +41 -103
  16. package/dist/application.test.d.ts +0 -1
  17. package/dist/application.test.js +0 -15
  18. package/dist/authentication.d.ts +0 -13
  19. package/dist/authentication.js +0 -16
  20. package/dist/cache.d.ts +0 -12
  21. package/dist/cache.js +0 -78
  22. package/dist/cache.test.d.ts +0 -1
  23. package/dist/cache.test.js +0 -36
  24. package/dist/collection.d.ts +0 -43
  25. package/dist/collection.js +0 -231
  26. package/dist/collection.test.d.ts +0 -1
  27. package/dist/collection.test.js +0 -59
  28. package/dist/config.d.ts +0 -18
  29. package/dist/config.js +0 -58
  30. package/dist/config.test.d.ts +0 -1
  31. package/dist/config.test.js +0 -40
  32. package/dist/constants.d.ts +0 -1
  33. package/dist/constants.js +0 -4
  34. package/dist/container.d.ts +0 -30
  35. package/dist/container.js +0 -55
  36. package/dist/controller.d.ts +0 -50
  37. package/dist/controller.js +0 -71
  38. package/dist/controller.test.d.ts +0 -1
  39. package/dist/controller.test.js +0 -97
  40. package/dist/core/application.d.ts +0 -74
  41. package/dist/core/application.js +0 -424
  42. package/dist/core/router.d.ts +0 -44
  43. package/dist/core/router.js +0 -520
  44. package/dist/core/testing.d.ts +0 -21
  45. package/dist/core/testing.js +0 -104
  46. package/dist/core/types.d.ts +0 -67
  47. package/dist/core/types.js +0 -2
  48. package/dist/decorators.d.ts +0 -15
  49. package/dist/decorators.js +0 -41
  50. package/dist/environment-variables.d.ts +0 -49
  51. package/dist/environment-variables.js +0 -130
  52. package/dist/environment-variables.test.d.ts +0 -1
  53. package/dist/environment-variables.test.js +0 -70
  54. package/dist/event-dispatcher.d.ts +0 -22
  55. package/dist/event-dispatcher.js +0 -97
  56. package/dist/event-subscriber.d.ts +0 -14
  57. package/dist/event-subscriber.js +0 -87
  58. package/dist/exceptions/http-exceptions.d.ts +0 -50
  59. package/dist/exceptions/http-exceptions.js +0 -85
  60. package/dist/exceptions/index.d.ts +0 -1
  61. package/dist/exceptions/index.js +0 -17
  62. package/dist/exceptions/system-exception.d.ts +0 -22
  63. package/dist/exceptions/system-exception.js +0 -26
  64. package/dist/file-storage.d.ts +0 -69
  65. package/dist/file-storage.js +0 -323
  66. package/dist/file-storage.test.d.ts +0 -1
  67. package/dist/file-storage.test.js +0 -117
  68. package/dist/helpers.d.ts +0 -11
  69. package/dist/helpers.js +0 -27
  70. package/dist/helpers.test.d.ts +0 -1
  71. package/dist/helpers.test.js +0 -95
  72. package/dist/index.d.ts +0 -57
  73. package/dist/interfaces/avleon-application.d.ts +0 -75
  74. package/dist/interfaces/avleon-application.js +0 -2
  75. package/dist/kenx-provider.d.ts +0 -7
  76. package/dist/kenx-provider.js +0 -44
  77. package/dist/kenx-provider.test.d.ts +0 -1
  78. package/dist/kenx-provider.test.js +0 -36
  79. package/dist/logger.d.ts +0 -12
  80. package/dist/logger.js +0 -87
  81. package/dist/logger.test.d.ts +0 -1
  82. package/dist/logger.test.js +0 -42
  83. package/dist/map-types.d.ts +0 -17
  84. package/dist/map-types.js +0 -89
  85. package/dist/middleware.d.ts +0 -34
  86. package/dist/middleware.js +0 -73
  87. package/dist/middleware.test.d.ts +0 -1
  88. package/dist/middleware.test.js +0 -121
  89. package/dist/multipart.d.ts +0 -17
  90. package/dist/multipart.js +0 -70
  91. package/dist/multipart.test.d.ts +0 -1
  92. package/dist/multipart.test.js +0 -87
  93. package/dist/openapi.d.ts +0 -410
  94. package/dist/openapi.js +0 -59
  95. package/dist/openapi.test.d.ts +0 -1
  96. package/dist/openapi.test.js +0 -111
  97. package/dist/params.d.ts +0 -17
  98. package/dist/params.js +0 -64
  99. package/dist/params.test.d.ts +0 -1
  100. package/dist/params.test.js +0 -83
  101. package/dist/queue.d.ts +0 -29
  102. package/dist/queue.js +0 -84
  103. package/dist/response.d.ts +0 -16
  104. package/dist/response.js +0 -56
  105. package/dist/results.d.ts +0 -20
  106. package/dist/results.js +0 -32
  107. package/dist/route-methods.d.ts +0 -25
  108. package/dist/route-methods.js +0 -60
  109. package/dist/route-methods.test.d.ts +0 -1
  110. package/dist/route-methods.test.js +0 -129
  111. package/dist/swagger-schema.d.ts +0 -37
  112. package/dist/swagger-schema.js +0 -454
  113. package/dist/swagger-schema.test.d.ts +0 -1
  114. package/dist/swagger-schema.test.js +0 -125
  115. package/dist/types/app-builder.interface.d.ts +0 -15
  116. package/dist/types/app-builder.interface.js +0 -8
  117. package/dist/types/application.interface.d.ts +0 -8
  118. package/dist/types/application.interface.js +0 -2
  119. package/dist/utils/common-utils.d.ts +0 -17
  120. package/dist/utils/common-utils.js +0 -108
  121. package/dist/utils/di-utils.d.ts +0 -1
  122. package/dist/utils/di-utils.js +0 -22
  123. package/dist/utils/hash.d.ts +0 -2
  124. package/dist/utils/hash.js +0 -11
  125. package/dist/utils/index.d.ts +0 -2
  126. package/dist/utils/index.js +0 -18
  127. package/dist/utils/object-utils.d.ts +0 -11
  128. package/dist/utils/object-utils.js +0 -198
  129. package/dist/utils/optional-require.d.ts +0 -8
  130. package/dist/utils/optional-require.js +0 -70
  131. package/dist/utils/validation-utils.d.ts +0 -13
  132. package/dist/utils/validation-utils.js +0 -119
  133. package/dist/validation.d.ts +0 -39
  134. package/dist/validation.js +0 -108
  135. package/dist/validation.test.d.ts +0 -1
  136. package/dist/validation.test.js +0 -61
  137. package/dist/validator-extend.d.ts +0 -7
  138. package/dist/validator-extend.js +0 -28
  139. package/dist/websocket.d.ts +0 -10
  140. package/dist/websocket.js +0 -21
  141. package/dist/websocket.test.d.ts +0 -1
  142. package/dist/websocket.test.js +0 -27
@@ -1,67 +0,0 @@
1
- /**
2
- * @copyright 2024
3
- * @author Tareq Hossain
4
- * @email xtrinsic96@gmail.com
5
- * @url https://github.com/xtareq
6
- */
7
- import { FastifyRequest, FastifyReply } from "fastify";
8
- import { MultipartFile } from "../multipart";
9
- import { OpenApiUiOptions } from "../openapi";
10
- import { IAvleonApplication, AvleonApplicationOptions, CorsOptions, GlobalOptions, AutoControllerOptions, TestApplication, TestResponse } from "../interfaces/avleon-application";
11
- export { IAvleonApplication, AvleonApplicationOptions, CorsOptions, GlobalOptions, AutoControllerOptions, TestApplication, TestResponse };
12
- export interface IRequest extends Omit<FastifyRequest, "files" | "formData" | "file" | "saveRequestFiles"> {
13
- params: any;
14
- query: any;
15
- body: any;
16
- headers: any;
17
- user?: any;
18
- formData?: any;
19
- file?: MultipartFile;
20
- files?: MultipartFile[];
21
- saveRequestFiles?: (options?: any) => Promise<MultipartFile[]>;
22
- _argsCache?: Map<string, any[]>;
23
- }
24
- export interface IResponse extends FastifyReply {
25
- }
26
- export interface ParamMetaOptions {
27
- index: number;
28
- key: string;
29
- name: string;
30
- required: boolean;
31
- validate: boolean;
32
- dataType: any;
33
- validatorClass: boolean;
34
- schema?: any;
35
- type: "route:param" | "route:query" | "route:body" | "route:header" | "route:user" | "route:file" | "route:files";
36
- }
37
- export interface ParamMetaFilesOptions {
38
- index: number;
39
- type: "route:files";
40
- files: MultipartFile[];
41
- fieldName: string;
42
- }
43
- export interface MethodParamMeta {
44
- request: any[];
45
- params: ParamMetaOptions[];
46
- query: ParamMetaOptions[];
47
- body: ParamMetaOptions[];
48
- headers: ParamMetaOptions[];
49
- currentUser: ParamMetaOptions[];
50
- swagger?: OpenApiUiOptions;
51
- file?: any[];
52
- files?: ParamMetaFilesOptions[];
53
- }
54
- export interface IRoute {
55
- url: string;
56
- method: string;
57
- controller: string;
58
- }
59
- export type FuncRoute = {
60
- handler: Function;
61
- middlewares: any[];
62
- schema: any;
63
- };
64
- export type StaticFileOptions = {
65
- path?: string;
66
- prefix?: string;
67
- };
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,15 +0,0 @@
1
- /**
2
- * @copyright 2024
3
- * @author Tareq Hossain
4
- * @email xtrinsic96@gmail.com
5
- * @url https://github.com/xtareq
6
- */
7
- import { Service as _service } from "typedi";
8
- export declare function AppService(target: any): void;
9
- export declare function AppService(): any;
10
- export * from "./controller";
11
- export * from "./route-methods";
12
- export * from "./openapi";
13
- export declare const Utility: typeof _service;
14
- export declare const Helper: typeof _service;
15
- export * from "./params";
@@ -1,41 +0,0 @@
1
- "use strict";
2
- /**
3
- * @copyright 2024
4
- * @author Tareq Hossain
5
- * @email xtrinsic96@gmail.com
6
- * @url https://github.com/xtareq
7
- */
8
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9
- if (k2 === undefined) k2 = k;
10
- var desc = Object.getOwnPropertyDescriptor(m, k);
11
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
12
- desc = { enumerable: true, get: function() { return m[k]; } };
13
- }
14
- Object.defineProperty(o, k2, desc);
15
- }) : (function(o, m, k, k2) {
16
- if (k2 === undefined) k2 = k;
17
- o[k2] = m[k];
18
- }));
19
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
20
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
21
- };
22
- Object.defineProperty(exports, "__esModule", { value: true });
23
- exports.Helper = exports.Utility = void 0;
24
- exports.AppService = AppService;
25
- const typedi_1 = require("typedi");
26
- function AppService(target) {
27
- if (target) {
28
- (0, typedi_1.Service)()(target);
29
- }
30
- else {
31
- return function (tg) {
32
- (0, typedi_1.Service)()(tg);
33
- };
34
- }
35
- }
36
- __exportStar(require("./controller"), exports);
37
- __exportStar(require("./route-methods"), exports);
38
- __exportStar(require("./openapi"), exports);
39
- exports.Utility = typedi_1.Service;
40
- exports.Helper = typedi_1.Service;
41
- __exportStar(require("./params"), exports);
@@ -1,49 +0,0 @@
1
- /**
2
- * @copyright 2024
3
- * @author Tareq Hossain
4
- * @email xtrinsic96@gmail.com
5
- * @url https://github.com/xtareq
6
- */
7
- /**
8
- * @class Environment
9
- * @description A service class to manage access to environment variables.
10
- * It loads variables from `.env` file and merges them with `process.env`,
11
- * giving precedence to `process.env` values.
12
- */
13
- export declare class Environment {
14
- /**
15
- * Parses the given `.env` file and merges it with `process.env`.
16
- * Values from `process.env` take precedence.
17
- *
18
- * @private
19
- * @param filePath - Absolute path to the `.env` file.
20
- * @returns A dictionary of merged environment variables.
21
- */
22
- private parseEnvFile;
23
- /**
24
- * Retrieves the value of the specified environment variable.
25
- *
26
- * @template T
27
- * @param key - The name of the environment variable.
28
- * @returns The value of the variable, or `undefined` if not found.
29
- */
30
- get<T = any>(key: string): T;
31
- /**
32
- * Retrieves the value of the specified environment variable.
33
- * Throws an error if the variable is not found.
34
- *
35
- * @template T
36
- * @param key - The name of the environment variable.
37
- * @throws {EnvironmentVariableNotFound} If the variable does not exist.
38
- * @returns The value of the variable.
39
- */
40
- getOrThrow<T = any>(key: string): T;
41
- /**
42
- * Retrieves all available environment variables,
43
- * with `process.env` values taking precedence over `.env` values.
44
- *
45
- * @template T
46
- * @returns An object containing all environment variables.
47
- */
48
- getAll<T = any>(): T;
49
- }
@@ -1,130 +0,0 @@
1
- "use strict";
2
- /**
3
- * @copyright 2024
4
- * @author Tareq Hossain
5
- * @email xtrinsic96@gmail.com
6
- * @url https://github.com/xtareq
7
- */
8
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9
- if (k2 === undefined) k2 = k;
10
- var desc = Object.getOwnPropertyDescriptor(m, k);
11
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
12
- desc = { enumerable: true, get: function() { return m[k]; } };
13
- }
14
- Object.defineProperty(o, k2, desc);
15
- }) : (function(o, m, k, k2) {
16
- if (k2 === undefined) k2 = k;
17
- o[k2] = m[k];
18
- }));
19
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
20
- Object.defineProperty(o, "default", { enumerable: true, value: v });
21
- }) : function(o, v) {
22
- o["default"] = v;
23
- });
24
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
25
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
26
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
27
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
28
- return c > 3 && r && Object.defineProperty(target, key, r), r;
29
- };
30
- var __importStar = (this && this.__importStar) || (function () {
31
- var ownKeys = function(o) {
32
- ownKeys = Object.getOwnPropertyNames || function (o) {
33
- var ar = [];
34
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
35
- return ar;
36
- };
37
- return ownKeys(o);
38
- };
39
- return function (mod) {
40
- if (mod && mod.__esModule) return mod;
41
- var result = {};
42
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
43
- __setModuleDefault(result, mod);
44
- return result;
45
- };
46
- })();
47
- var __importDefault = (this && this.__importDefault) || function (mod) {
48
- return (mod && mod.__esModule) ? mod : { "default": mod };
49
- };
50
- Object.defineProperty(exports, "__esModule", { value: true });
51
- exports.Environment = void 0;
52
- const dotenv_1 = __importDefault(require("dotenv"));
53
- const path_1 = __importDefault(require("path"));
54
- const fs_1 = __importStar(require("fs"));
55
- const typedi_1 = require("typedi");
56
- const system_exception_1 = require("./exceptions/system-exception");
57
- dotenv_1.default.config({ path: path_1.default.join(process.cwd(), ".env"), quiet: true });
58
- /**
59
- * @class Environment
60
- * @description A service class to manage access to environment variables.
61
- * It loads variables from `.env` file and merges them with `process.env`,
62
- * giving precedence to `process.env` values.
63
- */
64
- let Environment = class Environment {
65
- /**
66
- * Parses the given `.env` file and merges it with `process.env`.
67
- * Values from `process.env` take precedence.
68
- *
69
- * @private
70
- * @param filePath - Absolute path to the `.env` file.
71
- * @returns A dictionary of merged environment variables.
72
- */
73
- parseEnvFile(filePath) {
74
- try {
75
- const isExis = (0, fs_1.existsSync)(filePath);
76
- if (!isExis) {
77
- return { ...process.env };
78
- }
79
- const fileContent = fs_1.default.readFileSync(filePath, "utf8");
80
- const parsedEnv = dotenv_1.default.parse(fileContent);
81
- return { ...parsedEnv, ...process.env };
82
- }
83
- catch (error) {
84
- console.error(`Error parsing .env file: ${error}`);
85
- return {};
86
- }
87
- }
88
- /**
89
- * Retrieves the value of the specified environment variable.
90
- *
91
- * @template T
92
- * @param key - The name of the environment variable.
93
- * @returns The value of the variable, or `undefined` if not found.
94
- */
95
- get(key) {
96
- const parsedEnv = this.parseEnvFile(path_1.default.join(process.cwd(), ".env"));
97
- return parsedEnv[key];
98
- }
99
- /**
100
- * Retrieves the value of the specified environment variable.
101
- * Throws an error if the variable is not found.
102
- *
103
- * @template T
104
- * @param key - The name of the environment variable.
105
- * @throws {EnvironmentVariableNotFound} If the variable does not exist.
106
- * @returns The value of the variable.
107
- */
108
- getOrThrow(key) {
109
- const parsedEnv = this.parseEnvFile(path_1.default.join(process.cwd(), ".env"));
110
- if (!Object(parsedEnv).hasOwnProperty(key)) {
111
- throw new system_exception_1.EnvironmentVariableNotFound(key);
112
- }
113
- return parsedEnv[key];
114
- }
115
- /**
116
- * Retrieves all available environment variables,
117
- * with `process.env` values taking precedence over `.env` values.
118
- *
119
- * @template T
120
- * @returns An object containing all environment variables.
121
- */
122
- getAll() {
123
- const parsedEnv = this.parseEnvFile(path_1.default.join(process.cwd(), ".env"));
124
- return parsedEnv;
125
- }
126
- };
127
- exports.Environment = Environment;
128
- exports.Environment = Environment = __decorate([
129
- (0, typedi_1.Service)()
130
- ], Environment);
@@ -1 +0,0 @@
1
- export {};
@@ -1,70 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const environment_variables_1 = require("./environment-variables");
7
- const fs_1 = __importDefault(require("fs"));
8
- const path_1 = __importDefault(require("path"));
9
- jest.mock("fs");
10
- const mockedFs = fs_1.default;
11
- describe("Environment", () => {
12
- const envFilePath = path_1.default.join(process.cwd(), ".env");
13
- const envContent = "TEST_KEY=123\nANOTHER_KEY=abc";
14
- const parsedEnv = { TEST_KEY: "123", ANOTHER_KEY: "abc" };
15
- beforeEach(() => {
16
- jest.resetModules();
17
- mockedFs.existsSync.mockClear();
18
- mockedFs.readFileSync.mockClear();
19
- process.env.TEST_KEY = "override";
20
- process.env.ONLY_PROCESS = "proc";
21
- });
22
- afterEach(() => {
23
- delete process.env.TEST_KEY;
24
- delete process.env.ONLY_PROCESS;
25
- });
26
- it("should get value from process.env if present", () => {
27
- mockedFs.existsSync.mockReturnValue(true);
28
- mockedFs.readFileSync.mockReturnValue(envContent);
29
- const env = new environment_variables_1.Environment();
30
- expect(env.get("TEST_KEY")).toBe("override");
31
- });
32
- it("should get value from .env file if not in process.env", () => {
33
- mockedFs.existsSync.mockReturnValue(true);
34
- mockedFs.readFileSync.mockReturnValue(envContent);
35
- const env = new environment_variables_1.Environment();
36
- expect(env.get("ANOTHER_KEY")).toBe("abc");
37
- });
38
- it("should return undefined for missing key", () => {
39
- mockedFs.existsSync.mockReturnValue(true);
40
- mockedFs.readFileSync.mockReturnValue(envContent);
41
- const env = new environment_variables_1.Environment();
42
- expect(env.get("MISSING_KEY")).toBeUndefined();
43
- });
44
- it("should throw EnvironmentVariableNotFound for getOrThrow if missing", () => {
45
- mockedFs.existsSync.mockReturnValue(true);
46
- mockedFs.readFileSync.mockReturnValue(envContent);
47
- const env = new environment_variables_1.Environment();
48
- expect(() => env.getOrThrow("MISSING_KEY")).toThrow();
49
- });
50
- it("should get all variables with process.env taking precedence", () => {
51
- mockedFs.existsSync.mockReturnValue(true);
52
- mockedFs.readFileSync.mockReturnValue(envContent);
53
- const env = new environment_variables_1.Environment();
54
- const all = env.getAll();
55
- expect(all.TEST_KEY).toBe("override");
56
- expect(all.ANOTHER_KEY).toBe("abc");
57
- expect(all.ONLY_PROCESS).toBe("proc");
58
- });
59
- it("should handle missing .env file gracefully", () => {
60
- mockedFs.existsSync.mockReturnValue(false);
61
- const env = new environment_variables_1.Environment();
62
- expect(env.get("ONLY_PROCESS")).toBe("proc");
63
- expect(env.get("TEST_KEY")).toBe("override");
64
- });
65
- it("should return empty object if error occurs during parsing", () => {
66
- mockedFs.existsSync.mockImplementation(() => { throw new Error("fs error"); });
67
- const env = new environment_variables_1.Environment();
68
- expect(env.getAll()).toEqual({});
69
- });
70
- });
@@ -1,22 +0,0 @@
1
- import { Socket } from "socket.io";
2
- export declare class SocketContextService {
3
- private readonly storage;
4
- run(socket: Socket, fn: () => void | Promise<void>): void;
5
- getSocket(): Socket | undefined;
6
- }
7
- export type DispatchOptions = {
8
- room?: string;
9
- broadcast?: boolean;
10
- transports?: ("socket" | "kafka" | "rabbitmq")[];
11
- retry?: number;
12
- retryDelay?: number;
13
- };
14
- export declare class EventDispatcher {
15
- private readonly _context;
16
- constructor(_context: SocketContextService);
17
- dispatch<T = any>(event: string, data: T, options?: DispatchOptions): Promise<void>;
18
- private dispatchToTransports;
19
- }
20
- export declare function Dispatch(event: string, options?: Omit<DispatchOptions, "transports"> & {
21
- transports?: DispatchOptions["transports"];
22
- }): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => void;
@@ -1,97 +0,0 @@
1
- "use strict";
2
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
- return c > 3 && r && Object.defineProperty(target, key, r), r;
7
- };
8
- var __metadata = (this && this.__metadata) || function (k, v) {
9
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.EventDispatcher = exports.SocketContextService = void 0;
13
- exports.Dispatch = Dispatch;
14
- const typedi_1 = require("typedi");
15
- const websocket_1 = require("./websocket");
16
- const node_async_hooks_1 = require("node:async_hooks");
17
- const helpers_1 = require("./helpers");
18
- let SocketContextService = class SocketContextService {
19
- constructor() {
20
- this.storage = new node_async_hooks_1.AsyncLocalStorage();
21
- }
22
- run(socket, fn) {
23
- this.storage.run({ socket }, fn);
24
- }
25
- getSocket() {
26
- var _a;
27
- return (_a = this.storage.getStore()) === null || _a === void 0 ? void 0 : _a.socket;
28
- }
29
- };
30
- exports.SocketContextService = SocketContextService;
31
- exports.SocketContextService = SocketContextService = __decorate([
32
- (0, typedi_1.Service)()
33
- ], SocketContextService);
34
- let EventDispatcher = class EventDispatcher {
35
- constructor(_context) {
36
- this._context = _context;
37
- }
38
- async dispatch(event, data, options = {}) {
39
- var _a, _b;
40
- const retryCount = (_a = options.retry) !== null && _a !== void 0 ? _a : 0;
41
- const delay = (_b = options.retryDelay) !== null && _b !== void 0 ? _b : 300;
42
- for (let attempt = 0; attempt <= retryCount; attempt++) {
43
- try {
44
- await this.dispatchToTransports(event, data, options);
45
- break;
46
- }
47
- catch (err) {
48
- if (attempt === retryCount)
49
- throw err;
50
- await (0, helpers_1.sleep)(delay * (attempt + 1));
51
- }
52
- }
53
- }
54
- async dispatchToTransports(event, data, options) {
55
- var _a;
56
- const transports = (_a = options.transports) !== null && _a !== void 0 ? _a : ["socket"];
57
- for (const transport of transports) {
58
- if (transport === "socket") {
59
- const io = typedi_1.Container.get(websocket_1.SocketIoServer);
60
- const context = typedi_1.Container.get(SocketContextService);
61
- const socket = context.getSocket();
62
- if (options.broadcast && socket) {
63
- if (options.room) {
64
- socket.broadcast.to(options.room).emit(event, data);
65
- }
66
- else {
67
- socket.broadcast.emit(event, data);
68
- }
69
- }
70
- else {
71
- if (options.room) {
72
- io.to(options.room).emit(event, data);
73
- }
74
- else {
75
- io.emit(event, data);
76
- }
77
- }
78
- }
79
- }
80
- }
81
- };
82
- exports.EventDispatcher = EventDispatcher;
83
- exports.EventDispatcher = EventDispatcher = __decorate([
84
- (0, typedi_1.Service)(),
85
- __metadata("design:paramtypes", [SocketContextService])
86
- ], EventDispatcher);
87
- function Dispatch(event, options) {
88
- return function (target, propertyKey, descriptor) {
89
- const original = descriptor.value;
90
- descriptor.value = async function (...args) {
91
- const result = await original.apply(this, args);
92
- const dispatcher = typedi_1.Container.get(EventDispatcher);
93
- await dispatcher.dispatch(event, result, options);
94
- return result;
95
- };
96
- };
97
- }
@@ -1,14 +0,0 @@
1
- import { Socket } from "socket.io";
2
- import { SocketContextService } from "./event-dispatcher";
3
- import "reflect-metadata";
4
- export declare function Private(channelResolver?: (socket: any) => string): (target: any, propertyKey: string) => void;
5
- export declare function isPrivate(target: any, propertyKey: string): boolean;
6
- export declare function getPrivateChannelResolver(target: any, propertyKey: string): ((socket: any) => string) | undefined;
7
- export declare function registerSocketSubscriber(target: Function): void;
8
- export declare function getSocketSubscribers(): Function[];
9
- export declare function Subscribe(event: string): MethodDecorator;
10
- export declare class EventSubscriberRegistry {
11
- private readonly socketContext;
12
- constructor(socketContext: SocketContextService);
13
- register(socket: Socket): void;
14
- }
@@ -1,87 +0,0 @@
1
- "use strict";
2
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
- return c > 3 && r && Object.defineProperty(target, key, r), r;
7
- };
8
- var __metadata = (this && this.__metadata) || function (k, v) {
9
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.EventSubscriberRegistry = void 0;
13
- exports.Private = Private;
14
- exports.isPrivate = isPrivate;
15
- exports.getPrivateChannelResolver = getPrivateChannelResolver;
16
- exports.registerSocketSubscriber = registerSocketSubscriber;
17
- exports.getSocketSubscribers = getSocketSubscribers;
18
- exports.Subscribe = Subscribe;
19
- const typedi_1 = require("typedi");
20
- const event_dispatcher_1 = require("./event-dispatcher");
21
- require("reflect-metadata");
22
- const PRIVATE_META_KEY = "avleon:private";
23
- function Private(channelResolver) {
24
- return function (target, propertyKey) {
25
- Reflect.defineMetadata(PRIVATE_META_KEY, true, target, propertyKey);
26
- Reflect.defineMetadata(`private:channel:${propertyKey}`, channelResolver, target);
27
- };
28
- }
29
- function isPrivate(target, propertyKey) {
30
- return Reflect.getMetadata(PRIVATE_META_KEY, target, propertyKey) || false;
31
- }
32
- function getPrivateChannelResolver(target, propertyKey) {
33
- return Reflect.getMetadata(`private:channel:${propertyKey}`, target);
34
- }
35
- const socketSubscriberClasses = new Set();
36
- function registerSocketSubscriber(target) {
37
- socketSubscriberClasses.add(target);
38
- }
39
- function getSocketSubscribers() {
40
- return Array.from(socketSubscriberClasses);
41
- }
42
- function Subscribe(event) {
43
- return (target, propertyKey) => {
44
- Reflect.defineMetadata("socket:event", event, target, propertyKey);
45
- registerSocketSubscriber(target.constructor);
46
- };
47
- }
48
- let EventSubscriberRegistry = class EventSubscriberRegistry {
49
- constructor(socketContext) {
50
- this.socketContext = socketContext;
51
- }
52
- register(socket) {
53
- const subscriberClasses = getSocketSubscribers();
54
- for (const SubscriberClass of subscriberClasses) {
55
- const instance = typedi_1.Container.get(SubscriberClass);
56
- const prototype = Object.getPrototypeOf(instance);
57
- const methodNames = Object.getOwnPropertyNames(prototype).filter((name) => typeof prototype[name] === "function");
58
- for (const methodName of methodNames) {
59
- const event = Reflect.getMetadata("socket:event", prototype, methodName);
60
- const isPrivateListener = isPrivate(instance, methodName);
61
- const channelResolver = getPrivateChannelResolver(instance, methodName);
62
- if (event) {
63
- const channel = isPrivateListener && channelResolver
64
- ? channelResolver(socket)
65
- : event;
66
- console.log("Channel", channel);
67
- socket.on(channel, (payload) => {
68
- this.socketContext.run(socket, async () => {
69
- if (isPrivateListener) {
70
- const user = socket.data.user;
71
- if (!user)
72
- return; // unauthorized
73
- // optionally add more validation here
74
- }
75
- await instance[methodName](payload, socket.data);
76
- });
77
- });
78
- }
79
- }
80
- }
81
- }
82
- };
83
- exports.EventSubscriberRegistry = EventSubscriberRegistry;
84
- exports.EventSubscriberRegistry = EventSubscriberRegistry = __decorate([
85
- (0, typedi_1.Service)(),
86
- __metadata("design:paramtypes", [event_dispatcher_1.SocketContextService])
87
- ], EventSubscriberRegistry);
@@ -1,50 +0,0 @@
1
- /**
2
- * @copyright 2024
3
- * @author Tareq Hossain
4
- * @email xtrinsic96@gmail.com
5
- * @url https://github.com/xtareq
6
- */
7
- export declare abstract class BaseHttpException extends Error {
8
- code: number;
9
- name: string;
10
- payload: any;
11
- constructor(message: any);
12
- isCustomException(): boolean;
13
- }
14
- export declare class BadRequestException extends BaseHttpException {
15
- name: string;
16
- code: number;
17
- constructor(message: any);
18
- }
19
- export declare class ValidationErrorException extends BadRequestException {
20
- name: string;
21
- }
22
- export declare class InternalErrorException extends BaseHttpException {
23
- name: string;
24
- code: number;
25
- constructor(message?: any);
26
- }
27
- export declare class NotFoundException extends BaseHttpException {
28
- name: string;
29
- code: number;
30
- constructor(message: any);
31
- }
32
- export declare class UnauthorizedException extends BaseHttpException {
33
- name: string;
34
- code: number;
35
- constructor(message: any);
36
- }
37
- export declare class ForbiddenException extends BaseHttpException {
38
- name: string;
39
- code: number;
40
- constructor(message: any);
41
- }
42
- export type HttpExceptionTypes = NotFoundException | BadRequestException | UnauthorizedException | InternalErrorException | ForbiddenException;
43
- export declare const HttpExceptions: {
44
- notFound: (message?: any) => NotFoundException;
45
- validationError: (message?: any) => ValidationErrorException;
46
- badRequest: (message?: any) => BadRequestException;
47
- unauthorized: (message?: any) => UnauthorizedException;
48
- forbidden: (message?: any) => ForbiddenException;
49
- internalError: (message?: any) => InternalErrorException;
50
- };