create-prisma-php-app 1.19.2 → 1.19.500

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