create-prisma-php-app 1.22.0 → 1.22.501

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