@catbee/utils 1.1.0 → 2.0.0-next.1

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 (90) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +79 -43
  3. package/array/index.cjs +355 -0
  4. package/array/index.d.ts +317 -0
  5. package/array/index.mjs +327 -0
  6. package/async/index.cjs +484 -0
  7. package/async/index.d.ts +299 -0
  8. package/async/index.mjs +463 -0
  9. package/cache/index.cjs +292 -0
  10. package/cache/index.d.ts +179 -0
  11. package/cache/index.mjs +290 -0
  12. package/config/index.cjs +150 -0
  13. package/config/index.d.ts +88 -0
  14. package/config/index.mjs +143 -0
  15. package/context-store/index.cjs +267 -0
  16. package/context-store/index.d.ts +216 -0
  17. package/context-store/index.mjs +261 -0
  18. package/crypto/index.cjs +182 -0
  19. package/crypto/index.d.ts +187 -0
  20. package/crypto/index.mjs +166 -0
  21. package/date/index.cjs +340 -0
  22. package/date/index.d.ts +214 -0
  23. package/date/index.mjs +326 -0
  24. package/decorators/index.cjs +2051 -0
  25. package/decorators/index.d.ts +708 -0
  26. package/decorators/index.mjs +2010 -0
  27. package/dir/index.cjs +417 -0
  28. package/dir/index.d.ts +219 -0
  29. package/dir/index.mjs +390 -0
  30. package/env/index.cjs +745 -0
  31. package/env/index.d.ts +403 -0
  32. package/env/index.mjs +742 -0
  33. package/exception/index.cjs +362 -0
  34. package/exception/index.d.ts +256 -0
  35. package/exception/index.mjs +338 -0
  36. package/fs/index.cjs +287 -0
  37. package/fs/index.d.ts +229 -0
  38. package/fs/index.mjs +258 -0
  39. package/http-status-codes/index.cjs +96 -0
  40. package/http-status-codes/index.d.ts +291 -0
  41. package/http-status-codes/index.mjs +94 -0
  42. package/id/index.cjs +62 -0
  43. package/id/index.d.ts +61 -0
  44. package/id/index.mjs +56 -0
  45. package/index.cjs +218 -0
  46. package/index.d.ts +51 -0
  47. package/index.mjs +51 -0
  48. package/logger/index.cjs +334 -0
  49. package/logger/index.d.ts +213 -0
  50. package/logger/index.mjs +313 -0
  51. package/middleware/index.cjs +177 -0
  52. package/middleware/index.d.ts +127 -0
  53. package/middleware/index.mjs +170 -0
  54. package/obj/index.cjs +305 -0
  55. package/obj/index.d.ts +160 -0
  56. package/obj/index.mjs +289 -0
  57. package/package.json +172 -20
  58. package/performance/index.cjs +231 -0
  59. package/performance/index.d.ts +162 -0
  60. package/performance/index.mjs +225 -0
  61. package/request/index.cjs +202 -0
  62. package/request/index.d.ts +265 -0
  63. package/request/index.mjs +194 -0
  64. package/response/index.cjs +234 -0
  65. package/response/index.d.ts +342 -0
  66. package/response/index.mjs +222 -0
  67. package/server/index.cjs +1631 -0
  68. package/server/index.d.ts +809 -0
  69. package/server/index.mjs +1622 -0
  70. package/stream/index.cjs +151 -0
  71. package/stream/index.d.ts +114 -0
  72. package/stream/index.mjs +144 -0
  73. package/string/index.cjs +109 -0
  74. package/string/index.d.ts +126 -0
  75. package/string/index.mjs +95 -0
  76. package/type/index.cjs +129 -0
  77. package/type/index.d.ts +131 -0
  78. package/type/index.mjs +119 -0
  79. package/types/index.cjs +34 -0
  80. package/types/index.d.ts +798 -0
  81. package/types/index.mjs +32 -0
  82. package/url/index.cjs +199 -0
  83. package/url/index.d.ts +166 -0
  84. package/url/index.mjs +187 -0
  85. package/validation/index.cjs +259 -0
  86. package/validation/index.d.ts +209 -0
  87. package/validation/index.mjs +231 -0
  88. package/build/index.cjs +0 -7694
  89. package/build/index.d.ts +0 -5792
  90. package/build/index.mjs +0 -7386
@@ -0,0 +1,290 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ import { getCatbeeGlobalConfig } from '@catbee/utils/config';
26
+
27
+ var __defProp = Object.defineProperty;
28
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
29
+ var TTLCache = class {
30
+ static {
31
+ __name(this, "TTLCache");
32
+ }
33
+ cache = /* @__PURE__ */ new Map();
34
+ ttlMs;
35
+ maxSize;
36
+ cleanupInterval;
37
+ /**
38
+ * @param options - Configuration options for the cache
39
+ */
40
+ constructor(options = {}) {
41
+ this.ttlMs = options.ttlMs ?? getCatbeeGlobalConfig().cache.defaultTtl;
42
+ this.maxSize = options.maxSize;
43
+ const autoCleanupMs = options.autoCleanupMs;
44
+ if (autoCleanupMs && autoCleanupMs > 0) {
45
+ this.cleanupInterval = setInterval(() => {
46
+ this.cleanup();
47
+ }, autoCleanupMs);
48
+ }
49
+ }
50
+ /**
51
+ * Sets a key-value pair in the cache with the default TTL.
52
+ *
53
+ * @param key - The key to set.
54
+ * @param value - The value to associate with the key.
55
+ */
56
+ set(key, value) {
57
+ this.setWithTTL(key, value, this.ttlMs);
58
+ }
59
+ /**
60
+ * Sets a key-value pair in the cache with a custom TTL.
61
+ *
62
+ * @param key - The key to set.
63
+ * @param value - The value to associate with the key.
64
+ * @param ttlMs - Time-to-live in milliseconds.
65
+ */
66
+ setWithTTL(key, value, ttlMs) {
67
+ const now = Date.now();
68
+ const expiresAt = now + ttlMs;
69
+ if (this.cache.has(key)) {
70
+ this.cache.delete(key);
71
+ }
72
+ this.cache.set(key, {
73
+ value,
74
+ expiresAt,
75
+ lastAccessed: now
76
+ });
77
+ if (this.maxSize && this.cache.size > this.maxSize) {
78
+ this.evictLRU();
79
+ }
80
+ }
81
+ /**
82
+ * Retrieves the value for a given key if it hasn't expired.
83
+ *
84
+ * @param key - The key to retrieve.
85
+ * @returns The cached value, or undefined if not found or expired.
86
+ */
87
+ get(key) {
88
+ const entry = this.cache.get(key);
89
+ if (!entry) return void 0;
90
+ const now = Date.now();
91
+ if (now > entry.expiresAt) {
92
+ this.cache.delete(key);
93
+ return void 0;
94
+ }
95
+ entry.lastAccessed = now;
96
+ this.cache.delete(key);
97
+ this.cache.set(key, entry);
98
+ return entry.value;
99
+ }
100
+ /**
101
+ * Retrieves or computes a value if it's not in the cache or has expired.
102
+ *
103
+ * @param key - The key to retrieve
104
+ * @param producer - Function to generate the value if not cached
105
+ * @param ttlMs - Optional custom TTL for the computed value
106
+ * @returns The cached or computed value
107
+ */
108
+ async getOrCompute(key, producer, ttlMs) {
109
+ const value = this.get(key);
110
+ if (value !== void 0) return value;
111
+ const newValue = await producer();
112
+ this.setWithTTL(key, newValue, ttlMs ?? this.ttlMs);
113
+ return newValue;
114
+ }
115
+ /**
116
+ * Checks if the key exists and hasn't expired.
117
+ *
118
+ * @param key - The key to check.
119
+ * @returns `true` if key exists and is valid, otherwise `false`.
120
+ */
121
+ has(key) {
122
+ return this.get(key) !== void 0;
123
+ }
124
+ /**
125
+ * Deletes a key from the cache.
126
+ *
127
+ * @param key - The key to delete.
128
+ * @returns `true` if the key existed and was removed, `false` otherwise.
129
+ */
130
+ delete(key) {
131
+ return this.cache.delete(key);
132
+ }
133
+ /**
134
+ * Clears all entries from the cache.
135
+ */
136
+ clear() {
137
+ this.cache.clear();
138
+ }
139
+ /**
140
+ * Returns the number of entries currently in the cache (includes expired entries until next access/cleanup).
141
+ *
142
+ * @returns Number of items in the cache (may include expired keys).
143
+ */
144
+ size() {
145
+ return this.cache.size;
146
+ }
147
+ /**
148
+ * Set multiple key-value pairs at once with the default TTL.
149
+ *
150
+ * @param entries - Array of [key, value] tuples to set
151
+ */
152
+ setMany(entries) {
153
+ for (const [key, value] of entries) {
154
+ this.set(key, value);
155
+ }
156
+ }
157
+ /**
158
+ * Get multiple values at once.
159
+ *
160
+ * @param keys - Array of keys to retrieve
161
+ * @returns Array of values (undefined for keys that don't exist or expired)
162
+ */
163
+ getMany(keys) {
164
+ return keys.map((key) => this.get(key));
165
+ }
166
+ /**
167
+ * Removes all expired entries from the cache.
168
+ *
169
+ * @returns Number of entries removed.
170
+ */
171
+ cleanup() {
172
+ let removed = 0;
173
+ const now = Date.now();
174
+ for (const [key, entry] of this.cache.entries()) {
175
+ if (now > entry.expiresAt) {
176
+ this.cache.delete(key);
177
+ removed++;
178
+ }
179
+ }
180
+ return removed;
181
+ }
182
+ /**
183
+ * Returns an iterator of all current valid [key, value] pairs.
184
+ *
185
+ * @returns IterableIterator<[K, V]>
186
+ */
187
+ *entries() {
188
+ for (const [key, entry] of this.cache.entries()) {
189
+ if (Date.now() <= entry.expiresAt) {
190
+ yield [
191
+ key,
192
+ entry.value
193
+ ];
194
+ }
195
+ }
196
+ }
197
+ /**
198
+ * Returns an iterator of all current valid keys.
199
+ *
200
+ * @returns IterableIterator<K>
201
+ */
202
+ *keys() {
203
+ for (const [key, entry] of this.cache.entries()) {
204
+ if (Date.now() <= entry.expiresAt) {
205
+ yield key;
206
+ }
207
+ }
208
+ }
209
+ /**
210
+ * Returns an iterator of all current valid values.
211
+ *
212
+ * @returns IterableIterator<V>
213
+ */
214
+ *values() {
215
+ for (const entry of this.cache.values()) {
216
+ if (Date.now() <= entry.expiresAt) {
217
+ yield entry.value;
218
+ }
219
+ }
220
+ }
221
+ /**
222
+ * Extends the expiration of a key by the specified time or default TTL.
223
+ *
224
+ * @param key - The key to refresh
225
+ * @param ttlMs - Optional new TTL in milliseconds (uses default if not specified)
226
+ * @returns true if the key was found and refreshed, false otherwise
227
+ */
228
+ refresh(key, ttlMs) {
229
+ const entry = this.cache.get(key);
230
+ if (!entry) return false;
231
+ const now = Date.now();
232
+ if (now > entry.expiresAt) {
233
+ this.cache.delete(key);
234
+ return false;
235
+ }
236
+ entry.expiresAt = now + (ttlMs ?? this.ttlMs);
237
+ entry.lastAccessed = now;
238
+ return true;
239
+ }
240
+ /**
241
+ * Returns a snapshot of cache stats.
242
+ *
243
+ * @returns Object containing cache statistics
244
+ */
245
+ stats() {
246
+ const now = Date.now();
247
+ let expired = 0;
248
+ let valid = 0;
249
+ for (const entry of this.cache.values()) {
250
+ if (now > entry.expiresAt) {
251
+ expired++;
252
+ } else {
253
+ valid++;
254
+ }
255
+ }
256
+ return {
257
+ size: this.cache.size,
258
+ validEntries: valid,
259
+ expiredEntries: expired,
260
+ maxSize: this.maxSize
261
+ };
262
+ }
263
+ /**
264
+ * Stop the auto-cleanup interval if it's running.
265
+ */
266
+ destroy() {
267
+ if (this.cleanupInterval) {
268
+ clearInterval(this.cleanupInterval);
269
+ this.cleanupInterval = void 0;
270
+ }
271
+ }
272
+ /**
273
+ * Evict the least recently used entry from the cache.
274
+ * @private
275
+ */
276
+ evictLRU() {
277
+ const now = Date.now();
278
+ for (const [key, entry] of Array.from(this.cache.entries())) {
279
+ if (now > entry.expiresAt) {
280
+ this.cache.delete(key);
281
+ }
282
+ }
283
+ while (this.maxSize && this.cache.size > this.maxSize) {
284
+ const oldestKey = this.cache.keys().next().value;
285
+ this.cache.delete(oldestKey);
286
+ }
287
+ }
288
+ };
289
+
290
+ export { TTLCache };
@@ -0,0 +1,150 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ 'use strict';
26
+
27
+ var env = require('@catbee/utils/env');
28
+ var id = require('@catbee/utils/id');
29
+ var obj = require('@catbee/utils/obj');
30
+
31
+ var __defProp = Object.defineProperty;
32
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
33
+ var defaultServerConfig = {
34
+ port: env.Env.getNumber("SERVER_PORT", 0) || env.Env.getNumber("PORT", 3e3),
35
+ host: env.Env.get("SERVER_HOST", "") || env.Env.get("HOST", "0.0.0.0"),
36
+ cors: env.Env.getBoolean("SERVER_CORS_ENABLE", false) ? {} : false,
37
+ helmet: env.Env.getBoolean("SERVER_HELMET_ENABLE", false) ? {} : false,
38
+ compression: env.Env.getBoolean("SERVER_COMPRESSION_ENABLE", false) ? {} : false,
39
+ bodyParser: {
40
+ json: {
41
+ limit: env.Env.get("SERVER_BODY_PARSER_JSON_LIMIT", "1mb")
42
+ },
43
+ urlencoded: {
44
+ extended: true,
45
+ limit: env.Env.get("SERVER_BODY_PARSER_URLENCODED_LIMIT", "1mb")
46
+ }
47
+ },
48
+ cookieParser: env.Env.getBoolean("SERVER_COOKIE_PARSER_ENABLE", false) ? {} : false,
49
+ isMicroservice: env.Env.getBoolean("SERVER_IS_MICROSERVICE", false),
50
+ appName: env.Env.get("SERVER_APP_NAME", env.Env.get("npm_package_name", "catbee_server")),
51
+ globalHeaders: env.Env.getJSON("SERVER_GLOBAL_HEADERS", {}),
52
+ rateLimit: {
53
+ enable: env.Env.getBoolean("SERVER_RATE_LIMIT_ENABLE", false),
54
+ windowMs: env.Env.getDuration("SERVER_RATE_LIMIT_WINDOW_MS", 15 * 60 * 1e3),
55
+ max: env.Env.getNumber("SERVER_RATE_LIMIT_MAX", 100),
56
+ message: env.Env.get("SERVER_RATE_LIMIT_MESSAGE", "Too many requests, please try again later."),
57
+ standardHeaders: env.Env.getBoolean("SERVER_RATE_LIMIT_STANDARD_HEADERS", true),
58
+ legacyHeaders: env.Env.getBoolean("SERVER_RATE_LIMIT_LEGACY_HEADERS", false)
59
+ },
60
+ requestLogging: {
61
+ enable: env.Env.getBoolean("SERVER_REQUEST_LOGGING_ENABLE", env.Env.isDev()),
62
+ ignorePaths: /* @__PURE__ */ __name((req, _res) => {
63
+ const skipPaths = [
64
+ "/healthz",
65
+ "/favicon.ico",
66
+ "/metrics",
67
+ "/docs",
68
+ "/.well-known"
69
+ ];
70
+ return skipPaths.some((path) => req.path.startsWith(path));
71
+ }, "ignorePaths"),
72
+ skipNotFoundRoutes: env.Env.getBoolean("SERVER_REQUEST_LOGGING_SKIP_NOT_FOUND_ROUTES", true)
73
+ },
74
+ trustProxy: env.Env.getBoolean("SERVER_TRUST_PROXY_ENABLE", false),
75
+ openApi: {
76
+ enable: env.Env.getBoolean("SERVER_OPENAPI_ENABLE", false),
77
+ mountPath: env.Env.get("SERVER_OPENAPI_MOUNT_PATH", "/docs"),
78
+ verbose: env.Env.getBoolean("SERVER_OPENAPI_VERBOSE", false),
79
+ withGlobalPrefix: env.Env.getBoolean("SERVER_OPENAPI_WITH_GLOBAL_PREFIX", false)
80
+ },
81
+ healthCheck: {
82
+ path: env.Env.get("SERVER_HEALTH_CHECK_PATH", "/healthz"),
83
+ detailed: env.Env.getBoolean("SERVER_HEALTH_CHECK_DETAILED_OUTPUT", true),
84
+ withGlobalPrefix: env.Env.getBoolean("SERVER_HEALTH_CHECK_WITH_GLOBAL_PREFIX", false)
85
+ },
86
+ requestTimeout: env.Env.getDuration("SERVER_REQUEST_TIMEOUT_MS", 0),
87
+ responseTime: {
88
+ enable: env.Env.getBoolean("SERVER_RESPONSE_TIME_ENABLE", false),
89
+ addHeader: env.Env.getBoolean("SERVER_RESPONSE_TIME_ADD_HEADER", true),
90
+ logOnComplete: env.Env.getBoolean("SERVER_RESPONSE_TIME_LOG_ON_COMPLETE", false)
91
+ },
92
+ requestId: {
93
+ headerName: env.Env.get("SERVER_REQUEST_ID_HEADER_NAME", "x-request-id"),
94
+ exposeHeader: env.Env.getBoolean("SERVER_REQUEST_ID_EXPOSE_HEADER", true),
95
+ generator: /* @__PURE__ */ __name(() => id.uuid(), "generator")
96
+ },
97
+ metrics: {
98
+ enable: env.Env.getBoolean("SERVER_METRICS_ENABLE", false),
99
+ path: env.Env.get("SERVER_METRICS_PATH", "/metrics"),
100
+ withGlobalPrefix: env.Env.getBoolean("SERVER_METRICS_WITH_GLOBAL_PREFIX", false)
101
+ },
102
+ serviceVersion: {
103
+ enable: env.Env.getBoolean("SERVER_SERVICE_VERSION_ENABLE", false),
104
+ headerName: env.Env.get("SERVER_SERVICE_VERSION_HEADER_NAME", "x-service-version"),
105
+ version: env.Env.get("SERVER_SERVICE_VERSION", "0.0.0")
106
+ },
107
+ skipHealthz: env.Env.getBoolean("SERVER_SKIP_HEALTHZ", false)
108
+ };
109
+ var defaultCatbeeConfig = {
110
+ logger: {
111
+ level: env.Env.get("LOGGER_LEVEL", env.Env.isDev() || env.Env.isTest() ? "debug" : "info"),
112
+ name: env.Env.get("LOGGER_NAME", env.Env.get("npm_package_name", "@catbee/utils")),
113
+ pretty: env.Env.getBoolean("LOGGER_PRETTY", false),
114
+ colorize: env.Env.getBoolean("LOGGER_PRETTY_COLORIZE", true),
115
+ singleLine: env.Env.getBoolean("LOGGER_PRETTY_SINGLE_LINE", false),
116
+ dir: env.Env.getPath("LOGGER_DIR", "", {
117
+ mustExist: false
118
+ })
119
+ },
120
+ cache: {
121
+ defaultTtl: env.Env.getNumber("CACHE_DEFAULT_TTL_SECONDS", 3600) * 1e3
122
+ },
123
+ server: defaultServerConfig
124
+ };
125
+ var _config = obj.deepClone(defaultCatbeeConfig);
126
+ function getCatbeeGlobalConfig() {
127
+ return obj.deepClone(_config);
128
+ }
129
+ __name(getCatbeeGlobalConfig, "getCatbeeGlobalConfig");
130
+ var getConfig = getCatbeeGlobalConfig;
131
+ function setCatbeeGlobalConfig(value) {
132
+ _config = obj.deepObjMerge(_config, value);
133
+ }
134
+ __name(setCatbeeGlobalConfig, "setCatbeeGlobalConfig");
135
+ var setConfig = setCatbeeGlobalConfig;
136
+ function setCatbeeServerGlobalConfig(value) {
137
+ _config.server = obj.deepObjMerge(_config.server, value);
138
+ }
139
+ __name(setCatbeeServerGlobalConfig, "setCatbeeServerGlobalConfig");
140
+ function getCatbeeServerGlobalConfig() {
141
+ return getCatbeeGlobalConfig().server;
142
+ }
143
+ __name(getCatbeeServerGlobalConfig, "getCatbeeServerGlobalConfig");
144
+
145
+ exports.getCatbeeGlobalConfig = getCatbeeGlobalConfig;
146
+ exports.getCatbeeServerGlobalConfig = getCatbeeServerGlobalConfig;
147
+ exports.getConfig = getConfig;
148
+ exports.setCatbeeGlobalConfig = setCatbeeGlobalConfig;
149
+ exports.setCatbeeServerGlobalConfig = setCatbeeServerGlobalConfig;
150
+ exports.setConfig = setConfig;
@@ -0,0 +1,88 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ import { CatbeeConfig, CatbeeGlobalServerConfig } from '@catbee/utils/types';
26
+ import { Logger } from '@catbee/utils/logger';
27
+
28
+ /**
29
+ * Extends Express Request interface to add request ID tracking.
30
+ * Added by requestId middleware during request processing.
31
+ */
32
+ declare global {
33
+ namespace Express {
34
+ interface Request {
35
+ /** Unique request identifier (set by middleware) */
36
+ id?: string;
37
+ /** Logger instance for the request (set by middleware) */
38
+ logger?: Logger;
39
+ /** User information (set by authentication middleware) */
40
+ user?: any;
41
+ }
42
+ }
43
+ }
44
+ /**
45
+ * Gets the global Catbee configuration.
46
+ *
47
+ * @returns The current Catbee configuration.
48
+ */
49
+ declare function getCatbeeGlobalConfig(): CatbeeConfig;
50
+ /**
51
+ * Gets the global Catbee configuration.
52
+ *
53
+ * @deprecated Use `getCatbeeGlobalConfig` from `@catbee/utils/config` instead.
54
+ * @alias getCatbeeGlobalConfig
55
+ * @returns The current Catbee configuration.
56
+ */
57
+ declare const getConfig: typeof getCatbeeGlobalConfig;
58
+ /**
59
+ * Sets the global Catbee configuration.
60
+ * Merges the provided partial configuration with the existing one.
61
+ *
62
+ * @param value - Partial Catbee configuration to set
63
+ */
64
+ declare function setCatbeeGlobalConfig(value: Partial<CatbeeConfig>): void;
65
+ /**
66
+ * Sets the global Catbee configuration.
67
+ * Merges the provided partial configuration with the existing one.
68
+ *
69
+ * @deprecated Use `setCatbeeGlobalConfig` from `@catbee/utils/config` instead.
70
+ * @alias setCatbeeGlobalConfig
71
+ * @param value - Partial Catbee configuration to set
72
+ */
73
+ declare const setConfig: typeof setCatbeeGlobalConfig;
74
+ /**
75
+ * Sets the global Catbee server configuration.
76
+ * Merges the provided partial server configuration with the existing one.
77
+ *
78
+ * @param value - Partial Catbee server configuration to set
79
+ */
80
+ declare function setCatbeeServerGlobalConfig(value: Partial<CatbeeGlobalServerConfig>): void;
81
+ /**
82
+ * Gets the global Catbee server configuration.
83
+ *
84
+ * @returns The current Catbee server configuration.
85
+ */
86
+ declare function getCatbeeServerGlobalConfig(): CatbeeGlobalServerConfig;
87
+
88
+ export { getCatbeeGlobalConfig, getCatbeeServerGlobalConfig, getConfig, setCatbeeGlobalConfig, setCatbeeServerGlobalConfig, setConfig };
@@ -0,0 +1,143 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies. https://catbee.in/license
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
24
+
25
+ import { Env } from '@catbee/utils/env';
26
+ import { uuid } from '@catbee/utils/id';
27
+ import { deepClone, deepObjMerge } from '@catbee/utils/obj';
28
+
29
+ var __defProp = Object.defineProperty;
30
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
31
+ var defaultServerConfig = {
32
+ port: Env.getNumber("SERVER_PORT", 0) || Env.getNumber("PORT", 3e3),
33
+ host: Env.get("SERVER_HOST", "") || Env.get("HOST", "0.0.0.0"),
34
+ cors: Env.getBoolean("SERVER_CORS_ENABLE", false) ? {} : false,
35
+ helmet: Env.getBoolean("SERVER_HELMET_ENABLE", false) ? {} : false,
36
+ compression: Env.getBoolean("SERVER_COMPRESSION_ENABLE", false) ? {} : false,
37
+ bodyParser: {
38
+ json: {
39
+ limit: Env.get("SERVER_BODY_PARSER_JSON_LIMIT", "1mb")
40
+ },
41
+ urlencoded: {
42
+ extended: true,
43
+ limit: Env.get("SERVER_BODY_PARSER_URLENCODED_LIMIT", "1mb")
44
+ }
45
+ },
46
+ cookieParser: Env.getBoolean("SERVER_COOKIE_PARSER_ENABLE", false) ? {} : false,
47
+ isMicroservice: Env.getBoolean("SERVER_IS_MICROSERVICE", false),
48
+ appName: Env.get("SERVER_APP_NAME", Env.get("npm_package_name", "catbee_server")),
49
+ globalHeaders: Env.getJSON("SERVER_GLOBAL_HEADERS", {}),
50
+ rateLimit: {
51
+ enable: Env.getBoolean("SERVER_RATE_LIMIT_ENABLE", false),
52
+ windowMs: Env.getDuration("SERVER_RATE_LIMIT_WINDOW_MS", 15 * 60 * 1e3),
53
+ max: Env.getNumber("SERVER_RATE_LIMIT_MAX", 100),
54
+ message: Env.get("SERVER_RATE_LIMIT_MESSAGE", "Too many requests, please try again later."),
55
+ standardHeaders: Env.getBoolean("SERVER_RATE_LIMIT_STANDARD_HEADERS", true),
56
+ legacyHeaders: Env.getBoolean("SERVER_RATE_LIMIT_LEGACY_HEADERS", false)
57
+ },
58
+ requestLogging: {
59
+ enable: Env.getBoolean("SERVER_REQUEST_LOGGING_ENABLE", Env.isDev()),
60
+ ignorePaths: /* @__PURE__ */ __name((req, _res) => {
61
+ const skipPaths = [
62
+ "/healthz",
63
+ "/favicon.ico",
64
+ "/metrics",
65
+ "/docs",
66
+ "/.well-known"
67
+ ];
68
+ return skipPaths.some((path) => req.path.startsWith(path));
69
+ }, "ignorePaths"),
70
+ skipNotFoundRoutes: Env.getBoolean("SERVER_REQUEST_LOGGING_SKIP_NOT_FOUND_ROUTES", true)
71
+ },
72
+ trustProxy: Env.getBoolean("SERVER_TRUST_PROXY_ENABLE", false),
73
+ openApi: {
74
+ enable: Env.getBoolean("SERVER_OPENAPI_ENABLE", false),
75
+ mountPath: Env.get("SERVER_OPENAPI_MOUNT_PATH", "/docs"),
76
+ verbose: Env.getBoolean("SERVER_OPENAPI_VERBOSE", false),
77
+ withGlobalPrefix: Env.getBoolean("SERVER_OPENAPI_WITH_GLOBAL_PREFIX", false)
78
+ },
79
+ healthCheck: {
80
+ path: Env.get("SERVER_HEALTH_CHECK_PATH", "/healthz"),
81
+ detailed: Env.getBoolean("SERVER_HEALTH_CHECK_DETAILED_OUTPUT", true),
82
+ withGlobalPrefix: Env.getBoolean("SERVER_HEALTH_CHECK_WITH_GLOBAL_PREFIX", false)
83
+ },
84
+ requestTimeout: Env.getDuration("SERVER_REQUEST_TIMEOUT_MS", 0),
85
+ responseTime: {
86
+ enable: Env.getBoolean("SERVER_RESPONSE_TIME_ENABLE", false),
87
+ addHeader: Env.getBoolean("SERVER_RESPONSE_TIME_ADD_HEADER", true),
88
+ logOnComplete: Env.getBoolean("SERVER_RESPONSE_TIME_LOG_ON_COMPLETE", false)
89
+ },
90
+ requestId: {
91
+ headerName: Env.get("SERVER_REQUEST_ID_HEADER_NAME", "x-request-id"),
92
+ exposeHeader: Env.getBoolean("SERVER_REQUEST_ID_EXPOSE_HEADER", true),
93
+ generator: /* @__PURE__ */ __name(() => uuid(), "generator")
94
+ },
95
+ metrics: {
96
+ enable: Env.getBoolean("SERVER_METRICS_ENABLE", false),
97
+ path: Env.get("SERVER_METRICS_PATH", "/metrics"),
98
+ withGlobalPrefix: Env.getBoolean("SERVER_METRICS_WITH_GLOBAL_PREFIX", false)
99
+ },
100
+ serviceVersion: {
101
+ enable: Env.getBoolean("SERVER_SERVICE_VERSION_ENABLE", false),
102
+ headerName: Env.get("SERVER_SERVICE_VERSION_HEADER_NAME", "x-service-version"),
103
+ version: Env.get("SERVER_SERVICE_VERSION", "0.0.0")
104
+ },
105
+ skipHealthz: Env.getBoolean("SERVER_SKIP_HEALTHZ", false)
106
+ };
107
+ var defaultCatbeeConfig = {
108
+ logger: {
109
+ level: Env.get("LOGGER_LEVEL", Env.isDev() || Env.isTest() ? "debug" : "info"),
110
+ name: Env.get("LOGGER_NAME", Env.get("npm_package_name", "@catbee/utils")),
111
+ pretty: Env.getBoolean("LOGGER_PRETTY", false),
112
+ colorize: Env.getBoolean("LOGGER_PRETTY_COLORIZE", true),
113
+ singleLine: Env.getBoolean("LOGGER_PRETTY_SINGLE_LINE", false),
114
+ dir: Env.getPath("LOGGER_DIR", "", {
115
+ mustExist: false
116
+ })
117
+ },
118
+ cache: {
119
+ defaultTtl: Env.getNumber("CACHE_DEFAULT_TTL_SECONDS", 3600) * 1e3
120
+ },
121
+ server: defaultServerConfig
122
+ };
123
+ var _config = deepClone(defaultCatbeeConfig);
124
+ function getCatbeeGlobalConfig() {
125
+ return deepClone(_config);
126
+ }
127
+ __name(getCatbeeGlobalConfig, "getCatbeeGlobalConfig");
128
+ var getConfig = getCatbeeGlobalConfig;
129
+ function setCatbeeGlobalConfig(value) {
130
+ _config = deepObjMerge(_config, value);
131
+ }
132
+ __name(setCatbeeGlobalConfig, "setCatbeeGlobalConfig");
133
+ var setConfig = setCatbeeGlobalConfig;
134
+ function setCatbeeServerGlobalConfig(value) {
135
+ _config.server = deepObjMerge(_config.server, value);
136
+ }
137
+ __name(setCatbeeServerGlobalConfig, "setCatbeeServerGlobalConfig");
138
+ function getCatbeeServerGlobalConfig() {
139
+ return getCatbeeGlobalConfig().server;
140
+ }
141
+ __name(getCatbeeServerGlobalConfig, "getCatbeeServerGlobalConfig");
142
+
143
+ export { getCatbeeGlobalConfig, getCatbeeServerGlobalConfig, getConfig, setCatbeeGlobalConfig, setCatbeeServerGlobalConfig, setConfig };