-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.mjs
More file actions
580 lines (520 loc) · 14.8 KB
/
index.mjs
File metadata and controls
580 lines (520 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
#!/usr/bin/env node
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { program } from "commander";
import chalk from "chalk";
import ora from "ora";
import { pathToFileURL } from "url";
import readline from "node:readline/promises";
import { stdin as input, stdout as output } from "node:process";
import inquirer from "inquirer";
console.log(
chalk.blueBright(`
____________ ___
|_ | _ \ \/ |
| | | | | . . |
| | | | | |\/| |
/\__/ / |/ /| | | |
\____/|___/ \_| |_/ CLI v1.0.0
`)
);
const author = "JDM";
let defaultConfig = {
project_name: "",
folder: "backend",
functions: "functions",
routes: "routes",
models: "models",
middlewares: "middlewares",
database_url: "your_database_url_here",
secret_key: "your_secret_key_here",
};
const configPath = path.join(process.cwd(), "jdm.config.js");
let config = {};
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
async function loadConfig() {
if (fs.existsSync(configPath)) {
try {
const userConfig = await import(pathToFileURL(configPath).href);
config = { ...defaultConfig, ...userConfig.default };
console.log(chalk.green("✅ Loaded and merged config file."));
console.log(
chalk.blueBright("---------------------------------------")
);
console.log(chalk.cyan("🔍 Final Config:"), config);
} catch (error) {
console.error(
chalk.red("❌ Failed to load config file:", error.message)
);
config = { ...defaultConfig };
}
} else {
config = { ...defaultConfig };
fs.writeFileSync(
configPath,
`// Author: ${author}\n// Created on: ${new Date().toISOString()}\nmodule.exports = ${JSON.stringify(
config,
null,
2
)};\n`,
"utf8"
);
console.log(
chalk.yellow(
"⚠️ No config file found. Created default `jdm.config.js`."
)
);
console.log(chalk.cyan("📄 Default Config:"), config);
}
}
async function cleanProject() {
const projectRoot = process.cwd();
fs.readdirSync(projectRoot).forEach((item) => {
const itemPath = path.join(projectRoot, item);
if (item === "jdm.config.js") return;
if (fs.statSync(itemPath).isDirectory()) {
fs.rmSync(itemPath, { recursive: true, force: true });
console.log(chalk.red(`🗑️ Deleted folder: ${itemPath}`));
} else {
fs.unlinkSync(itemPath);
console.log(chalk.red(`🗑️ Deleted file: ${itemPath}`));
}
});
console.log(chalk.green("✅ Project cleaned successfully."));
}
async function askToOverwrite(filePath, force = false) {
if (fs.existsSync(filePath)) {
console.log(chalk.yellow(`⚠️ File '${filePath}' already exists.`));
if (force) {
console.log(
chalk.green(
"🚀 Force mode is active. Automatically overwriting..."
)
);
return false;
}
const rl = readline.createInterface({ input, output });
const answer = await rl.question(chalk.redBright("Overwrite? (Y/N): "));
rl.close();
return answer.toLowerCase() !== "y";
}
return false;
}
function createFolder(folderPath) {
if (!fs.existsSync(folderPath)) {
fs.mkdirSync(folderPath, { recursive: true });
console.log(chalk.green(`📁 Created folder: ${folderPath}`));
}
}
async function createFile(filePath, content, force = false) {
if (!(await askToOverwrite(filePath, force))) {
fs.writeFileSync(filePath, content, "utf8");
console.log(chalk.green(`✅ Created file: ${filePath}`));
}
}
async function createOrUpdateGitignore() {
const gitignorePath = path.join(process.cwd(), ".gitignore");
const newEntries = [
`${config.folder || "backend"}/**`,
".netlify",
".env",
"node_modules",
];
if (!fs.existsSync(gitignorePath)) {
fs.writeFileSync(gitignorePath, newEntries.join("\n") + "\n", "utf8");
console.log(chalk.green(`✅ Created file: ${gitignorePath}`));
return;
}
const existingContent = fs.readFileSync(gitignorePath, "utf8").split("\n");
const finalEntries = [...new Set([...existingContent, ...newEntries])];
fs.writeFileSync(gitignorePath, finalEntries.join("\n") + "\n", "utf8");
console.log(chalk.green(`✅ Updated file: ${gitignorePath}`));
}
async function createOrUpdateEnv() {
const envPath = path.join(process.cwd(), ".env");
const newEntries = [
`DATABASE_URL=${config.database_url || "your_database_url_here"}`,
`SECRET_KEY=${config.secret_key || "your_secret_key_here"}`,
];
if (!fs.existsSync(envPath)) {
fs.writeFileSync(envPath, newEntries.join("\n") + "\n", "utf8");
console.log(chalk.green(`✅ Created file: ${envPath}`));
return;
}
const existingLines = fs
.readFileSync(envPath, "utf8")
.split("\n")
.filter(Boolean);
const existingKeys = new Set(
existingLines.map((line) => line.split("=")[0])
);
const finalEntries = [
...existingLines,
...newEntries.filter((line) => !existingKeys.has(line.split("=")[0])),
];
fs.writeFileSync(envPath, finalEntries.join("\n") + "\n", "utf8");
console.log(chalk.green(`✅ Updated file: ${envPath}`));
}
async function createOrUpdatePackageJson(customConfig = {}) {
const packageJsonPath = path.join(process.cwd(), "package.json");
let packageData = {
name: config.project_name || "my-project",
version: "1.0.0",
description: "",
main: "index.js",
scripts: {
start: "node index.js",
},
dependencies: {},
devDependencies: {},
};
const willCreate = !fs.existsSync(packageJsonPath);
if (!willCreate) {
console.log(chalk.yellow("Updating package.json..."));
const existingData = JSON.parse(
fs.readFileSync(packageJsonPath, "utf8")
);
packageData.scripts = {
...existingData.scripts,
...customConfig.scripts,
};
packageData.dependencies = {
...existingData.dependencies,
...customConfig.dependencies,
};
packageData.devDependencies = {
...existingData.devDependencies,
...customConfig.devDependencies,
};
packageData = { ...packageData, ...existingData };
} else {
console.log(chalk.yellow("Creating package.json..."));
packageData.scripts = {
...customConfig.scripts,
};
packageData.dependencies = {
...customConfig.dependencies,
};
packageData.devDependencies = {
...customConfig.devDependencies,
};
}
fs.writeFileSync(
packageJsonPath,
JSON.stringify(packageData, null, 2) + "\n",
"utf8"
);
console.log(
chalk.green(
`✅ ${willCreate ? "Created" : "Updated"} file: ${packageJsonPath}`
)
);
}
async function createFileFromTemplate(
templatePath,
destinationPath,
params = {},
force = false
) {
try {
const modulePath = pathToFileURL(
path.join(__dirname, templatePath)
).href;
const templateContent = await import(modulePath).then((mod) =>
mod.default(params)
);
await createFile(destinationPath, templateContent, force);
} catch (err) {
console.error("❌ Error loading template:", err.message);
process.exit(1);
}
}
function capitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function toTitleLike(str) {
return str.replace(/(^\w|[A-Z]|\b\w)/g, (match, index) =>
index === 0 ? match.toUpperCase() : match
);
}
program
.name("jdm")
.description(
chalk.yellow(
"JDM CLI - Generate setup, Express routers, models, middleware, and more effortlessly."
)
)
.version("1.0.1");
program
.command("license")
.description("Display JDM-CLI license information")
.action(() => {
const licensePath = path.join(__dirname, "LICENSE");
if (fs.existsSync(licensePath)) {
const licenseText = fs.readFileSync(licensePath, "utf8");
console.log(
chalk.green("JDM CLI is licensed under the MIT License.\n")
);
console.log(chalk.yellow(licenseText));
} else {
console.log(
chalk.red("License file not found in JDM-CLI directory.")
);
}
});
program
.command("clean")
.option("-f, --force", "Force clean without confirmation")
.action(async (options) => {
if (!options.force) {
console.log(
chalk.red(
"⚠️ WARNING: This will permanently delete files and cannot be undone!"
)
);
const { confirm } = await inquirer.prompt([
{
type: "confirm",
name: "confirm",
message:
"Are you sure you want to clean the project directory?",
default: false,
},
]);
if (!confirm) {
console.log(
chalk.yellow(
"❌ Operation cancelled. No files were deleted."
)
);
return;
}
} else {
console.log(
chalk.yellow(
"⚠️ Running clean command with --force. No confirmation required."
)
);
}
console.log(chalk.red("🧹 Cleaning project directory..."));
await cleanProject();
console.log(chalk.green("✅ Project cleaned successfully."));
});
program
.command("create <type> <name>")
.description("Generate a new router, model, or middleware")
.action(async (type, name) => {
await loadConfig();
const validTypes = ["router", "model", "middleware", "seeder"];
if (!validTypes.includes(type)) {
console.log(
chalk.red(
`❌ Unknown type: '${type}'. Available types: router, model, middlewar, seeder`
)
);
process.exit(1);
}
const templatePath = path.join(
__dirname,
"template",
`create-${type}.js`
);
if (!fs.existsSync(templatePath)) {
console.log(chalk.red(`❌ Template for '${type}' not found.`));
process.exit(1);
}
const paths = {
router: config.folder + "/" + config.routes || "backend/routes",
model: config.folder + "/" + config.models || "backend/models",
middleware:
config.folder + "/" + config.middlewares ||
"backend/middlewares",
seeder: "seeders"
};
const targetDir = path.join(process.cwd(), paths[type]);
const filePath = path.join(
targetDir,
`${name}${capitalizeFirstLetter(type)}.js`
);
if (!(await askToOverwrite(filePath))) {
await createFile();
}
async function createFile() {
const spinner = ora(
chalk.yellow(`Creating ${type} '${name}'...`)
).start();
try {
fs.mkdirSync(targetDir, { recursive: true });
const templateURL = pathToFileURL(templatePath).href;
const template = await import(templateURL).then((mod) =>
mod.default(name, config, author)
);
fs.writeFileSync(filePath, template, "utf8");
if (type === "model") {
const modelsFilePath = path.join(targetDir, "Models.js");
if (fs.existsSync(modelsFilePath)) {
let modelsFileContent = fs.readFileSync(
modelsFilePath,
"utf8"
);
const newModelEntry = `\t${name}: require("./${name}Model.js"),`;
if (!modelsFileContent.includes(newModelEntry)) {
modelsFileContent = modelsFileContent.replace(
/};\s*$/,
`${newModelEntry}\n};`
);
fs.writeFileSync(
modelsFilePath,
modelsFileContent,
"utf8"
);
spinner.succeed(
chalk.green(`✅ ${name} added to Models.js`)
);
} else {
spinner.info(
chalk.blue(
`ℹ️ ${name} already exists in Models.js`
)
);
}
} else {
const defaultModels = `module.exports = {\n\tsequelize: require("./Sequelize.js"),\n\t${name}: require("./${name}Model.js"),\n};`;
fs.writeFileSync(modelsFilePath, defaultModels, "utf8");
spinner.succeed(
chalk.green(
`✅ Models.js created and ${name} added`
)
);
}
}
spinner.succeed(
chalk.green(
`✅ ${
type.charAt(0).toUpperCase() + type.slice(1)
} '${name}' created at ${
paths[type]
}/${name}${capitalizeFirstLetter(type)}.js`
)
);
} catch (err) {
spinner.fail(
chalk.red(`❌ Error creating file: ${err.message}`)
);
process.exit(1);
}
}
});
program
.command("setup")
.description("Generate project structure and Netlify setup")
.option("-f, --force", "Force overwrite all files")
.option("-c, --clean", "Clean the project before setup")
.action(async (options) => {
await loadConfig();
const force = options.force || false;
const clean = options.clean || false;
if (clean) {
console.log(chalk.red("🧹 Cleaning project directory..."));
await cleanProject();
console.log(chalk.green("✅ Project cleaned successfully."));
}
console.log(chalk.yellow("Setting up project structure..."));
await createOrUpdateEnv();
await createOrUpdateGitignore();
await createOrUpdatePackageJson({
scripts: {
start: "netlify dev",
login: "netlify login",
build: "netlify deploy --prod",
migrate: `node ${config.folder || "backend"}/migrate.js`,
seed: "npx sequelize-cli db:seed:all",
},
dependencies: {
express: "^4.19.2",
"express-async-handler": "1.2.0",
"express-basic-auth": "^1.2.1",
http: "^0.0.1-security",
jsonwebtoken: "^9.0.2",
"live-server": "^1.2.2",
multer: "^1.4.5-lts.1",
"netlify-cli": "^17.26.2",
"netlify-lambda": "^2.0.16",
"node-forge": "^1.3.1",
nodemailer: "^6.9.14",
pg: "^8.12.0",
sequelize: "6.37.4",
"sequelize-cli": "6.6.2",
"serverless-http": "^3.2.0",
bcryptjs: "^2.4.3",
cors: "^2.8.5",
dotenv: "^16.4.5",
},
});
const folders = [
config.models || "models",
config.middlewares || "middlewares",
config.routes || "routes",
"service",
"lib",
"utils",
"helpers",
];
const mainFolder = config.folder || "backend";
const functionsFolder = config.functions || "functions";
const projectRoot = process.cwd() + "/" + mainFolder;
createFolder(path.join(process.cwd(), "config"));
createFolder(path.join(process.cwd(), "seeders"));
createFolder(path.join(projectRoot, functionsFolder));
folders.forEach((folder) =>
createFolder(path.join(projectRoot, folder))
);
console.log(chalk.green(`✅ Project folders succesfully created.`));
console.log(chalk.yellow("Creating template files..."));
await createFileFromTemplate(
"template/templates/netlify-template.js",
path.join(process.cwd(), "netlify.toml"),
{ config, author },
force
);
await createFileFromTemplate(
"template/templates/api-template.js",
path.join(projectRoot, config.functions || "functions", "api.js"),
{ config, author },
force
);
await createFileFromTemplate(
"template/templates/model-template.js",
path.join(projectRoot, config.models || "models", "Models.js"),
{ author },
force
);
await createFileFromTemplate(
"template/templates/router-template.js",
path.join(projectRoot, config.routes || "routes", "Routers.js"),
{ author },
force
);
await createFileFromTemplate(
"template/templates/sequelize-template.js",
path.join(projectRoot, config.models || "models", "Sequelize.js"),
{ author },
force
);
await createFileFromTemplate(
"template/templates/migrate-template.js",
path.join(process.cwd(), config.folder || "backend", "Migrate.js"),
{ config, author },
force
);
await createFileFromTemplate(
"template/templates/config-template.js",
path.join(process.cwd(), "config", "config.js"),
{ author },
force
);
console.log(chalk.green("✅ Project setup complete! 🎉"));
});
program.parse(process.argv);