@spfn/core 0.1.0-alpha.7 → 0.1.0-alpha.74

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 (59) hide show
  1. package/README.md +168 -195
  2. package/dist/auto-loader-JFaZ9gON.d.ts +80 -0
  3. package/dist/cache/index.d.ts +211 -0
  4. package/dist/cache/index.js +992 -0
  5. package/dist/cache/index.js.map +1 -0
  6. package/dist/client/index.d.ts +92 -92
  7. package/dist/client/index.js +80 -85
  8. package/dist/client/index.js.map +1 -1
  9. package/dist/codegen/generators/index.d.ts +19 -0
  10. package/dist/codegen/generators/index.js +1500 -0
  11. package/dist/codegen/generators/index.js.map +1 -0
  12. package/dist/codegen/index.d.ts +76 -60
  13. package/dist/codegen/index.js +1486 -736
  14. package/dist/codegen/index.js.map +1 -1
  15. package/dist/database-errors-BNNmLTJE.d.ts +86 -0
  16. package/dist/db/index.d.ts +844 -44
  17. package/dist/db/index.js +1262 -1309
  18. package/dist/db/index.js.map +1 -1
  19. package/dist/env/index.d.ts +508 -0
  20. package/dist/env/index.js +1106 -0
  21. package/dist/env/index.js.map +1 -0
  22. package/dist/error-handler-wjLL3v-a.d.ts +44 -0
  23. package/dist/errors/index.d.ts +136 -0
  24. package/dist/errors/index.js +172 -0
  25. package/dist/errors/index.js.map +1 -0
  26. package/dist/index-DHiAqhKv.d.ts +101 -0
  27. package/dist/index.d.ts +3 -374
  28. package/dist/index.js +2394 -2176
  29. package/dist/index.js.map +1 -1
  30. package/dist/logger/index.d.ts +94 -0
  31. package/dist/logger/index.js +774 -0
  32. package/dist/logger/index.js.map +1 -0
  33. package/dist/middleware/index.d.ts +33 -0
  34. package/dist/middleware/index.js +890 -0
  35. package/dist/middleware/index.js.map +1 -0
  36. package/dist/route/index.d.ts +21 -53
  37. package/dist/route/index.js +1234 -219
  38. package/dist/route/index.js.map +1 -1
  39. package/dist/server/index.d.ts +18 -0
  40. package/dist/server/index.js +2390 -2058
  41. package/dist/server/index.js.map +1 -1
  42. package/dist/types-Dzggq1Yb.d.ts +170 -0
  43. package/package.json +59 -15
  44. package/dist/auto-loader-C44TcLmM.d.ts +0 -125
  45. package/dist/bind-pssq1NRT.d.ts +0 -34
  46. package/dist/postgres-errors-CY_Es8EJ.d.ts +0 -1703
  47. package/dist/scripts/index.d.ts +0 -24
  48. package/dist/scripts/index.js +0 -1201
  49. package/dist/scripts/index.js.map +0 -1
  50. package/dist/scripts/templates/api-index.template.txt +0 -10
  51. package/dist/scripts/templates/api-tag.template.txt +0 -11
  52. package/dist/scripts/templates/contract.template.txt +0 -87
  53. package/dist/scripts/templates/entity-type.template.txt +0 -31
  54. package/dist/scripts/templates/entity.template.txt +0 -19
  55. package/dist/scripts/templates/index.template.txt +0 -10
  56. package/dist/scripts/templates/repository.template.txt +0 -37
  57. package/dist/scripts/templates/routes-id.template.txt +0 -59
  58. package/dist/scripts/templates/routes-index.template.txt +0 -44
  59. package/dist/types-SlzTr8ZO.d.ts +0 -143
@@ -0,0 +1,992 @@
1
+ import pino from 'pino';
2
+ import { existsSync, mkdirSync, accessSync, constants, writeFileSync, unlinkSync, createWriteStream, statSync, readdirSync, renameSync } from 'fs';
3
+ import { join } from 'path';
4
+
5
+ // src/logger/adapters/pino.ts
6
+ var PinoAdapter = class _PinoAdapter {
7
+ logger;
8
+ constructor(config) {
9
+ this.logger = pino({
10
+ level: config.level,
11
+ // 기본 필드
12
+ base: config.module ? { module: config.module } : void 0
13
+ });
14
+ }
15
+ child(module) {
16
+ const childLogger = new _PinoAdapter({ level: this.logger.level, module });
17
+ childLogger.logger = this.logger.child({ module });
18
+ return childLogger;
19
+ }
20
+ debug(message, context) {
21
+ this.logger.debug(context || {}, message);
22
+ }
23
+ info(message, context) {
24
+ this.logger.info(context || {}, message);
25
+ }
26
+ warn(message, errorOrContext, context) {
27
+ if (errorOrContext instanceof Error) {
28
+ this.logger.warn({ err: errorOrContext, ...context }, message);
29
+ } else {
30
+ this.logger.warn(errorOrContext || {}, message);
31
+ }
32
+ }
33
+ error(message, errorOrContext, context) {
34
+ if (errorOrContext instanceof Error) {
35
+ this.logger.error({ err: errorOrContext, ...context }, message);
36
+ } else {
37
+ this.logger.error(errorOrContext || {}, message);
38
+ }
39
+ }
40
+ fatal(message, errorOrContext, context) {
41
+ if (errorOrContext instanceof Error) {
42
+ this.logger.fatal({ err: errorOrContext, ...context }, message);
43
+ } else {
44
+ this.logger.fatal(errorOrContext || {}, message);
45
+ }
46
+ }
47
+ async close() {
48
+ }
49
+ };
50
+
51
+ // src/logger/types.ts
52
+ var LOG_LEVEL_PRIORITY = {
53
+ debug: 0,
54
+ info: 1,
55
+ warn: 2,
56
+ error: 3,
57
+ fatal: 4
58
+ };
59
+
60
+ // src/logger/formatters.ts
61
+ var SENSITIVE_KEYS = [
62
+ "password",
63
+ "passwd",
64
+ "pwd",
65
+ "secret",
66
+ "token",
67
+ "apikey",
68
+ "api_key",
69
+ "accesstoken",
70
+ "access_token",
71
+ "refreshtoken",
72
+ "refresh_token",
73
+ "authorization",
74
+ "auth",
75
+ "cookie",
76
+ "session",
77
+ "sessionid",
78
+ "session_id",
79
+ "privatekey",
80
+ "private_key",
81
+ "creditcard",
82
+ "credit_card",
83
+ "cardnumber",
84
+ "card_number",
85
+ "cvv",
86
+ "ssn",
87
+ "pin"
88
+ ];
89
+ var MASKED_VALUE = "***MASKED***";
90
+ function isSensitiveKey(key) {
91
+ const lowerKey = key.toLowerCase();
92
+ return SENSITIVE_KEYS.some((sensitive) => lowerKey.includes(sensitive));
93
+ }
94
+ function maskSensitiveData(data) {
95
+ if (data === null || data === void 0) {
96
+ return data;
97
+ }
98
+ if (Array.isArray(data)) {
99
+ return data.map((item) => maskSensitiveData(item));
100
+ }
101
+ if (typeof data === "object") {
102
+ const masked = {};
103
+ for (const [key, value] of Object.entries(data)) {
104
+ if (isSensitiveKey(key)) {
105
+ masked[key] = MASKED_VALUE;
106
+ } else if (typeof value === "object" && value !== null) {
107
+ masked[key] = maskSensitiveData(value);
108
+ } else {
109
+ masked[key] = value;
110
+ }
111
+ }
112
+ return masked;
113
+ }
114
+ return data;
115
+ }
116
+ var COLORS = {
117
+ reset: "\x1B[0m",
118
+ bright: "\x1B[1m",
119
+ dim: "\x1B[2m",
120
+ // 로그 레벨 컬러
121
+ debug: "\x1B[36m",
122
+ // cyan
123
+ info: "\x1B[32m",
124
+ // green
125
+ warn: "\x1B[33m",
126
+ // yellow
127
+ error: "\x1B[31m",
128
+ // red
129
+ fatal: "\x1B[35m",
130
+ // magenta
131
+ // 추가 컬러
132
+ gray: "\x1B[90m"
133
+ };
134
+ function formatTimestamp(date) {
135
+ return date.toISOString();
136
+ }
137
+ function formatTimestampHuman(date) {
138
+ const year = date.getFullYear();
139
+ const month = String(date.getMonth() + 1).padStart(2, "0");
140
+ const day = String(date.getDate()).padStart(2, "0");
141
+ const hours = String(date.getHours()).padStart(2, "0");
142
+ const minutes = String(date.getMinutes()).padStart(2, "0");
143
+ const seconds = String(date.getSeconds()).padStart(2, "0");
144
+ const ms = String(date.getMilliseconds()).padStart(3, "0");
145
+ return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${ms}`;
146
+ }
147
+ function formatError(error) {
148
+ const lines = [];
149
+ lines.push(`${error.name}: ${error.message}`);
150
+ if (error.stack) {
151
+ const stackLines = error.stack.split("\n").slice(1);
152
+ lines.push(...stackLines);
153
+ }
154
+ return lines.join("\n");
155
+ }
156
+ function formatConsole(metadata, colorize = true) {
157
+ const parts = [];
158
+ const timestamp = formatTimestampHuman(metadata.timestamp);
159
+ if (colorize) {
160
+ parts.push(`${COLORS.gray}[${timestamp}]${COLORS.reset}`);
161
+ } else {
162
+ parts.push(`[${timestamp}]`);
163
+ }
164
+ if (metadata.module) {
165
+ if (colorize) {
166
+ parts.push(`${COLORS.dim}[module=${metadata.module}]${COLORS.reset}`);
167
+ } else {
168
+ parts.push(`[module=${metadata.module}]`);
169
+ }
170
+ }
171
+ if (metadata.context && Object.keys(metadata.context).length > 0) {
172
+ Object.entries(metadata.context).forEach(([key, value]) => {
173
+ const valueStr = typeof value === "string" ? value : String(value);
174
+ if (colorize) {
175
+ parts.push(`${COLORS.dim}[${key}=${valueStr}]${COLORS.reset}`);
176
+ } else {
177
+ parts.push(`[${key}=${valueStr}]`);
178
+ }
179
+ });
180
+ }
181
+ const levelStr = metadata.level.toUpperCase();
182
+ if (colorize) {
183
+ const color = COLORS[metadata.level];
184
+ parts.push(`${color}(${levelStr})${COLORS.reset}:`);
185
+ } else {
186
+ parts.push(`(${levelStr}):`);
187
+ }
188
+ if (colorize) {
189
+ parts.push(`${COLORS.bright}${metadata.message}${COLORS.reset}`);
190
+ } else {
191
+ parts.push(metadata.message);
192
+ }
193
+ let output = parts.join(" ");
194
+ if (metadata.error) {
195
+ output += "\n" + formatError(metadata.error);
196
+ }
197
+ return output;
198
+ }
199
+ function formatJSON(metadata) {
200
+ const obj = {
201
+ timestamp: formatTimestamp(metadata.timestamp),
202
+ level: metadata.level,
203
+ message: metadata.message
204
+ };
205
+ if (metadata.module) {
206
+ obj.module = metadata.module;
207
+ }
208
+ if (metadata.context) {
209
+ obj.context = metadata.context;
210
+ }
211
+ if (metadata.error) {
212
+ obj.error = {
213
+ name: metadata.error.name,
214
+ message: metadata.error.message,
215
+ stack: metadata.error.stack
216
+ };
217
+ }
218
+ return JSON.stringify(obj);
219
+ }
220
+
221
+ // src/logger/logger.ts
222
+ var Logger = class _Logger {
223
+ config;
224
+ module;
225
+ constructor(config) {
226
+ this.config = config;
227
+ this.module = config.module;
228
+ }
229
+ /**
230
+ * Get current log level
231
+ */
232
+ get level() {
233
+ return this.config.level;
234
+ }
235
+ /**
236
+ * Create child logger (per module)
237
+ */
238
+ child(module) {
239
+ return new _Logger({
240
+ ...this.config,
241
+ module
242
+ });
243
+ }
244
+ /**
245
+ * Debug log
246
+ */
247
+ debug(message, context) {
248
+ this.log("debug", message, void 0, context);
249
+ }
250
+ /**
251
+ * Info log
252
+ */
253
+ info(message, context) {
254
+ this.log("info", message, void 0, context);
255
+ }
256
+ warn(message, errorOrContext, context) {
257
+ if (errorOrContext instanceof Error) {
258
+ this.log("warn", message, errorOrContext, context);
259
+ } else {
260
+ this.log("warn", message, void 0, errorOrContext);
261
+ }
262
+ }
263
+ error(message, errorOrContext, context) {
264
+ if (errorOrContext instanceof Error) {
265
+ this.log("error", message, errorOrContext, context);
266
+ } else {
267
+ this.log("error", message, void 0, errorOrContext);
268
+ }
269
+ }
270
+ fatal(message, errorOrContext, context) {
271
+ if (errorOrContext instanceof Error) {
272
+ this.log("fatal", message, errorOrContext, context);
273
+ } else {
274
+ this.log("fatal", message, void 0, errorOrContext);
275
+ }
276
+ }
277
+ /**
278
+ * Log processing (internal)
279
+ */
280
+ log(level, message, error, context) {
281
+ if (LOG_LEVEL_PRIORITY[level] < LOG_LEVEL_PRIORITY[this.config.level]) {
282
+ return;
283
+ }
284
+ const metadata = {
285
+ timestamp: /* @__PURE__ */ new Date(),
286
+ level,
287
+ message,
288
+ module: this.module,
289
+ error,
290
+ // Mask sensitive information in context to prevent credential leaks
291
+ context: context ? maskSensitiveData(context) : void 0
292
+ };
293
+ this.processTransports(metadata);
294
+ }
295
+ /**
296
+ * Process Transports
297
+ */
298
+ processTransports(metadata) {
299
+ const promises = this.config.transports.filter((transport) => transport.enabled).map((transport) => this.safeTransportLog(transport, metadata));
300
+ Promise.all(promises).catch((error) => {
301
+ const errorMessage = error instanceof Error ? error.message : String(error);
302
+ process.stderr.write(`[Logger] Transport error: ${errorMessage}
303
+ `);
304
+ });
305
+ }
306
+ /**
307
+ * Transport log (error-safe)
308
+ */
309
+ async safeTransportLog(transport, metadata) {
310
+ try {
311
+ await transport.log(metadata);
312
+ } catch (error) {
313
+ const errorMessage = error instanceof Error ? error.message : String(error);
314
+ process.stderr.write(`[Logger] Transport "${transport.name}" failed: ${errorMessage}
315
+ `);
316
+ }
317
+ }
318
+ /**
319
+ * Close all Transports
320
+ */
321
+ async close() {
322
+ const closePromises = this.config.transports.filter((transport) => transport.close).map((transport) => transport.close());
323
+ await Promise.all(closePromises);
324
+ }
325
+ };
326
+
327
+ // src/logger/transports/console.ts
328
+ var ConsoleTransport = class {
329
+ name = "console";
330
+ level;
331
+ enabled;
332
+ colorize;
333
+ constructor(config) {
334
+ this.level = config.level;
335
+ this.enabled = config.enabled;
336
+ this.colorize = config.colorize ?? true;
337
+ }
338
+ async log(metadata) {
339
+ if (!this.enabled) {
340
+ return;
341
+ }
342
+ if (LOG_LEVEL_PRIORITY[metadata.level] < LOG_LEVEL_PRIORITY[this.level]) {
343
+ return;
344
+ }
345
+ const message = formatConsole(metadata, this.colorize);
346
+ if (metadata.level === "warn" || metadata.level === "error" || metadata.level === "fatal") {
347
+ console.error(message);
348
+ } else {
349
+ console.log(message);
350
+ }
351
+ }
352
+ };
353
+ var FileTransport = class {
354
+ name = "file";
355
+ level;
356
+ enabled;
357
+ logDir;
358
+ maxFileSize;
359
+ maxFiles;
360
+ currentStream = null;
361
+ currentFilename = null;
362
+ constructor(config) {
363
+ this.level = config.level;
364
+ this.enabled = config.enabled;
365
+ this.logDir = config.logDir;
366
+ this.maxFileSize = config.maxFileSize ?? 10 * 1024 * 1024;
367
+ this.maxFiles = config.maxFiles ?? 10;
368
+ if (!existsSync(this.logDir)) {
369
+ mkdirSync(this.logDir, { recursive: true });
370
+ }
371
+ }
372
+ async log(metadata) {
373
+ if (!this.enabled) {
374
+ return;
375
+ }
376
+ if (LOG_LEVEL_PRIORITY[metadata.level] < LOG_LEVEL_PRIORITY[this.level]) {
377
+ return;
378
+ }
379
+ const message = formatJSON(metadata);
380
+ const filename = this.getLogFilename(metadata.timestamp);
381
+ if (this.currentFilename !== filename) {
382
+ await this.rotateStream(filename);
383
+ await this.cleanOldFiles();
384
+ } else if (this.currentFilename) {
385
+ await this.checkAndRotateBySize();
386
+ }
387
+ if (this.currentStream) {
388
+ return new Promise((resolve, reject) => {
389
+ this.currentStream.write(message + "\n", "utf-8", (error) => {
390
+ if (error) {
391
+ process.stderr.write(`[FileTransport] Failed to write log: ${error.message}
392
+ `);
393
+ reject(error);
394
+ } else {
395
+ resolve();
396
+ }
397
+ });
398
+ });
399
+ }
400
+ }
401
+ /**
402
+ * 스트림 교체 (날짜 변경 시)
403
+ */
404
+ async rotateStream(filename) {
405
+ if (this.currentStream) {
406
+ await this.closeStream();
407
+ }
408
+ const filepath = join(this.logDir, filename);
409
+ this.currentStream = createWriteStream(filepath, {
410
+ flags: "a",
411
+ // append mode
412
+ encoding: "utf-8"
413
+ });
414
+ this.currentFilename = filename;
415
+ this.currentStream.on("error", (error) => {
416
+ process.stderr.write(`[FileTransport] Stream error: ${error.message}
417
+ `);
418
+ this.currentStream = null;
419
+ this.currentFilename = null;
420
+ });
421
+ }
422
+ /**
423
+ * 현재 스트림 닫기
424
+ */
425
+ async closeStream() {
426
+ if (!this.currentStream) {
427
+ return;
428
+ }
429
+ return new Promise((resolve, reject) => {
430
+ this.currentStream.end((error) => {
431
+ if (error) {
432
+ reject(error);
433
+ } else {
434
+ this.currentStream = null;
435
+ this.currentFilename = null;
436
+ resolve();
437
+ }
438
+ });
439
+ });
440
+ }
441
+ /**
442
+ * 파일 크기 체크 및 크기 기반 로테이션
443
+ */
444
+ async checkAndRotateBySize() {
445
+ if (!this.currentFilename) {
446
+ return;
447
+ }
448
+ const filepath = join(this.logDir, this.currentFilename);
449
+ if (!existsSync(filepath)) {
450
+ return;
451
+ }
452
+ try {
453
+ const stats = statSync(filepath);
454
+ if (stats.size >= this.maxFileSize) {
455
+ await this.rotateBySize();
456
+ }
457
+ } catch (error) {
458
+ const errorMessage = error instanceof Error ? error.message : String(error);
459
+ process.stderr.write(`[FileTransport] Failed to check file size: ${errorMessage}
460
+ `);
461
+ }
462
+ }
463
+ /**
464
+ * 크기 기반 로테이션 수행
465
+ * 예: 2025-01-01.log -> 2025-01-01.1.log, 2025-01-01.1.log -> 2025-01-01.2.log
466
+ */
467
+ async rotateBySize() {
468
+ if (!this.currentFilename) {
469
+ return;
470
+ }
471
+ await this.closeStream();
472
+ const baseName = this.currentFilename.replace(/\.log$/, "");
473
+ const files = readdirSync(this.logDir);
474
+ const relatedFiles = files.filter((file) => file.startsWith(baseName) && file.endsWith(".log")).sort().reverse();
475
+ for (const file of relatedFiles) {
476
+ const match = file.match(/\.(\d+)\.log$/);
477
+ if (match) {
478
+ const oldNum = parseInt(match[1], 10);
479
+ const newNum = oldNum + 1;
480
+ const oldPath = join(this.logDir, file);
481
+ const newPath2 = join(this.logDir, `${baseName}.${newNum}.log`);
482
+ try {
483
+ renameSync(oldPath, newPath2);
484
+ } catch (error) {
485
+ const errorMessage = error instanceof Error ? error.message : String(error);
486
+ process.stderr.write(`[FileTransport] Failed to rotate file: ${errorMessage}
487
+ `);
488
+ }
489
+ }
490
+ }
491
+ const currentPath = join(this.logDir, this.currentFilename);
492
+ const newPath = join(this.logDir, `${baseName}.1.log`);
493
+ try {
494
+ if (existsSync(currentPath)) {
495
+ renameSync(currentPath, newPath);
496
+ }
497
+ } catch (error) {
498
+ const errorMessage = error instanceof Error ? error.message : String(error);
499
+ process.stderr.write(`[FileTransport] Failed to rotate current file: ${errorMessage}
500
+ `);
501
+ }
502
+ await this.rotateStream(this.currentFilename);
503
+ }
504
+ /**
505
+ * 오래된 로그 파일 정리
506
+ * maxFiles 개수를 초과하는 로그 파일 삭제
507
+ */
508
+ async cleanOldFiles() {
509
+ try {
510
+ if (!existsSync(this.logDir)) {
511
+ return;
512
+ }
513
+ const files = readdirSync(this.logDir);
514
+ const logFiles = files.filter((file) => file.endsWith(".log")).map((file) => {
515
+ const filepath = join(this.logDir, file);
516
+ const stats = statSync(filepath);
517
+ return { file, mtime: stats.mtime };
518
+ }).sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
519
+ if (logFiles.length > this.maxFiles) {
520
+ const filesToDelete = logFiles.slice(this.maxFiles);
521
+ for (const { file } of filesToDelete) {
522
+ const filepath = join(this.logDir, file);
523
+ try {
524
+ unlinkSync(filepath);
525
+ } catch (error) {
526
+ const errorMessage = error instanceof Error ? error.message : String(error);
527
+ process.stderr.write(`[FileTransport] Failed to delete old file "${file}": ${errorMessage}
528
+ `);
529
+ }
530
+ }
531
+ }
532
+ } catch (error) {
533
+ const errorMessage = error instanceof Error ? error.message : String(error);
534
+ process.stderr.write(`[FileTransport] Failed to clean old files: ${errorMessage}
535
+ `);
536
+ }
537
+ }
538
+ /**
539
+ * 날짜별 로그 파일명 생성
540
+ */
541
+ getLogFilename(date) {
542
+ const year = date.getFullYear();
543
+ const month = String(date.getMonth() + 1).padStart(2, "0");
544
+ const day = String(date.getDate()).padStart(2, "0");
545
+ return `${year}-${month}-${day}.log`;
546
+ }
547
+ async close() {
548
+ await this.closeStream();
549
+ }
550
+ };
551
+ function isFileLoggingEnabled() {
552
+ return process.env.LOGGER_FILE_ENABLED === "true";
553
+ }
554
+ function getDefaultLogLevel() {
555
+ const isProduction = process.env.NODE_ENV === "production";
556
+ const isDevelopment = process.env.NODE_ENV === "development";
557
+ if (isDevelopment) {
558
+ return "debug";
559
+ }
560
+ if (isProduction) {
561
+ return "info";
562
+ }
563
+ return "warn";
564
+ }
565
+ function getConsoleConfig() {
566
+ const isProduction = process.env.NODE_ENV === "production";
567
+ return {
568
+ level: "debug",
569
+ enabled: true,
570
+ colorize: !isProduction
571
+ // Dev: colored output, Production: plain text
572
+ };
573
+ }
574
+ function getFileConfig() {
575
+ const isProduction = process.env.NODE_ENV === "production";
576
+ return {
577
+ level: "info",
578
+ enabled: isProduction,
579
+ // File logging in production only
580
+ logDir: process.env.LOG_DIR || "./logs",
581
+ maxFileSize: 10 * 1024 * 1024,
582
+ // 10MB
583
+ maxFiles: 10
584
+ };
585
+ }
586
+ function validateDirectoryWritable(dirPath) {
587
+ if (!existsSync(dirPath)) {
588
+ try {
589
+ mkdirSync(dirPath, { recursive: true });
590
+ } catch (error) {
591
+ const errorMessage = error instanceof Error ? error.message : String(error);
592
+ throw new Error(`Failed to create log directory "${dirPath}": ${errorMessage}`);
593
+ }
594
+ }
595
+ try {
596
+ accessSync(dirPath, constants.W_OK);
597
+ } catch {
598
+ throw new Error(`Log directory "${dirPath}" is not writable. Please check permissions.`);
599
+ }
600
+ const testFile = join(dirPath, ".logger-write-test");
601
+ try {
602
+ writeFileSync(testFile, "test", "utf-8");
603
+ unlinkSync(testFile);
604
+ } catch (error) {
605
+ const errorMessage = error instanceof Error ? error.message : String(error);
606
+ throw new Error(`Cannot write to log directory "${dirPath}": ${errorMessage}`);
607
+ }
608
+ }
609
+ function validateFileConfig() {
610
+ if (!isFileLoggingEnabled()) {
611
+ return;
612
+ }
613
+ const logDir = process.env.LOG_DIR;
614
+ if (!logDir) {
615
+ throw new Error(
616
+ "LOG_DIR environment variable is required when LOGGER_FILE_ENABLED=true. Example: LOG_DIR=/var/log/myapp"
617
+ );
618
+ }
619
+ validateDirectoryWritable(logDir);
620
+ }
621
+ function validateSlackConfig() {
622
+ const webhookUrl = process.env.SLACK_WEBHOOK_URL;
623
+ if (!webhookUrl) {
624
+ return;
625
+ }
626
+ if (!webhookUrl.startsWith("https://hooks.slack.com/")) {
627
+ throw new Error(
628
+ `Invalid SLACK_WEBHOOK_URL: "${webhookUrl}". Slack webhook URLs must start with "https://hooks.slack.com/"`
629
+ );
630
+ }
631
+ }
632
+ function validateEmailConfig() {
633
+ const smtpHost = process.env.SMTP_HOST;
634
+ const smtpPort = process.env.SMTP_PORT;
635
+ const emailFrom = process.env.EMAIL_FROM;
636
+ const emailTo = process.env.EMAIL_TO;
637
+ const hasAnyEmailConfig = smtpHost || smtpPort || emailFrom || emailTo;
638
+ if (!hasAnyEmailConfig) {
639
+ return;
640
+ }
641
+ const missingFields = [];
642
+ if (!smtpHost) missingFields.push("SMTP_HOST");
643
+ if (!smtpPort) missingFields.push("SMTP_PORT");
644
+ if (!emailFrom) missingFields.push("EMAIL_FROM");
645
+ if (!emailTo) missingFields.push("EMAIL_TO");
646
+ if (missingFields.length > 0) {
647
+ throw new Error(
648
+ `Email transport configuration incomplete. Missing: ${missingFields.join(", ")}. Either set all required fields or remove all email configuration.`
649
+ );
650
+ }
651
+ const port = parseInt(smtpPort, 10);
652
+ if (isNaN(port) || port < 1 || port > 65535) {
653
+ throw new Error(
654
+ `Invalid SMTP_PORT: "${smtpPort}". Must be a number between 1 and 65535.`
655
+ );
656
+ }
657
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
658
+ if (!emailRegex.test(emailFrom)) {
659
+ throw new Error(`Invalid EMAIL_FROM format: "${emailFrom}"`);
660
+ }
661
+ const recipients = emailTo.split(",").map((e) => e.trim());
662
+ for (const email of recipients) {
663
+ if (!emailRegex.test(email)) {
664
+ throw new Error(`Invalid email address in EMAIL_TO: "${email}"`);
665
+ }
666
+ }
667
+ }
668
+ function validateEnvironment() {
669
+ const nodeEnv = process.env.NODE_ENV;
670
+ if (!nodeEnv) {
671
+ process.stderr.write(
672
+ "[Logger] Warning: NODE_ENV is not set. Defaulting to test environment.\n"
673
+ );
674
+ }
675
+ }
676
+ function validateConfig() {
677
+ try {
678
+ validateEnvironment();
679
+ validateFileConfig();
680
+ validateSlackConfig();
681
+ validateEmailConfig();
682
+ } catch (error) {
683
+ if (error instanceof Error) {
684
+ throw new Error(`[Logger] Configuration validation failed: ${error.message}`);
685
+ }
686
+ throw error;
687
+ }
688
+ }
689
+
690
+ // src/logger/adapters/custom.ts
691
+ function initializeTransports() {
692
+ const transports = [];
693
+ const consoleConfig = getConsoleConfig();
694
+ transports.push(new ConsoleTransport(consoleConfig));
695
+ const fileConfig = getFileConfig();
696
+ if (fileConfig.enabled) {
697
+ transports.push(new FileTransport(fileConfig));
698
+ }
699
+ return transports;
700
+ }
701
+ var CustomAdapter = class _CustomAdapter {
702
+ logger;
703
+ constructor(config) {
704
+ this.logger = new Logger({
705
+ level: config.level,
706
+ module: config.module,
707
+ transports: initializeTransports()
708
+ });
709
+ }
710
+ child(module) {
711
+ const adapter = new _CustomAdapter({ level: this.logger.level, module });
712
+ adapter.logger = this.logger.child(module);
713
+ return adapter;
714
+ }
715
+ debug(message, context) {
716
+ this.logger.debug(message, context);
717
+ }
718
+ info(message, context) {
719
+ this.logger.info(message, context);
720
+ }
721
+ warn(message, errorOrContext, context) {
722
+ if (errorOrContext instanceof Error) {
723
+ this.logger.warn(message, errorOrContext, context);
724
+ } else {
725
+ this.logger.warn(message, errorOrContext);
726
+ }
727
+ }
728
+ error(message, errorOrContext, context) {
729
+ if (errorOrContext instanceof Error) {
730
+ this.logger.error(message, errorOrContext, context);
731
+ } else {
732
+ this.logger.error(message, errorOrContext);
733
+ }
734
+ }
735
+ fatal(message, errorOrContext, context) {
736
+ if (errorOrContext instanceof Error) {
737
+ this.logger.fatal(message, errorOrContext, context);
738
+ } else {
739
+ this.logger.fatal(message, errorOrContext);
740
+ }
741
+ }
742
+ async close() {
743
+ await this.logger.close();
744
+ }
745
+ };
746
+
747
+ // src/logger/adapter-factory.ts
748
+ function createAdapter(type) {
749
+ const level = getDefaultLogLevel();
750
+ switch (type) {
751
+ case "pino":
752
+ return new PinoAdapter({ level });
753
+ case "custom":
754
+ return new CustomAdapter({ level });
755
+ default:
756
+ return new PinoAdapter({ level });
757
+ }
758
+ }
759
+ function getAdapterType() {
760
+ const adapterEnv = process.env.LOGGER_ADAPTER;
761
+ if (adapterEnv === "custom" || adapterEnv === "pino") {
762
+ return adapterEnv;
763
+ }
764
+ return "pino";
765
+ }
766
+ function initializeLogger() {
767
+ validateConfig();
768
+ return createAdapter(getAdapterType());
769
+ }
770
+ var logger = initializeLogger();
771
+
772
+ // src/cache/cache-factory.ts
773
+ var cacheLogger = logger.child("cache");
774
+ function hasCacheConfig() {
775
+ return !!// Modern (Valkey/Cache)
776
+ (process.env.VALKEY_URL || process.env.CACHE_URL || process.env.VALKEY_WRITE_URL || process.env.VALKEY_READ_URL || process.env.CACHE_WRITE_URL || process.env.CACHE_READ_URL || process.env.VALKEY_SENTINEL_HOSTS || process.env.VALKEY_CLUSTER_NODES || // Legacy (Redis - backward compatibility)
777
+ process.env.REDIS_URL || process.env.REDIS_WRITE_URL || process.env.REDIS_READ_URL || process.env.REDIS_SENTINEL_HOSTS || process.env.REDIS_CLUSTER_NODES);
778
+ }
779
+ function getEnv(valkeyKey, cacheKey, redisKey) {
780
+ return process.env[valkeyKey] || process.env[cacheKey] || process.env[redisKey];
781
+ }
782
+ function createClient(RedisClient, url) {
783
+ const options = {};
784
+ if (url.startsWith("rediss://") || url.startsWith("valkeys://")) {
785
+ const rejectUnauthorized = getEnv(
786
+ "VALKEY_TLS_REJECT_UNAUTHORIZED",
787
+ "CACHE_TLS_REJECT_UNAUTHORIZED",
788
+ "REDIS_TLS_REJECT_UNAUTHORIZED"
789
+ );
790
+ options.tls = {
791
+ rejectUnauthorized: rejectUnauthorized !== "false"
792
+ };
793
+ }
794
+ return new RedisClient(url, options);
795
+ }
796
+ async function createCacheFromEnv() {
797
+ if (!hasCacheConfig()) {
798
+ cacheLogger.info("No cache configuration found - running without cache");
799
+ return { write: void 0, read: void 0 };
800
+ }
801
+ try {
802
+ const ioredis = await import('ioredis');
803
+ const RedisClient = ioredis.default;
804
+ const singleUrl = getEnv("VALKEY_URL", "CACHE_URL", "REDIS_URL");
805
+ const writeUrl = getEnv("VALKEY_WRITE_URL", "CACHE_WRITE_URL", "REDIS_WRITE_URL");
806
+ const readUrl = getEnv("VALKEY_READ_URL", "CACHE_READ_URL", "REDIS_READ_URL");
807
+ const clusterNodes = getEnv("VALKEY_CLUSTER_NODES", "CACHE_CLUSTER_NODES", "REDIS_CLUSTER_NODES");
808
+ const sentinelHosts = getEnv("VALKEY_SENTINEL_HOSTS", "CACHE_SENTINEL_HOSTS", "REDIS_SENTINEL_HOSTS");
809
+ const masterName = getEnv("VALKEY_MASTER_NAME", "CACHE_MASTER_NAME", "REDIS_MASTER_NAME");
810
+ const password = getEnv("VALKEY_PASSWORD", "CACHE_PASSWORD", "REDIS_PASSWORD");
811
+ if (singleUrl && !writeUrl && !readUrl && !clusterNodes) {
812
+ const client = createClient(RedisClient, singleUrl);
813
+ cacheLogger.debug("Created single cache instance", { url: singleUrl.replace(/:[^:@]+@/, ":***@") });
814
+ return { write: client, read: client };
815
+ }
816
+ if (writeUrl && readUrl) {
817
+ const write = createClient(RedisClient, writeUrl);
818
+ const read = createClient(RedisClient, readUrl);
819
+ cacheLogger.debug("Created master-replica cache instances");
820
+ return { write, read };
821
+ }
822
+ if (sentinelHosts && masterName) {
823
+ const sentinels = sentinelHosts.split(",").map((host) => {
824
+ const [hostname, port] = host.trim().split(":");
825
+ return { host: hostname, port: Number(port) || 26379 };
826
+ });
827
+ const options = {
828
+ sentinels,
829
+ name: masterName,
830
+ password
831
+ };
832
+ const client = new RedisClient(options);
833
+ cacheLogger.debug("Created sentinel cache instance", { masterName, sentinels: sentinels.length });
834
+ return { write: client, read: client };
835
+ }
836
+ if (clusterNodes) {
837
+ const nodes = clusterNodes.split(",").map((node) => {
838
+ const [host, port] = node.trim().split(":");
839
+ return { host, port: Number(port) || 6379 };
840
+ });
841
+ const clusterOptions = {
842
+ redisOptions: {
843
+ password
844
+ }
845
+ };
846
+ const cluster = new RedisClient.Cluster(nodes, clusterOptions);
847
+ cacheLogger.debug("Created cluster cache instance", { nodes: nodes.length });
848
+ return { write: cluster, read: cluster };
849
+ }
850
+ if (singleUrl) {
851
+ const client = createClient(RedisClient, singleUrl);
852
+ cacheLogger.debug("Created cache instance (fallback)", { url: singleUrl.replace(/:[^:@]+@/, ":***@") });
853
+ return { write: client, read: client };
854
+ }
855
+ cacheLogger.info("No valid cache configuration found - running without cache");
856
+ return { write: void 0, read: void 0 };
857
+ } catch (error) {
858
+ if (error instanceof Error) {
859
+ if (error.message.includes("Cannot find module")) {
860
+ cacheLogger.warn(
861
+ "Cache client library not installed",
862
+ error,
863
+ {
864
+ suggestion: "Install ioredis to enable cache: pnpm install ioredis",
865
+ mode: "disabled"
866
+ }
867
+ );
868
+ } else {
869
+ cacheLogger.warn(
870
+ "Failed to create cache client",
871
+ error,
872
+ { mode: "disabled" }
873
+ );
874
+ }
875
+ } else {
876
+ cacheLogger.warn(
877
+ "Failed to create cache client",
878
+ { error: String(error), mode: "disabled" }
879
+ );
880
+ }
881
+ return { write: void 0, read: void 0 };
882
+ }
883
+ }
884
+ async function createSingleCacheFromEnv() {
885
+ const { write } = await createCacheFromEnv();
886
+ return write;
887
+ }
888
+
889
+ // src/cache/cache-manager.ts
890
+ var cacheLogger2 = logger.child("cache");
891
+ var writeInstance;
892
+ var readInstance;
893
+ var isDisabled = false;
894
+ function getCache() {
895
+ return writeInstance;
896
+ }
897
+ function getCacheRead() {
898
+ return readInstance ?? writeInstance;
899
+ }
900
+ function isCacheDisabled() {
901
+ return isDisabled;
902
+ }
903
+ function setCache(write, read) {
904
+ writeInstance = write;
905
+ readInstance = read ?? write;
906
+ isDisabled = !write;
907
+ }
908
+ async function initCache() {
909
+ if (writeInstance) {
910
+ return { write: writeInstance, read: readInstance, disabled: isDisabled };
911
+ }
912
+ const { write, read } = await createCacheFromEnv();
913
+ if (write) {
914
+ try {
915
+ await write.ping();
916
+ if (read && read !== write) {
917
+ await read.ping();
918
+ }
919
+ writeInstance = write;
920
+ readInstance = read;
921
+ isDisabled = false;
922
+ const hasReplica = read && read !== write;
923
+ cacheLogger2.info(
924
+ hasReplica ? "Cache connected (Master-Replica)" : "Cache connected",
925
+ { mode: "enabled" }
926
+ );
927
+ return { write: writeInstance, read: readInstance, disabled: false };
928
+ } catch (error) {
929
+ cacheLogger2.error(
930
+ "Cache connection failed - running in disabled mode",
931
+ error instanceof Error ? error : new Error(String(error)),
932
+ { mode: "disabled" }
933
+ );
934
+ try {
935
+ await write.quit();
936
+ if (read && read !== write) {
937
+ await read.quit();
938
+ }
939
+ } catch {
940
+ }
941
+ isDisabled = true;
942
+ return { write: void 0, read: void 0, disabled: true };
943
+ }
944
+ }
945
+ isDisabled = true;
946
+ cacheLogger2.info("Cache disabled - no configuration or library not installed", { mode: "disabled" });
947
+ return { write: void 0, read: void 0, disabled: true };
948
+ }
949
+ async function closeCache() {
950
+ if (isDisabled) {
951
+ cacheLogger2.debug("Cache already disabled, nothing to close");
952
+ return;
953
+ }
954
+ const closePromises = [];
955
+ if (writeInstance) {
956
+ closePromises.push(
957
+ writeInstance.quit().catch((err) => {
958
+ cacheLogger2.error("Error closing cache write instance", err);
959
+ })
960
+ );
961
+ }
962
+ if (readInstance && readInstance !== writeInstance) {
963
+ closePromises.push(
964
+ readInstance.quit().catch((err) => {
965
+ cacheLogger2.error("Error closing cache read instance", err);
966
+ })
967
+ );
968
+ }
969
+ await Promise.all(closePromises);
970
+ writeInstance = void 0;
971
+ readInstance = void 0;
972
+ isDisabled = true;
973
+ cacheLogger2.info("Cache connections closed", { mode: "disabled" });
974
+ }
975
+ function getCacheInfo() {
976
+ return {
977
+ hasWrite: !!writeInstance,
978
+ hasRead: !!readInstance,
979
+ isReplica: !!(readInstance && readInstance !== writeInstance),
980
+ disabled: isDisabled
981
+ };
982
+ }
983
+ var getRedis = getCache;
984
+ var getRedisRead = getCacheRead;
985
+ var setRedis = setCache;
986
+ var initRedis = initCache;
987
+ var closeRedis = closeCache;
988
+ var getRedisInfo = getCacheInfo;
989
+
990
+ export { closeCache, closeRedis, createCacheFromEnv, createCacheFromEnv as createRedisFromEnv, createSingleCacheFromEnv, createSingleCacheFromEnv as createSingleRedisFromEnv, getCache, getCacheInfo, getCacheRead, getRedis, getRedisInfo, getRedisRead, initCache, initRedis, isCacheDisabled, setCache, setRedis };
991
+ //# sourceMappingURL=index.js.map
992
+ //# sourceMappingURL=index.js.map