create-prisma-php-app 1.10.12 → 1.10.13

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