create-prisma-php-app 1.6.24 → 1.6.26

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