create-prisma-php-app 1.18.513 → 1.19.1

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