create-prisma-php-app 1.21.0 → 1.21.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.
Files changed (2) hide show
  1. package/dist/index.js +1 -1122
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,1123 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import { execSync } from "child_process";
3
- import fs from "fs";
4
- import { fileURLToPath } from "url";
5
- import path from "path";
6
- import chalk from "chalk";
7
- import prompts from "prompts";
8
- import https from "https";
9
- const __filename = fileURLToPath(import.meta.url);
10
- const __dirname = path.dirname(__filename);
11
- let updateAnswer = null;
12
- const nonBackendFiles = [
13
- "favicon.ico",
14
- "\\src\\app\\index.php",
15
- "metadata.php",
16
- "not-found.php",
17
- ];
18
- const dockerFiles = [
19
- ".dockerignore",
20
- "docker-compose.yml",
21
- "Dockerfile",
22
- "apache.conf",
23
- ];
24
- function bsConfigUrls(projectRootPath) {
25
- // Identify the base path dynamically up to and including 'htdocs'
26
- const htdocsIndex = projectRootPath.indexOf("\\htdocs\\");
27
- if (htdocsIndex === -1) {
28
- console.error(
29
- "Invalid PROJECT_ROOT_PATH. The path does not contain \\htdocs\\"
30
- );
31
- return {
32
- bsTarget: "",
33
- bsPathRewrite: {},
34
- };
35
- }
36
- // Extract the path up to and including 'htdocs\\'
37
- const basePathToRemove = projectRootPath.substring(
38
- 0,
39
- htdocsIndex + "\\htdocs\\".length
40
- );
41
- // Escape backslashes for the regex pattern
42
- const escapedBasePathToRemove = basePathToRemove.replace(/\\/g, "\\\\");
43
- // Remove the base path and replace backslashes with forward slashes for URL compatibility
44
- const relativeWebPath = projectRootPath
45
- .replace(new RegExp(`^${escapedBasePathToRemove}`), "")
46
- .replace(/\\/g, "/");
47
- // Construct the Browser Sync command with the correct proxy URL, being careful not to affect the protocol part
48
- let proxyUrl = `http://localhost/${relativeWebPath}`;
49
- // Ensure the proxy URL does not end with a slash before appending '/public'
50
- proxyUrl = proxyUrl.endsWith("/") ? proxyUrl.slice(0, -1) : proxyUrl;
51
- // Clean the URL by replacing "//" with "/" but not affecting "http://"
52
- // We replace instances of "//" that are not preceded by ":"
53
- const cleanUrl = proxyUrl.replace(/(?<!:)(\/\/+)/g, "/");
54
- const cleanRelativeWebPath = relativeWebPath.replace(/\/\/+/g, "/");
55
- // Correct the relativeWebPath to ensure it does not start with a "/"
56
- const adjustedRelativeWebPath = cleanRelativeWebPath.startsWith("/")
57
- ? cleanRelativeWebPath.substring(1)
58
- : cleanRelativeWebPath;
59
- return {
60
- bsTarget: `${cleanUrl}/`,
61
- bsPathRewrite: {
62
- "^/": `/${adjustedRelativeWebPath}/`,
63
- },
64
- };
65
- }
66
- function configureBrowserSyncCommand(baseDir) {
67
- // TypeScript content to write
68
- const bsConfigTsContent = `const { createProxyMiddleware } = require("http-proxy-middleware");
69
- const fs = require("fs");
70
-
71
- const jsonData = fs.readFileSync("prisma-php.json", "utf8");
72
- const config = JSON.parse(jsonData);
73
-
74
- module.exports = {
75
- proxy: "http://localhost:3000",
76
- middleware: [
77
- (req, res, next) => {
78
- res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
79
- res.setHeader("Pragma", "no-cache");
80
- res.setHeader("Expires", "0");
81
- next();
82
- },
83
- createProxyMiddleware({
84
- target: config.bsTarget,
85
- changeOrigin: true,
86
- pathRewrite: config.bsPathRewrite,
87
- }),
88
- ],
89
- files: "src/**/*.*",
90
- notify: false,
91
- open: false,
92
- ghostMode: false,
93
- codeSync: true, // Disable synchronization of code changes across clients
94
- };`;
95
- // Determine the path and write the bs-config.js
96
- const bsConfigPath = path.join(baseDir, "settings", "bs-config.cjs");
97
- fs.writeFileSync(bsConfigPath, bsConfigTsContent, "utf8");
98
- // Return the Browser Sync command string, using the cleaned URL
99
- return `browser-sync start --config settings/bs-config.cjs`;
100
- }
101
- async function updatePackageJson(baseDir, answer) {
102
- const packageJsonPath = path.join(baseDir, "package.json");
103
- if (checkExcludeFiles(packageJsonPath)) return;
104
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
105
- // Use the new function to configure the Browser Sync command
106
- const browserSyncCommand = configureBrowserSyncCommand(baseDir);
107
- packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), {
108
- projectName: "node settings/project-name.cjs",
109
- });
110
- let answersToInclude = [];
111
- if (answer.tailwindcss) {
112
- packageJson.scripts = Object.assign(
113
- Object.assign({}, packageJson.scripts),
114
- {
115
- tailwind:
116
- "postcss ./src/app/css/tailwind.css -o ./src/app/css/styles.css --watch",
117
- }
118
- );
119
- answersToInclude.push("tailwind");
120
- }
121
- if (answer.websocket) {
122
- packageJson.scripts = Object.assign(
123
- Object.assign({}, packageJson.scripts),
124
- { websocket: "node ./settings/restart-websocket.cjs" }
125
- );
126
- answersToInclude.push("websocket");
127
- }
128
- // if (answer.prisma) {
129
- // packageJson.scripts = {
130
- // ...packageJson.scripts,
131
- // postinstall: "prisma generate",
132
- // };
133
- // }
134
- if (answer.docker) {
135
- packageJson.scripts = Object.assign(
136
- Object.assign({}, packageJson.scripts),
137
- { docker: "docker-compose up" }
138
- );
139
- answersToInclude.push("docker");
140
- }
141
- if (answer.swaggerDocs) {
142
- packageJson.scripts = Object.assign(
143
- Object.assign({}, packageJson.scripts),
144
- { "create-swagger-docs": "node settings/swagger-setup.js" }
145
- );
146
- answersToInclude.push("create-swagger-docs");
147
- }
148
- // Initialize with existing scripts
149
- let updatedScripts = Object.assign({}, packageJson.scripts);
150
- // Conditionally add "browser-sync" command
151
- updatedScripts.browserSync = browserSyncCommand;
152
- updatedScripts._dev =
153
- answersToInclude.length > 0
154
- ? `npm-run-all -p ${answersToInclude.join(" ")}`
155
- : 'echo "No additional scripts to run"';
156
- updatedScripts.startDev = `node settings/start-dev.js`;
157
- updatedScripts.dev = `npm run startDev`;
158
- // Finally, assign the updated scripts back to packageJson
159
- packageJson.scripts = updatedScripts;
160
- packageJson.type = "module";
161
- if (answer.prisma)
162
- packageJson.prisma = {
163
- seed: "node prisma/seed.js",
164
- };
165
- fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
166
- }
167
- async function updateComposerJson(baseDir, answer) {
168
- const composerJsonPath = path.join(baseDir, "composer.json");
169
- if (checkExcludeFiles(composerJsonPath)) return;
170
- let composerJson;
171
- // Check if the composer.json file exists
172
- if (fs.existsSync(composerJsonPath)) {
173
- // Read the current composer.json content
174
- const composerJsonContent = fs.readFileSync(composerJsonPath, "utf8");
175
- composerJson = JSON.parse(composerJsonContent);
176
- } else {
177
- console.error("composer.json does not exist.");
178
- return;
179
- }
180
- // Conditionally add WebSocket dependency
181
- if (answer.websocket) {
182
- composerJson.require = Object.assign(
183
- Object.assign({}, composerJson.require),
184
- { "cboden/ratchet": "^0.4.4" }
185
- );
186
- }
187
- if (answer.prisma) {
188
- composerJson.require = Object.assign(
189
- Object.assign({}, composerJson.require),
190
- { "ramsey/uuid": "5.x-dev", "hidehalo/nanoid-php": "1.x-dev" }
191
- );
192
- }
193
- // Write the modified composer.json back to the file
194
- fs.writeFileSync(composerJsonPath, JSON.stringify(composerJson, null, 2));
195
- console.log("composer.json updated successfully.");
196
- }
197
- async function updateIndexJsForWebSocket(baseDir, answer) {
198
- if (!answer.websocket) {
199
- return;
200
- }
201
- const indexPath = path.join(baseDir, "src", "app", "js", "index.js");
202
- if (checkExcludeFiles(indexPath)) return;
203
- let indexContent = fs.readFileSync(indexPath, "utf8");
204
- // WebSocket initialization code to be appended
205
- const webSocketCode = `
206
- // WebSocket initialization
207
- const ws = new WebSocket("ws://localhost:8080");
208
- `;
209
- // Append WebSocket code if user chose to use WebSocket
210
- indexContent += webSocketCode;
211
- fs.writeFileSync(indexPath, indexContent, "utf8");
212
- console.log("WebSocket code added to index.js successfully.");
213
- }
214
- // This function updates the .gitignore file
215
- async function createUpdateGitignoreFile(baseDir, additions) {
216
- const gitignorePath = path.join(baseDir, ".gitignore");
217
- if (checkExcludeFiles(gitignorePath)) return;
218
- let gitignoreContent = "";
219
- additions.forEach((addition) => {
220
- if (!gitignoreContent.includes(addition)) {
221
- gitignoreContent += `\n${addition}`;
222
- }
223
- });
224
- // Ensure there's no leading newline if the file was just created
225
- gitignoreContent = gitignoreContent.trimStart();
226
- fs.writeFileSync(gitignorePath, gitignoreContent);
227
- }
228
- // Recursive copy function
229
- function copyRecursiveSync(src, dest, answer) {
230
- var _a;
231
- console.log("🚀 ~ copyRecursiveSync ~ dest:", dest);
232
- console.log("🚀 ~ copyRecursiveSync ~ src:", src);
233
- const exists = fs.existsSync(src);
234
- const stats = exists && fs.statSync(src);
235
- const isDirectory = exists && stats && stats.isDirectory();
236
- if (isDirectory) {
237
- const destLower = dest.toLowerCase();
238
- if (!answer.websocket && destLower.includes("src\\lib\\websocket")) return;
239
- if (!answer.prisma && destLower.includes("src\\lib\\prisma")) return;
240
- if (
241
- (answer.backendOnly && destLower.includes("src\\app\\js")) ||
242
- (answer.backendOnly && destLower.includes("src\\app\\css"))
243
- )
244
- return;
245
- if (!answer.swaggerDocs && destLower.includes("src\\app\\swagger-docs"))
246
- return;
247
- const destModified = dest.replace(/\\/g, "/");
248
- if (
249
- (_a =
250
- updateAnswer === null || updateAnswer === void 0
251
- ? void 0
252
- : updateAnswer.excludeFilePath) === null || _a === void 0
253
- ? void 0
254
- : _a.includes(destModified)
255
- )
256
- return;
257
- if (!fs.existsSync(dest)) fs.mkdirSync(dest, { recursive: true });
258
- fs.readdirSync(src).forEach((childItemName) => {
259
- copyRecursiveSync(
260
- path.join(src, childItemName),
261
- path.join(dest, childItemName),
262
- answer
263
- );
264
- });
265
- } else {
266
- if (checkExcludeFiles(dest)) return;
267
- if (
268
- !answer.tailwindcss &&
269
- (dest.includes("tailwind.css") || dest.includes("styles.css"))
270
- )
271
- return;
272
- if (
273
- !answer.websocket &&
274
- (dest.includes("restart-websocket.cjs") ||
275
- dest.includes("restart-websocket.bat"))
276
- )
277
- return;
278
- if (!answer.docker && dockerFiles.some((file) => dest.includes(file))) {
279
- return;
280
- }
281
- if (
282
- answer.backendOnly &&
283
- nonBackendFiles.some((file) => dest.includes(file))
284
- ) {
285
- return;
286
- }
287
- if (!answer.backendOnly && dest.includes("route.php")) return;
288
- if (
289
- answer.backendOnly &&
290
- !answer.swaggerDocs &&
291
- (dest.includes("start-dev.js") || dest.includes("swagger-setup.js"))
292
- ) {
293
- return;
294
- }
295
- fs.copyFileSync(src, dest, 0);
296
- }
297
- }
298
- // Function to execute the recursive copy for entire directories
299
- async function executeCopy(baseDir, directoriesToCopy, answer) {
300
- directoriesToCopy.forEach(({ srcDir, destDir }) => {
301
- const sourcePath = path.join(__dirname, srcDir);
302
- const destPath = path.join(baseDir, destDir);
303
- copyRecursiveSync(sourcePath, destPath, answer);
304
- });
305
- }
306
- function createOrUpdateTailwindConfig(baseDir) {
307
- console.log("🚀 ~ createOrUpdateTailwindConfig ~ baseDir:", baseDir);
308
- const filePath = path.join(baseDir, "tailwind.config.js");
309
- if (checkExcludeFiles(filePath)) return;
310
- const newContent = [
311
- "./src/app/**/*.{html,js,php}",
312
- // Add more paths as needed
313
- ];
314
- let configData = fs.readFileSync(filePath, "utf8");
315
- console.log("🚀 ~ createOrUpdateTailwindConfig ~ configData:", configData);
316
- const contentArrayString = newContent
317
- .map((item) => ` "${item}"`)
318
- .join(",\n");
319
- configData = configData.replace(
320
- /content: \[\],/g,
321
- `content: [\n${contentArrayString}\n],`
322
- );
323
- fs.writeFileSync(filePath, configData, { flag: "w" });
324
- console.log(chalk.green("Tailwind configuration updated successfully."));
325
- }
326
- function modifyPostcssConfig(baseDir) {
327
- const filePath = path.join(baseDir, "postcss.config.js");
328
- if (checkExcludeFiles(filePath)) return;
329
- const newContent = `export default {
330
- plugins: {
331
- tailwindcss: {},
332
- autoprefixer: {},
333
- cssnano: {},
334
- },
335
- };`;
336
- fs.writeFileSync(filePath, newContent, { flag: "w" });
337
- console.log(chalk.green("postcss.config.js updated successfully."));
338
- }
339
- function modifyLayoutPHP(baseDir, answer) {
340
- const layoutPath = path.join(baseDir, "src", "app", "layout.php");
341
- if (checkExcludeFiles(layoutPath)) return;
342
- try {
343
- let indexContent = fs.readFileSync(layoutPath, "utf8");
344
- let stylesAndLinks = "";
345
- if (!answer.backendOnly) {
346
- stylesAndLinks = `\n <link href="<?= $baseUrl; ?>/css/index.css" rel="stylesheet">\n <script src="<?= $baseUrl; ?>/js/index.js"></script>`;
347
- }
348
- // Tailwind CSS link or CDN script
349
- let tailwindLink = "";
350
- if (!answer.backendOnly) {
351
- tailwindLink = answer.tailwindcss
352
- ? ` <link href="<?= $baseUrl; ?>/css/styles.css" rel="stylesheet"> ${stylesAndLinks}`
353
- : ` <script src="https://cdn.tailwindcss.com"></script> ${stylesAndLinks}`;
354
- }
355
- // Insert before the closing </head> tag
356
- const breakLine = tailwindLink.length > 0 ? "\n" : "";
357
- indexContent = indexContent.replace(
358
- "</head>",
359
- `${tailwindLink}${breakLine} <!-- Dynamic Head -->
360
- <?= implode("\\n", $mainLayoutHead); ?>
361
- </head>`
362
- );
363
- fs.writeFileSync(layoutPath, indexContent, { flag: "w" });
364
- console.log(
365
- chalk.green(
366
- `layout.php modified successfully for ${
367
- answer.tailwindcss ? "local Tailwind CSS" : "Tailwind CSS CDN"
368
- }.`
369
- )
370
- );
371
- } catch (error) {
372
- console.error(chalk.red("Error modifying layout.php:"), error);
373
- }
374
- }
375
- // This function updates or creates the .env file
376
- async function createOrUpdateEnvFile(baseDir, content) {
377
- const envPath = path.join(baseDir, ".env");
378
- if (checkExcludeFiles(envPath)) return;
379
- console.log("🚀 ~ content:", content);
380
- fs.writeFileSync(envPath, content, { flag: "w" });
381
- }
382
- function checkExcludeFiles(destPath) {
383
- var _a, _b;
384
- if (
385
- !(updateAnswer === null || updateAnswer === void 0
386
- ? void 0
387
- : updateAnswer.isUpdate)
388
- )
389
- return false;
390
- return (_b =
391
- (_a =
392
- updateAnswer === null || updateAnswer === void 0
393
- ? void 0
394
- : updateAnswer.excludeFilePath) === null || _a === void 0
395
- ? void 0
396
- : _a.includes(destPath.replace(/\\/g, "/"))) !== null && _b !== void 0
397
- ? _b
398
- : false;
399
- }
400
- async function createDirectoryStructure(baseDir, answer) {
401
- console.log("🚀 ~ baseDir:", baseDir);
402
- console.log("🚀 ~ answer:", answer);
403
- const filesToCopy = [
404
- { src: "/bootstrap.php", dest: "/bootstrap.php" },
405
- { src: "/.htaccess", dest: "/.htaccess" },
406
- { src: "/../composer.json", dest: "/composer.json" },
407
- ];
408
- if (
409
- updateAnswer === null || updateAnswer === void 0
410
- ? void 0
411
- : updateAnswer.isUpdate
412
- ) {
413
- filesToCopy.push({ src: "/tsconfig.json", dest: "/tsconfig.json" });
414
- if (updateAnswer.tailwindcss) {
415
- filesToCopy.push(
416
- { src: "/postcss.config.js", dest: "/postcss.config.js" },
417
- { src: "/tailwind.config.js", dest: "/tailwind.config.js" }
418
- );
419
- }
420
- }
421
- const directoriesToCopy = [
422
- {
423
- srcDir: "/settings",
424
- destDir: "/settings",
425
- },
426
- {
427
- srcDir: "/src",
428
- destDir: "/src",
429
- },
430
- ];
431
- if (answer.backendOnly && answer.swaggerDocs) {
432
- directoriesToCopy.push({
433
- srcDir: "/swagger-docs-layout.php",
434
- destDir: "/src/app/layout.php",
435
- });
436
- }
437
- if (answer.swaggerDocs) {
438
- directoriesToCopy.push({
439
- srcDir: "/swagger-docs-index.php",
440
- destDir: "/src/app/swagger-docs/index.php",
441
- });
442
- }
443
- if (answer.prisma) {
444
- directoriesToCopy.push({
445
- srcDir: "/prisma",
446
- destDir: "/prisma",
447
- });
448
- }
449
- if (answer.docker) {
450
- directoriesToCopy.push(
451
- { srcDir: "/.dockerignore", destDir: "/.dockerignore" },
452
- { srcDir: "/docker-compose.yml", destDir: "/docker-compose.yml" },
453
- { srcDir: "/Dockerfile", destDir: "/Dockerfile" },
454
- { srcDir: "/apache.conf", destDir: "/apache.conf" }
455
- );
456
- }
457
- console.log("🚀 ~ directoriesToCopy:", directoriesToCopy);
458
- filesToCopy.forEach(({ src, dest }) => {
459
- const sourcePath = path.join(__dirname, src);
460
- const destPath = path.join(baseDir, dest);
461
- if (checkExcludeFiles(destPath)) return;
462
- const code = fs.readFileSync(sourcePath, "utf8");
463
- fs.writeFileSync(destPath, code, { flag: "w" });
464
- });
465
- await executeCopy(baseDir, directoriesToCopy, answer);
466
- await updatePackageJson(baseDir, answer);
467
- await updateComposerJson(baseDir, answer);
468
- if (!answer.backendOnly) {
469
- await updateIndexJsForWebSocket(baseDir, answer);
470
- }
471
- if (answer.tailwindcss) {
472
- createOrUpdateTailwindConfig(baseDir);
473
- modifyPostcssConfig(baseDir);
474
- }
475
- if (answer.tailwindcss || !answer.backendOnly || answer.swaggerDocs) {
476
- modifyLayoutPHP(baseDir, answer);
477
- }
478
- const prismaPHPEnvContent = `# Prisma PHP Auth Secret Key For development only - Change this in production
479
- AUTH_SECRET=uxsjXVPHN038DEYls2Kw0QUgBcXKUyrjv416nIFWPY4=
480
-
481
- # PHPMailer
482
- # SMTP_HOST=smtp.gmail.com or your SMTP host
483
- # SMTP_USERNAME=john.doe@gmail.com or your SMTP username
484
- # SMTP_PASSWORD=123456
485
- # SMTP_PORT=587 for TLS, 465 for SSL or your SMTP port
486
- # SMTP_ENCRYPTION=ssl or tls
487
- # MAIL_FROM=john.doe@gmail.com
488
- # MAIL_FROM_NAME="John Doe"
489
-
490
- # SHOW ERRORS - Set to true to show errors in the browser for development only - Change this in production to false
491
- SHOW_ERRORS=true
492
-
493
- # ChatGPT API Key
494
- # CHATGPT_API_KEY=sk-your-api-key
495
-
496
- # APP TIMEZONE - Set your application timezone - Default is "UTC"
497
- APP_TIMEZONE="UTC"`;
498
- if (answer.prisma) {
499
- const prismaEnvContent = `# Environment variables declared in this file are automatically made available to Prisma.
500
- # See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema
501
-
502
- # Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
503
- # See the documentation for all the connection string options: https://pris.ly/d/connection-strings
504
-
505
- DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"`;
506
- const envContent = `${prismaEnvContent}\n\n${prismaPHPEnvContent}`;
507
- await createOrUpdateEnvFile(baseDir, envContent);
508
- } else {
509
- await createOrUpdateEnvFile(baseDir, prismaPHPEnvContent);
510
- }
511
- // Add vendor to .gitignore
512
- await createUpdateGitignoreFile(baseDir, ["vendor", ".env", "node_modules"]);
513
- }
514
- async function getAnswer(predefinedAnswers = {}) {
515
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
516
- console.log("🚀 ~ predefinedAnswers:", predefinedAnswers);
517
- const questionsArray = [];
518
- if (!predefinedAnswers.projectName) {
519
- questionsArray.push({
520
- type: "text",
521
- name: "projectName",
522
- message: "What is your project named?",
523
- initial: "my-app",
524
- });
525
- }
526
- if (!predefinedAnswers.backendOnly) {
527
- questionsArray.push({
528
- type: "toggle",
529
- name: "backendOnly",
530
- message: "Would you like to create a backend-only project?",
531
- initial: false,
532
- active: "Yes",
533
- inactive: "No",
534
- });
535
- }
536
- // Execute the initial questionsArray first
537
- const onCancel = () => {
538
- console.log(chalk.red("Operation cancelled by the user."));
539
- process.exit(0);
540
- };
541
- const initialResponse = await prompts(questionsArray, { onCancel });
542
- console.log("🚀 ~ initialResponse:", initialResponse);
543
- const nonBackendOnlyQuestionsArray = [];
544
- if (initialResponse.backendOnly || predefinedAnswers.backendOnly) {
545
- // If it's a backend-only project, skip Tailwind CSS, but ask other questions
546
- if (!predefinedAnswers.swaggerDocs) {
547
- nonBackendOnlyQuestionsArray.push({
548
- type: "toggle",
549
- name: "swaggerDocs",
550
- message: `Would you like to use ${chalk.blue("Swagger Docs")}?`,
551
- initial: false,
552
- active: "Yes",
553
- inactive: "No",
554
- });
555
- }
556
- if (!predefinedAnswers.websocket) {
557
- nonBackendOnlyQuestionsArray.push({
558
- type: "toggle",
559
- name: "websocket",
560
- message: `Would you like to use ${chalk.blue("Websocket")}?`,
561
- initial: true,
562
- active: "Yes",
563
- inactive: "No",
564
- });
565
- }
566
- if (!predefinedAnswers.prisma) {
567
- nonBackendOnlyQuestionsArray.push({
568
- type: "toggle",
569
- name: "prisma",
570
- message: `Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,
571
- initial: true,
572
- active: "Yes",
573
- inactive: "No",
574
- });
575
- }
576
- if (!predefinedAnswers.docker) {
577
- nonBackendOnlyQuestionsArray.push({
578
- type: "toggle",
579
- name: "docker",
580
- message: `Would you like to use ${chalk.blue("Docker")}?`,
581
- initial: false,
582
- active: "Yes",
583
- inactive: "No",
584
- });
585
- }
586
- } else {
587
- // If it's not a backend-only project, ask Tailwind CSS as well
588
- if (!predefinedAnswers.swaggerDocs) {
589
- nonBackendOnlyQuestionsArray.push({
590
- type: "toggle",
591
- name: "swaggerDocs",
592
- message: `Would you like to use ${chalk.blue("Swagger Docs")}?`,
593
- initial: false,
594
- active: "Yes",
595
- inactive: "No",
596
- });
597
- }
598
- if (!predefinedAnswers.tailwindcss) {
599
- nonBackendOnlyQuestionsArray.push({
600
- type: "toggle",
601
- name: "tailwindcss",
602
- message: `Would you like to use ${chalk.blue("Tailwind CSS")}?`,
603
- initial: true,
604
- active: "Yes",
605
- inactive: "No",
606
- });
607
- }
608
- if (!predefinedAnswers.websocket) {
609
- nonBackendOnlyQuestionsArray.push({
610
- type: "toggle",
611
- name: "websocket",
612
- message: `Would you like to use ${chalk.blue("Websocket")}?`,
613
- initial: true,
614
- active: "Yes",
615
- inactive: "No",
616
- });
617
- }
618
- if (!predefinedAnswers.prisma) {
619
- nonBackendOnlyQuestionsArray.push({
620
- type: "toggle",
621
- name: "prisma",
622
- message: `Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,
623
- initial: true,
624
- active: "Yes",
625
- inactive: "No",
626
- });
627
- }
628
- if (!predefinedAnswers.docker) {
629
- nonBackendOnlyQuestionsArray.push({
630
- type: "toggle",
631
- name: "docker",
632
- message: `Would you like to use ${chalk.blue("Docker")}?`,
633
- initial: false,
634
- active: "Yes",
635
- inactive: "No",
636
- });
637
- }
638
- }
639
- const nonBackendOnlyResponse = await prompts(nonBackendOnlyQuestionsArray, {
640
- onCancel,
641
- });
642
- console.log("🚀 ~ nonBackendOnlyResponse:", nonBackendOnlyResponse);
643
- return {
644
- projectName: initialResponse.projectName
645
- ? String(initialResponse.projectName).trim().replace(/ /g, "-")
646
- : (_a = predefinedAnswers.projectName) !== null && _a !== void 0
647
- ? _a
648
- : "my-app",
649
- backendOnly:
650
- (_c =
651
- (_b = initialResponse.backendOnly) !== null && _b !== void 0
652
- ? _b
653
- : predefinedAnswers.backendOnly) !== null && _c !== void 0
654
- ? _c
655
- : false,
656
- swaggerDocs:
657
- (_e =
658
- (_d = nonBackendOnlyResponse.swaggerDocs) !== null && _d !== void 0
659
- ? _d
660
- : predefinedAnswers.swaggerDocs) !== null && _e !== void 0
661
- ? _e
662
- : false,
663
- tailwindcss:
664
- (_g =
665
- (_f = nonBackendOnlyResponse.tailwindcss) !== null && _f !== void 0
666
- ? _f
667
- : predefinedAnswers.tailwindcss) !== null && _g !== void 0
668
- ? _g
669
- : false,
670
- websocket:
671
- (_j =
672
- (_h = nonBackendOnlyResponse.websocket) !== null && _h !== void 0
673
- ? _h
674
- : predefinedAnswers.websocket) !== null && _j !== void 0
675
- ? _j
676
- : false,
677
- prisma:
678
- (_l =
679
- (_k = nonBackendOnlyResponse.prisma) !== null && _k !== void 0
680
- ? _k
681
- : predefinedAnswers.prisma) !== null && _l !== void 0
682
- ? _l
683
- : false,
684
- docker:
685
- (_o =
686
- (_m = nonBackendOnlyResponse.docker) !== null && _m !== void 0
687
- ? _m
688
- : predefinedAnswers.docker) !== null && _o !== void 0
689
- ? _o
690
- : false,
691
- };
692
- }
693
- /**
694
- * Install dependencies in the specified directory.
695
- * @param {string} baseDir - The base directory where to install the dependencies.
696
- * @param {string[]} dependencies - The list of dependencies to install.
697
- * @param {boolean} [isDev=false] - Whether to install the dependencies as devDependencies.
698
- */
699
- async function installDependencies(baseDir, dependencies, isDev = false) {
700
- console.log("Initializing new Node.js project...");
701
- // Initialize a package.json if it doesn't exist
702
- if (!fs.existsSync(path.join(baseDir, "package.json")))
703
- execSync("npm init -y", {
704
- stdio: "inherit",
705
- cwd: baseDir,
706
- });
707
- // Log the dependencies being installed
708
- console.log(
709
- `${
710
- isDev ? "Installing development dependencies" : "Installing dependencies"
711
- }:`
712
- );
713
- dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
714
- // Prepare the npm install command with the appropriate flag for dev dependencies
715
- const npmInstallCommand = `npm install ${
716
- isDev ? "--save-dev" : ""
717
- } ${dependencies.join(" ")}`;
718
- // Execute the npm install command
719
- execSync(npmInstallCommand, {
720
- stdio: "inherit",
721
- cwd: baseDir,
722
- });
723
- }
724
- async function uninstallDependencies(baseDir, dependencies, isDev = false) {
725
- console.log("Uninstalling dependencies:");
726
- dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
727
- // Prepare the npm uninstall command with the appropriate flag for dev dependencies
728
- const npmUninstallCommand = `npm uninstall ${
729
- isDev ? "--save-dev" : "--save"
730
- } ${dependencies.join(" ")}`;
731
- // Execute the npm uninstall command
732
- execSync(npmUninstallCommand, {
733
- stdio: "inherit",
734
- cwd: baseDir,
735
- });
736
- }
737
- function fetchPackageVersion(packageName) {
738
- return new Promise((resolve, reject) => {
739
- https
740
- .get(`https://registry.npmjs.org/${packageName}`, (res) => {
741
- let data = "";
742
- res.on("data", (chunk) => (data += chunk));
743
- res.on("end", () => {
744
- try {
745
- const parsed = JSON.parse(data);
746
- resolve(parsed["dist-tags"].latest);
747
- } catch (error) {
748
- reject(new Error("Failed to parse JSON response"));
749
- }
750
- });
751
- })
752
- .on("error", (err) => reject(err));
753
- });
754
- }
755
- const readJsonFile = (filePath) => {
756
- const jsonData = fs.readFileSync(filePath, "utf8");
757
- return JSON.parse(jsonData);
758
- };
759
- function compareVersions(installedVersion, currentVersion) {
760
- const installedVersionArray = installedVersion.split(".").map(Number);
761
- const currentVersionArray = currentVersion.split(".").map(Number);
762
- for (let i = 0; i < installedVersionArray.length; i++) {
763
- if (installedVersionArray[i] > currentVersionArray[i]) {
764
- return 1;
765
- } else if (installedVersionArray[i] < currentVersionArray[i]) {
766
- return -1;
767
- }
768
- }
769
- return 0;
770
- }
771
- function getInstalledPackageVersion(packageName) {
772
- try {
773
- const output = execSync(`npm list -g ${packageName} --depth=0`).toString();
774
- const versionMatch = output.match(
775
- new RegExp(`${packageName}@(\\d+\\.\\d+\\.\\d+)`)
776
- );
777
- if (versionMatch) {
778
- return versionMatch[1];
779
- } else {
780
- console.error(`Package ${packageName} is not installed`);
781
- return null;
782
- }
783
- } catch (error) {
784
- console.error(error instanceof Error ? error.message : String(error));
785
- return null;
786
- }
787
- }
788
- async function main() {
789
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
790
- try {
791
- const args = process.argv.slice(2);
792
- let projectName = args[0];
793
- let answer = null;
794
- if (projectName) {
795
- let useBackendOnly = args.includes("--backend-only");
796
- let useSwaggerDocs = args.includes("--swagger-docs");
797
- let useTailwind = args.includes("--tailwindcss");
798
- let useWebsocket = args.includes("--websocket");
799
- let usePrisma = args.includes("--prisma");
800
- let useDocker = args.includes("--docker");
801
- const predefinedAnswers = {
802
- projectName,
803
- backendOnly: useBackendOnly,
804
- swaggerDocs: useSwaggerDocs,
805
- tailwindcss: useTailwind,
806
- websocket: useWebsocket,
807
- prisma: usePrisma,
808
- docker: useDocker,
809
- };
810
- console.log("🚀 ~ main ~ predefinedAnswers:", predefinedAnswers);
811
- answer = await getAnswer(predefinedAnswers);
812
- if (answer === null) {
813
- console.log(chalk.red("Installation cancelled."));
814
- return;
815
- }
816
- const currentDir = process.cwd();
817
- const configPath = path.join(currentDir, "prisma-php.json");
818
- const localSettings = readJsonFile(configPath);
819
- let excludeFiles = [];
820
- (_a = localSettings.excludeFiles) === null || _a === void 0
821
- ? void 0
822
- : _a.map((file) => {
823
- const filePath = path.join(currentDir, file);
824
- if (fs.existsSync(filePath))
825
- excludeFiles.push(filePath.replace(/\\/g, "/"));
826
- });
827
- updateAnswer = {
828
- projectName,
829
- backendOnly:
830
- (_b =
831
- answer === null || answer === void 0
832
- ? void 0
833
- : answer.backendOnly) !== null && _b !== void 0
834
- ? _b
835
- : false,
836
- swaggerDocs:
837
- (_c =
838
- answer === null || answer === void 0
839
- ? void 0
840
- : answer.swaggerDocs) !== null && _c !== void 0
841
- ? _c
842
- : false,
843
- tailwindcss:
844
- (_d =
845
- answer === null || answer === void 0
846
- ? void 0
847
- : answer.tailwindcss) !== null && _d !== void 0
848
- ? _d
849
- : false,
850
- websocket:
851
- (_e =
852
- answer === null || answer === void 0
853
- ? void 0
854
- : answer.websocket) !== null && _e !== void 0
855
- ? _e
856
- : false,
857
- prisma:
858
- (_f =
859
- answer === null || answer === void 0 ? void 0 : answer.prisma) !==
860
- null && _f !== void 0
861
- ? _f
862
- : false,
863
- docker:
864
- (_g =
865
- answer === null || answer === void 0 ? void 0 : answer.docker) !==
866
- null && _g !== void 0
867
- ? _g
868
- : false,
869
- isUpdate: true,
870
- excludeFiles:
871
- (_h = localSettings.excludeFiles) !== null && _h !== void 0 ? _h : [],
872
- excludeFilePath:
873
- excludeFiles !== null && excludeFiles !== void 0 ? excludeFiles : [],
874
- filePath: currentDir,
875
- };
876
- } else {
877
- answer = await getAnswer();
878
- }
879
- if (answer === null) {
880
- console.warn(chalk.red("Installation cancelled."));
881
- return;
882
- }
883
- const latestVersionOfCreatePrismaPhpApp = await fetchPackageVersion(
884
- "create-prisma-php-app"
885
- );
886
- const isCreatePrismaPhpAppInstalled = getInstalledPackageVersion(
887
- "create-prisma-php-app"
888
- );
889
- if (isCreatePrismaPhpAppInstalled) {
890
- if (
891
- compareVersions(
892
- isCreatePrismaPhpAppInstalled,
893
- latestVersionOfCreatePrismaPhpApp
894
- ) === -1
895
- ) {
896
- execSync(`npm uninstall -g create-prisma-php-app`, {
897
- stdio: "inherit",
898
- });
899
- execSync(`npm install -g create-prisma-php-app`, {
900
- stdio: "inherit",
901
- });
902
- }
903
- } else {
904
- execSync("npm install -g create-prisma-php-app", { stdio: "inherit" });
905
- }
906
- const latestVersionOfBrowserSync = await fetchPackageVersion(
907
- "browser-sync"
908
- );
909
- const isBrowserSyncInstalled = getInstalledPackageVersion("browser-sync");
910
- if (isBrowserSyncInstalled) {
911
- if (
912
- compareVersions(isBrowserSyncInstalled, latestVersionOfBrowserSync) ===
913
- -1
914
- ) {
915
- execSync(`npm uninstall -g browser-sync`, {
916
- stdio: "inherit",
917
- });
918
- execSync(`npm install -g browser-sync`, {
919
- stdio: "inherit",
920
- });
921
- }
922
- } else {
923
- execSync("npm install -g browser-sync", { stdio: "inherit" });
924
- }
925
- // Create the project directory
926
- if (!projectName) fs.mkdirSync(answer.projectName);
927
- const currentDir = process.cwd();
928
- let projectPath = projectName
929
- ? currentDir
930
- : path.join(currentDir, answer.projectName);
931
- if (!projectName) process.chdir(answer.projectName);
932
- const dependencies = [
933
- "typescript",
934
- "@types/node",
935
- "ts-node",
936
- "http-proxy-middleware@^3.0.0",
937
- "chalk",
938
- "npm-run-all",
939
- ];
940
- if (answer.swaggerDocs) {
941
- dependencies.push("swagger-jsdoc");
942
- }
943
- if (answer.tailwindcss) {
944
- dependencies.push(
945
- "tailwindcss",
946
- "autoprefixer",
947
- "postcss",
948
- "postcss-cli",
949
- "cssnano"
950
- );
951
- }
952
- if (answer.websocket) {
953
- dependencies.push("chokidar-cli");
954
- }
955
- if (answer.prisma) {
956
- dependencies.push("prisma", "@prisma/client");
957
- }
958
- await installDependencies(projectPath, dependencies, true);
959
- if (!projectName) {
960
- execSync(`npx tsc --init`, { stdio: "inherit" });
961
- }
962
- if (answer.tailwindcss)
963
- execSync(`npx tailwindcss init -p`, { stdio: "inherit" });
964
- if (answer.prisma) {
965
- if (!fs.existsSync(path.join(projectPath, "prisma")))
966
- execSync(`npx prisma init`, { stdio: "inherit" });
967
- }
968
- await createDirectoryStructure(projectPath, answer);
969
- const publicDirPath = path.join(projectPath, "public");
970
- if (!fs.existsSync(publicDirPath)) {
971
- fs.mkdirSync(publicDirPath);
972
- }
973
- if (
974
- updateAnswer === null || updateAnswer === void 0
975
- ? void 0
976
- : updateAnswer.isUpdate
977
- ) {
978
- const updateUninstallDependencies = [];
979
- if (updateAnswer.backendOnly) {
980
- nonBackendFiles.forEach((file) => {
981
- const filePath = path.join(projectPath, "src", "app", file);
982
- if (fs.existsSync(filePath)) {
983
- fs.unlinkSync(filePath); // Delete each file if it exists
984
- console.log(`${file} was deleted successfully.`);
985
- } else {
986
- console.log(`${file} does not exist.`);
987
- }
988
- });
989
- const backendOnlyFolders = ["js", "css"];
990
- backendOnlyFolders.forEach((folder) => {
991
- const folderPath = path.join(projectPath, "src", "app", folder);
992
- if (fs.existsSync(folderPath)) {
993
- fs.rmSync(folderPath, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
994
- console.log(`${folder} was deleted successfully.`);
995
- } else {
996
- console.log(`${folder} does not exist.`);
997
- }
998
- });
999
- }
1000
- if (!updateAnswer.swaggerDocs) {
1001
- const swaggerDocsFolder = path.join(
1002
- projectPath,
1003
- "src",
1004
- "app",
1005
- "swagger-docs"
1006
- );
1007
- if (fs.existsSync(swaggerDocsFolder)) {
1008
- fs.rmSync(swaggerDocsFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
1009
- console.log(`swagger-docs was deleted successfully.`);
1010
- }
1011
- updateUninstallDependencies.push("swagger-jsdoc");
1012
- }
1013
- if (!updateAnswer.tailwindcss) {
1014
- const tailwindFiles = ["postcss.config.js", "tailwind.config.js"];
1015
- tailwindFiles.forEach((file) => {
1016
- const filePath = path.join(projectPath, file);
1017
- if (fs.existsSync(filePath)) {
1018
- fs.unlinkSync(filePath); // Delete each file if it exists
1019
- console.log(`${file} was deleted successfully.`);
1020
- } else {
1021
- console.log(`${file} does not exist.`);
1022
- }
1023
- });
1024
- updateUninstallDependencies.push(
1025
- "tailwindcss",
1026
- "autoprefixer",
1027
- "postcss",
1028
- "postcss-cli",
1029
- "cssnano"
1030
- );
1031
- }
1032
- if (!updateAnswer.websocket) {
1033
- updateUninstallDependencies.push("chokidar-cli");
1034
- }
1035
- if (!updateAnswer.prisma) {
1036
- updateUninstallDependencies.push("prisma", "@prisma/client");
1037
- }
1038
- if (!updateAnswer.docker) {
1039
- const dockerFiles = [
1040
- ".dockerignore",
1041
- "docker-compose.yml",
1042
- "Dockerfile",
1043
- "apache.conf",
1044
- ];
1045
- dockerFiles.forEach((file) => {
1046
- const filePath = path.join(projectPath, file);
1047
- if (fs.existsSync(filePath)) {
1048
- fs.unlinkSync(filePath); // Delete each file if it exists
1049
- console.log(`${file} was deleted successfully.`);
1050
- } else {
1051
- console.log(`${file} does not exist.`);
1052
- }
1053
- });
1054
- }
1055
- if (updateUninstallDependencies.length > 0) {
1056
- await uninstallDependencies(
1057
- projectPath,
1058
- updateUninstallDependencies,
1059
- true
1060
- );
1061
- }
1062
- }
1063
- const projectPathModified = projectPath.replace(/\\/g, "\\");
1064
- const bsConfig = bsConfigUrls(projectPathModified);
1065
- const phpGenerateClassPath = answer.prisma ? "src/Lib/Prisma/Classes" : "";
1066
- const prismaPhpConfig = {
1067
- projectName: answer.projectName,
1068
- projectRootPath: projectPathModified,
1069
- phpEnvironment: "XAMPP",
1070
- phpRootPathExe: "C:\\xampp\\php\\php.exe",
1071
- phpGenerateClassPath,
1072
- bsTarget: bsConfig.bsTarget,
1073
- bsPathRewrite: bsConfig.bsPathRewrite,
1074
- backendOnly: answer.backendOnly,
1075
- swaggerDocs: answer.swaggerDocs,
1076
- tailwindcss: answer.tailwindcss,
1077
- websocket: answer.websocket,
1078
- prisma: answer.prisma,
1079
- docker: answer.docker,
1080
- version: latestVersionOfCreatePrismaPhpApp,
1081
- excludeFiles:
1082
- (_j =
1083
- updateAnswer === null || updateAnswer === void 0
1084
- ? void 0
1085
- : updateAnswer.excludeFiles) !== null && _j !== void 0
1086
- ? _j
1087
- : [],
1088
- };
1089
- fs.writeFileSync(
1090
- path.join(projectPath, "prisma-php.json"),
1091
- JSON.stringify(prismaPhpConfig, null, 2),
1092
- { flag: "w" }
1093
- );
1094
- if (
1095
- updateAnswer === null || updateAnswer === void 0
1096
- ? void 0
1097
- : updateAnswer.isUpdate
1098
- ) {
1099
- execSync(
1100
- `C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar update`,
1101
- {
1102
- stdio: "inherit",
1103
- }
1104
- );
1105
- } else {
1106
- execSync(
1107
- `C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar install`,
1108
- {
1109
- stdio: "inherit",
1110
- }
1111
- );
1112
- }
1113
- console.log(
1114
- `${chalk.green("Success!")} Prisma PHP project successfully created in ${
1115
- answer.projectName
1116
- }!`
1117
- );
1118
- } catch (error) {
1119
- console.error("Error while creating the project:", error);
1120
- process.exit(1);
1121
- }
1122
- }
1123
- main();
2
+ import{execSync}from"child_process";import fs from"fs";import{fileURLToPath}from"url";import path from"path";import chalk from"chalk";import prompts from"prompts";import https from"https";const __filename=fileURLToPath(import.meta.url),__dirname=path.dirname(__filename);let updateAnswer=null;const nonBackendFiles=["favicon.ico","\\src\\app\\index.php","metadata.php","not-found.php"],dockerFiles=[".dockerignore","docker-compose.yml","Dockerfile","apache.conf"];function bsConfigUrls(e){const s=e.indexOf("\\htdocs\\");if(-1===s)return{bsTarget:"",bsPathRewrite:{}};const n=e.substring(0,s+"\\htdocs\\".length).replace(/\\/g,"\\\\"),t=e.replace(new RegExp(`^${n}`),"").replace(/\\/g,"/");let i=`http://localhost/${t}`;i=i.endsWith("/")?i.slice(0,-1):i;const c=i.replace(/(?<!:)(\/\/+)/g,"/"),r=t.replace(/\/\/+/g,"/");return{bsTarget:`${c}/`,bsPathRewrite:{"^/":`/${r.startsWith("/")?r.substring(1):r}/`}}}function configureBrowserSyncCommand(e){const s=path.join(e,"settings","bs-config.cjs");return fs.writeFileSync(s,'const { createProxyMiddleware } = require("http-proxy-middleware");\nconst fs = require("fs");\n\nconst jsonData = fs.readFileSync("prisma-php.json", "utf8");\nconst config = JSON.parse(jsonData);\n\nmodule.exports = {\n proxy: "http://localhost:3000",\n middleware: [\n (req, res, next) => {\n res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");\n res.setHeader("Pragma", "no-cache");\n res.setHeader("Expires", "0");\n next();\n },\n createProxyMiddleware({\n target: config.bsTarget,\n changeOrigin: true,\n pathRewrite: config.bsPathRewrite,\n }),\n ],\n files: "src/**/*.*",\n notify: false,\n open: false,\n ghostMode: false,\n codeSync: true, // Disable synchronization of code changes across clients\n};',"utf8"),"browser-sync start --config settings/bs-config.cjs"}async function updatePackageJson(e,s){const n=path.join(e,"package.json");if(checkExcludeFiles(n))return;const t=JSON.parse(fs.readFileSync(n,"utf8")),i=configureBrowserSyncCommand(e);t.scripts=Object.assign(Object.assign({},t.scripts),{projectName:"node settings/project-name.cjs"});let c=[];s.tailwindcss&&(t.scripts=Object.assign(Object.assign({},t.scripts),{tailwind:"postcss ./src/app/css/tailwind.css -o ./src/app/css/styles.css --watch"}),c.push("tailwind")),s.websocket&&(t.scripts=Object.assign(Object.assign({},t.scripts),{websocket:"node ./settings/restart-websocket.cjs"}),c.push("websocket")),s.docker&&(t.scripts=Object.assign(Object.assign({},t.scripts),{docker:"docker-compose up"}),c.push("docker")),s.swaggerDocs&&(t.scripts=Object.assign(Object.assign({},t.scripts),{"create-swagger-docs":"node settings/swagger-setup.js"}),c.push("create-swagger-docs"));let r=Object.assign({},t.scripts);r.browserSync=i,r._dev=c.length>0?`npm-run-all -p ${c.join(" ")}`:'echo "No additional scripts to run"',r.startDev="node settings/start-dev.js",r.dev="npm run startDev",t.scripts=r,t.type="module",s.prisma&&(t.prisma={seed:"node prisma/seed.js"}),fs.writeFileSync(n,JSON.stringify(t,null,2))}async function updateComposerJson(e,s){const n=path.join(e,"composer.json");if(checkExcludeFiles(n))return;let t;if(fs.existsSync(n)){{const e=fs.readFileSync(n,"utf8");t=JSON.parse(e)}s.websocket&&(t.require=Object.assign(Object.assign({},t.require),{"cboden/ratchet":"^0.4.4"})),s.prisma&&(t.require=Object.assign(Object.assign({},t.require),{"ramsey/uuid":"5.x-dev","hidehalo/nanoid-php":"1.x-dev"})),fs.writeFileSync(n,JSON.stringify(t,null,2))}}async function updateIndexJsForWebSocket(e,s){if(!s.websocket)return;const n=path.join(e,"src","app","js","index.js");if(checkExcludeFiles(n))return;let t=fs.readFileSync(n,"utf8");t+='\n// WebSocket initialization\nconst ws = new WebSocket("ws://localhost:8080");\n',fs.writeFileSync(n,t,"utf8")}async function createUpdateGitignoreFile(e,s){const n=path.join(e,".gitignore");if(checkExcludeFiles(n))return;let t="";s.forEach((e=>{t.includes(e)||(t+=`\n${e}`)})),t=t.trimStart(),fs.writeFileSync(n,t)}function copyRecursiveSync(e,s,n){var t;const i=fs.existsSync(e),c=i&&fs.statSync(e);if(i&&c&&c.isDirectory()){const i=s.toLowerCase();if(!n.websocket&&i.includes("src\\lib\\websocket"))return;if(!n.prisma&&i.includes("src\\lib\\prisma"))return;if(n.backendOnly&&i.includes("src\\app\\js")||n.backendOnly&&i.includes("src\\app\\css"))return;if(!n.swaggerDocs&&i.includes("src\\app\\swagger-docs"))return;const c=s.replace(/\\/g,"/");if(null===(t=null==updateAnswer?void 0:updateAnswer.excludeFilePath)||void 0===t?void 0:t.includes(c))return;fs.existsSync(s)||fs.mkdirSync(s,{recursive:!0}),fs.readdirSync(e).forEach((t=>{copyRecursiveSync(path.join(e,t),path.join(s,t),n)}))}else{if(checkExcludeFiles(s))return;if(!n.tailwindcss&&(s.includes("tailwind.css")||s.includes("styles.css")))return;if(!n.websocket&&(s.includes("restart-websocket.cjs")||s.includes("restart-websocket.bat")))return;if(!n.docker&&dockerFiles.some((e=>s.includes(e))))return;if(n.backendOnly&&nonBackendFiles.some((e=>s.includes(e))))return;if(!n.backendOnly&&s.includes("route.php"))return;if(n.backendOnly&&!n.swaggerDocs&&(s.includes("start-dev.js")||s.includes("swagger-setup.js")))return;fs.copyFileSync(e,s,0)}}async function executeCopy(e,s,n){s.forEach((({srcDir:s,destDir:t})=>{copyRecursiveSync(path.join(__dirname,s),path.join(e,t),n)}))}function createOrUpdateTailwindConfig(e){const s=path.join(e,"tailwind.config.js");if(checkExcludeFiles(s))return;let n=fs.readFileSync(s,"utf8");const t=["./src/app/**/*.{html,js,php}"].map((e=>` "${e}"`)).join(",\n");n=n.replace(/content: \[\],/g,`content: [\n${t}\n],`),fs.writeFileSync(s,n,{flag:"w"})}function modifyPostcssConfig(e){const s=path.join(e,"postcss.config.js");if(checkExcludeFiles(s))return;fs.writeFileSync(s,"export default {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n cssnano: {},\n },\n};",{flag:"w"})}function modifyLayoutPHP(e,s){const n=path.join(e,"src","app","layout.php");if(!checkExcludeFiles(n))try{let e=fs.readFileSync(n,"utf8"),t="";s.backendOnly||(t='\n <link href="<?= $baseUrl; ?>/css/index.css" rel="stylesheet">\n <script src="<?= $baseUrl; ?>/js/index.js"><\/script>');let i="";s.backendOnly||(i=s.tailwindcss?` <link href="<?= $baseUrl; ?>/css/styles.css" rel="stylesheet"> ${t}`:` <script src="https://cdn.tailwindcss.com"><\/script> ${t}`);const c=i.length>0?"\n":"";e=e.replace("</head>",`${i}${c} \x3c!-- Dynamic Head --\x3e\n <?= implode("\\n", $mainLayoutHead); ?>\n</head>`),fs.writeFileSync(n,e,{flag:"w"})}catch(e){}}async function createOrUpdateEnvFile(e,s){const n=path.join(e,".env");checkExcludeFiles(n)||fs.writeFileSync(n,s,{flag:"w"})}function checkExcludeFiles(e){var s,n;return!!(null==updateAnswer?void 0:updateAnswer.isUpdate)&&(null!==(n=null===(s=null==updateAnswer?void 0:updateAnswer.excludeFilePath)||void 0===s?void 0:s.includes(e.replace(/\\/g,"/")))&&void 0!==n&&n)}async function createDirectoryStructure(e,s){const n=[{src:"/bootstrap.php",dest:"/bootstrap.php"},{src:"/.htaccess",dest:"/.htaccess"},{src:"/../composer.json",dest:"/composer.json"}];(null==updateAnswer?void 0:updateAnswer.isUpdate)&&(n.push({src:"/tsconfig.json",dest:"/tsconfig.json"}),updateAnswer.tailwindcss&&n.push({src:"/postcss.config.js",dest:"/postcss.config.js"},{src:"/tailwind.config.js",dest:"/tailwind.config.js"}));const t=[{srcDir:"/settings",destDir:"/settings"},{srcDir:"/src",destDir:"/src"}];s.backendOnly&&s.swaggerDocs&&t.push({srcDir:"/swagger-docs-layout.php",destDir:"/src/app/layout.php"}),s.swaggerDocs&&t.push({srcDir:"/swagger-docs-index.php",destDir:"/src/app/swagger-docs/index.php"}),s.prisma&&t.push({srcDir:"/prisma",destDir:"/prisma"}),s.docker&&t.push({srcDir:"/.dockerignore",destDir:"/.dockerignore"},{srcDir:"/docker-compose.yml",destDir:"/docker-compose.yml"},{srcDir:"/Dockerfile",destDir:"/Dockerfile"},{srcDir:"/apache.conf",destDir:"/apache.conf"}),n.forEach((({src:s,dest:n})=>{const t=path.join(__dirname,s),i=path.join(e,n);if(checkExcludeFiles(i))return;const c=fs.readFileSync(t,"utf8");fs.writeFileSync(i,c,{flag:"w"})})),await executeCopy(e,t,s),await updatePackageJson(e,s),await updateComposerJson(e,s),s.backendOnly||await updateIndexJsForWebSocket(e,s),s.tailwindcss&&(createOrUpdateTailwindConfig(e),modifyPostcssConfig(e)),(s.tailwindcss||!s.backendOnly||s.swaggerDocs)&&modifyLayoutPHP(e,s);const i='# Prisma PHP Auth Secret Key For development only - Change this in production\nAUTH_SECRET=uxsjXVPHN038DEYls2Kw0QUgBcXKUyrjv416nIFWPY4= \n \n# PHPMailer\n# SMTP_HOST=smtp.gmail.com or your SMTP host\n# SMTP_USERNAME=john.doe@gmail.com or your SMTP username\n# SMTP_PASSWORD=123456\n# SMTP_PORT=587 for TLS, 465 for SSL or your SMTP port\n# SMTP_ENCRYPTION=ssl or tls\n# MAIL_FROM=john.doe@gmail.com\n# MAIL_FROM_NAME="John Doe"\n\n# SHOW ERRORS - Set to true to show errors in the browser for development only - Change this in production to false\nSHOW_ERRORS=true\n\n# ChatGPT API Key\n# CHATGPT_API_KEY=sk-your-api-key\n\n# APP TIMEZONE - Set your application timezone - Default is "UTC"\nAPP_TIMEZONE="UTC"';if(s.prisma){const s=`${'# Environment variables declared in this file are automatically made available to Prisma.\n# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema\n\n# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.\n# See the documentation for all the connection string options: https://pris.ly/d/connection-strings\n\nDATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"'}\n\n${i}`;await createOrUpdateEnvFile(e,s)}else await createOrUpdateEnvFile(e,i);await createUpdateGitignoreFile(e,["vendor",".env","node_modules"])}async function getAnswer(e={}){var s,n,t,i,c,r,a,o,l,p,d,u,h;const g=[];e.projectName||g.push({type:"text",name:"projectName",message:"What is your project named?",initial:"my-app"}),e.backendOnly||g.push({type:"toggle",name:"backendOnly",message:"Would you like to create a backend-only project?",initial:!1,active:"Yes",inactive:"No"});const m=()=>{process.exit(0)},f=await prompts(g,{onCancel:m}),y=[];f.backendOnly||e.backendOnly?(e.swaggerDocs||y.push({type:"toggle",name:"swaggerDocs",message:`Would you like to use ${chalk.blue("Swagger Docs")}?`,initial:!1,active:"Yes",inactive:"No"}),e.websocket||y.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!0,active:"Yes",inactive:"No"}),e.prisma||y.push({type:"toggle",name:"prisma",message:`Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,initial:!0,active:"Yes",inactive:"No"}),e.docker||y.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"})):(e.swaggerDocs||y.push({type:"toggle",name:"swaggerDocs",message:`Would you like to use ${chalk.blue("Swagger Docs")}?`,initial:!1,active:"Yes",inactive:"No"}),e.tailwindcss||y.push({type:"toggle",name:"tailwindcss",message:`Would you like to use ${chalk.blue("Tailwind CSS")}?`,initial:!0,active:"Yes",inactive:"No"}),e.websocket||y.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!0,active:"Yes",inactive:"No"}),e.prisma||y.push({type:"toggle",name:"prisma",message:`Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,initial:!0,active:"Yes",inactive:"No"}),e.docker||y.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"}));const w=await prompts(y,{onCancel:m});return{projectName:f.projectName?String(f.projectName).trim().replace(/ /g,"-"):null!==(s=e.projectName)&&void 0!==s?s:"my-app",backendOnly:null!==(t=null!==(n=f.backendOnly)&&void 0!==n?n:e.backendOnly)&&void 0!==t&&t,swaggerDocs:null!==(c=null!==(i=w.swaggerDocs)&&void 0!==i?i:e.swaggerDocs)&&void 0!==c&&c,tailwindcss:null!==(a=null!==(r=w.tailwindcss)&&void 0!==r?r:e.tailwindcss)&&void 0!==a&&a,websocket:null!==(l=null!==(o=w.websocket)&&void 0!==o?o:e.websocket)&&void 0!==l&&l,prisma:null!==(d=null!==(p=w.prisma)&&void 0!==p?p:e.prisma)&&void 0!==d&&d,docker:null!==(h=null!==(u=w.docker)&&void 0!==u?u:e.docker)&&void 0!==h&&h}}async function installDependencies(e,s,n=!1){fs.existsSync(path.join(e,"package.json"))||execSync("npm init -y",{stdio:"inherit",cwd:e}),s.forEach((e=>{}));const t=`npm install ${n?"--save-dev":""} ${s.join(" ")}`;execSync(t,{stdio:"inherit",cwd:e})}async function uninstallDependencies(e,s,n=!1){s.forEach((e=>{}));const t=`npm uninstall ${n?"--save-dev":"--save"} ${s.join(" ")}`;execSync(t,{stdio:"inherit",cwd:e})}function fetchPackageVersion(e){return new Promise(((s,n)=>{https.get(`https://registry.npmjs.org/${e}`,(e=>{let t="";e.on("data",(e=>t+=e)),e.on("end",(()=>{try{const e=JSON.parse(t);s(e["dist-tags"].latest)}catch(e){n(new Error("Failed to parse JSON response"))}}))})).on("error",(e=>n(e)))}))}const readJsonFile=e=>{const s=fs.readFileSync(e,"utf8");return JSON.parse(s)};function compareVersions(e,s){const n=e.split(".").map(Number),t=s.split(".").map(Number);for(let e=0;e<n.length;e++){if(n[e]>t[e])return 1;if(n[e]<t[e])return-1}return 0}function getInstalledPackageVersion(e){try{const s=execSync(`npm list -g ${e} --depth=0`).toString().match(new RegExp(`${e}@(\\d+\\.\\d+\\.\\d+)`));return s?s[1]:null}catch(e){return null}}async function main(){var e,s,n,t,i,c,r,a,o;try{const l=process.argv.slice(2);let p=l[0],d=null;if(p){const o={projectName:p,backendOnly:l.includes("--backend-only"),swaggerDocs:l.includes("--swagger-docs"),tailwindcss:l.includes("--tailwindcss"),websocket:l.includes("--websocket"),prisma:l.includes("--prisma"),docker:l.includes("--docker")};if(d=await getAnswer(o),null===d)return;const u=process.cwd(),h=path.join(u,"prisma-php.json"),g=readJsonFile(h);let m=[];null===(e=g.excludeFiles)||void 0===e||e.map((e=>{const s=path.join(u,e);fs.existsSync(s)&&m.push(s.replace(/\\/g,"/"))})),updateAnswer={projectName:p,backendOnly:null!==(s=null==d?void 0:d.backendOnly)&&void 0!==s&&s,swaggerDocs:null!==(n=null==d?void 0:d.swaggerDocs)&&void 0!==n&&n,tailwindcss:null!==(t=null==d?void 0:d.tailwindcss)&&void 0!==t&&t,websocket:null!==(i=null==d?void 0:d.websocket)&&void 0!==i&&i,prisma:null!==(c=null==d?void 0:d.prisma)&&void 0!==c&&c,docker:null!==(r=null==d?void 0:d.docker)&&void 0!==r&&r,isUpdate:!0,excludeFiles:null!==(a=g.excludeFiles)&&void 0!==a?a:[],excludeFilePath:null!=m?m:[],filePath:u}}else d=await getAnswer();if(null===d)return;const u=await fetchPackageVersion("create-prisma-php-app"),h=getInstalledPackageVersion("create-prisma-php-app");h?-1===compareVersions(h,u)&&(execSync("npm uninstall -g create-prisma-php-app",{stdio:"inherit"}),execSync("npm install -g create-prisma-php-app",{stdio:"inherit"})):execSync("npm install -g create-prisma-php-app",{stdio:"inherit"});const g=await fetchPackageVersion("browser-sync"),m=getInstalledPackageVersion("browser-sync");m?-1===compareVersions(m,g)&&(execSync("npm uninstall -g browser-sync",{stdio:"inherit"}),execSync("npm install -g browser-sync",{stdio:"inherit"})):execSync("npm install -g browser-sync",{stdio:"inherit"}),p||fs.mkdirSync(d.projectName);const f=process.cwd();let y=p?f:path.join(f,d.projectName);p||process.chdir(d.projectName);const w=["typescript","@types/node","ts-node","http-proxy-middleware@^3.0.0","chalk","npm-run-all"];d.swaggerDocs&&w.push("swagger-jsdoc"),d.tailwindcss&&w.push("tailwindcss","autoprefixer","postcss","postcss-cli","cssnano"),d.websocket&&w.push("chokidar-cli"),d.prisma&&w.push("prisma","@prisma/client"),await installDependencies(y,w,!0),p||execSync("npx tsc --init",{stdio:"inherit"}),d.tailwindcss&&execSync("npx tailwindcss init -p",{stdio:"inherit"}),d.prisma&&(fs.existsSync(path.join(y,"prisma"))||execSync("npx prisma init",{stdio:"inherit"})),await createDirectoryStructure(y,d);const k=path.join(y,"public");if(fs.existsSync(k)||fs.mkdirSync(k),null==updateAnswer?void 0:updateAnswer.isUpdate){const e=[];if(updateAnswer.backendOnly){nonBackendFiles.forEach((e=>{const s=path.join(y,"src","app",e);fs.existsSync(s)&&fs.unlinkSync(s)}));["js","css"].forEach((e=>{const s=path.join(y,"src","app",e);fs.existsSync(s)&&fs.rmSync(s,{recursive:!0,force:!0})}))}if(!updateAnswer.swaggerDocs){const s=path.join(y,"src","app","swagger-docs");fs.existsSync(s)&&fs.rmSync(s,{recursive:!0,force:!0}),e.push("swagger-jsdoc")}if(!updateAnswer.tailwindcss){["postcss.config.js","tailwind.config.js"].forEach((e=>{const s=path.join(y,e);fs.existsSync(s)&&fs.unlinkSync(s)})),e.push("tailwindcss","autoprefixer","postcss","postcss-cli","cssnano")}if(updateAnswer.websocket||e.push("chokidar-cli"),updateAnswer.prisma||e.push("prisma","@prisma/client"),!updateAnswer.docker){[".dockerignore","docker-compose.yml","Dockerfile","apache.conf"].forEach((e=>{const s=path.join(y,e);fs.existsSync(s)&&fs.unlinkSync(s)}))}e.length>0&&await uninstallDependencies(y,e,!0)}const b=y.replace(/\\/g,"\\"),S=bsConfigUrls(b),j=d.prisma?"src/Lib/Prisma/Classes":"",v={projectName:d.projectName,projectRootPath:b,phpEnvironment:"XAMPP",phpRootPathExe:"C:\\xampp\\php\\php.exe",phpGenerateClassPath:j,bsTarget:S.bsTarget,bsPathRewrite:S.bsPathRewrite,backendOnly:d.backendOnly,swaggerDocs:d.swaggerDocs,tailwindcss:d.tailwindcss,websocket:d.websocket,prisma:d.prisma,docker:d.docker,version:u,excludeFiles:null!==(o=null==updateAnswer?void 0:updateAnswer.excludeFiles)&&void 0!==o?o:[]};fs.writeFileSync(path.join(y,"prisma-php.json"),JSON.stringify(v,null,2),{flag:"w"}),(null==updateAnswer?void 0:updateAnswer.isUpdate)?execSync("C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar update",{stdio:"inherit"}):execSync("C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar install",{stdio:"inherit"})}catch(e){process.exit(1)}}main();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-prisma-php-app",
3
- "version": "1.21.0",
3
+ "version": "1.21.1",
4
4
  "description": "Prisma-PHP: A Revolutionary Library Bridging PHP with Prisma ORM",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",