@expressive-tea/core 2.0.0

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 (94) hide show
  1. package/.gitattributes +4 -0
  2. package/.swcrc +61 -0
  3. package/LICENSE +201 -0
  4. package/README.md +627 -0
  5. package/banner.png +0 -0
  6. package/classes/Boot.d.ts +145 -0
  7. package/classes/Boot.js +223 -0
  8. package/classes/Engine.d.ts +63 -0
  9. package/classes/Engine.js +90 -0
  10. package/classes/EngineRegistry.d.ts +154 -0
  11. package/classes/EngineRegistry.js +247 -0
  12. package/classes/LoadBalancer.d.ts +8 -0
  13. package/classes/LoadBalancer.js +28 -0
  14. package/classes/ProxyRoute.d.ts +14 -0
  15. package/classes/ProxyRoute.js +40 -0
  16. package/classes/Settings.d.ts +128 -0
  17. package/classes/Settings.js +172 -0
  18. package/decorators/annotations.d.ts +91 -0
  19. package/decorators/annotations.js +132 -0
  20. package/decorators/env.d.ts +145 -0
  21. package/decorators/env.js +177 -0
  22. package/decorators/health.d.ts +115 -0
  23. package/decorators/health.js +124 -0
  24. package/decorators/module.d.ts +34 -0
  25. package/decorators/module.js +39 -0
  26. package/decorators/proxy.d.ts +28 -0
  27. package/decorators/proxy.js +60 -0
  28. package/decorators/router.d.ts +199 -0
  29. package/decorators/router.js +252 -0
  30. package/decorators/server.d.ts +92 -0
  31. package/decorators/server.js +247 -0
  32. package/engines/constants/constants.d.ts +2 -0
  33. package/engines/constants/constants.js +5 -0
  34. package/engines/health/index.d.ts +120 -0
  35. package/engines/health/index.js +179 -0
  36. package/engines/http/index.d.ts +12 -0
  37. package/engines/http/index.js +59 -0
  38. package/engines/index.d.ts +32 -0
  39. package/engines/index.js +112 -0
  40. package/engines/socketio/index.d.ts +7 -0
  41. package/engines/socketio/index.js +30 -0
  42. package/engines/teacup/index.d.ts +27 -0
  43. package/engines/teacup/index.js +136 -0
  44. package/engines/teapot/index.d.ts +32 -0
  45. package/engines/teapot/index.js +167 -0
  46. package/engines/websocket/index.d.ts +9 -0
  47. package/engines/websocket/index.js +39 -0
  48. package/eslint.config.mjs +138 -0
  49. package/exceptions/BootLoaderExceptions.d.ts +26 -0
  50. package/exceptions/BootLoaderExceptions.js +31 -0
  51. package/exceptions/RequestExceptions.d.ts +75 -0
  52. package/exceptions/RequestExceptions.js +89 -0
  53. package/helpers/boot-helper.d.ts +7 -0
  54. package/helpers/boot-helper.js +84 -0
  55. package/helpers/decorators.d.ts +1 -0
  56. package/helpers/decorators.js +15 -0
  57. package/helpers/promise-helper.d.ts +1 -0
  58. package/helpers/promise-helper.js +6 -0
  59. package/helpers/server.d.ts +35 -0
  60. package/helpers/server.js +141 -0
  61. package/helpers/teapot-helper.d.ts +18 -0
  62. package/helpers/teapot-helper.js +88 -0
  63. package/helpers/websocket-helper.d.ts +3 -0
  64. package/helpers/websocket-helper.js +20 -0
  65. package/images/announcement-01.png +0 -0
  66. package/images/logo-sticky-01.png +0 -0
  67. package/images/logo-wp-01.png +0 -0
  68. package/images/logo.png +0 -0
  69. package/images/zero-oneit.png +0 -0
  70. package/interfaces/index.d.ts +4 -0
  71. package/interfaces/index.js +2 -0
  72. package/inversify.config.d.ts +9 -0
  73. package/inversify.config.js +8 -0
  74. package/libs/classNames.d.ts +1 -0
  75. package/libs/classNames.js +4 -0
  76. package/libs/utilities.d.ts +21910 -0
  77. package/libs/utilities.js +420 -0
  78. package/mixins/module.d.ts +45 -0
  79. package/mixins/module.js +71 -0
  80. package/mixins/proxy.d.ts +46 -0
  81. package/mixins/proxy.js +86 -0
  82. package/mixins/route.d.ts +48 -0
  83. package/mixins/route.js +96 -0
  84. package/package.json +137 -0
  85. package/services/DependencyInjection.d.ts +159 -0
  86. package/services/DependencyInjection.js +201 -0
  87. package/services/WebsocketService.d.ts +18 -0
  88. package/services/WebsocketService.js +47 -0
  89. package/types/core.d.ts +14 -0
  90. package/types/core.js +2 -0
  91. package/types/injection-types.d.ts +6 -0
  92. package/types/injection-types.js +10 -0
  93. package/types/inversify.d.ts +5 -0
  94. package/types/inversify.js +3 -0
@@ -0,0 +1,247 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ /**
4
+ * Engine Registry - Manages engine registration, dependency resolution, and initialization order
5
+ *
6
+ * Replaces hardcoded engine arrays with an extensible plugin system that:
7
+ * - Registers engines with metadata (name, version, priority, dependencies)
8
+ * - Resolves engine dependencies using topological sort
9
+ * - Detects circular dependencies
10
+ * - Filters engines based on their `canRegister()` method
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * // Register a custom engine
15
+ * EngineRegistry.register({
16
+ * engine: MyCustomEngine,
17
+ * name: 'custom',
18
+ * version: '1.0.0',
19
+ * priority: 15,
20
+ * dependencies: ['http']
21
+ * });
22
+ *
23
+ * // Get engines in dependency order
24
+ * const engines = EngineRegistry.getRegisteredEngines(context, settings);
25
+ * ```
26
+ *
27
+ * @class EngineRegistry
28
+ * @since 2.0.0
29
+ */
30
+ class EngineRegistry {
31
+ /**
32
+ * Register an engine with metadata
33
+ *
34
+ * @param {EngineMetadata} metadata - Engine metadata including name, version, priority, and dependencies
35
+ * @throws {Error} If engine with same name is already registered
36
+ *
37
+ * @example
38
+ * ```typescript
39
+ * EngineRegistry.register({
40
+ * engine: HTTPEngine,
41
+ * name: 'http',
42
+ * version: '2.0.0',
43
+ * priority: 0,
44
+ * dependencies: []
45
+ * });
46
+ * ```
47
+ */
48
+ static register(metadata) {
49
+ if (this.engines.has(metadata.name)) {
50
+ throw new Error(`Engine "${metadata.name}" is already registered`);
51
+ }
52
+ this.engines.set(metadata.name, metadata);
53
+ }
54
+ /**
55
+ * Unregister an engine by name
56
+ *
57
+ * @param {string} name - Engine name to unregister
58
+ * @returns {boolean} True if engine was unregistered, false if not found
59
+ *
60
+ * @example
61
+ * ```typescript
62
+ * EngineRegistry.unregister('custom');
63
+ * ```
64
+ */
65
+ static unregister(name) {
66
+ return this.engines.delete(name);
67
+ }
68
+ /**
69
+ * Clear all registered engines (useful for testing)
70
+ *
71
+ * @example
72
+ * ```typescript
73
+ * EngineRegistry.clear();
74
+ * ```
75
+ */
76
+ static clear() {
77
+ this.engines.clear();
78
+ }
79
+ /**
80
+ * Get all registered engine metadata
81
+ *
82
+ * @returns {EngineMetadata[]} Array of all registered engine metadata
83
+ */
84
+ static getAllEngines() {
85
+ return Array.from(this.engines.values());
86
+ }
87
+ /**
88
+ * Get engine metadata by name
89
+ *
90
+ * @param {string} name - Engine name
91
+ * @returns {EngineMetadata | undefined} Engine metadata or undefined if not found
92
+ */
93
+ static getEngine(name) {
94
+ return this.engines.get(name);
95
+ }
96
+ /**
97
+ * Get registered engines filtered by canRegister() and sorted by dependency order
98
+ *
99
+ * This method:
100
+ * 1. Filters engines using their static `canRegister()` method
101
+ * 2. Validates all dependencies are registered
102
+ * 3. Detects circular dependencies
103
+ * 4. Sorts engines using topological sort (dependencies first)
104
+ * 5. Applies priority sorting within same dependency level
105
+ *
106
+ * @param {unknown} context - Boot context to pass to canRegister()
107
+ * @param {unknown} settings - Settings to pass to canRegister()
108
+ * @returns {EngineConstructor[]} Array of engine constructors in initialization order
109
+ * @throws {Error} If circular dependency is detected
110
+ * @throws {Error} If required dependency is not registered
111
+ *
112
+ * @example
113
+ * ```typescript
114
+ * const engines = EngineRegistry.getRegisteredEngines(boot, settings);
115
+ * // Returns: [HTTPEngine, SocketIOEngine, TeapotEngine] in dependency order
116
+ * ```
117
+ */
118
+ static getRegisteredEngines(context, settings) {
119
+ // Filter engines by canRegister()
120
+ const availableEngines = Array.from(this.engines.values())
121
+ .filter(metadata => metadata.engine.canRegister(context, settings));
122
+ // Validate dependencies
123
+ this.validateDependencies(availableEngines);
124
+ // Detect circular dependencies
125
+ this.detectCircularDependencies(availableEngines);
126
+ // Topological sort with priority
127
+ const sorted = this.topologicalSort(availableEngines);
128
+ return sorted.map(metadata => metadata.engine);
129
+ }
130
+ /**
131
+ * Validate that all dependencies are registered
132
+ *
133
+ * @private
134
+ * @param {EngineMetadata[]} engines - Engines to validate
135
+ * @throws {Error} If a dependency is not registered
136
+ */
137
+ static validateDependencies(engines) {
138
+ const engineNames = new Set(engines.map(e => e.name));
139
+ for (const engine of engines) {
140
+ for (const dep of engine.dependencies) {
141
+ if (!engineNames.has(dep)) {
142
+ throw new Error(`Engine "${engine.name}" depends on "${dep}" which is not registered or cannot be registered`);
143
+ }
144
+ }
145
+ }
146
+ }
147
+ /**
148
+ * Detect circular dependencies using depth-first search
149
+ *
150
+ * @private
151
+ * @param {EngineMetadata[]} engines - Engines to check
152
+ * @throws {Error} If circular dependency is detected
153
+ */
154
+ static detectCircularDependencies(engines) {
155
+ const visited = new Set();
156
+ const recursionStack = new Set();
157
+ const engineMap = new Map(engines.map(e => [e.name, e]));
158
+ const visit = (engineName, path) => {
159
+ if (recursionStack.has(engineName)) {
160
+ const cycle = [...path, engineName].join(' -> ');
161
+ throw new Error(`Circular dependency detected: ${cycle}`);
162
+ }
163
+ if (visited.has(engineName)) {
164
+ return;
165
+ }
166
+ visited.add(engineName);
167
+ recursionStack.add(engineName);
168
+ const engine = engineMap.get(engineName);
169
+ if (engine) {
170
+ for (const dep of engine.dependencies) {
171
+ visit(dep, [...path, engineName]);
172
+ }
173
+ }
174
+ recursionStack.delete(engineName);
175
+ };
176
+ for (const engine of engines) {
177
+ if (!visited.has(engine.name)) {
178
+ visit(engine.name, []);
179
+ }
180
+ }
181
+ }
182
+ /**
183
+ * Topological sort with priority ordering
184
+ *
185
+ * Uses Kahn's algorithm for topological sorting, with priority-based ordering
186
+ * for engines at the same dependency level.
187
+ *
188
+ * @private
189
+ * @param {EngineMetadata[]} engines - Engines to sort
190
+ * @returns {EngineMetadata[]} Sorted engines (dependencies first, then by priority)
191
+ */
192
+ static topologicalSort(engines) {
193
+ var _a;
194
+ const engineMap = new Map(engines.map(e => [e.name, e]));
195
+ const inDegree = new Map();
196
+ const dependents = new Map();
197
+ // Initialize in-degree and dependents
198
+ for (const engine of engines) {
199
+ inDegree.set(engine.name, 0);
200
+ dependents.set(engine.name, []);
201
+ }
202
+ // Build dependency graph
203
+ for (const engine of engines) {
204
+ for (const dep of engine.dependencies) {
205
+ inDegree.set(engine.name, (inDegree.get(engine.name) || 0) + 1);
206
+ (_a = dependents.get(dep)) === null || _a === void 0 ? void 0 : _a.push(engine.name);
207
+ }
208
+ }
209
+ // Priority queue for engines with no dependencies
210
+ const queue = [];
211
+ for (const engine of engines) {
212
+ if (inDegree.get(engine.name) === 0) {
213
+ queue.push(engine);
214
+ }
215
+ }
216
+ // Sort queue by priority
217
+ queue.sort((a, b) => a.priority - b.priority);
218
+ const sorted = [];
219
+ while (queue.length > 0) {
220
+ // Remove engine with lowest priority
221
+ const current = queue.shift();
222
+ sorted.push(current);
223
+ // Reduce in-degree for dependents
224
+ const deps = dependents.get(current.name) || [];
225
+ for (const depName of deps) {
226
+ const newDegree = (inDegree.get(depName) || 0) - 1;
227
+ inDegree.set(depName, newDegree);
228
+ if (newDegree === 0) {
229
+ const engine = engineMap.get(depName);
230
+ if (engine) {
231
+ // Insert sorted by priority
232
+ const insertIndex = queue.findIndex(e => e.priority > engine.priority);
233
+ if (insertIndex === -1) {
234
+ queue.push(engine);
235
+ }
236
+ else {
237
+ queue.splice(insertIndex, 0, engine);
238
+ }
239
+ }
240
+ }
241
+ }
242
+ }
243
+ return sorted;
244
+ }
245
+ }
246
+ EngineRegistry.engines = new Map();
247
+ exports.default = EngineRegistry;
@@ -0,0 +1,8 @@
1
+ export default class LoadBalancer {
2
+ private readonly bins;
3
+ /**
4
+ * @offset should be used for unit testing and nothing else.
5
+ */
6
+ constructor(count: number, offset?: number);
7
+ pick(): number;
8
+ }
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ class LoadBalancer {
4
+ /**
5
+ * @offset should be used for unit testing and nothing else.
6
+ */
7
+ constructor(count, offset = 0) {
8
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
9
+ this.bins = new Array(count).fill(offset);
10
+ }
11
+ pick() {
12
+ const a = Math.trunc(Math.random() * this.bins.length);
13
+ const b = Math.trunc(Math.random() * this.bins.length);
14
+ const result = this.bins[a] < this.bins[b] ? a : b;
15
+ // Accounts for overflow if enough requests go through this balancer.
16
+ if (this.bins[result] === Number.MAX_SAFE_INTEGER) {
17
+ // Resets all bins as it assumes they have all received an equal
18
+ // number of requests. Starts again from a blank state.
19
+ for (let i = 0; i < this.bins.length; i++) {
20
+ this.bins[i] = 0;
21
+ }
22
+ }
23
+ // Increments the number of requests assigned to this bin.
24
+ this.bins[result]++;
25
+ return result;
26
+ }
27
+ }
28
+ exports.default = LoadBalancer;
@@ -0,0 +1,14 @@
1
+ import { type RequestHandler } from 'express';
2
+ export default class ProxyRoute {
3
+ readonly registeredOn: string;
4
+ private balancer;
5
+ private readonly servers;
6
+ private readonly clients;
7
+ private lastServerSelected;
8
+ constructor(registeredOn: string);
9
+ hasClients(): boolean;
10
+ isClientOnRoute(teacupId: string): boolean;
11
+ registerServer(address: string, teacupId: string): void;
12
+ unregisterServer(teacupId: string): void;
13
+ registerRoute(): RequestHandler;
14
+ }
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const proxy = require("express-http-proxy");
4
+ const LoadBalancer_1 = require("./LoadBalancer");
5
+ const utilities_1 = require("../libs/utilities");
6
+ class ProxyRoute {
7
+ constructor(registeredOn) {
8
+ this.registeredOn = registeredOn;
9
+ this.servers = [];
10
+ this.clients = [];
11
+ this.lastServerSelected = 0;
12
+ }
13
+ hasClients() {
14
+ return (0, utilities_1.size)(this.clients) > 0;
15
+ }
16
+ isClientOnRoute(teacupId) {
17
+ return (0, utilities_1.includes)(this.clients, teacupId);
18
+ }
19
+ registerServer(address, teacupId) {
20
+ this.servers.push({ teacupId, address });
21
+ this.clients.push(teacupId);
22
+ this.balancer = new LoadBalancer_1.default(this.servers.length, this.lastServerSelected);
23
+ }
24
+ unregisterServer(teacupId) {
25
+ const index = (0, utilities_1.indexOf)(this.clients, teacupId);
26
+ this.servers.splice(index, 1);
27
+ this.clients.splice(index, 1);
28
+ this.balancer = new LoadBalancer_1.default(this.servers.length);
29
+ }
30
+ registerRoute() {
31
+ return proxy(() => {
32
+ this.lastServerSelected = this.balancer.pick();
33
+ const server = this.servers[this.lastServerSelected];
34
+ return server.address;
35
+ }, {
36
+ memoizeHost: false
37
+ });
38
+ }
39
+ }
40
+ exports.default = ProxyRoute;
@@ -0,0 +1,128 @@
1
+ import { ExpressiveTeaServerProps } from '@expressive-tea/commons';
2
+ /**
3
+ * Declare the properties which the server will save into settings, is a semi dynamic object since is allowed to save
4
+ * any property but is contains only one defined property to keep the port of the server.
5
+ * @typedef {Object} ExpressiveTeaServerProps
6
+ * @property {number} [port] - Properties where server will be listen requests.
7
+ * @summary Expressive Tea Server Properties
8
+ */
9
+ /**
10
+ * Settings Singleton Class to allow store server, application and plugins settings during design mode. Can be used on
11
+ * run stage except by the port setting or any other in-design properties everything can be changed and reflected
12
+ * immediatly, the fact that some of the properties will be ignored after design stage is because is used only one time
13
+ * to provide initial settings or some initialization parameters.
14
+ *
15
+ * @class Settings
16
+ * @param {ExpressiveTeaServerProps} [options={ port: 3000 }]
17
+ * @param {boolean} [isIsolated=false]
18
+ * @summary Singleton Class to Store Server Settings
19
+ */
20
+ declare class Settings {
21
+ static isolatedContext: Map<any, Settings>;
22
+ /**
23
+ * Reset Singleton instance to the default values, all changes will be erased is not recommendable to use it
24
+ * multiple times since all your options will be lost. Unless you have an option how to recover this is not
25
+ * recommended to use often. Consider this is not DELETE initialization options, even if you deleted this is used
26
+ * one time at the application starts.
27
+ *
28
+ * @static
29
+ * @param {boolean} [resetIsolated=true] - If true, also reset all isolated contexts
30
+ * @summary Reset Singleton instance
31
+ * @memberof Settings
32
+ */
33
+ static reset(resetIsolated?: boolean): void;
34
+ /**
35
+ * Get Current Singleton Instance or Created if not exists. If a new instance is created it will created with default
36
+ * options.
37
+ *
38
+ * @static
39
+ * @returns {Settings}
40
+ * @memberof Settings
41
+ * @summary Get Singleton Instance.
42
+ */
43
+ static getInstance(ctx?: any): Settings;
44
+ /**
45
+ * Singleton Instance only for internal.
46
+ *
47
+ * @private
48
+ * @static
49
+ * @type {Settings}
50
+ * @memberof Settings
51
+ */
52
+ private static instance;
53
+ /**
54
+ * Server configuration options.
55
+ *
56
+ * @private
57
+ * @type {ExpressiveTeaServerProps}
58
+ * @memberof Settings
59
+ */
60
+ private options;
61
+ constructor(options?: ExpressiveTeaServerProps, isIsolated?: boolean);
62
+ /**
63
+ * It will return the latest snapshot options registered at the time that this method is called, as Expressive Tea
64
+ * is designed as async methods some time options should not be available.
65
+ *
66
+ * @returns {ExpressiveTeaServerProps}
67
+ * @memberof Settings
68
+ * @summary Retrieve all registered options.
69
+ */
70
+ getOptions(): ExpressiveTeaServerProps;
71
+ /**
72
+ * Retrieve the option as is designated on <settingName> parameter, if does not exist it will return null instead of
73
+ * undefined to give them a value and data consistency.
74
+ *
75
+ * @param {string} settingName
76
+ * @returns {*}
77
+ * @memberof Settings
78
+ * @summary Retrieve an option
79
+ */
80
+ get(settingName: string): any;
81
+ /**
82
+ * Initialize or Edit a application options, this is only for in run options, as explained above initialization
83
+ * options it won't affect any functionality as the application already started.
84
+ *
85
+ * @param {string} settingName
86
+ * @param {*} value
87
+ * @memberof Settings
88
+ * @summary Initialize an option.
89
+ */
90
+ set(settingName: string, value: any): void;
91
+ /**
92
+ * This Merge multiple options at the same time, this can edit or create the options.
93
+ *
94
+ * @param {ExpressiveTeaServerProps} [options={ port: 3000 }]
95
+ * @memberof Settings
96
+ * @summary Merge Options
97
+ */
98
+ merge(options?: ExpressiveTeaServerProps): void;
99
+ /**
100
+ * Get environment variables with optional type safety.
101
+ *
102
+ * Returns transformed environment variables if a transform function was provided
103
+ * to the @Env decorator, otherwise returns process.env.
104
+ *
105
+ * Use this method for type-safe access to environment variables when using
106
+ * the @Env decorator with a transform function (e.g., Zod validation).
107
+ *
108
+ * @template T - Type of environment variables (defaults to NodeJS.ProcessEnv)
109
+ * @returns Typed environment variables
110
+ * @since 2.0.1
111
+ * @summary Get type-safe environment variables
112
+ *
113
+ * @example
114
+ * // Basic usage (returns process.env)
115
+ * const env = Settings.getInstance().getEnv();
116
+ * console.log(env.NODE_ENV);
117
+ *
118
+ * @example
119
+ * // With type-safe transform from @Env decorator
120
+ * type Env = { PORT: number; DATABASE_URL: string };
121
+ *
122
+ * const env = Settings.getInstance().getEnv<Env>();
123
+ * console.log(env.PORT); // Type: number (transformed)
124
+ * console.log(env.DATABASE_URL); // Type: string (validated)
125
+ */
126
+ getEnv<T = Record<string, string>>(): T;
127
+ }
128
+ export default Settings;
@@ -0,0 +1,172 @@
1
+ "use strict";
2
+ var Settings_1;
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const tslib_1 = require("tslib");
5
+ const utilities_1 = require("../libs/utilities");
6
+ const commons_1 = require("@expressive-tea/commons");
7
+ const inversify_1 = require("inversify");
8
+ const server_1 = require("../helpers/server");
9
+ const env_1 = require("../decorators/env");
10
+ /**
11
+ * Declare the properties which the server will save into settings, is a semi dynamic object since is allowed to save
12
+ * any property but is contains only one defined property to keep the port of the server.
13
+ * @typedef {Object} ExpressiveTeaServerProps
14
+ * @property {number} [port] - Properties where server will be listen requests.
15
+ * @summary Expressive Tea Server Properties
16
+ */
17
+ /**
18
+ * Settings Singleton Class to allow store server, application and plugins settings during design mode. Can be used on
19
+ * run stage except by the port setting or any other in-design properties everything can be changed and reflected
20
+ * immediatly, the fact that some of the properties will be ignored after design stage is because is used only one time
21
+ * to provide initial settings or some initialization parameters.
22
+ *
23
+ * @class Settings
24
+ * @param {ExpressiveTeaServerProps} [options={ port: 3000 }]
25
+ * @param {boolean} [isIsolated=false]
26
+ * @summary Singleton Class to Store Server Settings
27
+ */
28
+ let Settings = Settings_1 = class Settings {
29
+ /**
30
+ * Reset Singleton instance to the default values, all changes will be erased is not recommendable to use it
31
+ * multiple times since all your options will be lost. Unless you have an option how to recover this is not
32
+ * recommended to use often. Consider this is not DELETE initialization options, even if you deleted this is used
33
+ * one time at the application starts.
34
+ *
35
+ * @static
36
+ * @param {boolean} [resetIsolated=true] - If true, also reset all isolated contexts
37
+ * @summary Reset Singleton instance
38
+ * @memberof Settings
39
+ */
40
+ static reset(resetIsolated = true) {
41
+ Settings_1.instance = undefined;
42
+ if (resetIsolated) {
43
+ Settings_1.isolatedContext.clear();
44
+ }
45
+ }
46
+ /**
47
+ * Get Current Singleton Instance or Created if not exists. If a new instance is created it will created with default
48
+ * options.
49
+ *
50
+ * @static
51
+ * @returns {Settings}
52
+ * @memberof Settings
53
+ * @summary Get Singleton Instance.
54
+ */
55
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
56
+ static getInstance(ctx) {
57
+ if (ctx) {
58
+ const context = (0, commons_1.nameOfClass)(ctx);
59
+ if (!Settings_1.isolatedContext.has(context)) {
60
+ Settings_1.isolatedContext.set(context, new Settings_1(undefined, true));
61
+ }
62
+ return Settings_1.isolatedContext.get(context);
63
+ }
64
+ return Settings_1.instance || new Settings_1();
65
+ }
66
+ constructor(options = {}, isIsolated = false) {
67
+ /**
68
+ * Server configuration options.
69
+ *
70
+ * @private
71
+ * @type {ExpressiveTeaServerProps}
72
+ * @memberof Settings
73
+ */
74
+ this.options = { port: 3000, securePort: 4443 };
75
+ if (Settings_1.instance && !isIsolated) {
76
+ return Settings_1.instance;
77
+ }
78
+ const settingsFile = (0, server_1.fileSettings)();
79
+ this.options = Object.assign(Object.assign(Object.assign({}, this.options), settingsFile.config), options);
80
+ if (!isIsolated) {
81
+ Settings_1.instance = this;
82
+ }
83
+ }
84
+ /**
85
+ * It will return the latest snapshot options registered at the time that this method is called, as Expressive Tea
86
+ * is designed as async methods some time options should not be available.
87
+ *
88
+ * @returns {ExpressiveTeaServerProps}
89
+ * @memberof Settings
90
+ * @summary Retrieve all registered options.
91
+ */
92
+ getOptions() {
93
+ return this.options;
94
+ }
95
+ /**
96
+ * Retrieve the option as is designated on <settingName> parameter, if does not exist it will return null instead of
97
+ * undefined to give them a value and data consistency.
98
+ *
99
+ * @param {string} settingName
100
+ * @returns {*}
101
+ * @memberof Settings
102
+ * @summary Retrieve an option
103
+ */
104
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
105
+ get(settingName) {
106
+ return (0, utilities_1.get)(this.options, settingName, null);
107
+ }
108
+ /**
109
+ * Initialize or Edit a application options, this is only for in run options, as explained above initialization
110
+ * options it won't affect any functionality as the application already started.
111
+ *
112
+ * @param {string} settingName
113
+ * @param {*} value
114
+ * @memberof Settings
115
+ * @summary Initialize an option.
116
+ */
117
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
118
+ set(settingName, value) {
119
+ (0, utilities_1.set)(this.options, settingName, value);
120
+ }
121
+ /**
122
+ * This Merge multiple options at the same time, this can edit or create the options.
123
+ *
124
+ * @param {ExpressiveTeaServerProps} [options={ port: 3000 }]
125
+ * @memberof Settings
126
+ * @summary Merge Options
127
+ */
128
+ merge(options = { port: 3000, securePort: 4443 }) {
129
+ this.options = Object.assign(this.options, options);
130
+ }
131
+ /**
132
+ * Get environment variables with optional type safety.
133
+ *
134
+ * Returns transformed environment variables if a transform function was provided
135
+ * to the @Env decorator, otherwise returns process.env.
136
+ *
137
+ * Use this method for type-safe access to environment variables when using
138
+ * the @Env decorator with a transform function (e.g., Zod validation).
139
+ *
140
+ * @template T - Type of environment variables (defaults to NodeJS.ProcessEnv)
141
+ * @returns Typed environment variables
142
+ * @since 2.0.1
143
+ * @summary Get type-safe environment variables
144
+ *
145
+ * @example
146
+ * // Basic usage (returns process.env)
147
+ * const env = Settings.getInstance().getEnv();
148
+ * console.log(env.NODE_ENV);
149
+ *
150
+ * @example
151
+ * // With type-safe transform from @Env decorator
152
+ * type Env = { PORT: number; DATABASE_URL: string };
153
+ *
154
+ * const env = Settings.getInstance().getEnv<Env>();
155
+ * console.log(env.PORT); // Type: number (transformed)
156
+ * console.log(env.DATABASE_URL); // Type: string (validated)
157
+ */
158
+ getEnv() {
159
+ const transformed = (0, env_1.getTransformedEnv)();
160
+ if (transformed !== null) {
161
+ return transformed;
162
+ }
163
+ return process.env;
164
+ }
165
+ };
166
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
167
+ Settings.isolatedContext = new Map();
168
+ Settings = Settings_1 = tslib_1.__decorate([
169
+ (0, inversify_1.injectable)(),
170
+ tslib_1.__metadata("design:paramtypes", [Object, Boolean])
171
+ ], Settings);
172
+ exports.default = Settings;