ioserver 1.4.2 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,301 @@
1
+ /**
2
+ * @fileoverview Base classes for IOServer components
3
+ *
4
+ * This module provides abstract base classes that define the common interface
5
+ * for Services, Controllers, Managers, Watchers, and Middlewares in the IOServer framework.
6
+ *
7
+ * @author Ben Mz <0x42en@users.noreply.github.com>
8
+ * @version 2.0.0
9
+ * @since 1.0.0
10
+ */
11
+ import { AppHandle } from './IOServer';
12
+ /**
13
+ * Abstract base class for real-time services
14
+ *
15
+ * Services handle WebSocket connections and real-time events.
16
+ * Each public method automatically becomes a WebSocket event handler.
17
+ *
18
+ * @abstract
19
+ * @example
20
+ * ```typescript
21
+ * class ChatService extends BaseService {
22
+ * async sendMessage(socket: any, data: any, callback?: Function) {
23
+ * // Validate data
24
+ * if (!data.message) {
25
+ * throw new IOServerError('Message is required', 400);
26
+ * }
27
+ *
28
+ * // Broadcast to room
29
+ * socket.broadcast.to(data.room).emit('new_message', {
30
+ * message: data.message,
31
+ * username: data.username,
32
+ * timestamp: new Date()
33
+ * });
34
+ *
35
+ * // Send confirmation
36
+ * if (callback) {
37
+ * callback({ status: 'success', messageId: Date.now() });
38
+ * }
39
+ * }
40
+ * }
41
+ * ```
42
+ */
43
+ export declare abstract class BaseService {
44
+ /**
45
+ * Application handle providing access to shared functionality
46
+ * @protected
47
+ */
48
+ protected appHandle: AppHandle;
49
+ /**
50
+ * Creates a new service instance
51
+ * @param {AppHandle} appHandle - Application handle for shared functionality
52
+ */
53
+ constructor(appHandle: AppHandle);
54
+ }
55
+ /**
56
+ * Abstract base class for HTTP controllers
57
+ *
58
+ * Controllers handle HTTP requests and route mapping.
59
+ * Methods are mapped to routes via JSON configuration files.
60
+ *
61
+ * @abstract
62
+ * @example
63
+ * ```typescript
64
+ * class UsersController extends BaseController {
65
+ * async getUser(request: FastifyRequest, reply: FastifyReply) {
66
+ * const { id } = request.params as { id: string };
67
+ *
68
+ * try {
69
+ * const user = await this.appHandle.database.findUser(id);
70
+ *
71
+ * if (!user) {
72
+ * return reply.status(404).send({
73
+ * statusCode: 404,
74
+ * error: 'Not Found',
75
+ * message: 'User not found'
76
+ * });
77
+ * }
78
+ *
79
+ * reply.send(user);
80
+ * } catch (error) {
81
+ * this.appHandle.log(3, `Error fetching user: ${error}`);
82
+ * reply.status(500).send({
83
+ * statusCode: 500,
84
+ * error: 'Internal Server Error',
85
+ * message: 'Failed to fetch user'
86
+ * });
87
+ * }
88
+ * }
89
+ * }
90
+ * ```
91
+ */
92
+ export declare abstract class BaseController {
93
+ /**
94
+ * Application handle providing access to shared functionality
95
+ * @protected
96
+ */
97
+ protected appHandle: AppHandle;
98
+ /**
99
+ * Creates a new controller instance
100
+ * @param {AppHandle} appHandle - Application handle for shared functionality
101
+ */
102
+ constructor(appHandle: AppHandle);
103
+ }
104
+ /**
105
+ * Abstract base class for shared logic managers
106
+ *
107
+ * Managers provide shared functionality across services and controllers.
108
+ * They are registered in the appHandle and accessible by their name.
109
+ *
110
+ * @abstract
111
+ * @example
112
+ * ```typescript
113
+ * class DatabaseManager extends BaseManager {
114
+ * private connection: any;
115
+ *
116
+ * async connect() {
117
+ * try {
118
+ * this.connection = await createConnection({
119
+ * host: process.env.DB_HOST,
120
+ * database: process.env.DB_NAME
121
+ * });
122
+ * this.appHandle.log(6, 'Database connected successfully');
123
+ * } catch (error) {
124
+ * this.appHandle.log(3, `Database connection failed: ${error}`);
125
+ * throw error;
126
+ * }
127
+ * }
128
+ *
129
+ * async findUser(id: string) {
130
+ * return this.connection.query('SELECT * FROM users WHERE id = ?', [id]);
131
+ * }
132
+ *
133
+ * async createUser(userData: any) {
134
+ * const result = await this.connection.query(
135
+ * 'INSERT INTO users (name, email) VALUES (?, ?)',
136
+ * [userData.name, userData.email]
137
+ * );
138
+ * return { id: result.insertId, ...userData };
139
+ * }
140
+ * }
141
+ * ```
142
+ */
143
+ export declare abstract class BaseManager {
144
+ /**
145
+ * Application handle providing access to shared functionality
146
+ * @protected
147
+ */
148
+ protected appHandle: AppHandle;
149
+ /**
150
+ * Creates a new manager instance
151
+ * @param {AppHandle} appHandle - Application handle for shared functionality
152
+ */
153
+ constructor(appHandle: AppHandle);
154
+ }
155
+ /**
156
+ * Abstract base class for background watchers
157
+ *
158
+ * Watchers run background tasks and monitoring processes.
159
+ * The watch() method is called when the server starts.
160
+ *
161
+ * @abstract
162
+ * @example
163
+ * ```typescript
164
+ * class HealthWatcher extends BaseWatcher {
165
+ * private intervalId: NodeJS.Timeout | null = null;
166
+ *
167
+ * async watch() {
168
+ * this.appHandle.log(6, 'Starting health monitoring');
169
+ *
170
+ * this.intervalId = setInterval(async () => {
171
+ * await this.checkSystemHealth();
172
+ * }, 30000); // Check every 30 seconds
173
+ * }
174
+ *
175
+ * private async checkSystemHealth() {
176
+ * try {
177
+ * const memUsage = process.memoryUsage();
178
+ * const cpuUsage = process.cpuUsage();
179
+ *
180
+ * // Log memory usage
181
+ * const memMB = Math.round(memUsage.heapUsed / 1024 / 1024);
182
+ * this.appHandle.log(7, `Memory usage: ${memMB}MB`);
183
+ *
184
+ * // Alert on high memory usage
185
+ * if (memUsage.heapUsed > 100 * 1024 * 1024) { // 100MB
186
+ * this.appHandle.log(4, 'High memory usage detected');
187
+ *
188
+ * // Send alert to monitoring service
189
+ * this.appHandle.send({
190
+ * namespace: 'admin',
191
+ * event: 'health_alert',
192
+ * data: { type: 'memory', usage: memMB }
193
+ * });
194
+ * }
195
+ *
196
+ * } catch (error) {
197
+ * this.appHandle.log(3, `Health check failed: ${error}`);
198
+ * }
199
+ * }
200
+ *
201
+ * stop() {
202
+ * if (this.intervalId) {
203
+ * clearInterval(this.intervalId);
204
+ * this.intervalId = null;
205
+ * }
206
+ * }
207
+ * }
208
+ * ```
209
+ */
210
+ export declare abstract class BaseWatcher {
211
+ /**
212
+ * Application handle providing access to shared functionality
213
+ * @protected
214
+ */
215
+ protected appHandle: AppHandle;
216
+ /**
217
+ * Creates a new watcher instance
218
+ * @param {AppHandle} appHandle - Application handle for shared functionality
219
+ */
220
+ constructor(appHandle: AppHandle);
221
+ /**
222
+ * Abstract method that must be implemented by watchers
223
+ * This method is called when the server starts
224
+ * @abstract
225
+ * @returns {Promise<void>} Promise that resolves when watcher is started
226
+ */
227
+ abstract watch(): Promise<void>;
228
+ }
229
+ /**
230
+ * Abstract base class for middleware components
231
+ *
232
+ * Middlewares provide request/response processing for HTTP routes
233
+ * and WebSocket namespaces.
234
+ *
235
+ * @abstract
236
+ * @example
237
+ * ```typescript
238
+ * class AuthMiddleware extends BaseMiddleware {
239
+ * handle(appHandle: AppHandle) {
240
+ * return (req: any, reply: any, done: any) => {
241
+ * const token = req.headers.authorization;
242
+ *
243
+ * if (!token) {
244
+ * return reply.status(401).send({
245
+ * statusCode: 401,
246
+ * error: 'Unauthorized',
247
+ * message: 'Authorization header required'
248
+ * });
249
+ * }
250
+ *
251
+ * try {
252
+ * // Validate token (pseudo-code)
253
+ * const user = validateJWT(token);
254
+ * req.user = user;
255
+ * done();
256
+ * } catch (error) {
257
+ * appHandle.log(4, `Authentication failed: ${error}`);
258
+ * return reply.status(401).send({
259
+ * statusCode: 401,
260
+ * error: 'Unauthorized',
261
+ * message: 'Invalid token'
262
+ * });
263
+ * }
264
+ * };
265
+ * }
266
+ * }
267
+ *
268
+ * // For WebSocket middleware
269
+ * class SocketAuthMiddleware extends BaseMiddleware {
270
+ * handle(appHandle: AppHandle) {
271
+ * return (socket: any, next: any) => {
272
+ * const token = socket.handshake.auth.token;
273
+ *
274
+ * if (!token) {
275
+ * return next(new Error('Authentication required'));
276
+ * }
277
+ *
278
+ * try {
279
+ * const user = validateJWT(token);
280
+ * socket.user = user;
281
+ * next();
282
+ * } catch (error) {
283
+ * appHandle.log(4, `Socket authentication failed: ${error}`);
284
+ * next(new Error('Invalid token'));
285
+ * }
286
+ * };
287
+ * }
288
+ * }
289
+ * ```
290
+ */
291
+ export declare abstract class BaseMiddleware {
292
+ /**
293
+ * Abstract method that must be implemented by middlewares
294
+ * Returns a middleware function for Fastify or Socket.IO
295
+ * @abstract
296
+ * @param {AppHandle} appHandle - Application handle for shared functionality
297
+ * @returns {Function} Middleware function
298
+ */
299
+ abstract handle(appHandle: AppHandle): (req: any, reply: any, done: any) => void;
300
+ }
301
+ //# sourceMappingURL=BaseClasses.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BaseClasses.d.ts","sourceRoot":"","sources":["../src/BaseClasses.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEvC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,8BAAsB,WAAW;IAC/B;;;OAGG;IACH,SAAS,CAAC,SAAS,EAAE,SAAS,CAAC;IAE/B;;;OAGG;gBACS,SAAS,EAAE,SAAS;CAGjC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,8BAAsB,cAAc;IAClC;;;OAGG;IACH,SAAS,CAAC,SAAS,EAAE,SAAS,CAAC;IAE/B;;;OAGG;gBACS,SAAS,EAAE,SAAS;CAGjC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,8BAAsB,WAAW;IAC/B;;;OAGG;IACH,SAAS,CAAC,SAAS,EAAE,SAAS,CAAC;IAE/B;;;OAGG;gBACS,SAAS,EAAE,SAAS;CAGjC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsDG;AACH,8BAAsB,WAAW;IAC/B;;;OAGG;IACH,SAAS,CAAC,SAAS,EAAE,SAAS,CAAC;IAE/B;;;OAGG;gBACS,SAAS,EAAE,SAAS;IAIhC;;;;;OAKG;IACH,QAAQ,CAAC,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAChC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6DG;AACH,8BAAsB,cAAc;IAClC;;;;;;OAMG;IACH,QAAQ,CAAC,MAAM,CACb,SAAS,EAAE,SAAS,GACnB,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,KAAK,IAAI;CAC7C"}
@@ -0,0 +1,281 @@
1
+ "use strict";
2
+ /**
3
+ * @fileoverview Base classes for IOServer components
4
+ *
5
+ * This module provides abstract base classes that define the common interface
6
+ * for Services, Controllers, Managers, Watchers, and Middlewares in the IOServer framework.
7
+ *
8
+ * @author Ben Mz <0x42en@users.noreply.github.com>
9
+ * @version 2.0.0
10
+ * @since 1.0.0
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.BaseMiddleware = exports.BaseWatcher = exports.BaseManager = exports.BaseController = exports.BaseService = void 0;
14
+ /**
15
+ * Abstract base class for real-time services
16
+ *
17
+ * Services handle WebSocket connections and real-time events.
18
+ * Each public method automatically becomes a WebSocket event handler.
19
+ *
20
+ * @abstract
21
+ * @example
22
+ * ```typescript
23
+ * class ChatService extends BaseService {
24
+ * async sendMessage(socket: any, data: any, callback?: Function) {
25
+ * // Validate data
26
+ * if (!data.message) {
27
+ * throw new IOServerError('Message is required', 400);
28
+ * }
29
+ *
30
+ * // Broadcast to room
31
+ * socket.broadcast.to(data.room).emit('new_message', {
32
+ * message: data.message,
33
+ * username: data.username,
34
+ * timestamp: new Date()
35
+ * });
36
+ *
37
+ * // Send confirmation
38
+ * if (callback) {
39
+ * callback({ status: 'success', messageId: Date.now() });
40
+ * }
41
+ * }
42
+ * }
43
+ * ```
44
+ */
45
+ class BaseService {
46
+ /**
47
+ * Creates a new service instance
48
+ * @param {AppHandle} appHandle - Application handle for shared functionality
49
+ */
50
+ constructor(appHandle) {
51
+ this.appHandle = appHandle;
52
+ }
53
+ }
54
+ exports.BaseService = BaseService;
55
+ /**
56
+ * Abstract base class for HTTP controllers
57
+ *
58
+ * Controllers handle HTTP requests and route mapping.
59
+ * Methods are mapped to routes via JSON configuration files.
60
+ *
61
+ * @abstract
62
+ * @example
63
+ * ```typescript
64
+ * class UsersController extends BaseController {
65
+ * async getUser(request: FastifyRequest, reply: FastifyReply) {
66
+ * const { id } = request.params as { id: string };
67
+ *
68
+ * try {
69
+ * const user = await this.appHandle.database.findUser(id);
70
+ *
71
+ * if (!user) {
72
+ * return reply.status(404).send({
73
+ * statusCode: 404,
74
+ * error: 'Not Found',
75
+ * message: 'User not found'
76
+ * });
77
+ * }
78
+ *
79
+ * reply.send(user);
80
+ * } catch (error) {
81
+ * this.appHandle.log(3, `Error fetching user: ${error}`);
82
+ * reply.status(500).send({
83
+ * statusCode: 500,
84
+ * error: 'Internal Server Error',
85
+ * message: 'Failed to fetch user'
86
+ * });
87
+ * }
88
+ * }
89
+ * }
90
+ * ```
91
+ */
92
+ class BaseController {
93
+ /**
94
+ * Creates a new controller instance
95
+ * @param {AppHandle} appHandle - Application handle for shared functionality
96
+ */
97
+ constructor(appHandle) {
98
+ this.appHandle = appHandle;
99
+ }
100
+ }
101
+ exports.BaseController = BaseController;
102
+ /**
103
+ * Abstract base class for shared logic managers
104
+ *
105
+ * Managers provide shared functionality across services and controllers.
106
+ * They are registered in the appHandle and accessible by their name.
107
+ *
108
+ * @abstract
109
+ * @example
110
+ * ```typescript
111
+ * class DatabaseManager extends BaseManager {
112
+ * private connection: any;
113
+ *
114
+ * async connect() {
115
+ * try {
116
+ * this.connection = await createConnection({
117
+ * host: process.env.DB_HOST,
118
+ * database: process.env.DB_NAME
119
+ * });
120
+ * this.appHandle.log(6, 'Database connected successfully');
121
+ * } catch (error) {
122
+ * this.appHandle.log(3, `Database connection failed: ${error}`);
123
+ * throw error;
124
+ * }
125
+ * }
126
+ *
127
+ * async findUser(id: string) {
128
+ * return this.connection.query('SELECT * FROM users WHERE id = ?', [id]);
129
+ * }
130
+ *
131
+ * async createUser(userData: any) {
132
+ * const result = await this.connection.query(
133
+ * 'INSERT INTO users (name, email) VALUES (?, ?)',
134
+ * [userData.name, userData.email]
135
+ * );
136
+ * return { id: result.insertId, ...userData };
137
+ * }
138
+ * }
139
+ * ```
140
+ */
141
+ class BaseManager {
142
+ /**
143
+ * Creates a new manager instance
144
+ * @param {AppHandle} appHandle - Application handle for shared functionality
145
+ */
146
+ constructor(appHandle) {
147
+ this.appHandle = appHandle;
148
+ }
149
+ }
150
+ exports.BaseManager = BaseManager;
151
+ /**
152
+ * Abstract base class for background watchers
153
+ *
154
+ * Watchers run background tasks and monitoring processes.
155
+ * The watch() method is called when the server starts.
156
+ *
157
+ * @abstract
158
+ * @example
159
+ * ```typescript
160
+ * class HealthWatcher extends BaseWatcher {
161
+ * private intervalId: NodeJS.Timeout | null = null;
162
+ *
163
+ * async watch() {
164
+ * this.appHandle.log(6, 'Starting health monitoring');
165
+ *
166
+ * this.intervalId = setInterval(async () => {
167
+ * await this.checkSystemHealth();
168
+ * }, 30000); // Check every 30 seconds
169
+ * }
170
+ *
171
+ * private async checkSystemHealth() {
172
+ * try {
173
+ * const memUsage = process.memoryUsage();
174
+ * const cpuUsage = process.cpuUsage();
175
+ *
176
+ * // Log memory usage
177
+ * const memMB = Math.round(memUsage.heapUsed / 1024 / 1024);
178
+ * this.appHandle.log(7, `Memory usage: ${memMB}MB`);
179
+ *
180
+ * // Alert on high memory usage
181
+ * if (memUsage.heapUsed > 100 * 1024 * 1024) { // 100MB
182
+ * this.appHandle.log(4, 'High memory usage detected');
183
+ *
184
+ * // Send alert to monitoring service
185
+ * this.appHandle.send({
186
+ * namespace: 'admin',
187
+ * event: 'health_alert',
188
+ * data: { type: 'memory', usage: memMB }
189
+ * });
190
+ * }
191
+ *
192
+ * } catch (error) {
193
+ * this.appHandle.log(3, `Health check failed: ${error}`);
194
+ * }
195
+ * }
196
+ *
197
+ * stop() {
198
+ * if (this.intervalId) {
199
+ * clearInterval(this.intervalId);
200
+ * this.intervalId = null;
201
+ * }
202
+ * }
203
+ * }
204
+ * ```
205
+ */
206
+ class BaseWatcher {
207
+ /**
208
+ * Creates a new watcher instance
209
+ * @param {AppHandle} appHandle - Application handle for shared functionality
210
+ */
211
+ constructor(appHandle) {
212
+ this.appHandle = appHandle;
213
+ }
214
+ }
215
+ exports.BaseWatcher = BaseWatcher;
216
+ /**
217
+ * Abstract base class for middleware components
218
+ *
219
+ * Middlewares provide request/response processing for HTTP routes
220
+ * and WebSocket namespaces.
221
+ *
222
+ * @abstract
223
+ * @example
224
+ * ```typescript
225
+ * class AuthMiddleware extends BaseMiddleware {
226
+ * handle(appHandle: AppHandle) {
227
+ * return (req: any, reply: any, done: any) => {
228
+ * const token = req.headers.authorization;
229
+ *
230
+ * if (!token) {
231
+ * return reply.status(401).send({
232
+ * statusCode: 401,
233
+ * error: 'Unauthorized',
234
+ * message: 'Authorization header required'
235
+ * });
236
+ * }
237
+ *
238
+ * try {
239
+ * // Validate token (pseudo-code)
240
+ * const user = validateJWT(token);
241
+ * req.user = user;
242
+ * done();
243
+ * } catch (error) {
244
+ * appHandle.log(4, `Authentication failed: ${error}`);
245
+ * return reply.status(401).send({
246
+ * statusCode: 401,
247
+ * error: 'Unauthorized',
248
+ * message: 'Invalid token'
249
+ * });
250
+ * }
251
+ * };
252
+ * }
253
+ * }
254
+ *
255
+ * // For WebSocket middleware
256
+ * class SocketAuthMiddleware extends BaseMiddleware {
257
+ * handle(appHandle: AppHandle) {
258
+ * return (socket: any, next: any) => {
259
+ * const token = socket.handshake.auth.token;
260
+ *
261
+ * if (!token) {
262
+ * return next(new Error('Authentication required'));
263
+ * }
264
+ *
265
+ * try {
266
+ * const user = validateJWT(token);
267
+ * socket.user = user;
268
+ * next();
269
+ * } catch (error) {
270
+ * appHandle.log(4, `Socket authentication failed: ${error}`);
271
+ * next(new Error('Invalid token'));
272
+ * }
273
+ * };
274
+ * }
275
+ * }
276
+ * ```
277
+ */
278
+ class BaseMiddleware {
279
+ }
280
+ exports.BaseMiddleware = BaseMiddleware;
281
+ //# sourceMappingURL=BaseClasses.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BaseClasses.js","sourceRoot":"","sources":["../src/BaseClasses.ts"],"names":[],"mappings":";AAAA;;;;;;;;;GASG;;;AAIH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,MAAsB,WAAW;IAO/B;;;OAGG;IACH,YAAY,SAAoB;QAC9B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;CACF;AAdD,kCAcC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,MAAsB,cAAc;IAOlC;;;OAGG;IACH,YAAY,SAAoB;QAC9B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;CACF;AAdD,wCAcC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,MAAsB,WAAW;IAO/B;;;OAGG;IACH,YAAY,SAAoB;QAC9B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;CACF;AAdD,kCAcC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsDG;AACH,MAAsB,WAAW;IAO/B;;;OAGG;IACH,YAAY,SAAoB;QAC9B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;CASF;AAtBD,kCAsBC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6DG;AACH,MAAsB,cAAc;CAWnC;AAXD,wCAWC"}