nexus-fca 2.0.0 โ†’ 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.
package/README.md CHANGED
@@ -2,450 +2,147 @@
2
2
 
3
3
  <img src="https://i.ibb.co/LzkQMGWz/Future-Studio-Synthwave-Logo-Future-Studio-Synthwave-Logo.png" alt="Nexus-FCA Logo" width="500"/>
4
4
 
5
- <h2 align="center"><b>Nexus-FCA: Advanced Facebook Chat API</b></h2>
5
+ </div>
6
6
 
7
- ---
8
-
9
- **๐Ÿš€ Advanced โ€ข ๐Ÿ’Ž Enhanced โ€ข โšก High-Performance Facebook Chat API**
7
+ # Nexus-FCA (2.0.0)
10
8
 
11
- Nexus-FCA is a modern, safe, and advanced Facebook Chat API for Node.js. Built with TypeScript support, enhanced performance optimizations, MQTT connection stability, robust error handling, and a complete compatibility layer for seamless migration from other FCA packages.
9
+ > **A next-generation, high-performance, developer-friendly Facebook Messenger bot framework.**
12
10
 
13
11
  ---
14
12
 
15
- ## โœจ New Enhanced Features
16
-
17
- ### ๐Ÿ”ฅ **Performance Optimizations**
18
- - **Smart Caching System:** LRU/LFU/FIFO cache strategies with automatic cleanup
19
- - **Rate Limiting:** Advanced rate limiting with sliding window algorithm
20
- - **Memory Management:** Automatic memory optimization and garbage collection
21
- - **Metrics Collection:** Real-time performance monitoring and analytics
22
- - **Connection Pooling:** Efficient resource management
23
-
24
- ### ๐Ÿ’Ž **Enhanced TypeScript Support**
25
- - **Complete Type Definitions:** Full TypeScript support with enhanced interfaces
26
- - **Modern ES6+ Features:** Built with latest JavaScript standards
27
- - **Type-Safe APIs:** Compile-time error checking and IntelliSense support
28
- - **Rich Object Models:** Discord.js-style message, user, and thread objects
29
-
30
- ### ๐ŸŒ **MQTT Connection Stability**
31
- - **Auto-Reconnection:** Intelligent reconnection with exponential backoff
32
- - **Heartbeat Monitoring:** Real-time connection health monitoring
33
- - **Circuit Breaker:** Fault tolerance with automatic recovery
34
- - **Connection Pooling:** Multiple connection management
35
- - **Quality of Service:** Guaranteed message delivery
36
-
37
- ### ๐Ÿ”„ **API Compatibility Layer**
38
- - **fca-unofficial Compatible:** Drop-in replacement for fca-unofficial
39
- - **ws3-fca Compatible:** Full compatibility with ws3-fca methods
40
- - **fca-utils Style:** Modern client-based API similar to fca-utils
41
- - **Migration Tools:** Automated migration helpers from other packages
42
- - **Legacy Support:** Backward compatibility with older FCA versions
43
-
44
- ### ๐Ÿ“จ **Enhanced Message Handling**
45
- - **Rich Message Objects:** Discord.js-style message manipulation
46
- - **Attachment Management:** Advanced file and media handling
47
- - **Reaction System:** Full emoji reaction support with management
48
- - **Threading Support:** Reply chains and conversation threading
49
- - **Message History:** Persistent message storage and retrieval
50
-
51
- ### ๐Ÿ’พ **Database & Caching System**
52
- - **SQLite Integration:** High-performance local database storage
53
- - **Session Management:** Persistent login sessions with auto-renewal
54
- - **User & Thread Caching:** Smart caching of user and thread data
55
- - **Message History:** Complete conversation history storage
56
- - **Analytics & Events:** Comprehensive event logging and analytics
57
-
58
- ### โš ๏ธ **Enhanced Error Handling**
59
- - **Retry Mechanisms:** Intelligent retry with exponential backoff
60
- - **Circuit Breaker Pattern:** Automatic failure detection and recovery
61
- - **Fallback Strategies:** Graceful degradation with fallback methods
62
- - **Error Classification:** Smart error categorization and handling
63
- - **Recovery Strategies:** Automatic session recovery and reconnection
64
-
65
- ### ๐ŸŽฏ **Advanced MQTT Features**
66
- - **Multiple Connection Types:** Support for various MQTT protocols
67
- - **Message Queuing:** Reliable message queuing and delivery
68
- - **Topic Management:** Advanced topic subscription and management
69
- - **Load Balancing:** Intelligent load distribution across connections
70
- - **Monitoring & Alerting:** Real-time connection monitoring
13
+ ## ๐Ÿš€ What's New in 2.0.0
14
+ - **PerformanceManager**: Smart caching, metrics, and rate limiting for blazing speed.
15
+ - **Advanced ErrorHandler**: Retry logic, circuit breaker, and fallback strategies for robust bots.
16
+ - **AdvancedMqttManager**: Auto-reconnect, heartbeat, and stable MQTT event handling.
17
+ - **API Compatibility Layer**: Drop-in support for fca-unofficial, ws3-fca, and fca-utils codebases.
18
+ - **Rich Message, Thread, User Classes**: Discord.js-style objects for easy, powerful bot logic.
19
+ - **EnhancedDatabase**: Persistent, high-speed storage for sessions, users, threads, and history.
20
+ - **Full TypeScript Support**: Modern, type-safe APIs and definitions.
21
+ - **Modern Command & Middleware System**: Event-driven, modular, and extensible.
22
+ - **Advanced MQTT Features**: Topic management, load balancing, and real-time monitoring.
23
+ - **Professional Logging**: Clean, colorized, and filterable logs for all environments.
71
24
 
72
25
  ---
73
26
 
74
- ## ๐Ÿš€ Quick Start
75
-
76
- ### Basic Installation
77
- ```bash
78
- npm install nexus-fca
79
- ```
80
-
81
- ### Enhanced Client Usage (Recommended)
82
- ```js
83
- const { NexusClient } = require('nexus-fca');
84
-
85
- const client = new NexusClient({
86
- prefix: '!',
87
- rateLimitEnabled: true,
88
- performanceOptimization: true,
89
- cachingEnabled: true,
90
- logLevel: 'info'
91
- });
92
-
93
- client.on('ready', (api, userID) => {
94
- console.log(`๐Ÿš€ Nexus-FCA Client ready! Logged in as ${userID}`);
95
- });
96
-
97
- client.on('message', async (message) => {
98
- console.log(`๐Ÿ“จ ${message.author.name}: ${message.body}`);
99
-
100
- // Rich message object with methods
101
- if (message.body === 'ping') {
102
- await message.reply('๐Ÿ“ Pong!');
103
- }
104
-
105
- if (message.body === 'react') {
106
- await message.react('โค๏ธ');
107
- }
108
- });
109
-
110
- client.on('command', async ({ name, args, message }) => {
111
- if (name === 'info') {
112
- const thread = await message.getThread();
113
- await message.reply(`๐Ÿ“Š Thread: ${thread.name || 'Private'}\n๐Ÿ‘ฅ Participants: ${thread.participantCount}`);
114
- }
115
- });
116
-
117
- // Login with enhanced error handling
118
- client.login({ appState: require('./appstate.json') })
119
- .catch(console.error);
120
- ```
121
-
122
- ### Traditional Login (Backward Compatible)
123
- ```js
124
- const login = require("nexus-fca");
125
-
126
- login({ appState: [] }, (err, api) => {
127
- if (err) return console.error(err);
128
-
129
- // Enhanced MQTT listening with auto-reconnect
130
- api.listenMqtt((err, event) => {
131
- if (err) return console.error(err);
132
-
133
- // Performance-optimized message sending
134
- api.sendMessage(event.body, event.threadID);
135
- });
136
- });
137
- ```
138
-
139
- ---
140
-
141
- ## ๐ŸŽฏ Advanced Usage Examples
142
-
143
- ### Performance Monitoring
144
- ```js
145
- const { PerformanceManager } = require('nexus-fca');
146
-
147
- const perfManager = new PerformanceManager();
148
-
149
- // Monitor performance metrics
150
- setInterval(() => {
151
- const metrics = perfManager.getMetrics();
152
- console.log(`๐Ÿ“Š Performance Metrics:
153
- ๐Ÿ“ˆ Requests: ${metrics.requestCount}
154
- โฑ๏ธ Avg Response: ${metrics.averageResponseTime}ms
155
- ๐Ÿ’พ Cache Hit Rate: ${metrics.cacheHitRate}%
156
- ๐Ÿง  Memory Usage: ${metrics.memoryUsage}%`);
157
- }, 30000);
158
- ```
159
-
160
- ### Enhanced Error Handling
161
- ```js
162
- const { ErrorHandler } = require('nexus-fca');
163
-
164
- const errorHandler = new ErrorHandler({
165
- retryOptions: {
166
- maxAttempts: 3,
167
- backoffStrategy: 'exponential',
168
- baseDelay: 1000
169
- },
170
- circuitBreakerOptions: {
171
- failureThreshold: 5,
172
- resetTimeout: 60000
173
- }
174
- });
175
-
176
- // Wrap functions with enhanced error handling
177
- const safeSendMessage = errorHandler.retry(async (message, threadID) => {
178
- return await api.sendMessage(message, threadID);
179
- });
180
- ```
181
-
182
- ### Database Integration
183
- ```js
184
- const { EnhancedDatabase } = require('nexus-fca');
185
-
186
- const database = new EnhancedDatabase({
187
- dbPath: './nexus-data.sqlite',
188
- cacheSize: 2000
189
- });
190
-
191
- await database.initialize();
192
-
193
- // Save and retrieve messages
194
- database.on('message', async (message) => {
195
- await database.saveMessage(message);
196
-
197
- // Get conversation history
198
- const history = await database.getMessages(message.threadId, 50);
199
- console.log(`๐Ÿ“š Retrieved ${history.length} messages from history`);
200
- });
201
- ```
202
-
203
- ### Migration from Other FCA Packages
204
- ```js
205
- const { CompatibilityLayer } = require('nexus-fca');
206
-
207
- // Migrate from fca-unofficial
208
- const fcaUnofficial = require('fca-unofficial');
209
- const compatibility = new CompatibilityLayer(api);
210
- const legacyApi = compatibility.createWrapper('fca-unofficial');
211
-
212
- // Your existing fca-unofficial code works unchanged
213
- legacyApi.getThreadHistory(threadID, 50, null, (err, history) => {
214
- console.log('๐Ÿ“œ Thread history:', history);
215
- });
27
+ ## ๐Ÿ–ผ๏ธ Demo
216
28
 
217
- // Auto-adapt existing API
218
- const adaptedApi = compatibility.autoAdapt(yourExistingApi);
219
- ```
220
-
221
- ---
222
-
223
- ---
224
-
225
- ## Key Features
226
-
227
- - **Modern & Safe:**
228
- - Built with ES6+ features and TypeScript. No legacy code.
229
- - **Active Development:**
230
- - Regular updates and improvements. Open to contributions.
231
- - **Easy to Use:**
232
- - Simple API with clear documentation. Get started quickly.
233
- - **No External Dependencies:**
234
- - No need for external libraries. Everything is included.
235
- - **No WebView/Browser Required:**
236
- - Directly interacts with Facebook's Messenger API. No browser automation.
237
- - **No CAPTCHA/Verification:**
238
- - Bypass CAPTCHA and verification challenges. Use at your own risk.
239
- - **No Rate Limits:**
240
- - No restrictions on message sending. Use responsibly.
241
- - **No Account Verification:**
242
- - No need to verify your account. Use with caution.
243
- - **All Major Messenger Features:**
244
- - Messaging, reactions, group management, user info, and more.
245
- - **Safe & Testable:**
246
- - No legacy/unsafe code. Test every feature live in Messenger.
247
- - **Admin & Safety Tools:**
248
- - Rate limiting, allow/block lists, Safe Mode.
249
- - **Easy Login:**
250
- - Use `appstate.json` for secure, passwordless login.
251
- - **Full Documentation:**
252
- - Every feature documented in the `docs/` folder with real usage examples.
29
+ <div align="center">
30
+ <img src="https://i.ibb.co/FbCSF0Pj/Capture.png" alt="Nexus-FCA Demo Screenshot" width="700"/>
31
+ </div>
253
32
 
254
33
  ---
255
34
 
256
- _Disclaimer_: Use responsibly. Nexus-FCA is not affiliated with Facebook. Your account may be at risk if you use this for spam or automation against Facebook's terms.
35
+ ## โœจ Key Features
36
+ - **Modern, Safe, and Actively Maintained**
37
+ - **No WebView/Browser Automation**
38
+ - **No CAPTCHA/Verification Required**
39
+ - **All Major Messenger Features**
40
+ - **Admin & Safety Tools**
41
+ - **Easy Login with `appstate.json`**
42
+ - **Full Documentation & Migration Guides**
257
43
 
258
44
  ---
259
45
 
260
- ## Install
261
-
46
+ ## ๐Ÿ“ฆ Installation
262
47
  ```bash
263
48
  npm install nexus-fca
264
49
  ```
265
50
 
266
- ## Example Usage
51
+ ---
267
52
 
53
+ ## ๐Ÿ› ๏ธ Quick Start Example
268
54
  ```js
269
55
  const login = require("nexus-fca");
270
56
 
271
- login({ appState: [] }, (err, api) => {
272
- if (err) return console.error(err);
273
-
57
+ login({ appState: require("./appstate.json") }, (err, api) => {
58
+ if (err) return console.error("Login error:", err);
274
59
  api.listenMqtt((err, event) => {
275
- if (err) return console.error(err);
276
- api.sendMessage(event.body, event.threadID);
60
+ if (err) return console.error("Listen error:", err);
61
+ if (event.body && event.threadID) {
62
+ api.sendMessage("Echo: " + event.body, event.threadID);
63
+ }
277
64
  });
278
65
  });
279
66
  ```
280
67
 
281
- Result:
282
-
283
- <img width="517" alt="screen shot 2016-11-04 at 14 36 00" src="https://cloud.githubusercontent.com/assets/4534692/20023545/f8c24130-a29d-11e6-9ef7-47568bdbc1f2.png">
284
-
285
- ## Main Functionality
286
-
287
- ### Sending a message
288
-
289
- #### api.sendMessage(message, threadID[, callback][, messageID])
290
-
291
- Various types of message can be sent:
292
-
293
- * *Regular:* set field `body` to the desired message as a string.
294
- * *Sticker:* set a field `sticker` to the desired sticker ID.
295
- * *File or image:* Set field `attachment` to a readable stream or an array of readable streams.
296
- * *URL:* set a field `url` to the desired URL.
297
- * *Emoji:* set field `emoji` to the desired emoji as a string and set field `emojiSize` with size of the emoji (`small`, `medium`, `large`)
298
-
299
- Note that a message can only be a regular message (which can be empty) and optionally one of the following: a sticker, an attachment or a url.
300
-
301
- __Tip__: to find your own ID, you can look inside the cookies. The `userID` is under the name `c_user`.
302
-
303
- __Example (Basic Message)__
68
+ ---
304
69
 
70
+ ## ๐Ÿง‘โ€๐Ÿ’ป Modern Client Example (Recommended)
305
71
  ```js
306
- const login = require("nexus-fca");
72
+ const { NexusClient } = require('nexus-fca');
307
73
 
308
- login({ appState: [] }, (err, api) => {
309
- if (err) {
310
- console.error("Login Error:", err);
311
- return;
312
- }
313
-
314
- let yourID = "000000000000000"; // Replace with actual Facebook ID
315
- let msg = "Hey!";
316
-
317
- api.sendMessage(msg, yourID, (err) => {
318
- if (err) console.error("Message Sending Error:", err);
319
- else console.log("Message sent successfully!");
320
- });
74
+ const client = new NexusClient({
75
+ prefix: '!',
76
+ rateLimitEnabled: true,
77
+ performanceOptimization: true,
78
+ cachingEnabled: true,
79
+ logLevel: 'info'
321
80
  });
322
81
 
323
- ```
324
-
325
- __Example (File upload)__
82
+ client.on('ready', (api, userID) => {
83
+ console.log(`โœ… Ready as ${userID}`);
84
+ });
326
85
 
327
- ```js
328
- const login = require("nexus-fca");
329
- const fs = require("fs"); // โœ… Required the fs module
330
-
331
- login({ appState: [] }, (err, api) => {
332
- if (err) {
333
- console.error("Login Error:", err);
334
- return;
335
- }
336
-
337
- let yourID = "000000000000000"; // Replace with actual Facebook ID
338
- let imagePath = __dirname + "/image.jpg";
339
-
340
- // Check if the file exists before sending
341
- if (!fs.existsSync(imagePath)) {
342
- console.error("Error: Image file not found!");
343
- return;
344
- }
345
-
346
- let msg = {
347
- body: "Hey!",
348
- attachment: fs.createReadStream(imagePath)
349
- };
350
-
351
- api.sendMessage(msg, yourID, (err) => {
352
- if (err) console.error("Message Sending Error:", err);
353
- else console.log("Message sent successfully!");
354
- });
86
+ client.on('message', async (message) => {
87
+ if (message.body === 'ping') await message.reply('๐Ÿ“ Pong!');
355
88
  });
356
89
 
90
+ client.login({ appState: require('./appstate.json') });
357
91
  ```
358
92
 
359
93
  ---
360
94
 
361
- ### Saving session.
362
-
363
- To avoid logging in every time you should save AppState (cookies etc.) to a file, then you can use it without having password in your scripts.
364
-
365
- __Example__
366
-
367
- ```js
368
- const fs = require("fs");
369
- const login = require("nexus-fca");
370
-
371
- const credentials = { appState: [] };
372
-
373
- login(credentials, (err, api) => {
374
- if (err) {
375
- console.error("Login Error:", err);
376
- return;
377
- }
378
-
379
- try {
380
- const appState = JSON.stringify(api.getAppState(), null, 2); // Pretty print for readability
381
- fs.writeFileSync("appstate.json", appState);
382
- console.log("โœ… AppState saved successfully!");
383
- } catch (error) {
384
- console.error("Error saving AppState:", error);
385
- }
386
- });
387
-
388
- ```
95
+ ## ๐Ÿ—๏ธ Architecture Overview
96
+ - **lib/performance/PerformanceManager.js**: Caching, metrics, rate limiting
97
+ - **lib/error/ErrorHandler.js**: Retry, circuit breaker, fallback
98
+ - **lib/mqtt/AdvancedMqttManager.js**: Robust MQTT connection
99
+ - **lib/compatibility/NexusClient.js**: Modern API, command system, middleware
100
+ - **lib/message/Message.js, Thread.js, User.js**: Rich object models
101
+ - **lib/database/EnhancedDatabase.js**: Persistent, high-speed storage
102
+ - **lib/compatibility/CompatibilityLayer.js**: API migration and compatibility
389
103
 
390
104
  ---
391
105
 
392
- ### Listening to a chat
106
+ ## ๐Ÿ”„ Migration & Compatibility
107
+ - **fca-unofficial**: Drop-in replacement, all methods supported
108
+ - **ws3-fca**: Compatible method names and event system
109
+ - **fca-utils**: Modern client API, command/middleware system
110
+ - **Migration helpers**: See `docs/Migration-fca-unofficial.md` for step-by-step guides
393
111
 
394
- #### api.listenMqtt(callback)
112
+ ---
395
113
 
396
- Listen watches for messages sent in a chat. By default this won't receive events (joining/leaving a chat, title change etcโ€ฆ) but it can be activated with `api.setOptions({listenEvents: true})`. This will by default ignore messages sent by the current account, you can enable listening to your own messages with `api.setOptions({selfListen: true})`.
114
+ ## ๐Ÿ“ Advanced Features
115
+ - **PerformanceManager**: `getMetrics()`, `setCache()`, `checkRateLimit()`
116
+ - **ErrorHandler**: `retry()`, `setFallback()`, `getErrorStats()`
117
+ - **AdvancedMqttManager**: `connect()`, `on('connected')`, `startHeartbeat()`
118
+ - **EnhancedDatabase**: `saveUser()`, `getMessages()`, `saveSession()`, `logEvent()`
119
+ - **CompatibilityLayer**: `createWrapper()`, `autoAdapt()`, `createLegacyApi()`
120
+ - **Rich Message Objects**: `reply()`, `react()`, `edit()`, `forward()`, `pin()`, `markAsRead()`
121
+ - **Thread/User Objects**: `addUser()`, `removeUser()`, `changeName()`, `getAdmins()`, `makeAdmin()`
397
122
 
398
- __Example__
123
+ ---
399
124
 
400
- ```js
401
- const fs = require("fs");
402
- const login = require("nexus-fca");
125
+ ## ๐Ÿ“š Documentation & Guides
126
+ - **Full API Reference**: See [`DOCS.md`](./DOCS.md)
127
+ - **Migration Guides**: See [`docs/`](./docs/) for fca-unofficial, ws3-fca, fca-utils
128
+ - **TypeScript Usage**: Complete types in [`index.d.ts`](./index.d.ts)
129
+ - **Performance & Error Handling**: See advanced sections in docs
403
130
 
404
- // Simple echo bot: Repeats everything you say. Stops when you say "/stop".
405
- login({ appState: JSON.parse(fs.readFileSync("appstate.json", "utf8")) }, (err, api) => {
406
- if (err) {
407
- console.error("Login Error:", err);
408
- return;
409
- }
131
+ ---
410
132
 
411
- api.setOptions({ listenEvents: true });
133
+ ## ๐Ÿ›ก๏ธ Troubleshooting
134
+ - **MQTT Connection Refused**: Check your `appstate.json`, resolve Facebook checkpoints, or try a new account.
135
+ - **TypeScript Errors**: Ensure you are using the latest `index.d.ts` and TypeScript version.
136
+ - **Other Issues**: See logs, check for updates, or open an issue on GitHub.
412
137
 
413
- const stopListening = api.listenMqtt((err, event) => {
414
- if (err) {
415
- console.error("Listen Error:", err);
416
- return;
417
- }
418
-
419
- // Mark message as read
420
- api.markAsRead(event.threadID, (err) => {
421
- if (err) console.error("Mark as read error:", err);
422
- });
423
-
424
- // Handle different event types
425
- switch (event.type) {
426
- case "message":
427
- if (event.body && event.body.trim().toLowerCase() === "/stop") {
428
- api.sendMessage("Goodbyeโ€ฆ", event.threadID);
429
- stopListening();
430
- return;
431
- }
432
- api.sendMessage(`TEST BOT: ${event.body}`, event.threadID);
433
- break;
434
-
435
- case "event":
436
- console.log("Event Received:", event);
437
- break;
438
- }
439
- });
440
- });
138
+ ---
441
139
 
442
- ```
140
+ ## ๐Ÿ’ฌ Community & Support
141
+ - **GitHub**: [github.com/Nexus-016/Nexus-fCA](https://github.com/Nexus-016/Nexus-fCA)
142
+ - **Docs**: See `/docs` for per-feature usage and migration
143
+ - **Contributions**: PRs and issues welcome!
443
144
 
444
145
  ---
445
146
 
446
- ## Advanced Safety & Admin Features
447
-
448
- - **Global Rate Limiting:** Prevents spam and abuse for all sensitive actions (e.g., avatar change, messaging).
449
- - **Safe Mode:** Set `NEXUS_FCA_SAFE_MODE=1` in your environment to disable risky features (like avatar/group changes) for extra protection.
450
- - **Allow/Block List:** Control who can use the API with `NEXUS_FCA_ALLOW_LIST` and `NEXUS_FCA_BLOCK_LIST` (comma-separated user IDs).
451
- - **Health Check:** Use `api.healthCheck((err, status) => { ... })` to verify the bot is running and see current safety status.
147
+ ## โš ๏ธ Disclaimer
148
+ Nexus-FCA is not affiliated with Facebook. Use responsibly and at your own risk. Automation may violate Facebookโ€™s terms of service.
package/index.js CHANGED
@@ -24,8 +24,8 @@ const { User } = require('./lib/message/User');
24
24
 
25
25
  // Legacy imports for backward compatibility
26
26
  const MqttManager = require('./lib/mqtt/MqttManager');
27
- const { DatabaseManager } = require('./lib/database/DatabaseManager');
28
- const { PerformanceOptimizer } = require('./lib/performance/PerformanceOptimizer');
27
+ const { DatabaseManager, getInstance } = require('./lib/database/DatabaseManager');
28
+ const { PerformanceOptimizer, getInstance: getPerformanceOptimizerInstance } = require('./lib/performance/PerformanceOptimizer');
29
29
 
30
30
  let checkVerified = null;
31
31
  const defaultLogRecordSize = 100;
@@ -150,7 +150,6 @@ function buildAPI(globalOptions, html, jar) {
150
150
  const url = new URL(mqttEndpoint);
151
151
  region = url.searchParams.get("region")?.toUpperCase() || "PRN";
152
152
  }
153
- logger(`Server region ${region}`, 'info');
154
153
  } catch (e) {
155
154
  log.warning("login", "Not MQTT endpoint");
156
155
  }
@@ -161,8 +160,8 @@ function buildAPI(globalOptions, html, jar) {
161
160
 
162
161
 
163
162
  // Initialize enhanced systems
164
- const dbManager = DatabaseManager.getInstance();
165
- const performanceOptimizer = PerformanceOptimizer.getInstance();
163
+ const dbManager = getInstance();
164
+ const performanceOptimizer = getPerformanceOptimizerInstance();
166
165
  (async () => {
167
166
  try {
168
167
  await models.sequelize.authenticate();
@@ -174,7 +173,7 @@ function buildAPI(globalOptions, html, jar) {
174
173
  })();
175
174
  // Professional gradient banner for Nexus-FCA
176
175
  logger('โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•', 'info');
177
- logger(' Welcome to Nexus-FCA - Advanced & Safe Facebook Chat API', 'info');
176
+ logger(' Nexus-FCA - Advanced & Safe Facebook Chat API', 'info');
178
177
  logger('โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•', 'info');
179
178
  logger(`Nexus-FCA`, 'info');
180
179
  const ctx = {
@@ -386,6 +385,8 @@ function login(loginData, options, callback) {
386
385
  return returnPromise;
387
386
  }
388
387
 
388
+ const enhancedDatabase = new EnhancedDatabase();
389
+
389
390
  // Enhanced exports
390
391
  module.exports = login;
391
392
  module.exports.NexusClient = NexusClient;
@@ -270,375 +270,8 @@ class RateLimitError extends NexusError {
270
270
  }
271
271
 
272
272
  /**
273
- * Enhanced Error Handler Class
273
+ * Create singleton instance
274
274
  */
275
- class ErrorHandler {
276
- constructor() {
277
- this.errorLog = [];
278
- this.maxLogSize = 1000;
279
- this.errorCounts = new Map();
280
- this.recoveryStrategies = new Map();
281
- this.userFriendlyMessages = new Map();
282
-
283
- this._setupErrorMappings();
284
- this._setupRecoveryStrategies();
285
- this._setupUserFriendlyMessages();
286
- }
287
-
288
- /**
289
- * Setup error code mappings
290
- * @private
291
- */
292
- _setupErrorMappings() {
293
- this.errorMappings = {
294
- // Login errors
295
- 'ECONNREFUSED': 'LOGIN_NETWORK_ERROR',
296
- 'ETIMEDOUT': 'LOGIN_TIMEOUT',
297
- 'ENOTFOUND': 'LOGIN_DNS_ERROR',
298
-
299
- // Session errors
300
- 'Session expired': 'SESSION_EXPIRED',
301
- 'Not logged in': 'SESSION_INVALID',
302
- 'Invalid session': 'SESSION_INVALID',
303
-
304
- // Rate limiting
305
- 'Rate limit exceeded': 'RATE_LIMITED',
306
- 'Too many requests': 'RATE_LIMITED',
307
-
308
- // Network errors
309
- 'ECONNRESET': 'NETWORK_CONNECTION_RESET',
310
- 'ECONNABORTED': 'NETWORK_CONNECTION_ABORTED',
311
-
312
- // Facebook-specific errors
313
- 'GraphMethodException': 'FB_GRAPH_ERROR',
314
- 'OAuthException': 'FB_AUTH_ERROR',
315
- 'MQTT connection failed': 'MQTT_CONNECTION_ERROR',
316
-
317
- // Validation errors
318
- 'Invalid threadID': 'INVALID_THREAD_ID',
319
- 'Invalid userID': 'INVALID_USER_ID',
320
- 'Invalid message format': 'INVALID_MESSAGE_FORMAT'
321
- };
322
- }
323
-
324
- /**
325
- * Setup recovery strategies
326
- * @private
327
- */
328
- _setupRecoveryStrategies() {
329
- this.recoveryStrategies.set('SESSION_EXPIRED', async (error, context) => {
330
- logger('๐Ÿ”„ Attempting session recovery...', 'warn');
331
- // Try to refresh tokens
332
- if (context.api && context.api.refreshFb_dtsg) {
333
- try {
334
- await context.api.refreshFb_dtsg();
335
- return { success: true, message: 'Session refreshed successfully' };
336
- } catch (refreshError) {
337
- return { success: false, message: 'Session refresh failed', requiresReLogin: true };
338
- }
339
- }
340
- return { success: false, message: 'No refresh method available', requiresReLogin: true };
341
- });
342
-
343
- this.recoveryStrategies.set('NETWORK_ERROR', async (error, context) => {
344
- logger('๐Ÿ”„ Attempting network recovery...', 'warn');
345
- // Implement exponential backoff
346
- const retryDelay = Math.min(1000 * Math.pow(2, error.retryCount || 0), 30000);
347
- await this._delay(retryDelay);
348
- return { success: true, message: `Retrying after ${retryDelay}ms`, retry: true };
349
- });
350
-
351
- this.recoveryStrategies.set('MQTT_CONNECTION_ERROR', async (error, context) => {
352
- logger('๐Ÿ”„ Attempting MQTT recovery...', 'warn');
353
- if (context.mqttManager) {
354
- try {
355
- await context.mqttManager.connect();
356
- return { success: true, message: 'MQTT reconnected successfully' };
357
- } catch (mqttError) {
358
- return { success: false, message: 'MQTT recovery failed', retry: true };
359
- }
360
- }
361
- return { success: false, message: 'No MQTT manager available' };
362
- });
363
-
364
- this.recoveryStrategies.set('RATE_LIMITED', async (error, context) => {
365
- logger('โณ Rate limit detected, implementing backoff...', 'warn');
366
- const backoffTime = error.retryAfter ? error.retryAfter * 1000 : 60000;
367
- await this._delay(backoffTime);
368
- return { success: true, message: `Rate limit backoff completed`, retry: true };
369
- });
370
- }
371
-
372
- /**
373
- * Setup user-friendly error messages
374
- * @private
375
- */
376
- _setupUserFriendlyMessages() {
377
- this.userFriendlyMessages.set('LOGIN_FAILED', 'Failed to login. Please check your credentials and try again.');
378
- this.userFriendlyMessages.set('SESSION_EXPIRED', 'Your session has expired. Please login again.');
379
- this.userFriendlyMessages.set('NETWORK_ERROR', 'Network connection issue. Please check your internet connection.');
380
- this.userFriendlyMessages.set('RATE_LIMITED', 'You are sending messages too quickly. Please slow down.');
381
- this.userFriendlyMessages.set('INVALID_THREAD_ID', 'Invalid chat/group ID provided.');
382
- this.userFriendlyMessages.set('INVALID_USER_ID', 'Invalid user ID provided.');
383
- this.userFriendlyMessages.set('MQTT_CONNECTION_ERROR', 'Real-time connection issue. Attempting to reconnect...');
384
- this.userFriendlyMessages.set('FB_AUTH_ERROR', 'Facebook authentication error. Please re-login.');
385
- this.userFriendlyMessages.set('UNKNOWN_ERROR', 'An unexpected error occurred. Please try again.');
386
- }
387
-
388
- /**
389
- * Enhanced error processing
390
- */
391
- async handleError(error, context = {}) {
392
- const processedError = this._processError(error);
393
-
394
- // Log the error
395
- this._logError(processedError, context);
396
-
397
- // Attempt recovery if possible
398
- let recoveryResult = null;
399
- if (processedError.recoverable) {
400
- recoveryResult = await this._attemptRecovery(processedError, context);
401
- }
402
-
403
- // Return processed error with recovery info
404
- return {
405
- error: processedError,
406
- recovery: recoveryResult,
407
- userMessage: this._getUserFriendlyMessage(processedError.code),
408
- timestamp: new Date().toISOString()
409
- };
410
- }
411
-
412
- /**
413
- * Process raw error into structured format
414
- * @private
415
- */
416
- _processError(error) {
417
- let processedError;
418
-
419
- if (error instanceof NexusError) {
420
- processedError = error;
421
- } else {
422
- // Map common errors to structured format
423
- const errorCode = this._mapErrorCode(error);
424
- const isRecoverable = this._isRecoverable(errorCode);
425
-
426
- processedError = new NexusError(
427
- error.message || 'Unknown error',
428
- errorCode,
429
- isRecoverable
430
- );
431
- processedError.originalError = error;
432
- }
433
-
434
- // Add additional context
435
- processedError.stack = error.stack;
436
- processedError.retryCount = (processedError.retryCount || 0);
437
-
438
- return processedError;
439
- }
440
-
441
- /**
442
- * Map error message/code to structured code
443
- * @private
444
- */
445
- _mapErrorCode(error) {
446
- const message = error.message || '';
447
- const code = error.code || '';
448
-
449
- // Check direct code mapping
450
- if (this.errorMappings[code]) {
451
- return this.errorMappings[code];
452
- }
453
-
454
- // Check message content mapping
455
- for (const [pattern, mappedCode] of Object.entries(this.errorMappings)) {
456
- if (message.includes(pattern)) {
457
- return mappedCode;
458
- }
459
- }
460
-
461
- // Check error type
462
- if (error.name === 'ValidationError') return 'VALIDATION_ERROR';
463
- if (error.name === 'TypeError') return 'TYPE_ERROR';
464
- if (error.name === 'ReferenceError') return 'REFERENCE_ERROR';
465
-
466
- return 'UNKNOWN_ERROR';
467
- }
468
-
469
- /**
470
- * Determine if error is recoverable
471
- * @private
472
- */
473
- _isRecoverable(errorCode) {
474
- const recoverableErrors = [
475
- 'NETWORK_ERROR',
476
- 'NETWORK_CONNECTION_RESET',
477
- 'NETWORK_CONNECTION_ABORTED',
478
- 'LOGIN_TIMEOUT',
479
- 'LOGIN_NETWORK_ERROR',
480
- 'MQTT_CONNECTION_ERROR',
481
- 'SESSION_EXPIRED',
482
- 'RATE_LIMITED'
483
- ];
484
-
485
- return recoverableErrors.includes(errorCode);
486
- }
487
-
488
- /**
489
- * Attempt error recovery
490
- * @private
491
- */
492
- async _attemptRecovery(error, context) {
493
- const strategy = this.recoveryStrategies.get(error.code);
494
-
495
- if (!strategy) {
496
- return { success: false, message: 'No recovery strategy available' };
497
- }
498
-
499
- try {
500
- logger(`๐Ÿ”„ Attempting recovery for ${error.code}...`, 'info');
501
- const result = await strategy(error, context);
502
-
503
- if (result.success) {
504
- logger(`โœ… Recovery successful for ${error.code}`, 'info');
505
- } else {
506
- logger(`โŒ Recovery failed for ${error.code}: ${result.message}`, 'warn');
507
- }
508
-
509
- return result;
510
- } catch (recoveryError) {
511
- logger(`โŒ Recovery strategy failed: ${recoveryError.message}`, 'error');
512
- return {
513
- success: false,
514
- message: `Recovery strategy failed: ${recoveryError.message}`
515
- };
516
- }
517
- }
518
-
519
- /**
520
- * Log error with context
521
- * @private
522
- */
523
- _logError(error, context) {
524
- const errorEntry = {
525
- timestamp: new Date().toISOString(),
526
- code: error.code,
527
- message: error.message,
528
- recoverable: error.recoverable,
529
- context: {
530
- userID: context.userID,
531
- threadID: context.threadID,
532
- action: context.action,
533
- retryCount: error.retryCount
534
- },
535
- stack: error.stack
536
- };
537
-
538
- // Add to memory log
539
- this.errorLog.push(errorEntry);
540
- if (this.errorLog.length > this.maxLogSize) {
541
- this.errorLog.shift();
542
- }
543
-
544
- // Update error counts
545
- const count = this.errorCounts.get(error.code) || 0;
546
- this.errorCounts.set(error.code, count + 1);
547
-
548
- // Log to console with appropriate level
549
- const logLevel = error.recoverable ? 'warn' : 'error';
550
- logger(`[${error.code}] ${error.message}`, logLevel);
551
-
552
- // Save to file if critical
553
- if (!error.recoverable) {
554
- this._saveErrorToFile(errorEntry);
555
- }
556
- }
557
-
558
- /**
559
- * Save critical errors to file
560
- * @private
561
- */
562
- _saveErrorToFile(errorEntry) {
563
- try {
564
- const logDir = path.join(__dirname, '../../logs');
565
- if (!fs.existsSync(logDir)) {
566
- fs.mkdirSync(logDir, { recursive: true });
567
- }
568
-
569
- const logFile = path.join(logDir, 'errors.log');
570
- const logLine = `${errorEntry.timestamp} [${errorEntry.code}] ${errorEntry.message}\n`;
571
-
572
- fs.appendFileSync(logFile, logLine, 'utf8');
573
- } catch (fileError) {
574
- logger(`Failed to save error to file: ${fileError.message}`, 'warn');
575
- }
576
- }
577
-
578
- /**
579
- * Get user-friendly error message
580
- * @private
581
- */
582
- _getUserFriendlyMessage(errorCode) {
583
- return this.userFriendlyMessages.get(errorCode) ||
584
- this.userFriendlyMessages.get('UNKNOWN_ERROR');
585
- }
586
-
587
- /**
588
- * Utility delay function
589
- * @private
590
- */
591
- _delay(ms) {
592
- return new Promise(resolve => setTimeout(resolve, ms));
593
- }
594
-
595
- /**
596
- * Get error statistics
597
- */
598
- getErrorStats() {
599
- const totalErrors = this.errorLog.length;
600
- const errorsByCode = Object.fromEntries(this.errorCounts);
601
- const recentErrors = this.errorLog.slice(-10);
602
-
603
- return {
604
- totalErrors,
605
- errorsByCode,
606
- recentErrors,
607
- memoryLogSize: this.errorLog.length
608
- };
609
- }
610
-
611
- /**
612
- * Clear error log
613
- */
614
- clearErrorLog() {
615
- this.errorLog = [];
616
- this.errorCounts.clear();
617
- logger('๐Ÿงน Error log cleared', 'info');
618
- }
619
-
620
- /**
621
- * Add custom recovery strategy
622
- */
623
- addRecoveryStrategy(errorCode, strategy) {
624
- if (typeof strategy !== 'function') {
625
- throw new ValidationError('Recovery strategy must be a function');
626
- }
627
-
628
- this.recoveryStrategies.set(errorCode, strategy);
629
- logger(`โœ… Added recovery strategy for ${errorCode}`, 'info');
630
- }
631
-
632
- /**
633
- * Add custom user-friendly message
634
- */
635
- addUserFriendlyMessage(errorCode, message) {
636
- this.userFriendlyMessages.set(errorCode, message);
637
- logger(`โœ… Added user-friendly message for ${errorCode}`, 'info');
638
- }
639
- }
640
-
641
- // Create singleton instance
642
275
  const errorHandler = new ErrorHandler();
643
276
 
644
277
  /**
@@ -671,11 +304,6 @@ function wrapWithErrorHandling(fn, context = {}) {
671
304
  }
672
305
 
673
306
  module.exports = {
674
- NexusError,
675
- LoginError,
676
- NetworkError,
677
- ValidationError,
678
- RateLimitError,
679
307
  ErrorHandler,
680
308
  errorHandler,
681
309
  wrapWithErrorHandling
@@ -70,8 +70,6 @@ class PerformanceOptimizer {
70
70
  this.metricsInterval = setInterval(() => {
71
71
  this._collectMetrics();
72
72
  }, 60 * 1000);
73
-
74
- logger('๐Ÿ“Š Performance monitoring started', 'info');
75
73
  }
76
74
 
77
75
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nexus-fca",
3
- "version": "2.0.0",
3
+ "version": "2.0.1",
4
4
  "description": "A modern, safe, and advanced Facebook Chat API for Node.js with enhanced performance, smart caching, and TypeScript support. Messenger automation, bots, and integrations made easy.",
5
5
  "main": "index.js",
6
6
  "repository": {
package/src/listenMqtt.js CHANGED
@@ -234,7 +234,7 @@ function listenMqtt(defaultFuncs, api, ctx, globalCallback) {
234
234
  });
235
235
  mqttClient.on("connect", function () {
236
236
  if (process.env.OnStatus === undefined) {
237
- logger("Nexus-FCA premium features loaded", "info");
237
+ logger("Nexus-FCA premium features works only with Nexus-Bot framework(Kidding)", "info");
238
238
  process.env.OnStatus = true;
239
239
  }
240
240
  topics.forEach((topicsub) => mqttClient.subscribe(topicsub));