mwalajs 1.0.5 → 1.0.7

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/bin/mwala.mjs CHANGED
@@ -55,7 +55,7 @@ switch (command) {
55
55
  case '-v':
56
56
  case 'v':
57
57
  case '--version':
58
- console.log('MwalaJS Version: 1.0.5');
58
+ console.log('MwalaJS Version: 1.0.6');
59
59
  process.exit(0);
60
60
 
61
61
  case 'create-project':
@@ -8,17 +8,45 @@ import dotenv from 'dotenv';
8
8
 
9
9
  const { Client } = pkg;
10
10
 
11
- // Function to reset the .env file before processing
11
+ /* -----------------------------------------------------------
12
+ NEW FUNCTION: CREATE BACKUP OF .ENV BEFORE DELETE
13
+ ----------------------------------------------------------- */
14
+ const backupEnvFile = () => {
15
+ try {
16
+ if (!fs.existsSync('.env')) {
17
+ console.log(' ⚠️ No .env file found to backup.');
18
+ return;
19
+ }
20
+
21
+ const timestamp = new Date()
22
+ .toISOString()
23
+ .replace(/[:.]/g, '-'); // safe filename
24
+
25
+ const backupName = `.env.backup-${timestamp}`;
26
+
27
+ fs.copyFileSync('.env', backupName);
28
+
29
+ console.log(` 📦 Backup created: ${backupName}`);
30
+ } catch (error) {
31
+ console.error(' ❌ Failed to create .env backup:', error.message);
32
+ }
33
+ };
34
+
35
+ /* -----------------------------------------------------------
36
+ RESET ENV FILE
37
+ ----------------------------------------------------------- */
12
38
  const resetEnvFile = () => {
13
39
  try {
14
- fs.writeFileSync('.env', '', 'utf8'); // Empty the .env file
15
- console.log(' Cleared .env file.');
40
+ fs.writeFileSync('.env', '', 'utf8');
41
+ console.log(' 🧹 Cleared .env file.');
16
42
  } catch (error) {
17
- console.error(' Failed to clear .env file:', error.message);
43
+ console.error(' Failed to clear .env file:', error.message);
18
44
  }
19
45
  };
20
46
 
21
- // Function to write data to the .env file
47
+ /* -----------------------------------------------------------
48
+ WRITE DATA TO .ENV
49
+ ----------------------------------------------------------- */
22
50
  const writeToEnv = (data) => {
23
51
  const envContent = Object.keys(data)
24
52
  .map(key => `${key}=${data[key]}`)
@@ -27,14 +55,20 @@ const writeToEnv = (data) => {
27
55
  fs.writeFileSync('.env', envContent, 'utf8');
28
56
  };
29
57
 
30
-
31
- // Function to create the database connection
58
+ /* -----------------------------------------------------------
59
+ MAIN FUNCTION: CREATE/CONNECT DATABASE
60
+ ----------------------------------------------------------- */
32
61
  export const getDbConnection = async () => {
33
- resetEnvFile(); // Clear .env file before proceeding
34
62
 
35
- dotenv.config(); // Reload the (now empty) .env file
63
+ // 🔥 FIRST CREATE BACKUP
64
+ backupEnvFile();
65
+
66
+ // 🔥 THEN CLEAR OLD ENV
67
+ resetEnvFile();
68
+
69
+ // Reload environment
70
+ dotenv.config();
36
71
 
37
- // Supported database types
38
72
  const supportedDbTypes = {
39
73
  mysql: 'mysql',
40
74
  my: 'mysql',
@@ -48,19 +82,21 @@ export const getDbConnection = async () => {
48
82
 
49
83
  let dbType;
50
84
  while (true) {
51
- dbType = readlineSync.question('Enter the database type (mysql/my, postgresql/pg, mongodb/mn, sqlite/sq): ').toLowerCase();
85
+ dbType = readlineSync.question(
86
+ 'Enter DB type (mysql/my, postgresql/pg, mongodb/mn, sqlite/sq): '
87
+ ).toLowerCase();
88
+
52
89
  if (supportedDbTypes[dbType]) {
53
- dbType = supportedDbTypes[dbType]; // Normalize input
90
+ dbType = supportedDbTypes[dbType];
54
91
  break;
55
92
  } else {
56
- console.log('❌ Invalid database type. Please enter a valid option.');
93
+ console.log(' ❌ Invalid database type. Try again.');
57
94
  }
58
95
  }
59
96
 
60
- // Prompt for database details
61
97
  const dbName = readlineSync.question('Enter the database name: ').trim();
62
98
  if (!dbName) {
63
- console.log(' Database name cannot be empty.');
99
+ console.log(' Database name cannot be empty.');
64
100
  return;
65
101
  }
66
102
 
@@ -69,64 +105,70 @@ export const getDbConnection = async () => {
69
105
  let dbPassword = '';
70
106
 
71
107
  if (dbType !== 'sqlite') {
72
- dbHost = readlineSync.question('Enter the database host (default: localhost): ') || 'localhost';
73
- dbUser = readlineSync.question('Enter the database user: ').trim();
74
- dbPassword = readlineSync.question('Enter the database password: ', { hideEchoBack: true }).trim();
108
+ dbHost = readlineSync.question('Enter DB host (default: localhost): ') || 'localhost';
109
+ dbUser = readlineSync.question('Enter DB user: ').trim();
110
+ dbPassword = readlineSync.question('Enter DB password: ', { hideEchoBack: true }).trim();
75
111
  }
76
112
 
77
- // Save valid details to .env
78
113
  const envData = {
79
114
  DB_TYPE: dbType,
80
115
  DB_NAME: dbName,
81
116
  DB_HOST: dbHost,
82
117
  DB_USER: dbUser,
83
- DB_PASSWORD: dbPassword,
118
+ DB_PASSWORD: dbPassword
84
119
  };
85
120
 
86
121
  writeToEnv(envData);
87
- console.log(' Database credentials saved to .env file.');
122
+ console.log(' Database credentials saved to .env');
88
123
 
89
124
  let connection;
90
125
 
91
126
  try {
127
+ /* -------------------- MYSQL -------------------- */
92
128
  if (dbType === 'mysql') {
93
129
  const tempConnection = await mysql.createConnection({
94
130
  host: dbHost,
95
131
  user: dbUser,
96
- password: dbPassword,
132
+ password: dbPassword
97
133
  });
98
134
 
99
135
  const [rows] = await tempConnection.query(`SHOW DATABASES LIKE '${dbName}'`);
100
136
  if (rows.length === 0) {
101
137
  await tempConnection.query(`CREATE DATABASE \`${dbName}\``);
102
- console.log(` MySQL Database "${dbName}" created successfully.`);
138
+ console.log(` MySQL database "${dbName}" created.`);
103
139
  } else {
104
- console.log(` MySQL Database "${dbName}" already exists.`);
140
+ console.log(` MySQL database "${dbName}" already exists.`);
105
141
  }
106
142
 
107
143
  connection = await mysql.createConnection({
108
144
  host: dbHost,
109
145
  user: dbUser,
110
146
  password: dbPassword,
111
- database: dbName,
147
+ database: dbName
112
148
  });
113
149
 
114
150
  await tempConnection.end();
115
- } else if (dbType === 'postgresql') {
151
+ }
152
+
153
+ /* -------------------- POSTGRESQL -------------------- */
154
+ else if (dbType === 'postgresql') {
116
155
  const tempClient = new Client({
117
156
  host: dbHost,
118
157
  user: dbUser,
119
- password: dbPassword,
158
+ password: dbPassword
120
159
  });
121
160
 
122
161
  await tempClient.connect();
123
162
 
124
- const checkDb = await tempClient.query(`SELECT datname FROM pg_database WHERE datname = '${dbName}'`);
163
+ const checkDb = await tempClient.query(
164
+ `SELECT datname FROM pg_database WHERE datname = '${dbName}'`
165
+ );
166
+
125
167
  if (checkDb.rows.length === 0) {
126
168
  await tempClient.query(`CREATE DATABASE ${dbName}`);
127
- console.log(` PostgreSQL Database "${dbName}" created successfully.`);
169
+ console.log(` PostgreSQL database "${dbName}" created.`);
128
170
  } else {
129
- console.log(` PostgreSQL Database "${dbName}" already exists.`);
171
+ console.log(` PostgreSQL database "${dbName}" already exists.`);
130
172
  }
131
173
 
132
174
  await tempClient.end();
@@ -135,23 +177,186 @@ export const getDbConnection = async () => {
135
177
  host: dbHost,
136
178
  user: dbUser,
137
179
  password: dbPassword,
138
- database: dbName,
180
+ database: dbName
139
181
  });
140
182
 
141
183
  await connection.connect();
142
- } else if (dbType === 'mongodb') {
184
+ }
185
+
186
+ /* -------------------- MONGODB -------------------- */
187
+ else if (dbType === 'mongodb') {
143
188
  connection = await MongoClient.connect(`mongodb://${dbHost}:27017`);
144
- console.log(` MongoDB connection to "${dbName}" established.`);
145
- } else if (dbType === 'sqlite') {
189
+ console.log(` MongoDB connected.`);
190
+ }
191
+
192
+ /* -------------------- SQLITE -------------------- */
193
+ else if (dbType === 'sqlite') {
146
194
  connection = new sqlite3.Database(`./${dbName}.sqlite`);
147
- console.log(` SQLite Database "${dbName}.sqlite" is ready.`);
148
- } else {
149
- throw new Error(` Unsupported DB type: ${dbType}`);
195
+ console.log(` SQLite database "${dbName}.sqlite" ready.`);
150
196
  }
197
+
151
198
  } catch (error) {
152
- console.error(` Failed to create database: ${error.message}`);
199
+ console.error(` Failed to create database: ${error.message}`);
153
200
  return;
154
201
  }
155
202
 
156
203
  return connection;
157
204
  };
205
+
206
+ // import fs from 'fs';
207
+ // import readlineSync from 'readline-sync';
208
+ // import mysql from 'mysql2/promise';
209
+ // import { MongoClient } from 'mongodb';
210
+ // import sqlite3 from 'sqlite3';
211
+ // import pkg from 'pg';
212
+ // import dotenv from 'dotenv';
213
+
214
+ // const { Client } = pkg;
215
+
216
+ // // Function to reset the .env file before processing
217
+ // const resetEnvFile = () => {
218
+ // try {
219
+ // fs.writeFileSync('.env', '', 'utf8'); // Empty the .env file
220
+ // console.log(' Cleared .env file.');
221
+ // } catch (error) {
222
+ // console.error(' Failed to clear .env file:', error.message);
223
+ // }
224
+ // };
225
+
226
+ // // Function to write data to the .env file
227
+ // const writeToEnv = (data) => {
228
+ // const envContent = Object.keys(data)
229
+ // .map(key => `${key}=${data[key]}`)
230
+ // .join('\n');
231
+
232
+ // fs.writeFileSync('.env', envContent, 'utf8');
233
+ // };
234
+
235
+
236
+ // // Function to create the database connection
237
+ // export const getDbConnection = async () => {
238
+ // resetEnvFile(); // Clear .env file before proceeding
239
+
240
+ // dotenv.config(); // Reload the (now empty) .env file
241
+
242
+ // // Supported database types
243
+ // const supportedDbTypes = {
244
+ // mysql: 'mysql',
245
+ // my: 'mysql',
246
+ // postgresql: 'postgresql',
247
+ // pg: 'postgresql',
248
+ // mongodb: 'mongodb',
249
+ // mn: 'mongodb',
250
+ // sqlite: 'sqlite',
251
+ // sq: 'sqlite'
252
+ // };
253
+
254
+ // let dbType;
255
+ // while (true) {
256
+ // dbType = readlineSync.question('Enter the database type (mysql/my, postgresql/pg, mongodb/mn, sqlite/sq): ').toLowerCase();
257
+ // if (supportedDbTypes[dbType]) {
258
+ // dbType = supportedDbTypes[dbType]; // Normalize input
259
+ // break;
260
+ // } else {
261
+ // console.log('❌ Invalid database type. Please enter a valid option.');
262
+ // }
263
+ // }
264
+
265
+ // // Prompt for database details
266
+ // const dbName = readlineSync.question('Enter the database name: ').trim();
267
+ // if (!dbName) {
268
+ // console.log(' Database name cannot be empty.');
269
+ // return;
270
+ // }
271
+
272
+ // let dbHost = 'localhost';
273
+ // let dbUser = '';
274
+ // let dbPassword = '';
275
+
276
+ // if (dbType !== 'sqlite') {
277
+ // dbHost = readlineSync.question('Enter the database host (default: localhost): ') || 'localhost';
278
+ // dbUser = readlineSync.question('Enter the database user: ').trim();
279
+ // dbPassword = readlineSync.question('Enter the database password: ', { hideEchoBack: true }).trim();
280
+ // }
281
+
282
+ // // Save valid details to .env
283
+ // const envData = {
284
+ // DB_TYPE: dbType,
285
+ // DB_NAME: dbName,
286
+ // DB_HOST: dbHost,
287
+ // DB_USER: dbUser,
288
+ // DB_PASSWORD: dbPassword,
289
+ // };
290
+
291
+ // writeToEnv(envData);
292
+ // console.log(' Database credentials saved to .env file.');
293
+
294
+ // let connection;
295
+
296
+ // try {
297
+ // if (dbType === 'mysql') {
298
+ // const tempConnection = await mysql.createConnection({
299
+ // host: dbHost,
300
+ // user: dbUser,
301
+ // password: dbPassword,
302
+ // });
303
+
304
+ // const [rows] = await tempConnection.query(`SHOW DATABASES LIKE '${dbName}'`);
305
+ // if (rows.length === 0) {
306
+ // await tempConnection.query(`CREATE DATABASE \`${dbName}\``);
307
+ // console.log(` MySQL Database "${dbName}" created successfully.`);
308
+ // } else {
309
+ // console.log(` MySQL Database "${dbName}" already exists.`);
310
+ // }
311
+
312
+ // connection = await mysql.createConnection({
313
+ // host: dbHost,
314
+ // user: dbUser,
315
+ // password: dbPassword,
316
+ // database: dbName,
317
+ // });
318
+
319
+ // await tempConnection.end();
320
+ // } else if (dbType === 'postgresql') {
321
+ // const tempClient = new Client({
322
+ // host: dbHost,
323
+ // user: dbUser,
324
+ // password: dbPassword,
325
+ // });
326
+
327
+ // await tempClient.connect();
328
+
329
+ // const checkDb = await tempClient.query(`SELECT datname FROM pg_database WHERE datname = '${dbName}'`);
330
+ // if (checkDb.rows.length === 0) {
331
+ // await tempClient.query(`CREATE DATABASE ${dbName}`);
332
+ // console.log(` PostgreSQL Database "${dbName}" created successfully.`);
333
+ // } else {
334
+ // console.log(` PostgreSQL Database "${dbName}" already exists.`);
335
+ // }
336
+
337
+ // await tempClient.end();
338
+
339
+ // connection = new Client({
340
+ // host: dbHost,
341
+ // user: dbUser,
342
+ // password: dbPassword,
343
+ // database: dbName,
344
+ // });
345
+
346
+ // await connection.connect();
347
+ // } else if (dbType === 'mongodb') {
348
+ // connection = await MongoClient.connect(`mongodb://${dbHost}:27017`);
349
+ // console.log(` MongoDB connection to "${dbName}" established.`);
350
+ // } else if (dbType === 'sqlite') {
351
+ // connection = new sqlite3.Database(`./${dbName}.sqlite`);
352
+ // console.log(` SQLite Database "${dbName}.sqlite" is ready.`);
353
+ // } else {
354
+ // throw new Error(` Unsupported DB type: ${dbType}`);
355
+ // }
356
+ // } catch (error) {
357
+ // console.error(` Failed to create database: ${error.message}`);
358
+ // return;
359
+ // }
360
+
361
+ // return connection;
362
+ // };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mwalajs",
3
- "version": "1.0.5",
3
+ "version": "1.0.7",
4
4
  "description": "MwalaJS Framework CLI Tool and Web Framework for Backend and Frontend Development.",
5
5
  "type": "module",
6
6
  "main": "app.mjs",
@@ -26,6 +26,7 @@
26
26
  "mongoose": "^8.12.1",
27
27
  "mpath": "^0.9.0",
28
28
  "multer": "^1.4.2",
29
+ "mwalajs": "^1.0.6",
29
30
  "mysql2": "^3.13.0",
30
31
  "pg": "^8.13.3",
31
32
  "pg-hstore": "^2.3.4",
package/setupMwalajs.mjs CHANGED
@@ -1,58 +1,75 @@
1
- import { execSync } from 'child_process';
2
- import fs from 'fs-extra';
1
+ import fs from 'fs';
3
2
  import path from 'path';
4
3
  import os from 'os';
4
+ import readline from 'readline';
5
+ import { execSync } from 'child_process';
5
6
  import { fileURLToPath } from 'url';
6
7
 
8
+ // Convert __dirname and __filename for ES module
9
+ const __filename = fileURLToPath(import.meta.url);
10
+ const __dirname = path.dirname(__filename);
11
+
12
+ // Create readline interface
13
+ const rl = readline.createInterface({
14
+ input: process.stdin,
15
+ output: process.stdout
16
+ });
17
+
18
+ async function prompt(question) {
19
+ return new Promise((resolve) => rl.question(question, resolve));
20
+ }
21
+
7
22
  /**
8
- * Function to install express in mwalajs and copy the folder into node_modules.
23
+ * Function to install mwalajs.
24
+ * - If package.json exists, it proceeds to install.
25
+ * - If not, it prompts user to auto-create or manually create.
26
+ * - When auto-creating, it sets "type": "module" and "main": "app.mjs" by default.
9
27
  */
10
28
  async function setupMwalajs() {
11
- const projectDir = process.cwd(); // Get project root directory
12
- const mwalajsDir = path.join(projectDir, 'mwalajs'); // mwalajs folder
13
- const nodeModulesDir = path.join(projectDir, 'node_modules'); // node_modules
14
- const targetMwalajs = path.join(nodeModulesDir, 'mwalajs'); // Destination folder inside node_modules
29
+ const projectDir = process.cwd();
30
+ const packageJsonPath = path.join(projectDir, 'package.json');
15
31
 
16
32
  try {
17
- console.log(" Detecting Operating System...");
18
- const userOS = os.platform(); // Get user OS (win32, linux, darwin)
19
- console.log(` Running on: ${userOS === "win32" ? "Windows" : userOS === "darwin" ? "MacOS" : "Linux"}`);
20
-
21
- // Check if mwalajs exists
22
- if (!fs.existsSync(mwalajsDir)) {
23
- console.error(" Error: 'mwalajs' folder not found! Please ensure it exists.");
24
- return;
25
- }
33
+ console.log("Detecting Operating System...");
34
+ const userOS = os.platform();
35
+ console.log(`Running on: ${userOS === "win32" ? "Windows" : userOS === "darwin" ? "MacOS" : "Linux"}`);
26
36
 
27
- console.log(" Installing 'dependencies' inside 'mwalajs'...");
28
- execSync('npm install express --prefix mwalajs', { stdio: 'inherit' });
37
+ if (!fs.existsSync(packageJsonPath)) {
38
+ console.log("No package.json found in the current directory.");
39
+ const choice = await prompt("Do you want to create one now? (y/n): ");
29
40
 
30
- // Ensure node_modules exists
31
- if (!fs.existsSync(nodeModulesDir)) {
32
- fs.mkdirSync(nodeModulesDir);
33
- }
41
+ if (choice.toLowerCase() === 'y') {
42
+ console.log("Initializing package.json...");
43
+ execSync('npm init -y', { stdio: 'inherit' });
34
44
 
35
- // Delete existing mwalajs in node_modules if present
36
- if (fs.existsSync(targetMwalajs)) {
37
- console.log(" Removing old 'mwalajs' from node_modules...");
38
- fs.removeSync(targetMwalajs);
45
+ // Modify package.json with defaults
46
+ const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
47
+ pkg.type = "module";
48
+ pkg.main = "app.mjs";
49
+ fs.writeFileSync(packageJsonPath, JSON.stringify(pkg, null, 2));
50
+ console.log('package.json created with type: "module" and main: "app.mjs"');
51
+ } else {
52
+ console.log("Please create a package.json file manually using `npm init`.");
53
+ rl.close();
54
+ return;
55
+ }
39
56
  }
40
57
 
41
- console.log(" Copying 'mwalajs' to 'node_modules'...");
42
- fs.copySync(mwalajsDir, targetMwalajs, { overwrite: true });
43
-
44
- console.log(` Successfully installed 'dependencies' and moved 'mwalajs' to:`);
45
- console.log(` ${targetMwalajs}`);
58
+ console.log("Installing mwalajs in current directory...");
59
+ execSync('npm install mwalajs', { stdio: 'inherit' });
60
+ console.log("mwalajs installed successfully.");
46
61
 
47
62
  } catch (error) {
48
- console.error(" Error:", error.message);
63
+ console.error("Error:", error.message);
64
+ } finally {
65
+ rl.close();
49
66
  }
50
67
  }
51
68
 
52
- // Export the function so it can be used anywhere
69
+ // Export the function
53
70
  export { setupMwalajs };
54
71
 
55
- // Prevent auto-execution unless explicitly called (ES Module Fix)
72
+ // Only execute if run directly
56
73
  if (import.meta.url === `file://${process.argv[1]}`) {
57
74
  setupMwalajs();
58
75
  }