create-prisma-php-app 1.6.24 → 1.6.27

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 +405 -1
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,5 +1,409 @@
1
1
  #!/usr/bin/env node
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);function configureBrowserSyncCommand(e,t){const s=t.PROJECT_ROOT_PATH.indexOf("\\htdocs\\");if(-1===s)return"";const n=t.PROJECT_ROOT_PATH.substring(0,s+"\\htdocs\\".length).replace(/\\/g,"\\\\"),i=t.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 };`,p=path.join(e,"settings","bs-config.cjs");return fs.writeFileSync(p,a,"utf8"),"browser-sync start --config settings/bs-config.cjs"}async function updatePackageJson(e,t,s){const n=path.join(e,"package.json"),i=JSON.parse(fs.readFileSync(n,"utf8")),c=configureBrowserSyncCommand(e,t);i.scripts=Object.assign(Object.assign({},i.scripts),{postinstall:"prisma generate"});let r=[];s.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")),s.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,t){if(!t.websocket)return;const s=path.join(e,"composer.json");let n;if(fs.existsSync(s)){{const e=fs.readFileSync(s,"utf8");n=JSON.parse(e)}t.websocket&&(n.require=Object.assign(Object.assign({},n.require),{"cboden/ratchet":"^0.4.4"})),fs.writeFileSync(s,JSON.stringify(n,null,2))}}async function updateIndexJsForWebSocket(e,t){if(!t.websocket)return;const s=path.join(e,"src","app","js","index.js");let n=fs.readFileSync(s,"utf8");n+='\n// WebSocket initialization\nconst ws = new WebSocket("ws://localhost:8080");\n',fs.writeFileSync(s,n,"utf8")}async function createUpdateGitignoreFile(e,t){const s=path.join(e,".gitignore");let n="";fs.existsSync(s)&&(n=fs.readFileSync(s,"utf8")),t.forEach((e=>{n.includes(e)||(n+=`\n${e}`)})),n=n.trimStart(),fs.writeFileSync(s,n)}function copyRecursiveSync(e,t){const s=fs.existsSync(e),n=s&&fs.statSync(e);s&&n&&n.isDirectory()?(fs.existsSync(t)&&fs.rmSync(t,{recursive:!0,force:!0}),fs.mkdirSync(t,{recursive:!0}),fs.readdirSync(e).forEach((s=>{copyRecursiveSync(path.join(e,s),path.join(t,s))}))):fs.copyFileSync(e,t)}async function executeCopy(e,t){t.forEach((({srcDir:t,destDir:s})=>{copyRecursiveSync(path.join(__dirname,t),path.join(e,s))}))}function modifyTailwindConfig(e){const t=path.join(e,"tailwind.config.js");let s=fs.readFileSync(t,"utf8");const n=["./src/app/**/*.{html,js,php}"].map((e=>` "${e}"`)).join(",\n");s=s.replace(/content: \[\],/g,`content: [\n${n}\n],`),fs.writeFileSync(t,s,"utf8")}function modifyPostcssConfig(e){const t=path.join(e,"postcss.config.js");fs.writeFileSync(t,"export default {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n cssnano: {},\n },\n};","utf8")}function modifyIndexPHP(e,t){const s=path.join(e,"src","app","layout.php");try{let e=fs.readFileSync(s,"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=t?` <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(s,e,"utf8")}catch(e){}}async function updateOrCreateEnvFile(e,t){const s=path.join(e,".env");let n=fs.existsSync(s)?fs.readFileSync(s,"utf8"):"";n+=`${""!==n?"\n\n":""}${t}`,fs.writeFileSync(s,n)}async function createDirectoryStructure(e,t,s){[{src:"/bootstrap.php",dest:"/bootstrap.php"},{src:"/.htaccess",dest:"/.htaccess"},{src:"/../composer.json",dest:"/composer.json"}].forEach((({src:t,dest:s})=>{const n=path.join(__dirname,t),i=path.join(e,s),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"}]),await updatePackageJson(e,s,t),await updateComposerJson(e,t),await updateIndexJsForWebSocket(e,t),t.tailwindcss?(modifyTailwindConfig(e),modifyIndexPHP(e,!0),modifyPostcssConfig(e)):modifyIndexPHP(e,!1);await updateOrCreateEnvFile(e,'# PHPMailer\nSMTP_HOST=\nSMTP_USERNAME=\nSMTP_PASSWORD=\nSMTP_PORT=\nSMTP_ENCRYPTION=ssl\nMAIL_FROM=\nMAIL_FROM_NAME=""'),await createUpdateGitignoreFile(e,["vendor"])}async function getAnswer(e={}){var t,s,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=()=>!1;try{const r=await prompts(i,{onCancel:c});return 0===Object.keys(r).length?null:{projectName:r.projectName?String(r.projectName).trim().replace(/ /g,"-"):null!==(t=e.projectName)&&void 0!==t?t:"my-app",tailwindcss:null!==(s=r.tailwindcss)&&void 0!==s?s:e.tailwindcss,websocket:null!==(n=r.websocket)&&void 0!==n?n:e.websocket}}catch(e){return null}}async function installDependencies(e,t,s=!1){fs.existsSync(path.join(e,"package.json"))||execSync("npm init -y",{stdio:"inherit",cwd:e}),t.forEach((e=>{}));const n=`npm install ${s?"--save-dev":""} ${t.join(" ")}`;execSync(n,{stdio:"inherit",cwd:e})}function fetchPackageVersion(e){return new Promise(((t,s)=>{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);t(e["dist-tags"].latest)}catch(e){s(new Error("Failed to parse JSON response"))}}))})).on("error",(e=>s(e)))}))}
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
+ function configureBrowserSyncCommand(baseDir, projectSettings) {
12
+ // Identify the base path dynamically up to and including 'htdocs'
13
+ const htdocsIndex = projectSettings.PROJECT_ROOT_PATH.indexOf("\\htdocs\\");
14
+ if (htdocsIndex === -1) {
15
+ console.error("Invalid PROJECT_ROOT_PATH. The path does not contain \\htdocs\\");
16
+ return ""; // Return an empty string or handle the error as appropriate
17
+ }
18
+ // Extract the path up to and including 'htdocs\\'
19
+ const basePathToRemove = projectSettings.PROJECT_ROOT_PATH.substring(0, htdocsIndex + "\\htdocs\\".length);
20
+ // Escape backslashes for the regex pattern
21
+ const escapedBasePathToRemove = basePathToRemove.replace(/\\/g, "\\\\");
22
+ // Remove the base path and replace backslashes with forward slashes for URL compatibility
23
+ const relativeWebPath = projectSettings.PROJECT_ROOT_PATH.replace(new RegExp(`^${escapedBasePathToRemove}`), "").replace(/\\/g, "/");
24
+ // Construct the Browser Sync command with the correct proxy URL, being careful not to affect the protocol part
25
+ let proxyUrl = `http://localhost/${relativeWebPath}`;
26
+ // Ensure the proxy URL does not end with a slash before appending '/public'
27
+ proxyUrl = proxyUrl.endsWith("/") ? proxyUrl.slice(0, -1) : proxyUrl;
28
+ // Clean the URL by replacing "//" with "/" but not affecting "http://"
29
+ // We replace instances of "//" that are not preceded by ":"
30
+ const cleanUrl = proxyUrl.replace(/(?<!:)(\/\/+)/g, "/");
31
+ const cleanRelativeWebPath = relativeWebPath.replace(/\/\/+/g, "/");
32
+ // Correct the relativeWebPath to ensure it does not start with a "/"
33
+ const adjustedRelativeWebPath = cleanRelativeWebPath.startsWith("/")
34
+ ? cleanRelativeWebPath.substring(1)
35
+ : cleanRelativeWebPath;
36
+ // TypeScript content to write
37
+ const bsConfigTsContent = `
38
+ const { createProxyMiddleware } = require("http-proxy-middleware");
39
+
40
+ module.exports = {
41
+ // First middleware: Set Cache-Control headers
42
+ function (req, res, next) {
43
+ res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
44
+ res.setHeader("Pragma", "no-cache");
45
+ res.setHeader("Expires", "0");
46
+ next();
47
+ },
48
+ // Use the 'middleware' option to create a proxy that masks the deep URL.
49
+ middleware: [
50
+ // This middleware intercepts requests to the root and proxies them to the deep path.
51
+ createProxyMiddleware("/", {
52
+ target:
53
+ "${cleanUrl}",
54
+ changeOrigin: true,
55
+ pathRewrite: {
56
+ "^/": "/${adjustedRelativeWebPath}", // Rewrite the path.
57
+ },
58
+ }),
59
+ ],
60
+ proxy: "http://localhost:3000", // Proxy the BrowserSync server.
61
+ // serveStatic: ["src/app"], // Serve static files from this directory.
62
+ files: "src/**/*.*",
63
+ notify: false,
64
+ open: false,
65
+ ghostMode: false,
66
+ };`;
67
+ // Determine the path and write the bs-config.js
68
+ const bsConfigPath = path.join(baseDir, "settings", "bs-config.cjs");
69
+ fs.writeFileSync(bsConfigPath, bsConfigTsContent, "utf8");
70
+ // Return the Browser Sync command string, using the cleaned URL
71
+ return `browser-sync start --config settings/bs-config.cjs`;
72
+ }
73
+ async function updatePackageJson(baseDir, projectSettings, answer) {
74
+ const packageJsonPath = path.join(baseDir, "package.json");
75
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
76
+ // Use the new function to configure the Browser Sync command
77
+ const browserSyncCommand = configureBrowserSyncCommand(baseDir, projectSettings);
78
+ packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), { postinstall: "prisma generate" });
79
+ let answersToInclude = [];
80
+ if (answer.tailwindcss) {
81
+ packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), { tailwind: "postcss ./src/app/css/tailwind.css -o ./src/app/css/styles.css --watch" });
82
+ answersToInclude.push("tailwind");
83
+ }
84
+ if (answer.websocket) {
85
+ packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), { websocket: "node ./settings/restartWebsocket.cjs" });
86
+ answersToInclude.push("websocket");
87
+ }
88
+ // Initialize with existing scripts
89
+ const updatedScripts = Object.assign({}, packageJson.scripts);
90
+ // Conditionally add "browser-sync" command
91
+ if (answersToInclude.length > 0) {
92
+ updatedScripts["browser-sync"] = browserSyncCommand;
93
+ }
94
+ // Conditionally set the "dev" command
95
+ updatedScripts.dev =
96
+ answersToInclude.length > 0
97
+ ? `npm-run-all --parallel browser-sync ${answersToInclude.join(" ")}`
98
+ : browserSyncCommand;
99
+ // Finally, assign the updated scripts back to packageJson
100
+ packageJson.scripts = updatedScripts;
101
+ packageJson.type = "module";
102
+ packageJson.prisma = {
103
+ seed: "node prisma/seed.js",
104
+ };
105
+ fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
106
+ }
107
+ async function updateComposerJson(baseDir, answer) {
108
+ if (!answer.websocket)
109
+ return;
110
+ const composerJsonPath = path.join(baseDir, "composer.json");
111
+ let composerJson;
112
+ // Check if the composer.json file exists
113
+ if (fs.existsSync(composerJsonPath)) {
114
+ // Read the current composer.json content
115
+ const composerJsonContent = fs.readFileSync(composerJsonPath, "utf8");
116
+ composerJson = JSON.parse(composerJsonContent);
117
+ }
118
+ else {
119
+ console.error("composer.json does not exist.");
120
+ return;
121
+ }
122
+ // Conditionally add WebSocket dependency
123
+ if (answer.websocket) {
124
+ composerJson.require = Object.assign(Object.assign({}, composerJson.require), { "cboden/ratchet": "^0.4.4" });
125
+ }
126
+ // Write the modified composer.json back to the file
127
+ fs.writeFileSync(composerJsonPath, JSON.stringify(composerJson, null, 2));
128
+ console.log("composer.json updated successfully.");
129
+ }
130
+ async function updateIndexJsForWebSocket(baseDir, answer) {
131
+ if (!answer.websocket) {
132
+ return;
133
+ }
134
+ const indexPath = path.join(baseDir, "src", "app", "js", "index.js");
135
+ let indexContent = fs.readFileSync(indexPath, "utf8");
136
+ // WebSocket initialization code to be appended
137
+ const webSocketCode = `
138
+ // WebSocket initialization
139
+ const ws = new WebSocket("ws://localhost:8080");
140
+ `;
141
+ // Append WebSocket code if user chose to use WebSocket
142
+ indexContent += webSocketCode;
143
+ fs.writeFileSync(indexPath, indexContent, "utf8");
144
+ console.log("WebSocket code added to index.js successfully.");
145
+ }
146
+ // This function updates the .gitignore file
147
+ async function createUpdateGitignoreFile(baseDir, additions) {
148
+ const gitignorePath = path.join(baseDir, ".gitignore");
149
+ // Check if the .gitignore file exists, create if it doesn't
150
+ let gitignoreContent = "";
151
+ if (fs.existsSync(gitignorePath)) {
152
+ gitignoreContent = fs.readFileSync(gitignorePath, "utf8");
153
+ }
154
+ additions.forEach((addition) => {
155
+ if (!gitignoreContent.includes(addition)) {
156
+ gitignoreContent += `\n${addition}`;
157
+ }
158
+ });
159
+ // Ensure there's no leading newline if the file was just created
160
+ gitignoreContent = gitignoreContent.trimStart();
161
+ fs.writeFileSync(gitignorePath, gitignoreContent);
162
+ }
163
+ // Recursive copy function
164
+ function copyRecursiveSync(src, dest) {
165
+ const exists = fs.existsSync(src);
166
+ const stats = exists && fs.statSync(src);
167
+ const isDirectory = exists && stats && stats.isDirectory();
168
+ console.log("🚀 ~ copyRecursiveSync ~ isDirectory:", isDirectory);
169
+ if (isDirectory) {
170
+ if (fs.existsSync(dest)) {
171
+ fs.rmSync(dest, { recursive: true, force: true }); // Remove the directory if it exists
172
+ }
173
+ fs.mkdirSync(dest, { recursive: true }); // Recreate the directory
174
+ fs.readdirSync(src).forEach((childItemName) => {
175
+ copyRecursiveSync(path.join(src, childItemName), path.join(dest, childItemName));
176
+ });
177
+ }
178
+ else {
179
+ fs.copyFileSync(src, dest); // This line ensures files are overwritten
180
+ }
181
+ }
182
+ // Function to execute the recursive copy for entire directories
183
+ async function executeCopy(baseDir, directoriesToCopy) {
184
+ directoriesToCopy.forEach(({ srcDir, destDir }) => {
185
+ const sourcePath = path.join(__dirname, srcDir);
186
+ const destPath = path.join(baseDir, destDir);
187
+ copyRecursiveSync(sourcePath, destPath);
188
+ });
189
+ }
190
+ function modifyTailwindConfig(baseDir) {
191
+ const filePath = path.join(baseDir, "tailwind.config.js");
192
+ const newContent = [
193
+ "./src/app/**/*.{html,js,php}",
194
+ // Add more paths as needed
195
+ ];
196
+ let configData = fs.readFileSync(filePath, "utf8");
197
+ const contentArrayString = newContent
198
+ .map((item) => ` "${item}"`)
199
+ .join(",\n");
200
+ configData = configData.replace(/content: \[\],/g, `content: [\n${contentArrayString}\n],`);
201
+ fs.writeFileSync(filePath, configData, "utf8");
202
+ console.log(chalk.green("Tailwind configuration updated successfully."));
203
+ }
204
+ function modifyPostcssConfig(baseDir) {
205
+ const filePath = path.join(baseDir, "postcss.config.js");
206
+ const newContent = `export default {
207
+ plugins: {
208
+ tailwindcss: {},
209
+ autoprefixer: {},
210
+ cssnano: {},
211
+ },
212
+ };`;
213
+ fs.writeFileSync(filePath, newContent, "utf8");
214
+ console.log(chalk.green("postcss.config.js updated successfully."));
215
+ }
216
+ function modifyIndexPHP(baseDir, useTailwind) {
217
+ const indexPath = path.join(baseDir, "src", "app", "layout.php");
218
+ try {
219
+ let indexContent = fs.readFileSync(indexPath, "utf8");
220
+ 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>`;
221
+ // Tailwind CSS link or CDN script
222
+ const tailwindLink = useTailwind
223
+ ? ` <link href="<?php echo $baseUrl; ?>css/styles.css" rel="stylesheet"> ${stylesAndLinks}`
224
+ : ` <script src="https://cdn.tailwindcss.com"></script> ${stylesAndLinks}`;
225
+ // Insert before the closing </head> tag
226
+ indexContent = indexContent.replace("</head>", `${tailwindLink}\n</head>`);
227
+ fs.writeFileSync(indexPath, indexContent, "utf8");
228
+ console.log(chalk.green(`index.php modified successfully for ${useTailwind ? "local Tailwind CSS" : "Tailwind CSS CDN"}.`));
229
+ }
230
+ catch (error) {
231
+ console.error(chalk.red("Error modifying index.php:"), error);
232
+ }
233
+ }
234
+ // This function updates or creates the .env file
235
+ async function updateOrCreateEnvFile(baseDir, content) {
236
+ const envPath = path.join(baseDir, ".env");
237
+ let envContent = fs.existsSync(envPath)
238
+ ? fs.readFileSync(envPath, "utf8")
239
+ : "";
240
+ envContent += `${envContent !== "" ? "\n\n" : ""}${content}`;
241
+ fs.writeFileSync(envPath, envContent);
242
+ }
243
+ async function createDirectoryStructure(baseDir, answer, projectSettings) {
244
+ console.log("🚀 ~ baseDir:", baseDir);
245
+ console.log("🚀 ~ answer:", answer);
246
+ console.log("🚀 ~ projectSettings:", projectSettings);
247
+ const filesToCopy = [
248
+ { src: "/bootstrap.php", dest: "/bootstrap.php" },
249
+ { src: "/.htaccess", dest: "/.htaccess" },
250
+ { src: "/../composer.json", dest: "/composer.json" },
251
+ ];
252
+ // if (answer.websocket) {
253
+ // filesToCopy.push({
254
+ // src: "/../composer-websocket.lock",
255
+ // dest: "/composer.lock",
256
+ // });
257
+ // } else {
258
+ // filesToCopy.push({ src: "/../composer.lock", dest: "/composer.lock" });
259
+ // }
260
+ const directoriesToCopy = [
261
+ {
262
+ srcDir: "/settings",
263
+ destDir: "/settings",
264
+ },
265
+ {
266
+ srcDir: "/prisma",
267
+ destDir: "/prisma",
268
+ },
269
+ {
270
+ srcDir: "/src",
271
+ destDir: "/src",
272
+ },
273
+ {
274
+ srcDir: "/../vendor",
275
+ destDir: "/vendor",
276
+ },
277
+ ];
278
+ console.log("🚀 ~ directoriesToCopy:", directoriesToCopy);
279
+ filesToCopy.forEach(({ src, dest }) => {
280
+ const sourcePath = path.join(__dirname, src);
281
+ const destPath = path.join(baseDir, dest);
282
+ const code = fs.readFileSync(sourcePath, "utf8");
283
+ fs.writeFileSync(destPath, code, { flag: "w" });
284
+ });
285
+ await executeCopy(baseDir, directoriesToCopy);
286
+ await updatePackageJson(baseDir, projectSettings, answer);
287
+ await updateComposerJson(baseDir, answer);
288
+ await updateIndexJsForWebSocket(baseDir, answer);
289
+ if (answer.tailwindcss) {
290
+ modifyTailwindConfig(baseDir);
291
+ modifyIndexPHP(baseDir, true);
292
+ modifyPostcssConfig(baseDir);
293
+ }
294
+ else {
295
+ modifyIndexPHP(baseDir, false);
296
+ }
297
+ const envContent = `# PHPMailer
298
+ SMTP_HOST=
299
+ SMTP_USERNAME=
300
+ SMTP_PASSWORD=
301
+ SMTP_PORT=
302
+ SMTP_ENCRYPTION=ssl
303
+ MAIL_FROM=
304
+ MAIL_FROM_NAME=""`;
305
+ await updateOrCreateEnvFile(baseDir, envContent);
306
+ // Add vendor to .gitignore
307
+ await createUpdateGitignoreFile(baseDir, ["vendor"]);
308
+ }
309
+ async function getAnswer(predefinedAnswers = {}) {
310
+ var _a, _b, _c;
311
+ console.log("🚀 ~ predefinedAnswers:", predefinedAnswers);
312
+ const questions = [];
313
+ if (!predefinedAnswers.projectName) {
314
+ questions.push({
315
+ type: "text",
316
+ name: "projectName",
317
+ message: "What is your project named?",
318
+ initial: "my-app",
319
+ });
320
+ }
321
+ if (!predefinedAnswers.tailwindcss) {
322
+ questions.push({
323
+ type: "toggle",
324
+ name: "tailwindcss",
325
+ message: `Would you like to use ${chalk.blue("Tailwind CSS")}?`,
326
+ initial: true,
327
+ active: "Yes",
328
+ inactive: "No",
329
+ });
330
+ }
331
+ if (!predefinedAnswers.websocket) {
332
+ questions.push({
333
+ type: "toggle",
334
+ name: "websocket",
335
+ message: `Would you like to use ${chalk.blue("Websocket")}?`,
336
+ initial: true,
337
+ active: "Yes",
338
+ inactive: "No",
339
+ });
340
+ }
341
+ console.log("🚀 ~ questions:", questions);
342
+ const onCancel = () => {
343
+ return false;
344
+ };
345
+ try {
346
+ const response = await prompts(questions, { onCancel });
347
+ if (Object.keys(response).length === 0) {
348
+ return null;
349
+ }
350
+ return {
351
+ projectName: response.projectName
352
+ ? String(response.projectName).trim().replace(/ /g, "-")
353
+ : (_a = predefinedAnswers.projectName) !== null && _a !== void 0 ? _a : "my-app",
354
+ tailwindcss: (_b = response.tailwindcss) !== null && _b !== void 0 ? _b : predefinedAnswers.tailwindcss,
355
+ websocket: (_c = response.websocket) !== null && _c !== void 0 ? _c : predefinedAnswers.websocket,
356
+ };
357
+ }
358
+ catch (error) {
359
+ console.error(chalk.red("Prompt error:"), error);
360
+ return null;
361
+ }
362
+ }
363
+ /**
364
+ * Install dependencies in the specified directory.
365
+ * @param {string} baseDir - The base directory where to install the dependencies.
366
+ * @param {string[]} dependencies - The list of dependencies to install.
367
+ * @param {boolean} [isDev=false] - Whether to install the dependencies as devDependencies.
368
+ */
369
+ async function installDependencies(baseDir, dependencies, isDev = false) {
370
+ console.log("Initializing new Node.js project...");
371
+ // Initialize a package.json if it doesn't exist
372
+ if (!fs.existsSync(path.join(baseDir, "package.json")))
373
+ execSync("npm init -y", {
374
+ stdio: "inherit",
375
+ cwd: baseDir,
376
+ });
377
+ // Log the dependencies being installed
378
+ console.log(`${isDev ? "Installing development dependencies" : "Installing dependencies"}:`);
379
+ dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
380
+ // Prepare the npm install command with the appropriate flag for dev dependencies
381
+ const npmInstallCommand = `npm install ${isDev ? "--save-dev" : ""} ${dependencies.join(" ")}`;
382
+ // Execute the npm install command
383
+ execSync(npmInstallCommand, {
384
+ stdio: "inherit",
385
+ cwd: baseDir,
386
+ });
387
+ }
388
+ function fetchPackageVersion(packageName) {
389
+ return new Promise((resolve, reject) => {
390
+ https
391
+ .get(`https://registry.npmjs.org/${packageName}`, (res) => {
392
+ let data = "";
393
+ res.on("data", (chunk) => (data += chunk));
394
+ res.on("end", () => {
395
+ try {
396
+ const parsed = JSON.parse(data);
397
+ resolve(parsed["dist-tags"].latest);
398
+ }
399
+ catch (error) {
400
+ reject(new Error("Failed to parse JSON response"));
401
+ }
402
+ });
403
+ })
404
+ .on("error", (err) => reject(err));
405
+ });
406
+ }
3
407
  async function main() {
4
408
  try {
5
409
  const args = process.argv.slice(2);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-prisma-php-app",
3
- "version": "1.6.24",
3
+ "version": "1.6.27",
4
4
  "description": "Prisma-PHP: A Revolutionary Library Bridging PHP with Prisma ORM",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",