create-prisma-php-app 1.8.8 → 1.8.9

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 -748
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,749 +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 configureBrowserSyncCommand(baseDir, projectSettings) {
13
- // Identify the base path dynamically up to and including 'htdocs'
14
- const htdocsIndex = projectSettings.PROJECT_ROOT_PATH.indexOf("\\htdocs\\");
15
- if (htdocsIndex === -1) {
16
- console.error(
17
- "Invalid PROJECT_ROOT_PATH. The path does not contain \\htdocs\\"
18
- );
19
- return ""; // Return an empty string or handle the error as appropriate
20
- }
21
- // Extract the path up to and including 'htdocs\\'
22
- const basePathToRemove = projectSettings.PROJECT_ROOT_PATH.substring(
23
- 0,
24
- htdocsIndex + "\\htdocs\\".length
25
- );
26
- // Escape backslashes for the regex pattern
27
- const escapedBasePathToRemove = basePathToRemove.replace(/\\/g, "\\\\");
28
- // Remove the base path and replace backslashes with forward slashes for URL compatibility
29
- const relativeWebPath = projectSettings.PROJECT_ROOT_PATH.replace(
30
- new RegExp(`^${escapedBasePathToRemove}`),
31
- ""
32
- ).replace(/\\/g, "/");
33
- // Construct the Browser Sync command with the correct proxy URL, being careful not to affect the protocol part
34
- let proxyUrl = `http://localhost/${relativeWebPath}`;
35
- // Ensure the proxy URL does not end with a slash before appending '/public'
36
- proxyUrl = proxyUrl.endsWith("/") ? proxyUrl.slice(0, -1) : proxyUrl;
37
- // Clean the URL by replacing "//" with "/" but not affecting "http://"
38
- // We replace instances of "//" that are not preceded by ":"
39
- const cleanUrl = proxyUrl.replace(/(?<!:)(\/\/+)/g, "/");
40
- const cleanRelativeWebPath = relativeWebPath.replace(/\/\/+/g, "/");
41
- // Correct the relativeWebPath to ensure it does not start with a "/"
42
- const adjustedRelativeWebPath = cleanRelativeWebPath.startsWith("/")
43
- ? cleanRelativeWebPath.substring(1)
44
- : cleanRelativeWebPath;
45
- // TypeScript content to write
46
- const bsConfigTsContent = `
47
- const { createProxyMiddleware } = require("http-proxy-middleware");
48
-
49
- module.exports = {
50
- // First middleware: Set Cache-Control headers
51
- function (req, res, next) {
52
- res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
53
- res.setHeader("Pragma", "no-cache");
54
- res.setHeader("Expires", "0");
55
- next();
56
- },
57
- // Use the 'middleware' option to create a proxy that masks the deep URL.
58
- middleware: [
59
- // This middleware intercepts requests to the root and proxies them to the deep path.
60
- createProxyMiddleware("/", {
61
- target:
62
- "${cleanUrl}",
63
- changeOrigin: true,
64
- pathRewrite: {
65
- "^/": "/${adjustedRelativeWebPath}", // Rewrite the path.
66
- },
67
- }),
68
- ],
69
- proxy: "http://localhost:3000", // Proxy the BrowserSync server.
70
- // serveStatic: ["src/app"], // Serve static files from this directory.
71
- files: "src/**/*.*",
72
- notify: false,
73
- open: false,
74
- ghostMode: false,
75
- };`;
76
- // Determine the path and write the bs-config.js
77
- const bsConfigPath = path.join(baseDir, "settings", "bs-config.cjs");
78
- fs.writeFileSync(bsConfigPath, bsConfigTsContent, "utf8");
79
- // Return the Browser Sync command string, using the cleaned URL
80
- return `browser-sync start --config settings/bs-config.cjs`;
81
- }
82
- async function updatePackageJson(baseDir, projectSettings, answer) {
83
- const packageJsonPath = path.join(baseDir, "package.json");
84
- if (checkExcludeFiles(packageJsonPath)) return;
85
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
86
- // Use the new function to configure the Browser Sync command
87
- const browserSyncCommand = configureBrowserSyncCommand(
88
- baseDir,
89
- projectSettings
90
- );
91
- packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), {
92
- postinstall: "prisma generate",
93
- });
94
- let answersToInclude = [];
95
- if (answer.tailwindcss) {
96
- packageJson.scripts = Object.assign(
97
- Object.assign({}, packageJson.scripts),
98
- {
99
- tailwind:
100
- "postcss ./src/app/css/tailwind.css -o ./src/app/css/styles.css --watch",
101
- }
102
- );
103
- answersToInclude.push("tailwind");
104
- }
105
- if (answer.websocket) {
106
- packageJson.scripts = Object.assign(
107
- Object.assign({}, packageJson.scripts),
108
- { websocket: "node ./settings/restartWebsocket.cjs" }
109
- );
110
- answersToInclude.push("websocket");
111
- }
112
- // Initialize with existing scripts
113
- const updatedScripts = Object.assign({}, packageJson.scripts);
114
- // Conditionally add "browser-sync" command
115
- if (answersToInclude.length > 0) {
116
- updatedScripts["browser-sync"] = browserSyncCommand;
117
- }
118
- // Conditionally set the "dev" command
119
- updatedScripts.dev =
120
- answersToInclude.length > 0
121
- ? `npm-run-all --parallel browser-sync ${answersToInclude.join(" ")}`
122
- : browserSyncCommand;
123
- // Finally, assign the updated scripts back to packageJson
124
- packageJson.scripts = updatedScripts;
125
- packageJson.type = "module";
126
- packageJson.prisma = {
127
- seed: "node prisma/seed.js",
128
- };
129
- fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
130
- }
131
- async function updateComposerJson(baseDir, answer) {
132
- if (!answer.websocket) return;
133
- const composerJsonPath = path.join(baseDir, "composer.json");
134
- if (checkExcludeFiles(composerJsonPath)) return;
135
- let composerJson;
136
- // Check if the composer.json file exists
137
- if (fs.existsSync(composerJsonPath)) {
138
- // Read the current composer.json content
139
- const composerJsonContent = fs.readFileSync(composerJsonPath, "utf8");
140
- composerJson = JSON.parse(composerJsonContent);
141
- } else {
142
- console.error("composer.json does not exist.");
143
- return;
144
- }
145
- // Conditionally add WebSocket dependency
146
- if (answer.websocket) {
147
- composerJson.require = Object.assign(
148
- Object.assign({}, composerJson.require),
149
- { "cboden/ratchet": "^0.4.4" }
150
- );
151
- }
152
- // Write the modified composer.json back to the file
153
- fs.writeFileSync(composerJsonPath, JSON.stringify(composerJson, null, 2));
154
- console.log("composer.json updated successfully.");
155
- }
156
- async function updateIndexJsForWebSocket(baseDir, answer) {
157
- if (!answer.websocket) {
158
- return;
159
- }
160
- const indexPath = path.join(baseDir, "src", "app", "js", "index.js");
161
- if (checkExcludeFiles(indexPath)) return;
162
- let indexContent = fs.readFileSync(indexPath, "utf8");
163
- // WebSocket initialization code to be appended
164
- const webSocketCode = `
165
- // WebSocket initialization
166
- const ws = new WebSocket("ws://localhost:8080");
167
- `;
168
- // Append WebSocket code if user chose to use WebSocket
169
- indexContent += webSocketCode;
170
- fs.writeFileSync(indexPath, indexContent, "utf8");
171
- console.log("WebSocket code added to index.js successfully.");
172
- }
173
- // This function updates the .gitignore file
174
- async function createUpdateGitignoreFile(baseDir, additions) {
175
- const gitignorePath = path.join(baseDir, ".gitignore");
176
- if (checkExcludeFiles(gitignorePath)) return;
177
- // Check if the .gitignore file exists, create if it doesn't
178
- let gitignoreContent = "";
179
- if (fs.existsSync(gitignorePath)) {
180
- gitignoreContent = fs.readFileSync(gitignorePath, "utf8");
181
- }
182
- additions.forEach((addition) => {
183
- if (!gitignoreContent.includes(addition)) {
184
- gitignoreContent += `\n${addition}`;
185
- }
186
- });
187
- // Ensure there's no leading newline if the file was just created
188
- gitignoreContent = gitignoreContent.trimStart();
189
- fs.writeFileSync(gitignorePath, gitignoreContent);
190
- }
191
- // Recursive copy function
192
- function copyRecursiveSync(src, dest) {
193
- console.log("🚀 ~ copyRecursiveSync ~ dest:", dest);
194
- console.log("🚀 ~ copyRecursiveSync ~ src:", src);
195
- const exists = fs.existsSync(src);
196
- const stats = exists && fs.statSync(src);
197
- const isDirectory = exists && stats && stats.isDirectory();
198
- if (isDirectory) {
199
- fs.mkdirSync(dest, { recursive: true });
200
- fs.readdirSync(src).forEach((childItemName) => {
201
- copyRecursiveSync(
202
- path.join(src, childItemName),
203
- path.join(dest, childItemName)
204
- );
205
- });
206
- } else {
207
- if (checkExcludeFiles(dest)) return;
208
- fs.copyFileSync(src, dest, 0);
209
- }
210
- }
211
- // Function to execute the recursive copy for entire directories
212
- async function executeCopy(baseDir, directoriesToCopy) {
213
- directoriesToCopy.forEach(({ srcDir, destDir }) => {
214
- const sourcePath = path.join(__dirname, srcDir);
215
- const destPath = path.join(baseDir, destDir);
216
- copyRecursiveSync(sourcePath, destPath);
217
- });
218
- }
219
- function createOrUpdateTailwindConfig(baseDir) {
220
- console.log("🚀 ~ createOrUpdateTailwindConfig ~ baseDir:", baseDir);
221
- const filePath = path.join(baseDir, "tailwind.config.js");
222
- if (checkExcludeFiles(filePath)) return;
223
- const newContent = [
224
- "./src/app/**/*.{html,js,php}",
225
- // Add more paths as needed
226
- ];
227
- let configData = fs.readFileSync(filePath, "utf8");
228
- console.log("🚀 ~ createOrUpdateTailwindConfig ~ configData:", configData);
229
- const contentArrayString = newContent
230
- .map((item) => ` "${item}"`)
231
- .join(",\n");
232
- configData = configData.replace(
233
- /content: \[\],/g,
234
- `content: [\n${contentArrayString}\n],`
235
- );
236
- fs.writeFileSync(filePath, configData, { flag: "w" });
237
- console.log(chalk.green("Tailwind configuration updated successfully."));
238
- }
239
- function modifyPostcssConfig(baseDir) {
240
- const filePath = path.join(baseDir, "postcss.config.js");
241
- if (checkExcludeFiles(filePath)) return;
242
- const newContent = `export default {
243
- plugins: {
244
- tailwindcss: {},
245
- autoprefixer: {},
246
- cssnano: {},
247
- },
248
- };`;
249
- fs.writeFileSync(filePath, newContent, { flag: "w" });
250
- console.log(chalk.green("postcss.config.js updated successfully."));
251
- }
252
- function modifyLayoutPHP(baseDir, useTailwind) {
253
- const layoutPath = path.join(baseDir, "src", "app", "layout.php");
254
- if (checkExcludeFiles(layoutPath)) return;
255
- try {
256
- let indexContent = fs.readFileSync(layoutPath, "utf8");
257
- const stylesAndLinks = `\n <link href="<?php echo $baseUrl; ?>css/index.css" rel="stylesheet">\n <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">\n <script src="<?php echo $baseUrl; ?>js/index.js"></script>`;
258
- // Tailwind CSS link or CDN script
259
- const tailwindLink = useTailwind
260
- ? ` <link href="<?php echo $baseUrl; ?>css/styles.css" rel="stylesheet"> ${stylesAndLinks}`
261
- : ` <script src="https://cdn.tailwindcss.com"></script> ${stylesAndLinks}`;
262
- // Insert before the closing </head> tag
263
- indexContent = indexContent.replace("</head>", `${tailwindLink}\n</head>`);
264
- fs.writeFileSync(layoutPath, indexContent, { flag: "w" });
265
- console.log(
266
- chalk.green(
267
- `index.php modified successfully for ${
268
- useTailwind ? "local Tailwind CSS" : "Tailwind CSS CDN"
269
- }.`
270
- )
271
- );
272
- } catch (error) {
273
- console.error(chalk.red("Error modifying index.php:"), error);
274
- }
275
- }
276
- // This function updates or creates the .env file
277
- async function createOrUpdateEnvFile(baseDir, content) {
278
- const envPath = path.join(baseDir, ".env");
279
- if (checkExcludeFiles(envPath)) return;
280
- let envContent = fs.existsSync(envPath)
281
- ? fs.readFileSync(envPath, "utf8")
282
- : "";
283
- // Check if the content already exists in the .env file
284
- if (!envContent.includes(content)) {
285
- envContent += `${envContent !== "" ? "\n\n" : ""}${content}`;
286
- fs.writeFileSync(envPath, envContent, { flag: "w" });
287
- }
288
- }
289
- function checkExcludeFiles(destPath) {
290
- var _a, _b;
291
- if (
292
- !(updateAnswer === null || updateAnswer === void 0
293
- ? void 0
294
- : updateAnswer.isUpdate)
295
- )
296
- return false;
297
- return (_b =
298
- (_a =
299
- updateAnswer === null || updateAnswer === void 0
300
- ? void 0
301
- : updateAnswer.excludeFilePath) === null || _a === void 0
302
- ? void 0
303
- : _a.includes(destPath.replace(/\\/g, "/"))) !== null && _b !== void 0
304
- ? _b
305
- : false;
306
- }
307
- async function createDirectoryStructure(baseDir, answer, projectSettings) {
308
- console.log("🚀 ~ baseDir:", baseDir);
309
- console.log("🚀 ~ answer:", answer);
310
- console.log("🚀 ~ projectSettings:", projectSettings);
311
- const filesToCopy = [
312
- { src: "/bootstrap.php", dest: "/bootstrap.php" },
313
- { src: "/.htaccess", dest: "/.htaccess" },
314
- { src: "/../composer.json", dest: "/composer.json" },
315
- ];
316
- if (
317
- updateAnswer === null || updateAnswer === void 0
318
- ? void 0
319
- : updateAnswer.isUpdate
320
- ) {
321
- filesToCopy.push(
322
- { src: "/.env", dest: "/.env" },
323
- { src: "/tsconfig.json", dest: "/tsconfig.json" }
324
- );
325
- if (updateAnswer.tailwindcss) {
326
- filesToCopy.push(
327
- { src: "/postcss.config.js", dest: "/postcss.config.js" },
328
- { src: "/tailwind.config.js", dest: "/tailwind.config.js" }
329
- );
330
- }
331
- }
332
- // if (answer.websocket) {
333
- // filesToCopy.push({
334
- // src: "/../composer-websocket.lock",
335
- // dest: "/composer.lock",
336
- // });
337
- // } else {
338
- // filesToCopy.push({ src: "/../composer.lock", dest: "/composer.lock" });
339
- // }
340
- const directoriesToCopy = [
341
- {
342
- srcDir: "/settings",
343
- destDir: "/settings",
344
- },
345
- {
346
- srcDir: "/prisma",
347
- destDir: "/prisma",
348
- },
349
- {
350
- srcDir: "/src",
351
- destDir: "/src",
352
- },
353
- ];
354
- console.log("🚀 ~ directoriesToCopy:", directoriesToCopy);
355
- filesToCopy.forEach(({ src, dest }) => {
356
- const sourcePath = path.join(__dirname, src);
357
- const destPath = path.join(baseDir, dest);
358
- if (checkExcludeFiles(destPath)) return;
359
- const code = fs.readFileSync(sourcePath, "utf8");
360
- fs.writeFileSync(destPath, code, { flag: "w" });
361
- });
362
- await executeCopy(baseDir, directoriesToCopy);
363
- await updatePackageJson(baseDir, projectSettings, answer);
364
- await updateComposerJson(baseDir, answer);
365
- await updateIndexJsForWebSocket(baseDir, answer);
366
- if (answer.tailwindcss) {
367
- createOrUpdateTailwindConfig(baseDir);
368
- modifyLayoutPHP(baseDir, true);
369
- modifyPostcssConfig(baseDir);
370
- } else {
371
- modifyLayoutPHP(baseDir, false);
372
- }
373
- const envContent = `# 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
- await createOrUpdateEnvFile(baseDir, envContent);
382
- // Add vendor to .gitignore
383
- await createUpdateGitignoreFile(baseDir, ["vendor"]);
384
- }
385
- async function getAnswer(predefinedAnswers = {}) {
386
- var _a, _b, _c;
387
- console.log("🚀 ~ predefinedAnswers:", predefinedAnswers);
388
- const questionsArray = [];
389
- if (!predefinedAnswers.projectName) {
390
- questionsArray.push({
391
- type: "text",
392
- name: "projectName",
393
- message: "What is your project named?",
394
- initial: "my-app",
395
- });
396
- }
397
- if (!predefinedAnswers.tailwindcss) {
398
- questionsArray.push({
399
- type: "toggle",
400
- name: "tailwindcss",
401
- message: `Would you like to use ${chalk.blue("Tailwind CSS")}?`,
402
- initial: true,
403
- active: "Yes",
404
- inactive: "No",
405
- });
406
- }
407
- if (!predefinedAnswers.websocket) {
408
- questionsArray.push({
409
- type: "toggle",
410
- name: "websocket",
411
- message: `Would you like to use ${chalk.blue("Websocket")}?`,
412
- initial: true,
413
- active: "Yes",
414
- inactive: "No",
415
- });
416
- }
417
- const questions = questionsArray;
418
- console.log("🚀 ~ questions:", questions);
419
- const onCancel = () => {
420
- console.log(chalk.red("Operation cancelled by the user."));
421
- process.exit(0);
422
- };
423
- try {
424
- const response = await prompts(questions, { onCancel });
425
- console.log("🚀 ~ response:", response);
426
- if (Object.keys(response).length === 0) {
427
- return null;
428
- }
429
- return {
430
- projectName: response.projectName
431
- ? String(response.projectName).trim().replace(/ /g, "-")
432
- : (_a = predefinedAnswers.projectName) !== null && _a !== void 0
433
- ? _a
434
- : "my-app",
435
- tailwindcss:
436
- (_b = response.tailwindcss) !== null && _b !== void 0
437
- ? _b
438
- : predefinedAnswers.tailwindcss,
439
- websocket:
440
- (_c = response.websocket) !== null && _c !== void 0
441
- ? _c
442
- : predefinedAnswers.websocket,
443
- };
444
- } catch (error) {
445
- console.error(chalk.red("Prompt error:"), error);
446
- return null;
447
- }
448
- }
449
- /**
450
- * Install dependencies in the specified directory.
451
- * @param {string} baseDir - The base directory where to install the dependencies.
452
- * @param {string[]} dependencies - The list of dependencies to install.
453
- * @param {boolean} [isDev=false] - Whether to install the dependencies as devDependencies.
454
- */
455
- async function installDependencies(baseDir, dependencies, isDev = false) {
456
- console.log("Initializing new Node.js project...");
457
- // Initialize a package.json if it doesn't exist
458
- if (!fs.existsSync(path.join(baseDir, "package.json")))
459
- execSync("npm init -y", {
460
- stdio: "inherit",
461
- cwd: baseDir,
462
- });
463
- // Log the dependencies being installed
464
- console.log(
465
- `${
466
- isDev ? "Installing development dependencies" : "Installing dependencies"
467
- }:`
468
- );
469
- dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
470
- // Prepare the npm install command with the appropriate flag for dev dependencies
471
- const npmInstallCommand = `npm install ${
472
- isDev ? "--save-dev" : ""
473
- } ${dependencies.join(" ")}`;
474
- // Execute the npm install command
475
- execSync(npmInstallCommand, {
476
- stdio: "inherit",
477
- cwd: baseDir,
478
- });
479
- }
480
- async function uninstallDependencies(baseDir, dependencies, isDev = false) {
481
- console.log("Uninstalling dependencies:");
482
- dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
483
- // Prepare the npm uninstall command with the appropriate flag for dev dependencies
484
- const npmUninstallCommand = `npm uninstall ${
485
- isDev ? "--save-dev" : "--save"
486
- } ${dependencies.join(" ")}`;
487
- // Execute the npm uninstall command
488
- execSync(npmUninstallCommand, {
489
- stdio: "inherit",
490
- cwd: baseDir,
491
- });
492
- }
493
- function fetchPackageVersion(packageName) {
494
- return new Promise((resolve, reject) => {
495
- https
496
- .get(`https://registry.npmjs.org/${packageName}`, (res) => {
497
- let data = "";
498
- res.on("data", (chunk) => (data += chunk));
499
- res.on("end", () => {
500
- try {
501
- const parsed = JSON.parse(data);
502
- resolve(parsed["dist-tags"].latest);
503
- } catch (error) {
504
- reject(new Error("Failed to parse JSON response"));
505
- }
506
- });
507
- })
508
- .on("error", (err) => reject(err));
509
- });
510
- }
511
- const readJsonFile = (filePath) => {
512
- const jsonData = fs.readFileSync(filePath, "utf8");
513
- return JSON.parse(jsonData);
514
- };
515
- async function main() {
516
- var _a, _b, _c, _d, _e;
517
- try {
518
- const args = process.argv.slice(2);
519
- let projectName = args[0];
520
- let answer = null;
521
- if (projectName) {
522
- let useTailwind = args.includes("--tailwindcss");
523
- let useWebsocket = args.includes("--websocket");
524
- const predefinedAnswers = {
525
- projectName,
526
- tailwindcss: useTailwind,
527
- websocket: useWebsocket,
528
- };
529
- answer = await getAnswer(predefinedAnswers);
530
- if (answer === null) {
531
- console.log(chalk.red("Installation cancelled."));
532
- return;
533
- }
534
- const currentDir = process.cwd();
535
- const configPath = path.join(currentDir, "prisma-php.json");
536
- const localSettings = readJsonFile(configPath);
537
- let excludeFiles = [];
538
- (_a = localSettings.excludeFiles) === null || _a === void 0
539
- ? void 0
540
- : _a.map((file) => {
541
- const filePath = path.join(currentDir, file);
542
- if (fs.existsSync(filePath))
543
- excludeFiles.push(filePath.replace(/\\/g, "/"));
544
- });
545
- updateAnswer = {
546
- projectName,
547
- tailwindcss:
548
- (_b =
549
- answer === null || answer === void 0
550
- ? void 0
551
- : answer.tailwindcss) !== null && _b !== void 0
552
- ? _b
553
- : false,
554
- websocket:
555
- (_c =
556
- answer === null || answer === void 0
557
- ? void 0
558
- : answer.websocket) !== null && _c !== void 0
559
- ? _c
560
- : false,
561
- isUpdate: true,
562
- excludeFiles:
563
- (_d = localSettings.excludeFiles) !== null && _d !== void 0 ? _d : [],
564
- excludeFilePath:
565
- excludeFiles !== null && excludeFiles !== void 0 ? excludeFiles : [],
566
- filePath: currentDir,
567
- };
568
- } else {
569
- answer = await getAnswer();
570
- }
571
- if (answer === null) {
572
- console.log(chalk.red("Installation cancelled."));
573
- return;
574
- }
575
- execSync(`npm install -g create-prisma-php-app`, { stdio: "inherit" }); // TODO: Uncomment this line before publishing the package
576
- // Support for browser-sync
577
- execSync(`npm install -g browser-sync`, { stdio: "inherit" });
578
- // Create the project directory
579
- if (!projectName) fs.mkdirSync(answer.projectName);
580
- const currentDir = process.cwd();
581
- let projectPath = projectName
582
- ? currentDir
583
- : path.join(currentDir, answer.projectName);
584
- if (!projectName) process.chdir(answer.projectName);
585
- const dependencies = [
586
- "prisma",
587
- "@prisma/client",
588
- "typescript",
589
- "@types/node",
590
- "ts-node",
591
- "http-proxy-middleware",
592
- ];
593
- if (answer.tailwindcss) {
594
- dependencies.push(
595
- "tailwindcss",
596
- "autoprefixer",
597
- "postcss",
598
- "postcss-cli",
599
- "cssnano"
600
- );
601
- }
602
- if (answer.websocket) {
603
- dependencies.push("chokidar-cli");
604
- }
605
- if (answer.tailwindcss || answer.websocket) {
606
- dependencies.push("npm-run-all");
607
- }
608
- await installDependencies(projectPath, dependencies, true);
609
- if (!projectName) {
610
- execSync(`npx prisma init`, { stdio: "inherit" });
611
- execSync(`npx tsc --init`, { stdio: "inherit" });
612
- }
613
- if (answer.tailwindcss) {
614
- execSync(`npx tailwindcss init -p`, { stdio: "inherit" });
615
- }
616
- const projectSettings = {
617
- PROJECT_NAME: answer.projectName,
618
- PROJECT_ROOT_PATH: projectPath.replace(/\\/g, "\\\\"),
619
- PHP_ROOT_PATH_EXE: "D:\\\\xampp\\\\php\\\\php.exe",
620
- PHP_GENERATE_CLASS_PATH: "src/Lib/Prisma/Classes",
621
- };
622
- await createDirectoryStructure(projectPath, answer, projectSettings);
623
- // execSync(`composer install`, { stdio: "inherit" });
624
- // execSync(`composer dump-autoload`, { stdio: "inherit" });
625
- // Create settings file
626
- const settingsPath = path.join(
627
- projectPath,
628
- "settings",
629
- "project-settings.js"
630
- );
631
- const settingsCode = `export const projectSettings = {
632
- PROJECT_NAME: "${answer.projectName}",
633
- PROJECT_ROOT_PATH: "${projectPath.replace(/\\/g, "\\\\")}",
634
- PHP_ROOT_PATH_EXE: "D:\\\\xampp\\\\php\\\\php.exe",
635
- PHP_GENERATE_CLASS_PATH: "src/Lib/Prisma/Classes",
636
- };`;
637
- fs.writeFileSync(settingsPath, settingsCode, { flag: "w" });
638
- const publicDirPath = path.join(projectPath, "public");
639
- if (!fs.existsSync(publicDirPath)) {
640
- fs.mkdirSync(publicDirPath);
641
- }
642
- if (!answer.tailwindcss) {
643
- const cssPath = path.join(projectPath, "src", "app", "css");
644
- const tailwindFiles = ["tailwind.css", "styles.css"];
645
- tailwindFiles.forEach((file) => {
646
- const filePath = path.join(cssPath, file);
647
- if (fs.existsSync(filePath)) {
648
- fs.unlinkSync(filePath); // Delete each file if it exists
649
- console.log(`${file} was deleted successfully.`);
650
- } else {
651
- console.log(`${file} does not exist.`);
652
- }
653
- });
654
- }
655
- // Update websocket if not chosen by the user
656
- if (!answer.websocket) {
657
- const wsPath = path.join(projectPath, "src", "lib", "websocket");
658
- // Check if the websocket directory exists
659
- if (fs.existsSync(wsPath)) {
660
- // Use fs.rmSync with recursive option set to true to delete the directory and its contents
661
- fs.rmSync(wsPath, { recursive: true, force: true }); // force option is not necessary but can be used to ensure deletion
662
- console.log("Websocket directory was deleted successfully.");
663
- } else {
664
- console.log("Websocket directory does not exist.");
665
- }
666
- // Update settings directory if websocket is not chosen
667
- const settingsPath = path.join(projectPath, "settings");
668
- const websocketFiles = ["restartWebsocket.cjs", "restart_websocket.bat"];
669
- websocketFiles.forEach((file) => {
670
- const filePath = path.join(settingsPath, file);
671
- if (fs.existsSync(filePath)) {
672
- fs.unlinkSync(filePath); // Delete each file if it exists
673
- console.log(`${file} was deleted successfully.`);
674
- } else {
675
- console.log(`${file} does not exist.`);
676
- }
677
- });
678
- }
679
- if (
680
- updateAnswer === null || updateAnswer === void 0
681
- ? void 0
682
- : updateAnswer.isUpdate
683
- ) {
684
- const updateUninstallDependencies = [];
685
- if (!updateAnswer.tailwindcss) {
686
- const tailwindFiles = ["postcss.config.js", "tailwind.config.js"];
687
- tailwindFiles.forEach((file) => {
688
- const filePath = path.join(projectPath, file);
689
- if (fs.existsSync(filePath)) {
690
- fs.unlinkSync(filePath); // Delete each file if it exists
691
- console.log(`${file} was deleted successfully.`);
692
- } else {
693
- console.log(`${file} does not exist.`);
694
- }
695
- });
696
- updateUninstallDependencies.push(
697
- "tailwindcss",
698
- "autoprefixer",
699
- "postcss",
700
- "postcss-cli",
701
- "cssnano"
702
- );
703
- }
704
- if (!updateAnswer.websocket) {
705
- updateUninstallDependencies.push("chokidar-cli");
706
- }
707
- if (updateUninstallDependencies.length > 0) {
708
- await uninstallDependencies(
709
- projectPath,
710
- updateUninstallDependencies,
711
- true
712
- );
713
- }
714
- // if (fs.existsSync(path.join(projectPath, "composer.lock"))) {
715
- // if (checkExcludeFiles(path.join(projectPath, "composer.lock"))) return;
716
- // fs.unlinkSync(path.join(projectPath, "composer.lock"));
717
- // console.log("composer.lock file deleted successfully.");
718
- // }
719
- }
720
- const version = await fetchPackageVersion("create-prisma-php-app");
721
- const prismaPhpConfig = {
722
- projectName: answer.projectName,
723
- tailwindcss: answer.tailwindcss,
724
- websocket: answer.websocket,
725
- version,
726
- excludeFiles:
727
- (_e =
728
- updateAnswer === null || updateAnswer === void 0
729
- ? void 0
730
- : updateAnswer.excludeFiles) !== null && _e !== void 0
731
- ? _e
732
- : [],
733
- };
734
- fs.writeFileSync(
735
- path.join(projectPath, "prisma-php.json"),
736
- JSON.stringify(prismaPhpConfig, null, 2),
737
- { flag: "w" }
738
- );
739
- console.log(
740
- `${chalk.green("Success!")} Prisma PHP project successfully created in ${
741
- answer.projectName
742
- }!`
743
- );
744
- } catch (error) {
745
- console.error("Error while creating the project:", error);
746
- process.exit(1);
747
- }
748
- }
749
- 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 configureBrowserSyncCommand(e,s){const t=s.PROJECT_ROOT_PATH.indexOf("\\htdocs\\");if(-1===t)return"";const n=s.PROJECT_ROOT_PATH.substring(0,t+"\\htdocs\\".length).replace(/\\/g,"\\\\"),i=s.PROJECT_ROOT_PATH.replace(new RegExp(`^${n}`),"").replace(/\\/g,"/");let c=`http://localhost/${i}`;c=c.endsWith("/")?c.slice(0,-1):c;const r=c.replace(/(?<!:)(\/\/+)/g,"/"),o=i.replace(/\/\/+/g,"/"),a=`\n const { createProxyMiddleware } = require("http-proxy-middleware");\n\n module.exports = {\n // First middleware: Set Cache-Control headers\n function (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 // Use the 'middleware' option to create a proxy that masks the deep URL.\n middleware: [\n // This middleware intercepts requests to the root and proxies them to the deep path.\n createProxyMiddleware("/", {\n target:\n "${r}",\n changeOrigin: true,\n pathRewrite: {\n "^/": "/${o.startsWith("/")?o.substring(1):o}", // Rewrite the path.\n },\n }),\n ],\n proxy: "http://localhost:3000", // Proxy the BrowserSync server.\n // serveStatic: ["src/app"], // Serve static files from this directory.\n files: "src/**/*.*",\n notify: false,\n open: false,\n ghostMode: false,\n };`,l=path.join(e,"settings","bs-config.cjs");return fs.writeFileSync(l,a,"utf8"),"browser-sync start --config settings/bs-config.cjs"}async function updatePackageJson(e,s,t){const n=path.join(e,"package.json");if(checkExcludeFiles(n))return;const i=JSON.parse(fs.readFileSync(n,"utf8")),c=configureBrowserSyncCommand(e,s);i.scripts=Object.assign(Object.assign({},i.scripts),{postinstall:"prisma generate"});let r=[];t.tailwindcss&&(i.scripts=Object.assign(Object.assign({},i.scripts),{tailwind:"postcss ./src/app/css/tailwind.css -o ./src/app/css/styles.css --watch"}),r.push("tailwind")),t.websocket&&(i.scripts=Object.assign(Object.assign({},i.scripts),{websocket:"node ./settings/restartWebsocket.cjs"}),r.push("websocket"));const o=Object.assign({},i.scripts);r.length>0&&(o["browser-sync"]=c),o.dev=r.length>0?`npm-run-all --parallel browser-sync ${r.join(" ")}`:c,i.scripts=o,i.type="module",i.prisma={seed:"node prisma/seed.js"},fs.writeFileSync(n,JSON.stringify(i,null,2))}async function updateComposerJson(e,s){if(!s.websocket)return;const t=path.join(e,"composer.json");if(checkExcludeFiles(t))return;let n;if(fs.existsSync(t)){{const e=fs.readFileSync(t,"utf8");n=JSON.parse(e)}s.websocket&&(n.require=Object.assign(Object.assign({},n.require),{"cboden/ratchet":"^0.4.4"})),fs.writeFileSync(t,JSON.stringify(n,null,2))}}async function updateIndexJsForWebSocket(e,s){if(!s.websocket)return;const t=path.join(e,"src","app","js","index.js");if(checkExcludeFiles(t))return;let n=fs.readFileSync(t,"utf8");n+='\n// WebSocket initialization\nconst ws = new WebSocket("ws://localhost:8080");\n',fs.writeFileSync(t,n,"utf8")}async function createUpdateGitignoreFile(e,s){const t=path.join(e,".gitignore");if(checkExcludeFiles(t))return;let n="";fs.existsSync(t)&&(n=fs.readFileSync(t,"utf8")),s.forEach((e=>{n.includes(e)||(n+=`\n${e}`)})),n=n.trimStart(),fs.writeFileSync(t,n)}function copyRecursiveSync(e,s){const t=fs.existsSync(e),n=t&&fs.statSync(e);if(t&&n&&n.isDirectory())fs.mkdirSync(s,{recursive:!0}),fs.readdirSync(e).forEach((t=>{copyRecursiveSync(path.join(e,t),path.join(s,t))}));else{if(checkExcludeFiles(s))return;fs.copyFileSync(e,s,0)}}async function executeCopy(e,s){s.forEach((({srcDir:s,destDir:t})=>{copyRecursiveSync(path.join(__dirname,s),path.join(e,t))}))}function createOrUpdateTailwindConfig(e){const s=path.join(e,"tailwind.config.js");if(checkExcludeFiles(s))return;let t=fs.readFileSync(s,"utf8");const n=["./src/app/**/*.{html,js,php}"].map((e=>` "${e}"`)).join(",\n");t=t.replace(/content: \[\],/g,`content: [\n${n}\n],`),fs.writeFileSync(s,t,{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 t=path.join(e,"src","app","layout.php");if(!checkExcludeFiles(t))try{let e=fs.readFileSync(t,"utf8");const n='\n <link href="<?php echo $baseUrl; ?>css/index.css" rel="stylesheet">\n <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">\n <script src="<?php echo $baseUrl; ?>js/index.js"><\/script>',i=s?` <link href="<?php echo $baseUrl; ?>css/styles.css" rel="stylesheet"> ${n}`:` <script src="https://cdn.tailwindcss.com"><\/script> ${n}`;e=e.replace("</head>",`${i}\n</head>`),fs.writeFileSync(t,e,{flag:"w"})}catch(e){}}async function createOrUpdateEnvFile(e,s){const t=path.join(e,".env");if(checkExcludeFiles(t))return;let n=fs.existsSync(t)?fs.readFileSync(t,"utf8"):"";n.includes(s)||(n+=`${""!==n?"\n\n":""}${s}`,fs.writeFileSync(t,n,{flag:"w"}))}function checkExcludeFiles(e){var s,t;return!!(null==updateAnswer?void 0:updateAnswer.isUpdate)&&(null!==(t=null===(s=null==updateAnswer?void 0:updateAnswer.excludeFilePath)||void 0===s?void 0:s.includes(e.replace(/\\/g,"/")))&&void 0!==t&&t)}async function createDirectoryStructure(e,s,t){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:"/.env",dest:"/.env"},{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"}));n.forEach((({src:s,dest:t})=>{const n=path.join(__dirname,s),i=path.join(e,t);if(checkExcludeFiles(i))return;const c=fs.readFileSync(n,"utf8");fs.writeFileSync(i,c,{flag:"w"})})),await executeCopy(e,[{srcDir:"/settings",destDir:"/settings"},{srcDir:"/prisma",destDir:"/prisma"},{srcDir:"/src",destDir:"/src"}]),await updatePackageJson(e,t,s),await updateComposerJson(e,s),await updateIndexJsForWebSocket(e,s),s.tailwindcss?(createOrUpdateTailwindConfig(e),modifyLayoutPHP(e,!0),modifyPostcssConfig(e)):modifyLayoutPHP(e,!1);await createOrUpdateEnvFile(e,'# 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"'),await createUpdateGitignoreFile(e,["vendor"])}async function getAnswer(e={}){var s,t,n;const i=[];e.projectName||i.push({type:"text",name:"projectName",message:"What is your project named?",initial:"my-app"}),e.tailwindcss||i.push({type:"toggle",name:"tailwindcss",message:`Would you like to use ${chalk.blue("Tailwind CSS")}?`,initial:!0,active:"Yes",inactive:"No"}),e.websocket||i.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!0,active:"Yes",inactive:"No"});const c=i,r=()=>{process.exit(0)};try{const i=await prompts(c,{onCancel:r});return 0===Object.keys(i).length?null:{projectName:i.projectName?String(i.projectName).trim().replace(/ /g,"-"):null!==(s=e.projectName)&&void 0!==s?s:"my-app",tailwindcss:null!==(t=i.tailwindcss)&&void 0!==t?t:e.tailwindcss,websocket:null!==(n=i.websocket)&&void 0!==n?n:e.websocket}}catch(e){return null}}async function installDependencies(e,s,t=!1){fs.existsSync(path.join(e,"package.json"))||execSync("npm init -y",{stdio:"inherit",cwd:e}),s.forEach((e=>{}));const n=`npm install ${t?"--save-dev":""} ${s.join(" ")}`;execSync(n,{stdio:"inherit",cwd:e})}async function uninstallDependencies(e,s,t=!1){s.forEach((e=>{}));const n=`npm uninstall ${t?"--save-dev":"--save"} ${s.join(" ")}`;execSync(n,{stdio:"inherit",cwd:e})}function fetchPackageVersion(e){return new Promise(((s,t)=>{https.get(`https://registry.npmjs.org/${e}`,(e=>{let n="";e.on("data",(e=>n+=e)),e.on("end",(()=>{try{const e=JSON.parse(n);s(e["dist-tags"].latest)}catch(e){t(new Error("Failed to parse JSON response"))}}))})).on("error",(e=>t(e)))}))}const readJsonFile=e=>{const s=fs.readFileSync(e,"utf8");return JSON.parse(s)};async function main(){var e,s,t,n,i;try{const c=process.argv.slice(2);let r=c[0],o=null;if(r){const i={projectName:r,tailwindcss:c.includes("--tailwindcss"),websocket:c.includes("--websocket")};if(o=await getAnswer(i),null===o)return;const a=process.cwd(),l=path.join(a,"prisma-php.json"),p=readJsonFile(l);let d=[];null===(e=p.excludeFiles)||void 0===e||e.map((e=>{const s=path.join(a,e);fs.existsSync(s)&&d.push(s.replace(/\\/g,"/"))})),updateAnswer={projectName:r,tailwindcss:null!==(s=null==o?void 0:o.tailwindcss)&&void 0!==s&&s,websocket:null!==(t=null==o?void 0:o.websocket)&&void 0!==t&&t,isUpdate:!0,excludeFiles:null!==(n=p.excludeFiles)&&void 0!==n?n:[],excludeFilePath:null!=d?d:[],filePath:a}}else o=await getAnswer();if(null===o)return;execSync("npm install -g create-prisma-php-app",{stdio:"inherit"}),execSync("npm install -g browser-sync",{stdio:"inherit"}),r||fs.mkdirSync(o.projectName);const a=process.cwd();let l=r?a:path.join(a,o.projectName);r||process.chdir(o.projectName);const p=["prisma","@prisma/client","typescript","@types/node","ts-node","http-proxy-middleware"];o.tailwindcss&&p.push("tailwindcss","autoprefixer","postcss","postcss-cli","cssnano"),o.websocket&&p.push("chokidar-cli"),(o.tailwindcss||o.websocket)&&p.push("npm-run-all"),await installDependencies(l,p,!0),r||(execSync("npx prisma init",{stdio:"inherit"}),execSync("npx tsc --init",{stdio:"inherit"})),o.tailwindcss&&execSync("npx tailwindcss init -p",{stdio:"inherit"});const d={PROJECT_NAME:o.projectName,PROJECT_ROOT_PATH:l.replace(/\\/g,"\\\\"),PHP_ROOT_PATH_EXE:"D:\\\\xampp\\\\php\\\\php.exe",PHP_GENERATE_CLASS_PATH:"src/Lib/Prisma/Classes"};await createDirectoryStructure(l,o,d);const u=path.join(l,"settings","project-settings.js"),f=`export const projectSettings = {\n PROJECT_NAME: "${o.projectName}",\n PROJECT_ROOT_PATH: "${l.replace(/\\/g,"\\\\")}",\n PHP_ROOT_PATH_EXE: "D:\\\\xampp\\\\php\\\\php.exe",\n PHP_GENERATE_CLASS_PATH: "src/Lib/Prisma/Classes",\n };`;fs.writeFileSync(u,f,{flag:"w"});const h=path.join(l,"public");if(fs.existsSync(h)||fs.mkdirSync(h),!o.tailwindcss){const e=path.join(l,"src","app","css");["tailwind.css","styles.css"].forEach((s=>{const t=path.join(e,s);fs.existsSync(t)&&fs.unlinkSync(t)}))}if(!o.websocket){const e=path.join(l,"src","lib","websocket");fs.existsSync(e)&&fs.rmSync(e,{recursive:!0,force:!0});const s=path.join(l,"settings");["restartWebsocket.cjs","restart_websocket.bat"].forEach((e=>{const t=path.join(s,e);fs.existsSync(t)&&fs.unlinkSync(t)}))}if(null==updateAnswer?void 0:updateAnswer.isUpdate){const e=[];if(!updateAnswer.tailwindcss){["postcss.config.js","tailwind.config.js"].forEach((e=>{const s=path.join(l,e);fs.existsSync(s)&&fs.unlinkSync(s)})),e.push("tailwindcss","autoprefixer","postcss","postcss-cli","cssnano")}updateAnswer.websocket||e.push("chokidar-cli"),e.length>0&&await uninstallDependencies(l,e,!0)}const w=await fetchPackageVersion("create-prisma-php-app"),y={projectName:o.projectName,tailwindcss:o.tailwindcss,websocket:o.websocket,version:w,excludeFiles:null!==(i=null==updateAnswer?void 0:updateAnswer.excludeFiles)&&void 0!==i?i:[]};fs.writeFileSync(path.join(l,"prisma-php.json"),JSON.stringify(y,null,2),{flag:"w"})}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.8.8",
3
+ "version": "1.8.9",
4
4
  "description": "Prisma-PHP: A Revolutionary Library Bridging PHP with Prisma ORM",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",