create-prisma-php-app 1.6.56 → 1.6.57

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