topsyde-utils 1.0.7 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,1039 +1,83 @@
1
- var __create = Object.create;
2
- var __getProtoOf = Object.getPrototypeOf;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __toESM = (mod, isNodeMode, target) => {
8
- target = mod != null ? __create(__getProtoOf(mod)) : {};
9
- const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
10
- for (let key of __getOwnPropNames(mod))
11
- if (!__hasOwnProp.call(to, key))
12
- __defProp(to, key, {
13
- get: () => mod[key],
14
- enumerable: true
15
- });
16
- return to;
17
- };
18
- var __moduleCache = /* @__PURE__ */ new WeakMap;
19
- var __toCommonJS = (from) => {
20
- var entry = __moduleCache.get(from), desc;
21
- if (entry)
22
- return entry;
23
- entry = __defProp({}, "__esModule", { value: true });
24
- if (from && typeof from === "object" || typeof from === "function")
25
- __getOwnPropNames(from).map((key) => !__hasOwnProp.call(entry, key) && __defProp(entry, key, {
26
- get: () => from[key],
27
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
28
- }));
29
- __moduleCache.set(from, entry);
30
- return entry;
31
- };
32
- var __export = (target, all) => {
33
- for (var name in all)
34
- __defProp(target, name, {
35
- get: all[name],
36
- enumerable: true,
37
- configurable: true,
38
- set: (newValue) => all[name] = () => newValue
39
- });
40
- };
41
-
42
- // src/index.ts
43
- var exports_src = {};
44
- __export(exports_src, {
45
- WS_ERROR_CODE: () => WS_ERROR_CODE,
46
- Throwable: () => throwable_default,
47
- Singleton: () => singleton_default,
48
- ServerController: () => Controller,
49
- Server: () => exports_server,
50
- RouterRouter_internal: () => router_internal_default,
51
- RouterRouter: () => router_default,
52
- Router: () => exports_router,
53
- RESPONSE_METHOD_OPTIONS: () => RESPONSE_METHOD_OPTIONS,
54
- RESPONSE_INIT: () => RESPONSE_INIT,
55
- Lib: () => lib_default,
56
- LOG_COLORS: () => LOG_COLORS,
57
- Initializable: () => initializable_default,
58
- HTTP_ERROR_CODE: () => HTTP_ERROR_CODE,
59
- Guards: () => guards_default,
60
- E_IS: () => E_IS,
61
- E_ENVIRONMENTS: () => E_ENVIRONMENTS,
62
- ERROR_CODE: () => ERROR_CODE,
63
- DEFAULT_FALSE_RESPONSE: () => DEFAULT_FALSE_RESPONSE,
64
- Application: () => application_default
1
+ "use strict";
2
+ // This file is auto-generated by scripts/generate-indexes.sh
3
+ // Do not edit this file directly
4
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5
+ if (k2 === undefined) k2 = k;
6
+ var desc = Object.getOwnPropertyDescriptor(m, k);
7
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
8
+ desc = { enumerable: true, get: function() { return m[k]; } };
9
+ }
10
+ Object.defineProperty(o, k2, desc);
11
+ }) : (function(o, m, k, k2) {
12
+ if (k2 === undefined) k2 = k;
13
+ o[k2] = m[k];
14
+ }));
15
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
16
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
17
+ }) : function(o, v) {
18
+ o["default"] = v;
65
19
  });
66
- module.exports = __toCommonJS(exports_src);
67
-
68
- // src/application.ts
69
- var RESPONSE_INIT = (status, headers) => {
70
- return {
71
- status: status ?? 200,
72
- headers: {
73
- "Content-Type": "application/json",
74
- "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
75
- "Access-Control-Allow-Headers": "Content-Type, Authorization",
76
- "Access-Control-Allow-Credentials": "true"
77
- }
78
- };
79
- };
80
- var RESPONSE_METHOD_OPTIONS = {
81
- name: "Access-Control-Max-Age",
82
- value: "86400"
83
- };
84
-
85
- class Application {
86
- static Response(data, status = 200, headers) {
87
- const response = {
88
- status: true,
89
- data
20
+ var __importStar = (this && this.__importStar) || (function () {
21
+ var ownKeys = function(o) {
22
+ ownKeys = Object.getOwnPropertyNames || function (o) {
23
+ var ar = [];
24
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
25
+ return ar;
26
+ };
27
+ return ownKeys(o);
90
28
  };
91
- return Response.json(response, RESPONSE_INIT(status, headers));
92
- }
93
- static Error(error, status = 200, headers) {
94
- const response = {
95
- status: false,
96
- data: error,
97
- error
29
+ return function (mod) {
30
+ if (mod && mod.__esModule) return mod;
31
+ var result = {};
32
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
33
+ __setModuleDefault(result, mod);
34
+ return result;
98
35
  };
99
- return Response.json(response, RESPONSE_INIT(status, headers));
100
- }
101
- static Throw(error, status = 400, headers) {
102
- return Response.json(error, RESPONSE_INIT(status, headers));
103
- }
104
- }
105
- var application_default = Application;
106
- // src/lib.ts
107
- var fs = __toESM(require("fs"));
108
- var path = __toESM(require("path"));
109
-
110
- // src/enums.ts
111
- var E_IS;
112
- ((E_IS2) => {
113
- E_IS2["ARRAY"] = "array";
114
- E_IS2["OBJECT"] = "object";
115
- E_IS2["FUNCTION"] = "function";
116
- E_IS2["STRING"] = "string";
117
- E_IS2["NUMBER"] = "number";
118
- E_IS2["BOOLEAN"] = "boolean";
119
- E_IS2["REGEX"] = "regex";
120
- })(E_IS ||= {});
121
- var E_ENVIRONMENTS;
122
- ((E_ENVIRONMENTS2) => {
123
- E_ENVIRONMENTS2["DEV"] = "development";
124
- E_ENVIRONMENTS2["PROD"] = "production";
125
- })(E_ENVIRONMENTS ||= {});
126
-
127
- // src/throwable.ts
128
- class Throwable extends Error {
129
- isDeliberate = true;
130
- originalError;
131
- context;
132
- constructor(message, options = {}) {
133
- const { logError = true, context } = options;
134
- const _message = guards_default.IsString(message) ? message : message instanceof Error ? message.message : JSON.stringify(message);
135
- super(_message);
136
- this.name = "Throwable";
137
- this.context = context;
138
- if (logError) {
139
- if (context) {
140
- lib_default.$Log("Throwable: ", _message, "Context:", context);
141
- } else {
142
- lib_default.$Log("Throwable: ", message);
143
- }
144
- }
145
- if (message instanceof Error) {
146
- this.stack = message.stack;
147
- this.cause = message.cause;
148
- this.originalError = message;
149
- }
150
- }
151
- static IsThrowable(e) {
152
- return e instanceof Throwable;
153
- }
154
- static from(error, context) {
155
- if (error instanceof Throwable) {
156
- return error;
157
- }
158
- return new Throwable(error, { context });
159
- }
160
- }
161
- var throwable_default = Throwable;
162
-
163
- // src/lib.ts
164
- var __dirname = "/Volumes/dev/Repositories/topsyde_utils/src";
165
-
166
- class Lib {
167
- static Log(...args) {
168
- const timestamp = new Date().toLocaleTimeString();
169
- console.log(`[${timestamp}]:`, ...args);
170
- }
171
- static LogObject(object, text) {
172
- const timestamp = new Date().toLocaleTimeString();
173
- console.log(`[${timestamp}]:`, text ?? "", JSON.stringify(object, null, 2));
174
- }
175
- static Warn(...args) {
176
- const timestamp = new Date().toLocaleTimeString();
177
- console.error(`[${timestamp}] Handled Error: `, ...args);
178
- }
179
- static $Log(...args) {
180
- const timestamp = new Date().toLocaleTimeString();
181
- console.error(`[${timestamp}]`, ...args);
182
- }
183
- static secondsToMilliseconds(seconds) {
184
- return seconds * 1000;
185
- }
186
- static minutesToMilliseconds(minutes) {
187
- return minutes * 60 * 1000;
188
- }
189
- static hoursToMilliseconds(hours) {
190
- return hours * 60 * 60 * 1000;
191
- }
192
- static GetTimestamp(milliseconds_ago) {
193
- const now = new Date;
194
- return new Date(now.getTime() - milliseconds_ago);
195
- }
196
- static GetDateTimestamp(date, format = "DD/MM/YYYY HH:mm", isUTC = false) {
197
- if (typeof date === "string") {
198
- const formatParts = format.split(/[-\/. :]/);
199
- const dateParts = date.split(/[-\/. :]/);
200
- let day;
201
- let month;
202
- let year;
203
- let hours = 0;
204
- let minutes = 0;
205
- formatParts.forEach((part, index) => {
206
- switch (part) {
207
- case "DD":
208
- case "dd":
209
- day = parseInt(dateParts[index], 10);
210
- break;
211
- case "MM":
212
- month = parseInt(dateParts[index], 10) - 1;
213
- break;
214
- case "YYYY":
215
- case "yyyy":
216
- year = parseInt(dateParts[index], 10);
217
- break;
218
- case "HH":
219
- case "hh":
220
- hours = parseInt(dateParts[index], 10);
221
- break;
222
- case "mm":
223
- minutes = parseInt(dateParts[index], 10);
224
- break;
225
- }
226
- });
227
- if (day === undefined || month === undefined || year === undefined) {
228
- throw new Error("Invalid date format or date string");
229
- }
230
- let dateObj;
231
- if (isUTC) {
232
- dateObj = new Date(Date.UTC(year, month, day, hours, minutes));
233
- } else {
234
- dateObj = new Date(year, month, day, hours, minutes);
235
- }
236
- return dateObj.getTime();
237
- } else {
238
- return date.getTime();
239
- }
240
- }
241
- static calculatePercentage(x, y) {
242
- if (y === 0) {
243
- throw new Error("The denominator (y) cannot be zero.");
244
- }
245
- return x / y;
246
- }
247
- static MYSQLTimestamp() {
248
- const now = new Date;
249
- const year = now.getFullYear();
250
- const month = now.getMonth() + 1;
251
- const day = now.getDate();
252
- const hours = now.getHours();
253
- const minutes = now.getMinutes();
254
- const seconds = now.getSeconds();
255
- const formattedDate = `${year}-${month.toString().padStart(2, "0")}-${day.toString().padStart(2, "0")}`;
256
- const formattedTime = `${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
257
- return `${formattedDate} ${formattedTime}`;
258
- }
259
- static FormatUnixToDate(unix_time_stamp, in_milliseconds = false) {
260
- const date = new Date(unix_time_stamp * (in_milliseconds ? 1 : 1000));
261
- return date;
262
- }
263
- static FormatDate(date, format = "MM/dd/yyyy") {
264
- try {
265
- const leadingZero = (value) => value < 10 ? `0${value}` : `${value}`;
266
- if (!date)
267
- throw new Error("Lib.FormatDate() Exception: Date is required");
268
- if (typeof date === "string") {
269
- date = new Date(date);
270
- }
271
- const day = leadingZero(date.getDate());
272
- const month = leadingZero(date.getMonth() + 1);
273
- const year = date.getFullYear();
274
- const hours = leadingZero(date.getHours());
275
- const minutes = leadingZero(date.getMinutes());
276
- const seconds = leadingZero(date.getSeconds());
277
- let result = format.replace(/DD|dd/g, day).replace(/MM/g, month).replace(/yyyy|YYYY/g, year.toString());
278
- if (format.includes("HH")) {
279
- result = result.replace(/HH/g, hours);
280
- }
281
- if (format.toLowerCase().includes("mm")) {
282
- result = result.replace(/mm/g, minutes);
283
- }
284
- if (format.includes("ss")) {
285
- result = result.replace(/ss/g, seconds);
286
- }
287
- return result;
288
- } catch (e) {
289
- throw e;
290
- }
291
- }
292
- static DaysBetweenDates(startDate, endDate, format = "MM/dd/yyyy") {
293
- if (startDate === null || startDate === undefined || endDate === null || endDate === undefined) {
294
- throw new Error("Lib.DaysBetweenDates() Exception: Dates are required" + startDate + " " + endDate);
295
- }
296
- const start = new Date(this.FormatDate(startDate, format)).getTime();
297
- const end = new Date(this.FormatDate(endDate, format)).getTime();
298
- const difference = end - start;
299
- const daysPassed = difference / (1000 * 3600 * 24);
300
- return Math.floor(daysPassed);
301
- }
302
- static IsPastDate(date, format = "MM/dd/yyyy HH:mm:ss", debug = false, currentDate) {
303
- const truncateToSecond = (d) => new Date(Math.floor(d.getTime() / 1000) * 1000);
304
- const now = truncateToSecond(currentDate ? typeof currentDate === "string" ? new Date(currentDate) : currentDate : new Date);
305
- const check = truncateToSecond(typeof date === "string" ? new Date(date) : date);
306
- if (debug) {
307
- Debug.Log("Now:", this.FormatDate(now, format));
308
- Debug.Log("Check:", this.FormatDate(check, format));
309
- }
310
- return now.getTime() > check.getTime();
311
- }
312
- static IsPastDateFrom(date, from, format = "MM/dd/yyyy") {
313
- const now = this.FormatDate(from, format);
314
- const check = this.FormatDate(date, format);
315
- return new Date(now).getTime() > new Date(check).getTime();
316
- }
317
- static addTimeFromDate(date, milliseconds) {
318
- const dateObj = new Date(typeof date === "string" ? new Date(date).getTime() : date.getTime() + milliseconds);
319
- return dateObj;
320
- }
321
- static UUID(minLength = 36) {
322
- const template = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
323
- let uuid = template.replace(/[xy]/g, function(c) {
324
- var r = Math.random() * 16 | 0, v = c === "x" ? r : r & 3 | 8;
325
- return v.toString(16);
326
- });
327
- while (uuid.length < minLength) {
328
- uuid += (Math.random() * 16 | 0).toString(16);
329
- }
330
- return uuid.substring(0, minLength);
331
- }
332
- static Debounce(callback, delay = 500) {
333
- let timeout;
334
- return (...args) => {
335
- clearTimeout(timeout);
336
- timeout = setTimeout(() => {
337
- return callback(...args);
338
- }, delay);
339
- };
340
- }
341
- static IsNil(value) {
342
- return value === null || value === undefined;
343
- }
344
- static IsPrimitive(value) {
345
- return this.IsNumber(value) || this.IsString(value) || this.IsBoolean(value);
346
- }
347
- static EmptyObject(value) {
348
- let empty_object = true;
349
- if (this.GetType(value) !== "object") {
350
- empty_object = false;
351
- return empty_object;
352
- }
353
- if (Object.keys(value).length === 0) {
354
- empty_object = true;
355
- return empty_object;
356
- }
357
- for (let k in value) {
358
- if (!this.IsNil(value[k]) && value[k] !== "") {
359
- empty_object = false;
360
- }
361
- }
362
- return empty_object;
363
- }
364
- static IsNumpty(value, _objectsOnly = false) {
365
- return typeof value === "number" ? false : this.IsNil(value) || this.IsEmpty(value, _objectsOnly);
366
- }
367
- static IsEmpty(value, _objectsOnly = false) {
368
- return this.GetType(value) === "array" && value.length === 0 && !_objectsOnly || this.GetType(value) === "object" && this.EmptyObject(value) || typeof value === "string" && value.trim().length === 0;
369
- }
370
- static IsArray(variable) {
371
- return this.GetType(variable) === "array" /* ARRAY */;
372
- }
373
- static IsString(variable) {
374
- return this.GetType(variable) === "string" /* STRING */;
375
- }
376
- static IsNumber(variable) {
377
- return this.GetType(variable) === "number" /* NUMBER */;
378
- }
379
- static IsObject(variable) {
380
- return this.GetType(variable) === "object" /* OBJECT */;
381
- }
382
- static IsFunction(variable) {
383
- return this.GetType(variable) === "function" /* FUNCTION */;
384
- }
385
- static IsRegex(variable) {
386
- return this.GetType(variable) === "regex" /* REGEX */;
387
- }
388
- static IsBoolean(variable) {
389
- return this.GetType(variable, true) === "boolean" /* BOOLEAN */;
390
- }
391
- static GetType(value, asTypeOf = false) {
392
- if (asTypeOf) {
393
- return typeof value;
394
- }
395
- if (value === "0" || value === "1") {
396
- return "number";
397
- }
398
- if (value === true) {
399
- return true;
400
- } else if (value === false) {
401
- return false;
402
- } else if (value === null || value === undefined) {
403
- return null;
404
- } else if (Array.isArray(value)) {
405
- return "array";
406
- } else if (value instanceof RegExp) {
407
- return "regex";
408
- } else if (!isNaN(Number(value))) {
409
- return "number";
410
- } else if (typeof value === "string") {
411
- return "string";
412
- } else if ({}.toString.call(value) === "[object Function]" || typeof value === "function") {
413
- return "function";
414
- } else {
415
- return "object";
416
- }
417
- }
418
- static GetProjectRoot(startDir = __dirname, rootReference = "package.json") {
419
- let currentDir = startDir;
420
- while (!fs.existsSync(path.join(currentDir, rootReference))) {
421
- const parentDir = path.resolve(currentDir, "..");
422
- if (parentDir === currentDir) {
423
- throw new Error("Unable to find project root");
424
- }
425
- currentDir = parentDir;
426
- }
427
- return currentDir;
428
- }
429
- static async RunTaskWithTimeout(task, timeout) {
430
- return Promise.race([task(), new Promise((_, reject) => setTimeout(() => reject(new Error("Task timed out")), timeout))]);
431
- }
432
- static GetFolderPath(folder) {
433
- return path.join(this.GetProjectRoot(), folder);
434
- }
435
- static GetFilePath(folder, file) {
436
- return path.join(this.GetFolderPath(folder), file);
437
- }
438
- static async CreateDirectory(folderToCreate) {
439
- const directoryPath = Lib.GetFolderPath(folderToCreate);
440
- await fs.promises.access(directoryPath, fs.constants.F_OK).catch(async () => {
441
- await fs.promises.mkdir(directoryPath, { recursive: true });
442
- });
443
- return directoryPath;
444
- }
445
- static async DeleteDirectory(folderToDelete) {
446
- const directoryPath = path.join(this.GetProjectRoot(), folderToDelete);
447
- await fs.promises.rm(directoryPath, { recursive: true, force: true });
448
- }
449
- static async CreateFile(folderPath, filePath, content) {
450
- await Lib.CreateDirectory(folderPath);
451
- const file = Lib.GetFilePath(folderPath, filePath);
452
- await fs.promises.writeFile(file, content, "utf8");
453
- }
454
- static GetFile(filePathFromRoot) {
455
- return fs.createReadStream(filePathFromRoot);
456
- }
457
- static GetFilesInDirectory(directoryPath) {
458
- return fs.readdirSync(directoryPath);
459
- }
460
- static async DeleteFile(filePathFromRoot) {
461
- await fs.promises.unlink(filePathFromRoot);
462
- }
463
- static Timestamp(log = false) {
464
- const currentTime = new Date().toLocaleTimeString();
465
- if (log)
466
- console.log(`[${currentTime}]`);
467
- return currentTime;
468
- }
469
- static RemoveWhitespace(value) {
470
- return value.replace(/\s/g, "");
471
- }
472
- static msToString(ms) {
473
- if (ms === 0)
474
- return "0ms";
475
- const seconds = Math.floor(ms / 1000);
476
- const minutes = Math.floor(seconds / 60);
477
- const hours = Math.floor(minutes / 60);
478
- let output = hours > 0 ? `${hours}h ` : "";
479
- output += minutes > 0 ? `${minutes % 60}m ` : "";
480
- output += seconds % 60 > 0 ? `${seconds % 60}s ` : "";
481
- output += ms % 1000 > 0 ? `${(ms % 1000).toFixed(2)}ms` : "";
482
- return output.trim();
483
- }
484
- static FormatPhone(phone_number) {
485
- let output = phone_number;
486
- output = output.replace(/\D/g, "");
487
- if (!output.startsWith("+")) {
488
- output = `+${output}`;
489
- }
490
- return output;
491
- }
492
- static ToMB(bytes, as_KB = true, decimalPlaces = 2) {
493
- const kb = bytes / 1024;
494
- return (as_KB ? kb : kb / 1024).toFixed(decimalPlaces);
495
- }
496
- static ToGB(bytes, as_KB = true, decimalPlaces = 2) {
497
- const mb = this.ToMB(bytes, as_KB, decimalPlaces);
498
- return (parseInt(mb) / 1024).toFixed(decimalPlaces);
499
- }
500
- static async RetryHandler(func, retries = 3, ...args) {
501
- let attempts = 0;
502
- let toThrow;
503
- while (attempts < retries) {
504
- try {
505
- return await func(...args);
506
- } catch (e) {
507
- attempts++;
508
- toThrow = e;
509
- if (attempts <= retries && !throwable_default.IsThrowable(e)) {
510
- Lib.$Log(`Attempt ${attempts} failed. Retrying...(${func.name})`);
511
- if (attempts == 1)
512
- Lib.Warn(toThrow);
513
- await new Promise((resolve2) => setTimeout(resolve2, 1000));
514
- }
515
- }
516
- }
517
- throw toThrow;
518
- }
519
- static Difference(x, y) {
520
- return x.filter((x2) => !y.includes(x2));
521
- }
522
- static async ReadFileContent(filePath) {
523
- return fs.promises.readFile(filePath, "utf8");
524
- }
525
- static async measureExecutionTime(func, ...args) {
526
- const start = performance.now();
527
- const result = await func(...args);
528
- const end = performance.now();
529
- return { result, time: this.msToString(end - start) };
530
- }
531
- static ToCamelCase(str) {
532
- return str.replace(/(?:^\w|[A-Z]|\b\w)/g, (word, index) => index === 0 ? word.toLowerCase() : word.toUpperCase()).replace(/\s+/g, "");
533
- }
534
- static ToSnakeCase(str) {
535
- return str.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();
536
- }
537
- static ToKebebCase(str) {
538
- return str.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
539
- }
540
- }
541
- var lib_default = Lib;
542
-
543
- class Debug {
544
- static Log(...args) {
545
- if (false)
546
- ;
547
- Lib.Log(...args);
548
- }
549
- static $Log(...args) {
550
- if (false)
551
- ;
552
- Lib.$Log(...args);
553
- }
554
- static LogObject(object, text) {
555
- if (false)
556
- ;
557
- Lib.LogObject(object, text);
558
- }
559
- }
560
-
561
- // src/guards.ts
562
- class Guards {
563
- static IsString(value, excludeNull = false) {
564
- const output = lib_default.IsString(value);
565
- return excludeNull ? !Guards.IsNil(value) && output : output;
566
- }
567
- static IsNumber(value, excludeNull = false) {
568
- const output = lib_default.IsNumber(value);
569
- return excludeNull ? !Guards.IsNil(value) && output : output;
570
- }
571
- static IsBoolean(value, excludeNull = false) {
572
- const output = lib_default.GetType(value, true) === "boolean";
573
- return excludeNull ? !Guards.IsNil(value) && output : output;
574
- }
575
- static IsArray(value, excludeNull = false) {
576
- const output = lib_default.IsArray(value);
577
- return excludeNull ? !Guards.IsNil(value) && output : output;
578
- }
579
- static IsObject(value, excludeNull = false) {
580
- const output = lib_default.IsObject(value);
581
- return excludeNull ? !Guards.IsNil(value) && output : output;
582
- }
583
- static IsFunction(value, excludeNull = false) {
584
- const output = lib_default.IsFunction(value);
585
- return excludeNull ? !Guards.IsNil(value) && output : output;
586
- }
587
- static IsNil(value) {
588
- return lib_default.IsNil(value);
589
- }
590
- static IsType(obj, keys) {
591
- if (!keys)
592
- return !this.IsNil(obj);
593
- return keys.every((key) => (key in obj));
594
- }
595
- }
596
- var guards_default = Guards;
597
- // src/initializable.ts
598
- class Initializable {
599
- retries;
600
- retryInterval;
601
- _initialized = false;
602
- initializing = false;
603
- failed = false;
604
- timeout;
605
- listeners = new Map;
606
- abortController = null;
607
- constructor(options = {}) {
608
- this.retries = options.retries ?? 25;
609
- this.retryInterval = options.retryInterval ?? 200;
610
- this.timeout = options.timeout;
611
- if (options.autoInitialize) {
612
- setTimeout(() => this.initialize(), 0);
613
- }
614
- }
615
- async initialize() {
616
- if (this._initialized) {
617
- return;
618
- }
619
- if (this.initializing) {
620
- return this.waitForInitialization();
621
- }
622
- this.initializing = true;
623
- this.failed = false;
624
- this.abortController = new AbortController;
625
- try {
626
- this.emit("initializing");
627
- await this.doInitialize();
628
- this._initialized = true;
629
- this.initializing = false;
630
- this.emit("initialized");
631
- } catch (error) {
632
- this.failed = true;
633
- this.initializing = false;
634
- this.emit("failed", error);
635
- throw error instanceof Error ? error : new Error(`Initialization failed: ${String(error)}`);
636
- } finally {
637
- this.abortController = null;
638
- }
639
- }
640
- async doInitialize() {
641
- this._initialized = true;
642
- }
643
- async isInitialized(waitForIt = false) {
644
- if (this._initialized) {
645
- return true;
646
- }
647
- if (!waitForIt || this.failed) {
648
- return this._initialized;
649
- }
650
- try {
651
- await this.waitForInitialization();
652
- return true;
653
- } catch (error) {
654
- return false;
655
- }
656
- }
657
- async waitForInitialization() {
658
- if (this._initialized) {
659
- return;
660
- }
661
- if (!this.initializing) {
662
- return this.initialize();
663
- }
664
- const className = this.constructor.name;
665
- const maxTime = this.timeout ?? this.retries * this.retryInterval;
666
- let retries = this.retries;
667
- return new Promise((resolve2, reject) => {
668
- const onInitialized = () => {
669
- this.off("initialized", onInitialized);
670
- this.off("failed", onFailed);
671
- this.off("timeout", onTimeout);
672
- resolve2();
673
- };
674
- const onFailed = (error) => {
675
- this.off("initialized", onInitialized);
676
- this.off("failed", onFailed);
677
- this.off("timeout", onTimeout);
678
- reject(error);
679
- };
680
- const onTimeout = () => {
681
- this.off("initialized", onInitialized);
682
- this.off("failed", onFailed);
683
- this.off("timeout", onTimeout);
684
- reject(new Error(`Initialization of ${className} timed out after ${maxTime}ms`));
685
- };
686
- this.on("initialized", onInitialized);
687
- this.on("failed", onFailed);
688
- this.on("timeout", onTimeout);
689
- const checkInterval = setInterval(() => {
690
- retries--;
691
- if (this._initialized) {
692
- clearInterval(checkInterval);
693
- } else if (retries <= 0) {
694
- clearInterval(checkInterval);
695
- this.emit("timeout");
696
- }
697
- }, this.retryInterval);
698
- });
699
- }
700
- cancel() {
701
- if (this.initializing && this.abortController) {
702
- this.abortController.abort();
703
- this.initializing = false;
704
- this.failed = true;
705
- this.emit("failed", new Error("Initialization cancelled"));
706
- }
707
- }
708
- reset() {
709
- if (this.initializing) {
710
- this.cancel();
711
- }
712
- this._initialized = false;
713
- this.initializing = false;
714
- this.failed = false;
715
- }
716
- on(event, callback) {
717
- if (!this.listeners.has(event)) {
718
- this.listeners.set(event, []);
719
- }
720
- this.listeners.get(event).push(callback);
721
- return this;
722
- }
723
- off(event, callback) {
724
- if (this.listeners.has(event)) {
725
- const callbacks = this.listeners.get(event);
726
- const index = callbacks.indexOf(callback);
727
- if (index !== -1) {
728
- callbacks.splice(index, 1);
729
- }
730
- }
731
- return this;
732
- }
733
- emit(event, ...args) {
734
- if (this.listeners.has(event)) {
735
- const callbacks = [...this.listeners.get(event)];
736
- callbacks.forEach((callback) => {
737
- try {
738
- callback(...args);
739
- } catch (error) {
740
- console.error(`Error in ${event} event listener:`, error);
741
- }
742
- });
743
- }
744
- }
745
- get abortSignal() {
746
- return this.abortController?.signal;
747
- }
748
- get initialized() {
749
- return this._initialized;
750
- }
751
- get isInitializing() {
752
- return this.initializing;
753
- }
754
- get hasFailed() {
755
- return this.failed;
756
- }
757
- }
758
- var initializable_default = Initializable;
759
- // src/errors.ts
760
- var ERROR_CODE;
761
- ((ERROR_CODE2) => {
762
- ERROR_CODE2[ERROR_CODE2["NO_REQUEST"] = -1] = "NO_REQUEST";
763
- ERROR_CODE2[ERROR_CODE2["UNKNOWN_ERROR"] = 0] = "UNKNOWN_ERROR";
764
- ERROR_CODE2[ERROR_CODE2["INVALID_METHOD"] = 1] = "INVALID_METHOD";
765
- ERROR_CODE2[ERROR_CODE2["INVALID_REQUEST"] = 2] = "INVALID_REQUEST";
766
- ERROR_CODE2[ERROR_CODE2["INVALID_CONTROLLER"] = 3] = "INVALID_CONTROLLER";
767
- ERROR_CODE2[ERROR_CODE2["INVALID_ACTION"] = 4] = "INVALID_ACTION";
768
- ERROR_CODE2[ERROR_CODE2["NO_ACTION_IN_MAP"] = 5] = "NO_ACTION_IN_MAP";
769
- ERROR_CODE2[ERROR_CODE2["NO_METHOD_HANDLER"] = 6] = "NO_METHOD_HANDLER";
770
- ERROR_CODE2[ERROR_CODE2["INVALID_METHOD_INPUT"] = 7] = "INVALID_METHOD_INPUT";
771
- ERROR_CODE2[ERROR_CODE2["REQ_BODY_EMPTY"] = 8] = "REQ_BODY_EMPTY";
772
- })(ERROR_CODE ||= {});
773
- var HTTP_ERROR_CODE;
774
- ((HTTP_ERROR_CODE2) => {
775
- HTTP_ERROR_CODE2[HTTP_ERROR_CODE2["OK"] = 200] = "OK";
776
- HTTP_ERROR_CODE2[HTTP_ERROR_CODE2["BAD_REQUEST"] = 400] = "BAD_REQUEST";
777
- HTTP_ERROR_CODE2[HTTP_ERROR_CODE2["UNAUTHORIZED"] = 401] = "UNAUTHORIZED";
778
- HTTP_ERROR_CODE2[HTTP_ERROR_CODE2["FORBIDDEN"] = 403] = "FORBIDDEN";
779
- HTTP_ERROR_CODE2[HTTP_ERROR_CODE2["NOT_FOUND"] = 404] = "NOT_FOUND";
780
- HTTP_ERROR_CODE2[HTTP_ERROR_CODE2["INTERNAL_SERVER_ERROR"] = 500] = "INTERNAL_SERVER_ERROR";
781
- })(HTTP_ERROR_CODE ||= {});
782
- var WS_ERROR_CODE;
783
- ((WS_ERROR_CODE2) => {
784
- WS_ERROR_CODE2[WS_ERROR_CODE2["NORMAL_CLOSURE"] = 1000] = "NORMAL_CLOSURE";
785
- WS_ERROR_CODE2[WS_ERROR_CODE2["GOING_AWAY"] = 1001] = "GOING_AWAY";
786
- WS_ERROR_CODE2[WS_ERROR_CODE2["PROTOCOL_ERROR"] = 1002] = "PROTOCOL_ERROR";
787
- WS_ERROR_CODE2[WS_ERROR_CODE2["UNSUPPORTED_DATA"] = 1003] = "UNSUPPORTED_DATA";
788
- WS_ERROR_CODE2[WS_ERROR_CODE2["NO_STATUS_RECEIVED"] = 1005] = "NO_STATUS_RECEIVED";
789
- WS_ERROR_CODE2[WS_ERROR_CODE2["ABNORMAL_CLOSURE"] = 1006] = "ABNORMAL_CLOSURE";
790
- WS_ERROR_CODE2[WS_ERROR_CODE2["INVALID_FRAME_PAYLOAD_DATA"] = 1007] = "INVALID_FRAME_PAYLOAD_DATA";
791
- WS_ERROR_CODE2[WS_ERROR_CODE2["POLICY_VIOLATION"] = 1008] = "POLICY_VIOLATION";
792
- WS_ERROR_CODE2[WS_ERROR_CODE2["MESSAGE_TOO_BIG"] = 1009] = "MESSAGE_TOO_BIG";
793
- WS_ERROR_CODE2[WS_ERROR_CODE2["MISSING_EXTENSION"] = 1010] = "MISSING_EXTENSION";
794
- WS_ERROR_CODE2[WS_ERROR_CODE2["INTERNAL_ERROR"] = 1011] = "INTERNAL_ERROR";
795
- WS_ERROR_CODE2[WS_ERROR_CODE2["SERVICE_RESTART"] = 1012] = "SERVICE_RESTART";
796
- WS_ERROR_CODE2[WS_ERROR_CODE2["TRY_AGAIN_LATER"] = 1013] = "TRY_AGAIN_LATER";
797
- WS_ERROR_CODE2[WS_ERROR_CODE2["BAD_GATEWAY"] = 1014] = "BAD_GATEWAY";
798
- WS_ERROR_CODE2[WS_ERROR_CODE2["TLS_HANDSHAKE"] = 1015] = "TLS_HANDSHAKE";
799
- })(WS_ERROR_CODE ||= {});
800
-
801
- // src/router/router.internal.ts
802
- class Router_Internal {
803
- registry = new Map;
804
- routes;
805
- constructor(routes) {
806
- this.routes = routes ?? {};
807
- }
808
- async post(req) {
809
- return await this.handleRequest(req);
810
- }
811
- async get(req) {
812
- return await this.handleRequest(req);
813
- }
814
- async handleRequest(request) {
815
- const path2 = this.getPath(request);
816
- const output = await this.resolve(path2).call(request);
817
- return output;
818
- }
819
- getPath(request) {
820
- return new URL(request.url).pathname;
821
- }
822
- resolve(path2) {
823
- const controllerKey = path2.split("/")[1];
824
- return this.register(controllerKey, () => this.controllerFactory(controllerKey));
825
- }
826
- register(controllerKey, factory) {
827
- if (!this.registry.has(controllerKey)) {
828
- this.registry.set(controllerKey, factory());
829
- Debug.Log(`Caching controller: /${controllerKey}`);
830
- }
831
- return this.registry.get(controllerKey);
832
- }
833
- setRoutes(routes) {
834
- this.routes = routes;
835
- }
836
- controllerFactory(controllerKey) {
837
- if (!(controllerKey in this.routes))
838
- throw new throwable_default(`${3 /* INVALID_CONTROLLER */}: ${controllerKey}`, { logError: false });
839
- const ControllerClass = this.routes[controllerKey];
840
- return new ControllerClass;
841
- }
842
- }
843
- var router_internal_default = Router_Internal;
844
- // src/singleton.ts
845
- class Singleton {
846
- static instances = new WeakMap;
847
- static initializationLocks = new WeakMap;
848
- static activeInstances = new Map;
849
- constructor() {
850
- const constructorName = this.constructor.name;
851
- const callerName = new Error().stack?.split(`
852
- `)[2]?.trim() || "";
853
- if (!callerName.includes("getInstance")) {
854
- console.warn(`${constructorName} is a singleton and should be accessed via ${constructorName}.getInstance()`);
855
- }
856
- }
857
- static GetInstance(...args) {
858
- const classReference = this;
859
- if (Singleton.instances.has(classReference)) {
860
- return Singleton.instances.get(classReference);
861
- }
862
- if (Singleton.initializationLocks.get(classReference)) {
863
- throw new Error(`Concurrent initialization of ${classReference.name} singleton detected`);
864
- }
865
- try {
866
- Singleton.initializationLocks.set(classReference, true);
867
- if (!Singleton.instances.has(classReference)) {
868
- const instance = new classReference(...args);
869
- Singleton.instances.set(classReference, instance);
870
- Singleton.activeInstances.set(classReference.name, classReference);
871
- }
872
- return Singleton.instances.get(classReference);
873
- } catch (error) {
874
- throw new Error(`Failed to initialize ${classReference.name} singleton: ${error instanceof Error ? error.message : String(error)}`);
875
- } finally {
876
- Singleton.initializationLocks.delete(classReference);
877
- }
878
- }
879
- static HasInstance() {
880
- return Singleton.instances.has(this);
881
- }
882
- static ClearInstance() {
883
- const hadInstance = Singleton.instances.has(this);
884
- Singleton.instances.delete(this);
885
- Singleton.activeInstances.delete(this.name);
886
- return hadInstance;
887
- }
888
- static CreateFactory(...args) {
889
- const classReference = this;
890
- return () => classReference.GetInstance(...args);
891
- }
892
- static ClearAllInstances() {
893
- const instanceCount = Singleton.GetInstanceCount();
894
- Singleton.activeInstances.forEach((constructor) => {
895
- Singleton.instances.delete(constructor);
896
- });
897
- Singleton.activeInstances.clear();
898
- console.log(`Cleared ${instanceCount} singleton instances`);
899
- }
900
- static GetInstanceCount() {
901
- return Singleton.activeInstances.size;
902
- }
903
- static GetActiveInstanceNames() {
904
- return Array.from(Singleton.activeInstances.keys());
905
- }
906
- }
907
- var singleton_default = Singleton;
908
-
909
- // src/router/router.ts
910
- class Router extends singleton_default {
911
- internal;
912
- constructor(routes) {
913
- super();
914
- this.internal = new router_internal_default(routes);
915
- }
916
- setRoutes(routes) {
917
- this.internal.setRoutes(routes);
918
- }
919
- static async Call(request) {
920
- if (guards_default.IsNil(request))
921
- throw -1 /* NO_REQUEST */;
922
- const methods = this.getMethodMap();
923
- const method = methods[request.method];
924
- if (guards_default.IsNil(method))
925
- throw 1 /* INVALID_METHOD */;
926
- return await method(request);
927
- }
928
- static SetRoutes(routes) {
929
- Router.GetInstance().setRoutes(routes);
930
- }
931
- static getMethodMap() {
932
- const router = Router.GetInstance();
933
- return {
934
- GET: async (req) => await router.internal.get(req),
935
- POST: async (req) => await router.internal.post(req)
936
- };
937
- }
938
- static GetQueryParams(request) {
939
- const url = new URL(request.url);
940
- return url.searchParams;
941
- }
942
- }
943
- var router_default = Router;
944
- // src/server/controller.ts
945
- class Controller extends initializable_default {
946
- path;
947
- post = new Map;
948
- get = new Map;
949
- controllerMap = new Map;
950
- constructor(options) {
951
- super(options);
952
- this.POST();
953
- this.GET();
954
- this.setControllerMap();
955
- }
956
- static Create() {
957
- return new this;
958
- }
959
- static async AsyncCreate() {
960
- return new this;
961
- }
962
- async call(request) {
963
- await this.isInitialized();
964
- const action = this.resolve(request);
965
- return await action(request);
966
- }
967
- setControllerMap() {
968
- this.controllerMap.set("GET", this.get);
969
- this.controllerMap.set("POST", this.post);
970
- }
971
- resolve(req) {
972
- const url = new URL(req.url);
973
- const endpointArray = url.pathname.split("/");
974
- const actionName = endpointArray.slice(2).join("/");
975
- if (!guards_default.IsString(actionName, true))
976
- throw 4 /* INVALID_ACTION */;
977
- const methodMap = this.controllerMap.get(req.method);
978
- if (guards_default.IsNil(methodMap)) {
979
- throw 1 /* INVALID_METHOD */;
980
- }
981
- return this.resolveAction(methodMap, actionName);
982
- }
983
- resolveAction(methodMap, actionName) {
984
- const action = methodMap.get(actionName);
985
- if (!guards_default.IsFunction(action, true)) {
986
- throw 5 /* NO_ACTION_IN_MAP */;
987
- }
988
- return action;
989
- }
990
- }
991
- // src/consts.ts
992
- var DEFAULT_FALSE_RESPONSE = "Something went wrong. Please try again later.";
993
- var LOG_COLORS = {
994
- reset: "\x1B[0m",
995
- bright: "\x1B[1m",
996
- dim: "\x1B[2m",
997
- underscore: "\x1B[4m",
998
- blink: "\x1B[5m",
999
- reverse: "\x1B[7m",
1000
- hidden: "\x1B[8m",
1001
- text: {
1002
- black: "\x1B[30m",
1003
- red: "\x1B[31m",
1004
- green: "\x1B[32m",
1005
- yellow: "\x1B[33m",
1006
- blue: "\x1B[34m",
1007
- magenta: "\x1B[35m",
1008
- cyan: "\x1B[36m",
1009
- white: "\x1B[37m"
1010
- },
1011
- bg: {
1012
- black: "\x1B[40m",
1013
- red: "\x1B[41m",
1014
- green: "\x1B[42m",
1015
- yellow: "\x1B[43m",
1016
- blue: "\x1B[44m",
1017
- magenta: "\x1B[45m",
1018
- cyan: "\x1B[46m",
1019
- white: "\x1B[47m"
1020
- }
36
+ })();
37
+ var __importDefault = (this && this.__importDefault) || function (mod) {
38
+ return (mod && mod.__esModule) ? mod : { "default": mod };
1021
39
  };
1022
- // src/router/index.ts
1023
- var exports_router = {};
1024
- __export(exports_router, {
1025
- routes: () => routes,
1026
- Router_internal: () => router_internal_default,
1027
- Router: () => router_default
1028
- });
1029
-
1030
- // src/router/routes.ts
1031
- var routes = {};
1032
- // src/server/index.ts
1033
- var exports_server = {};
1034
- __export(exports_server, {
1035
- Controller: () => Controller
1036
- });
1037
-
1038
- //# debugId=0B1F55E649341FB164756E2164756E21
1039
- //# sourceMappingURL=index.js.map
40
+ Object.defineProperty(exports, "__esModule", { value: true });
41
+ exports.Server = exports.Router = exports.WS_ERROR_CODE = exports.HTTP_ERROR_CODE = exports.ERROR_CODE = exports.E_ENVIRONMENTS = exports.E_IS = exports.LOG_COLORS = exports.DEFAULT_FALSE_RESPONSE = exports.RESPONSE_METHOD_OPTIONS = exports.RESPONSE_INIT = exports.Throwable = exports.Singleton = exports.ServerController = exports.RouterRouter = exports.RouterRouter_internal = exports.Lib = exports.Initializable = exports.Guards = exports.Application = void 0;
42
+ // Export all modules
43
+ // Export default classes
44
+ var application_1 = require("./application");
45
+ Object.defineProperty(exports, "Application", { enumerable: true, get: function () { return __importDefault(application_1).default; } });
46
+ var guards_1 = require("./guards");
47
+ Object.defineProperty(exports, "Guards", { enumerable: true, get: function () { return __importDefault(guards_1).default; } });
48
+ var initializable_1 = require("./initializable");
49
+ Object.defineProperty(exports, "Initializable", { enumerable: true, get: function () { return __importDefault(initializable_1).default; } });
50
+ var lib_1 = require("./lib");
51
+ Object.defineProperty(exports, "Lib", { enumerable: true, get: function () { return __importDefault(lib_1).default; } });
52
+ var router_internal_1 = require("./router/router.internal");
53
+ Object.defineProperty(exports, "RouterRouter_internal", { enumerable: true, get: function () { return __importDefault(router_internal_1).default; } });
54
+ var router_1 = require("./router/router");
55
+ Object.defineProperty(exports, "RouterRouter", { enumerable: true, get: function () { return __importDefault(router_1).default; } });
56
+ var controller_1 = require("./server/controller");
57
+ Object.defineProperty(exports, "ServerController", { enumerable: true, get: function () { return __importDefault(controller_1).default; } });
58
+ var singleton_1 = require("./singleton");
59
+ Object.defineProperty(exports, "Singleton", { enumerable: true, get: function () { return __importDefault(singleton_1).default; } });
60
+ var throwable_1 = require("./throwable");
61
+ Object.defineProperty(exports, "Throwable", { enumerable: true, get: function () { return __importDefault(throwable_1).default; } });
62
+ // Re-export specific items for backward compatibility
63
+ var application_2 = require("./application");
64
+ Object.defineProperty(exports, "RESPONSE_INIT", { enumerable: true, get: function () { return application_2.RESPONSE_INIT; } });
65
+ Object.defineProperty(exports, "RESPONSE_METHOD_OPTIONS", { enumerable: true, get: function () { return application_2.RESPONSE_METHOD_OPTIONS; } });
66
+ var consts_1 = require("./consts");
67
+ Object.defineProperty(exports, "DEFAULT_FALSE_RESPONSE", { enumerable: true, get: function () { return consts_1.DEFAULT_FALSE_RESPONSE; } });
68
+ Object.defineProperty(exports, "LOG_COLORS", { enumerable: true, get: function () { return consts_1.LOG_COLORS; } });
69
+ var enums_1 = require("./enums");
70
+ Object.defineProperty(exports, "E_IS", { enumerable: true, get: function () { return enums_1.E_IS; } });
71
+ Object.defineProperty(exports, "E_ENVIRONMENTS", { enumerable: true, get: function () { return enums_1.E_ENVIRONMENTS; } });
72
+ var errors_1 = require("./errors");
73
+ Object.defineProperty(exports, "ERROR_CODE", { enumerable: true, get: function () { return errors_1.ERROR_CODE; } });
74
+ Object.defineProperty(exports, "HTTP_ERROR_CODE", { enumerable: true, get: function () { return errors_1.HTTP_ERROR_CODE; } });
75
+ Object.defineProperty(exports, "WS_ERROR_CODE", { enumerable: true, get: function () { return errors_1.WS_ERROR_CODE; } });
76
+ // Barrel exports for subdirectories
77
+ // Create module for router
78
+ const RouterModule = __importStar(require("./router"));
79
+ exports.Router = RouterModule;
80
+ // Create module for server
81
+ const ServerModule = __importStar(require("./server"));
82
+ exports.Server = ServerModule;
83
+ //# sourceMappingURL=index.js.map