@weconjs/core 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,24 +1,98 @@
1
1
  /**
2
2
  * @weconjs/core - Database Connection
3
3
  *
4
- * Manages database connections based on configuration.
4
+ * Manages MongoDB/Mongoose database connections with:
5
+ * - URI builder from config parts
6
+ * - Global plugin registration
7
+ * - FieldShield integration (optional)
8
+ * - Retry logic with exponential backoff
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * import { createDatabaseConnection, buildMongoUri } from '@weconjs/core';
13
+ *
14
+ * // Build URI from parts
15
+ * const uri = buildMongoUri({
16
+ * protocol: 'mongodb',
17
+ * host: 'localhost',
18
+ * port: 27017,
19
+ * database: 'myapp',
20
+ * });
21
+ *
22
+ * // Create connection
23
+ * const db = await createDatabaseConnection({
24
+ * uri,
25
+ * plugins: [myPlugin],
26
+ * fieldShield: { enabled: true, strict: true },
27
+ * });
28
+ *
29
+ * await db.connect();
30
+ * ```
5
31
  */
32
+ import type { DatabaseConfig } from "../types.js";
33
+ /**
34
+ * MongoDB URI parts for building connection string
35
+ */
36
+ export interface MongoUriParts {
37
+ protocol?: string;
38
+ host?: string;
39
+ port?: number;
40
+ database?: string;
41
+ auth?: {
42
+ username?: string;
43
+ password?: string;
44
+ };
45
+ options?: Record<string, string>;
46
+ }
6
47
  /**
7
48
  * Database connection options
8
49
  */
9
50
  export interface DatabaseOptions {
10
51
  /**
11
- * MongoDB connection URI
52
+ * Direct MongoDB connection URI
53
+ * If provided, takes precedence over config parts
12
54
  */
13
- uri: string;
55
+ uri?: string;
14
56
  /**
15
- * Database name
57
+ * Build URI from config parts (alternative to uri)
58
+ */
59
+ config?: MongoUriParts;
60
+ /**
61
+ * Database name (can override config.database)
16
62
  */
17
63
  name?: string;
18
64
  /**
19
- * Connection options
65
+ * Mongoose connection options
20
66
  */
21
67
  options?: Record<string, unknown>;
68
+ /**
69
+ * Global Mongoose plugins to register
70
+ */
71
+ plugins?: Array<{
72
+ plugin: (schema: unknown, options?: unknown) => void;
73
+ options?: unknown;
74
+ }>;
75
+ /**
76
+ * FieldShield integration options
77
+ * If enabled, installs FieldShield before connecting
78
+ */
79
+ fieldShield?: {
80
+ enabled: boolean;
81
+ strict?: boolean;
82
+ debug?: boolean;
83
+ };
84
+ /**
85
+ * Enable debug logging for Mongoose
86
+ */
87
+ debug?: boolean;
88
+ /**
89
+ * Retry configuration
90
+ */
91
+ retry?: {
92
+ maxAttempts?: number;
93
+ delayMs?: number;
94
+ backoffMultiplier?: number;
95
+ };
22
96
  }
23
97
  /**
24
98
  * Database connection instance
@@ -36,7 +110,29 @@ export interface DatabaseConnection {
36
110
  * Check if connected
37
111
  */
38
112
  isConnected: () => boolean;
113
+ /**
114
+ * Get the Mongoose instance (if available)
115
+ */
116
+ mongoose?: unknown;
39
117
  }
118
+ /**
119
+ * Build a MongoDB URI from parts
120
+ *
121
+ * @param parts - URI parts
122
+ * @returns MongoDB connection string
123
+ *
124
+ * @example
125
+ * ```typescript
126
+ * buildMongoUri({
127
+ * protocol: 'mongodb+srv',
128
+ * host: 'cluster0.abc123.mongodb.net',
129
+ * database: 'myapp',
130
+ * auth: { username: 'user', password: 'pass' }
131
+ * });
132
+ * // => 'mongodb+srv://user:pass@cluster0.abc123.mongodb.net/myapp'
133
+ * ```
134
+ */
135
+ export declare function buildMongoUri(parts: MongoUriParts): string;
40
136
  /**
41
137
  * Create a MongoDB database connection
42
138
  *
@@ -44,4 +140,11 @@ export interface DatabaseConnection {
44
140
  * @returns Database connection instance
45
141
  */
46
142
  export declare function createDatabaseConnection(options: DatabaseOptions): Promise<DatabaseConnection>;
143
+ /**
144
+ * Build URI from DatabaseConfig (convenience wrapper)
145
+ *
146
+ * @param config - DatabaseConfig from wecon.config.ts
147
+ * @returns MongoDB connection string
148
+ */
149
+ export declare function buildUriFromConfig(config: DatabaseConfig): string;
47
150
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/database/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B;;OAEG;IACH,GAAG,EAAE,MAAM,CAAC;IAEZ;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;IAEd;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACnC;AAED;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC;;OAEG;IACH,OAAO,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAE7B;;OAEG;IACH,UAAU,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAEhC;;OAEG;IACH,WAAW,EAAE,MAAM,OAAO,CAAC;CAC5B;AAED;;;;;GAKG;AACH,wBAAsB,wBAAwB,CAC5C,OAAO,EAAE,eAAe,GACvB,OAAO,CAAC,kBAAkB,CAAC,CA8B7B"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/database/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAElD;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE;QACL,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;KACnB,CAAC;IACF,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAClC;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B;;;OAGG;IACH,GAAG,CAAC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;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,cAAc,GAAG,MAAM,CAYjE"}
@@ -1,8 +1,75 @@
1
1
  /**
2
2
  * @weconjs/core - Database Connection
3
3
  *
4
- * Manages database connections based on configuration.
4
+ * Manages MongoDB/Mongoose database connections with:
5
+ * - URI builder from config parts
6
+ * - Global plugin registration
7
+ * - FieldShield integration (optional)
8
+ * - Retry logic with exponential backoff
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * import { createDatabaseConnection, buildMongoUri } from '@weconjs/core';
13
+ *
14
+ * // Build URI from parts
15
+ * const uri = buildMongoUri({
16
+ * protocol: 'mongodb',
17
+ * host: 'localhost',
18
+ * port: 27017,
19
+ * database: 'myapp',
20
+ * });
21
+ *
22
+ * // Create connection
23
+ * const db = await createDatabaseConnection({
24
+ * uri,
25
+ * plugins: [myPlugin],
26
+ * fieldShield: { enabled: true, strict: true },
27
+ * });
28
+ *
29
+ * await db.connect();
30
+ * ```
31
+ */
32
+ /**
33
+ * Build a MongoDB URI from parts
34
+ *
35
+ * @param parts - URI parts
36
+ * @returns MongoDB connection string
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * buildMongoUri({
41
+ * protocol: 'mongodb+srv',
42
+ * host: 'cluster0.abc123.mongodb.net',
43
+ * database: 'myapp',
44
+ * auth: { username: 'user', password: 'pass' }
45
+ * });
46
+ * // => 'mongodb+srv://user:pass@cluster0.abc123.mongodb.net/myapp'
47
+ * ```
5
48
  */
49
+ export function buildMongoUri(parts) {
50
+ const { protocol = "mongodb", host = "localhost", port, database = "test", auth, options, } = parts;
51
+ // Build auth string
52
+ let authStr = "";
53
+ if (auth?.username && auth?.password) {
54
+ authStr = `${encodeURIComponent(auth.username)}:${encodeURIComponent(auth.password)}@`;
55
+ }
56
+ // Build host with port
57
+ const hostStr = port && protocol === "mongodb" ? `${host}:${port}` : host;
58
+ // Build query string from options
59
+ let queryStr = "";
60
+ if (options && Object.keys(options).length > 0) {
61
+ queryStr = "?" + Object.entries(options)
62
+ .map(([k, v]) => `${k}=${encodeURIComponent(v)}`)
63
+ .join("&");
64
+ }
65
+ return `${protocol}://${authStr}${hostStr}/${database}${queryStr}`;
66
+ }
67
+ /**
68
+ * Sleep utility for retry logic
69
+ */
70
+ function sleep(ms) {
71
+ return new Promise((resolve) => setTimeout(resolve, ms));
72
+ }
6
73
  /**
7
74
  * Create a MongoDB database connection
8
75
  *
@@ -11,23 +78,71 @@
11
78
  */
12
79
  export async function createDatabaseConnection(options) {
13
80
  let connected = false;
14
- // Dynamic import mongoose to avoid bundling issues
15
- const mongoose = await import("mongoose");
81
+ let mongooseInstance = null;
82
+ // Resolve URI
83
+ const uri = options.uri ?? (options.config ? buildMongoUri(options.config) : null);
84
+ if (!uri) {
85
+ throw new Error("[Wecon] Database connection requires either uri or config. " +
86
+ "Provide options.uri or options.config with host/database.");
87
+ }
88
+ // Retry configuration
89
+ const { maxAttempts = 3, delayMs = 1000, backoffMultiplier = 2, } = options.retry ?? {};
16
90
  return {
17
91
  async connect() {
18
- try {
19
- await mongoose.default.connect(options.uri, options.options);
20
- connected = true;
21
- console.log("[Wecon] Database connected successfully");
92
+ // Dynamic import mongoose
93
+ const mongoose = await import("mongoose");
94
+ mongooseInstance = mongoose;
95
+ // Install FieldShield if enabled
96
+ if (options.fieldShield?.enabled) {
97
+ try {
98
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
99
+ const fieldShieldModule = await import("@weconjs/mongoose-field-shield");
100
+ fieldShieldModule.installFieldShield(mongoose.default, {
101
+ strict: options.fieldShield.strict ?? true,
102
+ debug: options.fieldShield.debug ?? false,
103
+ });
104
+ console.log("[Wecon] FieldShield installed");
105
+ }
106
+ catch {
107
+ console.warn("[Wecon] @weconjs/mongoose-field-shield not installed. Skipping FieldShield setup.");
108
+ }
109
+ }
110
+ // Register global plugins
111
+ if (options.plugins?.length) {
112
+ for (const { plugin, options: pluginOpts } of options.plugins) {
113
+ mongoose.default.plugin(plugin, pluginOpts);
114
+ }
115
+ console.log(`[Wecon] Registered ${options.plugins.length} Mongoose plugin(s)`);
22
116
  }
23
- catch (err) {
24
- console.error("[Wecon] Database connection failed:", err);
25
- throw err;
117
+ // Enable debug mode if requested
118
+ if (options.debug) {
119
+ mongoose.default.set("debug", true);
26
120
  }
121
+ // Connect with retry logic
122
+ let lastError = null;
123
+ let currentDelay = delayMs;
124
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
125
+ try {
126
+ await mongoose.default.connect(uri, options.options);
127
+ connected = true;
128
+ console.log("[Wecon] Database connected successfully");
129
+ return;
130
+ }
131
+ catch (err) {
132
+ lastError = err;
133
+ console.warn(`[Wecon] Database connection attempt ${attempt}/${maxAttempts} failed:`, err.message);
134
+ if (attempt < maxAttempts) {
135
+ console.log(`[Wecon] Retrying in ${currentDelay}ms...`);
136
+ await sleep(currentDelay);
137
+ currentDelay *= backoffMultiplier;
138
+ }
139
+ }
140
+ }
141
+ throw new Error(`[Wecon] Database connection failed after ${maxAttempts} attempts: ${lastError?.message}`);
27
142
  },
28
143
  async disconnect() {
29
- if (connected) {
30
- await mongoose.default.disconnect();
144
+ if (connected && mongooseInstance) {
145
+ await mongooseInstance.default.disconnect();
31
146
  connected = false;
32
147
  console.log("[Wecon] Database disconnected");
33
148
  }
@@ -35,6 +150,27 @@ export async function createDatabaseConnection(options) {
35
150
  isConnected() {
36
151
  return connected;
37
152
  },
153
+ get mongoose() {
154
+ return mongooseInstance?.default;
155
+ },
38
156
  };
39
157
  }
158
+ /**
159
+ * Build URI from DatabaseConfig (convenience wrapper)
160
+ *
161
+ * @param config - DatabaseConfig from wecon.config.ts
162
+ * @returns MongoDB connection string
163
+ */
164
+ export function buildUriFromConfig(config) {
165
+ if (!config.mongoose) {
166
+ throw new Error("[Wecon] config.database.mongoose is required to build URI");
167
+ }
168
+ return buildMongoUri({
169
+ protocol: config.mongoose.protocol,
170
+ host: config.mongoose.host,
171
+ port: config.mongoose.port,
172
+ database: config.mongoose.database,
173
+ auth: config.mongoose.auth,
174
+ });
175
+ }
40
176
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/database/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AA0CH;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,OAAwB;IAExB,IAAI,SAAS,GAAG,KAAK,CAAC;IAEtB,mDAAmD;IACnD,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,UAAU,CAAC,CAAC;IAE1C,OAAO;QACL,KAAK,CAAC,OAAO;YACX,IAAI,CAAC;gBACH,MAAM,QAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,OAAc,CAAC,CAAC;gBACpE,SAAS,GAAG,IAAI,CAAC;gBACjB,OAAO,CAAC,GAAG,CAAC,yCAAyC,CAAC,CAAC;YACzD,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,OAAO,CAAC,KAAK,CAAC,qCAAqC,EAAE,GAAG,CAAC,CAAC;gBAC1D,MAAM,GAAG,CAAC;YACZ,CAAC;QACH,CAAC;QAED,KAAK,CAAC,UAAU;YACd,IAAI,SAAS,EAAE,CAAC;gBACd,MAAM,QAAQ,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC;gBACpC,SAAS,GAAG,KAAK,CAAC;gBAClB,OAAO,CAAC,GAAG,CAAC,+BAA+B,CAAC,CAAC;YAC/C,CAAC;QACH,CAAC;QAED,WAAW;YACT,OAAO,SAAS,CAAC;QACnB,CAAC;KACF,CAAC;AACJ,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/database/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAsGH;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,aAAa,CAAC,KAAoB;IAChD,MAAM,EACJ,QAAQ,GAAG,SAAS,EACpB,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;YAED,MAAM,IAAI,KAAK,CACb,4CAA4C,WAAW,cAAc,SAAS,EAAE,OAAO,EAAE,CAC1F,CAAC;QACJ,CAAC;QAED,KAAK,CAAC,UAAU;YACd,IAAI,SAAS,IAAI,gBAAgB,EAAE,CAAC;gBAClC,MAAM,gBAAgB,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC;gBAC5C,SAAS,GAAG,KAAK,CAAC;gBAClB,OAAO,CAAC,GAAG,CAAC,+BAA+B,CAAC,CAAC;YAC/C,CAAC;QACH,CAAC;QAED,WAAW;YACT,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,IAAI,QAAQ;YACV,OAAO,gBAAgB,EAAE,OAAO,CAAC;QACnC,CAAC;KACF,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,kBAAkB,CAAC,MAAsB;IACvD,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;QACrB,MAAM,IAAI,KAAK,CAAC,2DAA2D,CAAC,CAAC;IAC/E,CAAC;IAED,OAAO,aAAa,CAAC;QACnB,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAC,QAAQ;QAClC,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC,IAAI;QAC1B,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC,IAAI;QAC1B,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAC,QAAQ;QAClC,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC,IAAI;KAC3B,CAAC,CAAC;AACL,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @wecon/core
2
+ * @weconjs/core
3
3
  *
4
4
  * Core package for the Wecon framework.
5
5
  * Provides configuration, module system, and runtime utilities.
@@ -7,12 +7,14 @@
7
7
  export { defineConfig, resolveConfig, loadConfig } from "./config.js";
8
8
  export { defineModule, loadModule, discoverSocketHandlers, discoverSocketMiddleware, resolveModuleDependencies, } from "./module.js";
9
9
  export { createContext, createLogger } from "./context.js";
10
+ export { createWinstonLogger, createConsoleLogger, } from "./logger/index.js";
11
+ export type { LoggerOptions, WinstonBasedLogger } from "./logger/index.js";
10
12
  export { createWecon } from "./server/index.js";
11
- export type { CreateWeconOptions, WeconApp } from "./server/index.js";
13
+ export type { CreateWeconOptions, WeconApp, ApiError, ApiResponse, RespondOptions, } from "./server/index.js";
12
14
  export { loadI18nResources, createI18nMiddleware, initI18n } from "./i18n/index.js";
13
15
  export type { I18nResources } from "./i18n/index.js";
14
- export { createDatabaseConnection } from "./database/index.js";
15
- export type { DatabaseOptions, DatabaseConnection } from "./database/index.js";
16
+ export { createDatabaseConnection, buildMongoUri, buildUriFromConfig, } from "./database/index.js";
17
+ export type { DatabaseOptions, DatabaseConnection, MongoUriParts, } from "./database/index.js";
16
18
  export { createSocketServer, discoverSocketHandlers as discoverSocketHandlersFromModules, discoverSocketMiddleware as discoverSocketMiddlewareFromModules, initializeSocket, setupSocketIO, } from "./socket/index.js";
17
19
  export type { SocketServer, SocketInstance, SocketHandler as SocketHandlerFn, SocketMiddleware as SocketMiddlewareFn, DiscoveredSocketHandler, SocketOptions, } from "./socket/index.js";
18
20
  export type { WeconConfig, ResolvedConfig, AppConfig, DatabaseConfig, LoggingConfig, HttpsConfig, SocketConfig, FeaturesConfig, ModeConfig, WeconHooks, ModuleDefinition, ModuleConfigDefinition, WeconModule, SocketHandler, SocketMiddleware, WeconContext, WeconLogger, WeconServices, Authenticable, AuthConfig, WeconRequest, WeconResponse, RouteHandler, WeconMiddleware, } from "./types.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGtE,OAAO,EACL,YAAY,EACZ,UAAU,EACV,sBAAsB,EACtB,wBAAwB,EACxB,yBAAyB,GAC1B,MAAM,aAAa,CAAC;AAGrB,O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b,YAAY,EACZ,eAAe,GAChB,MAAM,YAAY,CAAC"}
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @wecon/core
2
+ * @weconjs/core
3
3
  *
4
4
  * Core package for the Wecon framework.
5
5
  * Provides configuration, module system, and runtime utilities.
@@ -10,12 +10,14 @@ export { defineConfig, resolveConfig, loadConfig } from "./config.js";
10
10
  export { defineModule, loadModule, discoverSocketHandlers, discoverSocketMiddleware, resolveModuleDependencies, } from "./module.js";
11
11
  // Context
12
12
  export { createContext, createLogger } from "./context.js";
13
+ // Logger
14
+ export { createWinstonLogger, createConsoleLogger, } from "./logger/index.js";
13
15
  // Server
14
16
  export { createWecon } from "./server/index.js";
15
17
  // i18n
16
18
  export { loadI18nResources, createI18nMiddleware, initI18n } from "./i18n/index.js";
17
19
  // Database
18
- export { createDatabaseConnection } from "./database/index.js";
20
+ export { createDatabaseConnection, buildMongoUri, buildUriFromConfig, } from "./database/index.js";
19
21
  // Socket.IO
20
22
  export { createSocketServer, discoverSocketHandlers as discoverSocketHandlersFromModules, discoverSocketMiddleware as discoverSocketMiddlewareFromModules, initializeSocket, setupSocketIO, } from "./socket/index.js";
21
23
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,gBAAgB;AAChB,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEtE,gBAAgB;AAChB,OAAO,EACL,YAAY,EACZ,UAAU,EACV,sBAAsB,EACtB,wBAAwB,EACxB,yBAAyB,GAC1B,MAAM,aAAa,CAAC;AAErB,UAAU;AACV,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAE3D,SAAS;AACT,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGhD,OAAO;AACP,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAGpF,WAAW;AACX,OAAO,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AAG/D,YAAY;AACZ,OAAO,EACL,kBAAkB,EAClB,sBAAsB,IAAI,iCAAiC,EAC3D,wBAAwB,IAAI,mCAAmC,EAC/D,gBAAgB,EAChB,aAAa,GACd,MAAM,mBAAmB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,gBAAgB;AAChB,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEtE,gBAAgB;AAChB,OAAO,EACL,YAAY,EACZ,UAAU,EACV,sBAAsB,EACtB,wBAAwB,EACxB,yBAAyB,GAC1B,MAAM,aAAa,CAAC;AAErB,UAAU;AACV,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAE3D,SAAS;AACT,OAAO,EACL,mBAAmB,EACnB,mBAAmB,GACpB,MAAM,mBAAmB,CAAC;AAG3B,SAAS;AACT,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAShD,OAAO;AACP,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAGpF,WAAW;AACX,OAAO,EACL,wBAAwB,EACxB,aAAa,EACb,kBAAkB,GACnB,MAAM,qBAAqB,CAAC;AAO7B,YAAY;AACZ,OAAO,EACL,kBAAkB,EAClB,sBAAsB,IAAI,iCAAiC,EAC3D,wBAAwB,IAAI,mCAAmC,EAC/D,gBAAgB,EAChB,aAAa,GACd,MAAM,mBAAmB,CAAC"}
@@ -0,0 +1,102 @@
1
+ /**
2
+ * @weconjs/core - Logger Factory
3
+ *
4
+ * Creates Winston-based loggers with optional file rotation.
5
+ * This is the production-ready logger for Wecon applications.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * import { createWinstonLogger } from '@weconjs/core';
10
+ *
11
+ * const logger = createWinstonLogger({
12
+ * level: 'debug',
13
+ * appName: 'my-app',
14
+ * enableFile: true,
15
+ * enableConsole: true,
16
+ * });
17
+ *
18
+ * logger.info('Server started', { port: 3000 });
19
+ * ```
20
+ */
21
+ import type { WeconLogger } from "../types.js";
22
+ /**
23
+ * Logger configuration options
24
+ */
25
+ export interface LoggerOptions {
26
+ /**
27
+ * Log level: 'debug' | 'info' | 'warn' | 'error'
28
+ * @default 'info'
29
+ */
30
+ level?: "debug" | "info" | "warn" | "error";
31
+ /**
32
+ * Application name (used in log prefix)
33
+ */
34
+ appName?: string;
35
+ /**
36
+ * Enable console output
37
+ * @default true
38
+ */
39
+ enableConsole?: boolean;
40
+ /**
41
+ * Enable file output with daily rotation
42
+ * @default false
43
+ */
44
+ enableFile?: boolean;
45
+ /**
46
+ * Directory for log files
47
+ * @default 'logs'
48
+ */
49
+ logDir?: string;
50
+ /**
51
+ * Max file size before rotation (e.g., '20m', '100m')
52
+ * @default '20m'
53
+ */
54
+ maxSize?: string;
55
+ /**
56
+ * Max days to keep logs
57
+ * @default '14d'
58
+ */
59
+ maxFiles?: string;
60
+ /**
61
+ * Use JSON format (for production/log aggregation)
62
+ * @default false (uses pretty format)
63
+ */
64
+ jsonFormat?: boolean;
65
+ }
66
+ /**
67
+ * Extended logger with Winston instance access
68
+ */
69
+ export interface WinstonBasedLogger extends WeconLogger {
70
+ /**
71
+ * Access the underlying Winston logger (if available)
72
+ * This is undefined when Winston is not installed
73
+ */
74
+ winston?: unknown;
75
+ }
76
+ /**
77
+ * Create a production-ready Winston logger
78
+ *
79
+ * Falls back to console-based logger if winston is not installed.
80
+ *
81
+ * @param options - Logger configuration
82
+ * @returns WeconLogger instance
83
+ */
84
+ export declare function createWinstonLogger(options?: LoggerOptions): Promise<WinstonBasedLogger>;
85
+ /**
86
+ * Create a simple console-based logger
87
+ *
88
+ * This is a fallback when Winston is not available.
89
+ *
90
+ * @param options - Logger configuration
91
+ * @returns WeconLogger instance
92
+ */
93
+ export declare function createConsoleLogger(options?: LoggerOptions): WinstonBasedLogger;
94
+ /**
95
+ * Default export for convenience
96
+ */
97
+ declare const _default: {
98
+ createWinstonLogger: typeof createWinstonLogger;
99
+ createConsoleLogger: typeof createConsoleLogger;
100
+ };
101
+ export default _default;
102
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/logger/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE/C;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;IAE5C;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB;;;OAGG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IAExB;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IAErB;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAEhB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB;AAED;;GAEG;AACH,MAAM,WAAW,kBAAmB,SAAQ,WAAW;IACrD;;;OAGG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED;;;;;;;GAOG;AACH,wBAAsB,mBAAmB,CACvC,OAAO,GAAE,aAAkB,GAC1B,OAAO,CAAC,kBAAkB,CAAC,CAyG7B;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,GAAE,aAAkB,GAAG,kBAAkB,CAoCnF;AAED;;GAEG;;;;;AACH,wBAA4D"}
@@ -0,0 +1,147 @@
1
+ /**
2
+ * @weconjs/core - Logger Factory
3
+ *
4
+ * Creates Winston-based loggers with optional file rotation.
5
+ * This is the production-ready logger for Wecon applications.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * import { createWinstonLogger } from '@weconjs/core';
10
+ *
11
+ * const logger = createWinstonLogger({
12
+ * level: 'debug',
13
+ * appName: 'my-app',
14
+ * enableFile: true,
15
+ * enableConsole: true,
16
+ * });
17
+ *
18
+ * logger.info('Server started', { port: 3000 });
19
+ * ```
20
+ */
21
+ /**
22
+ * Create a production-ready Winston logger
23
+ *
24
+ * Falls back to console-based logger if winston is not installed.
25
+ *
26
+ * @param options - Logger configuration
27
+ * @returns WeconLogger instance
28
+ */
29
+ export async function createWinstonLogger(options = {}) {
30
+ const { level = "info", appName = "wecon", enableConsole = true, enableFile = false, logDir = "logs", maxSize = "20m", maxFiles = "14d", jsonFormat = false, } = options;
31
+ try {
32
+ // Dynamic import to avoid bundling issues if winston is not installed
33
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
34
+ const winston = await import("winston");
35
+ const { combine, timestamp, printf, json, errors, colorize } = winston.format;
36
+ // Pretty format for development
37
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
38
+ const prettyFormat = printf(({ level, message, timestamp, stack, ...meta }) => {
39
+ const metaStr = Object.keys(meta).length ? ` ${JSON.stringify(meta)}` : "";
40
+ const logMessage = stack ? `${message}\n${stack}` : message;
41
+ return `${timestamp} [${level.toUpperCase()}] [${appName}]: ${logMessage}${metaStr}`;
42
+ });
43
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
44
+ const transports = [];
45
+ // Console transport
46
+ if (enableConsole) {
47
+ transports.push(new winston.transports.Console({
48
+ handleExceptions: true,
49
+ format: jsonFormat ? json() : combine(colorize(), prettyFormat),
50
+ }));
51
+ }
52
+ // File transports with daily rotation
53
+ if (enableFile) {
54
+ try {
55
+ // Dynamic import for winston-daily-rotate-file
56
+ await import("winston-daily-rotate-file");
57
+ const DailyRotateFile = winston.transports.DailyRotateFile;
58
+ // Application logs
59
+ transports.push(new DailyRotateFile({
60
+ filename: `${logDir}/app-%DATE%.log`,
61
+ datePattern: "YYYY-MM-DD",
62
+ zippedArchive: true,
63
+ maxSize,
64
+ maxFiles,
65
+ level: "info",
66
+ }));
67
+ // Error logs (separate file)
68
+ transports.push(new DailyRotateFile({
69
+ filename: `${logDir}/error-%DATE%.log`,
70
+ datePattern: "YYYY-MM-DD",
71
+ zippedArchive: true,
72
+ maxSize,
73
+ maxFiles: "30d", // Keep error logs longer
74
+ level: "error",
75
+ }));
76
+ }
77
+ catch {
78
+ console.warn("[Wecon] winston-daily-rotate-file not installed. File logging disabled.");
79
+ }
80
+ }
81
+ const winstonLogger = winston.createLogger({
82
+ level,
83
+ format: combine(errors({ stack: true }), timestamp({ format: "YYYY-MM-DD HH:mm:ss" }), jsonFormat ? json() : prettyFormat),
84
+ transports,
85
+ exitOnError: false,
86
+ });
87
+ // Return WeconLogger interface
88
+ return {
89
+ debug: (message, meta) => winstonLogger.debug(message, meta),
90
+ info: (message, meta) => winstonLogger.info(message, meta),
91
+ warn: (message, meta) => winstonLogger.warn(message, meta),
92
+ error: (message, meta) => winstonLogger.error(message, meta),
93
+ winston: winstonLogger,
94
+ };
95
+ }
96
+ catch {
97
+ // Winston not installed - fall back to console logger
98
+ console.warn("[Wecon] winston not installed. Using console-based logger.");
99
+ return createConsoleLogger(options);
100
+ }
101
+ }
102
+ /**
103
+ * Create a simple console-based logger
104
+ *
105
+ * This is a fallback when Winston is not available.
106
+ *
107
+ * @param options - Logger configuration
108
+ * @returns WeconLogger instance
109
+ */
110
+ export function createConsoleLogger(options = {}) {
111
+ const { level = "info", appName = "wecon" } = options;
112
+ const levels = ["debug", "info", "warn", "error"];
113
+ const minLevel = levels.indexOf(level);
114
+ const shouldLog = (logLevel) => levels.indexOf(logLevel) >= minLevel;
115
+ const formatMessage = (lvl, message, meta) => {
116
+ const timestamp = new Date().toISOString();
117
+ const metaStr = meta && Object.keys(meta).length ? ` ${JSON.stringify(meta)}` : "";
118
+ return `${timestamp} [${lvl.toUpperCase()}] [${appName}]: ${message}${metaStr}`;
119
+ };
120
+ return {
121
+ debug: (message, meta) => {
122
+ if (shouldLog("debug")) {
123
+ console.debug(formatMessage("debug", message, meta));
124
+ }
125
+ },
126
+ info: (message, meta) => {
127
+ if (shouldLog("info")) {
128
+ console.info(formatMessage("info", message, meta));
129
+ }
130
+ },
131
+ warn: (message, meta) => {
132
+ if (shouldLog("warn")) {
133
+ console.warn(formatMessage("warn", message, meta));
134
+ }
135
+ },
136
+ error: (message, meta) => {
137
+ if (shouldLog("error")) {
138
+ console.error(formatMessage("error", message, meta));
139
+ }
140
+ },
141
+ };
142
+ }
143
+ /**
144
+ * Default export for convenience
145
+ */
146
+ export default { createWinstonLogger, createConsoleLogger };
147
+ //# sourceMappingURL=index.js.map