create-prisma-php-app 1.22.4 → 1.22.5

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.
@@ -636,12 +636,13 @@ register_shutdown_function(function () {
636
636
  }
637
637
  });
638
638
 
639
+ $_prismaPHPSettings = getPrismaSettings();
640
+ $_filesListRoutes = getFilesListRoutes();
641
+
639
642
  require_once SETTINGS_PATH . '/public-functions.php';
640
643
  require_once SETTINGS_PATH . '/request-methods.php';
641
644
  $_metadataFile = APP_PATH . '/metadata.php';
642
645
  $_metadataArray = file_exists($_metadataFile) ? require_once $_metadataFile : [];
643
- $_filesListRoutes = getFilesListRoutes();
644
- $_prismaPHPSettings = getPrismaSettings();
645
646
  $_fileToInclude = '';
646
647
 
647
648
  function authenticateUserToken()
package/dist/index.js CHANGED
@@ -1,2 +1,370 @@
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,"/"),o=t.replace(/\/\/+/g,"/");return{bsTarget:`${c}/`,bsPathRewrite:{"^/":`/${o.startsWith("/")?o.substring(1):o}/`}}}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");\nconst chokidar = require("chokidar");\nconst { execSync } = require("child_process");\n\nconst jsonData = fs.readFileSync("prisma-php.json", "utf8");\nconst config = JSON.parse(jsonData);\n\n// Watch for file changes (create, delete, save)\nconst watcher = chokidar.watch("src/**/*", {\n ignored: /(^|[\\/\\\\])\\../,\n persistent: true,\n usePolling: true,\n interval: 1000,\n});\n\nwatcher\n .on("add", async (path) => {\n execSync("node settings/files-list-config.js");\n })\n .on("change", async (path) => {\n execSync("node settings/files-list-config.js");\n })\n .on("unlink", async (path) => {\n execSync("node settings/files-list-config.js");\n });\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 watchOptions: {\n usePolling: true,\n interval: 1000,\n },\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 o=Object.assign({},t.scripts);o.browserSync=i,o.npmRunAll=c.length>0?`npm-run-all -p ${c.join(" ")}`:'echo "No additional scripts to run"',o.dev="node settings/start-dev.js",t.scripts=o,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.swaggerDocs&&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/**/*.{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"\n\n# APP ENV - Set your application environment - Default is "development" - Change this in production to "production"\nAPP_ENV=development';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,o,r,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!==(r=null!==(o=w.tailwindcss)&&void 0!==o?o:e.tailwindcss)&&void 0!==r&&r,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,o,r,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!==(o=null==d?void 0:d.docker)&&void 0!==o&&o,isUpdate:!0,excludeFiles:null!==(r=g.excludeFiles)&&void 0!==r?r:[],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});["swagger-setup.js"].forEach((e=>{const s=path.join(y,"settings",e);fs.existsSync(s)&&fs.unlinkSync(s)})),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 S=y.replace(/\\/g,"\\"),b=bsConfigUrls(S),j=d.prisma?"src/Lib/Prisma/Classes":"",v={projectName:d.projectName,projectRootPath:S,phpEnvironment:"XAMPP",phpRootPathExe:"C:\\xampp\\php\\php.exe",phpGenerateClassPath:j,bsTarget:b.bsTarget,bsPathRewrite:b.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";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 t=e.substring(0,s+"\\htdocs\\".length).replace(/\\/g,"\\\\"),n=e.replace(new RegExp(`^${t}`),"").replace(/\\/g,"/");let i=`http://localhost/${n}`;i=i.endsWith("/")?i.slice(0,-1):i;const c=i.replace(/(?<!:)(\/\/+)/g,"/"),o=n.replace(/\/\/+/g,"/");return{bsTarget:`${c}/`,bsPathRewrite:{"^/":`/${o.startsWith("/")?o.substring(1):o}/`}}}async function updatePackageJson(e,s){const t=path.join(e,"package.json");if(checkExcludeFiles(t))return;const n=JSON.parse(fs.readFileSync(t,"utf8"));n.scripts=Object.assign(Object.assign({},n.scripts),{projectName:"node settings/project-name.js"});let i=[];s.tailwindcss&&(n.scripts=Object.assign(Object.assign({},n.scripts),{tailwind:"postcss src/app/css/tailwind.css -o src/app/css/styles.css --watch"}),i.push("tailwind")),s.websocket&&(n.scripts=Object.assign(Object.assign({},n.scripts),{websocket:"node settings/restart-websocket.js"}),i.push("websocket")),s.docker&&(n.scripts=Object.assign(Object.assign({},n.scripts),{docker:"docker-compose up"}),i.push("docker")),s.swaggerDocs&&(n.scripts=Object.assign(Object.assign({},n.scripts),{"create-swagger-docs":"node settings/swagger-config.js"}),i.push("create-swagger-docs"));let c=Object.assign({},n.scripts);c.browserSync="node settings/bs-config.js",c.dev=`npm-run-all -p projectName browserSync ${i.join(" ")}`,n.scripts=c,n.type="module",s.prisma&&(n.prisma={seed:"node prisma/seed.js"}),fs.writeFileSync(t,JSON.stringify(n,null,2))}async function updateComposerJson(e,s){const t=path.join(e,"composer.json");if(checkExcludeFiles(t))return;let n;if(fs.existsSync(t)){{const e=fs.readFileSync(t,"utf8");n=JSON.parse(e)}s.websocket&&(n.require=Object.assign(Object.assign({},n.require),{"cboden/ratchet":"^0.4.4"})),s.prisma&&(n.require=Object.assign(Object.assign({},n.require),{"ramsey/uuid":"5.x-dev","hidehalo/nanoid-php":"1.x-dev"})),fs.writeFileSync(t,JSON.stringify(n,null,2))}}async function updateIndexJsForWebSocket(e,s){if(!s.websocket)return;const t=path.join(e,"src","app","js","index.js");if(checkExcludeFiles(t))return;let n=fs.readFileSync(t,"utf8");n+='\n// WebSocket initialization\nconst ws = new WebSocket("ws://localhost:8080");\n',fs.writeFileSync(t,n,"utf8")}async function createUpdateGitignoreFile(e,s){const t=path.join(e,".gitignore");if(checkExcludeFiles(t))return;let n="";s.forEach((e=>{n.includes(e)||(n+=`\n${e}`)})),n=n.trimStart(),fs.writeFileSync(t,n)}function copyRecursiveSync(e,s,t){var n;const i=fs.existsSync(e),c=i&&fs.statSync(e);if(i&&c&&c.isDirectory()){const i=s.toLowerCase();if(!t.websocket&&i.includes("src\\lib\\websocket"))return;if(!t.prisma&&i.includes("src\\lib\\prisma"))return;if(t.backendOnly&&i.includes("src\\app\\js")||t.backendOnly&&i.includes("src\\app\\css"))return;if(!t.swaggerDocs&&i.includes("src\\app\\swagger-docs"))return;const c=s.replace(/\\/g,"/");if(null===(n=null==updateAnswer?void 0:updateAnswer.excludeFilePath)||void 0===n?void 0:n.includes(c))return;fs.existsSync(s)||fs.mkdirSync(s,{recursive:!0}),fs.readdirSync(e).forEach((n=>{copyRecursiveSync(path.join(e,n),path.join(s,n),t)}))}else{if(checkExcludeFiles(s))return;if(!t.tailwindcss&&(s.includes("tailwind.css")||s.includes("styles.css")))return;if(!t.websocket&&(s.includes("restart-websocket.cjs")||s.includes("restart-websocket.bat")))return;if(!t.docker&&dockerFiles.some((e=>s.includes(e))))return;if(t.backendOnly&&nonBackendFiles.some((e=>s.includes(e))))return;if(!t.backendOnly&&s.includes("route.php"))return;if(!t.swaggerDocs&&s.includes("swagger-config.js"))return;fs.copyFileSync(e,s,0)}}async function executeCopy(e,s,t){s.forEach((({src:s,dest:n})=>{copyRecursiveSync(path.join(__dirname,s),path.join(e,n),t)}))}function createOrUpdateTailwindConfig(e){const s=path.join(e,"tailwind.config.js");if(checkExcludeFiles(s))return;let t=fs.readFileSync(s,"utf8");const n=["./src/**/*.{html,js,php}"].map((e=>` "${e}"`)).join(",\n");t=t.replace(/content: \[\],/g,`content: [\n${n}\n],`),fs.writeFileSync(s,t,{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 t=path.join(e,"src","app","layout.php");if(!checkExcludeFiles(t))try{let e=fs.readFileSync(t,"utf8"),n="";s.backendOnly||(n='\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"> ${n}`:` <script src="https://cdn.tailwindcss.com"><\/script> ${n}`);const c=i.length>0?"\n":"";e=e.replace("</head>",`${i}${c} \x3c!-- Dynamic Head --\x3e\n <?= implode("\\n", $mainLayoutHead); ?>\n</head>`),fs.writeFileSync(t,e,{flag:"w"})}catch(e){}}async function createOrUpdateEnvFile(e,s){const t=path.join(e,".env");checkExcludeFiles(t)||fs.writeFileSync(t,s,{flag:"w"})}function checkExcludeFiles(e){var s,t;return!!(null==updateAnswer?void 0:updateAnswer.isUpdate)&&(null!==(t=null===(s=null==updateAnswer?void 0:updateAnswer.excludeFilePath)||void 0===s?void 0:s.includes(e.replace(/\\/g,"/")))&&void 0!==t&&t)}async function createDirectoryStructure(e,s){const t=[{src:"/bootstrap.php",dest:"/bootstrap.php"},{src:"/.htaccess",dest:"/.htaccess"},{src:"/../composer.json",dest:"/composer.json"},{src:"/tsconfig.json",dest:"/tsconfig.json"}];s.tailwindcss&&t.push({src:"/postcss.config.js",dest:"/postcss.config.js"},{src:"/tailwind.config.js",dest:"/tailwind.config.js"});const n=[{src:"/settings",dest:"/settings"},{src:"/src",dest:"/src"}];s.backendOnly&&s.swaggerDocs&&n.push({src:"/swagger-docs-layout.php",dest:"/src/app/layout.php"}),s.prisma&&n.push({src:"/prisma",dest:"/prisma"}),s.docker&&n.push({src:"/.dockerignore",dest:"/.dockerignore"},{src:"/docker-compose.yml",dest:"/docker-compose.yml"},{src:"/Dockerfile",dest:"/Dockerfile"},{src:"/apache.conf",dest:"/apache.conf"}),t.forEach((({src:s,dest:t})=>{const n=path.join(__dirname,s),i=path.join(e,t);if(checkExcludeFiles(i))return;const c=fs.readFileSync(n,"utf8");fs.writeFileSync(i,c,{flag:"w"})})),await executeCopy(e,n,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# APP TIMEZONE - Set your application timezone - Default is "UTC"\nAPP_TIMEZONE="UTC"\n\n# APP ENV - Set your application environment - Default is "development" - Change this in production to "production"\nAPP_ENV=development';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,t,n,i,c,o,a,r,l,p,d,u,g;const m=[];e.projectName||m.push({type:"text",name:"projectName",message:"What is your project named?",initial:"my-app"}),e.backendOnly||m.push({type:"toggle",name:"backendOnly",message:"Would you like to create a backend-only project?",initial:!1,active:"Yes",inactive:"No"});const f=()=>{process.exit(0)},h=await prompts(m,{onCancel:f}),y=[];h.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:f});return{projectName:h.projectName?String(h.projectName).trim().replace(/ /g,"-"):null!==(s=e.projectName)&&void 0!==s?s:"my-app",backendOnly:null!==(n=null!==(t=h.backendOnly)&&void 0!==t?t:e.backendOnly)&&void 0!==n&&n,swaggerDocs:null!==(c=null!==(i=w.swaggerDocs)&&void 0!==i?i:e.swaggerDocs)&&void 0!==c&&c,tailwindcss:null!==(a=null!==(o=w.tailwindcss)&&void 0!==o?o:e.tailwindcss)&&void 0!==a&&a,websocket:null!==(l=null!==(r=w.websocket)&&void 0!==r?r: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!==(g=null!==(u=w.docker)&&void 0!==u?u:e.docker)&&void 0!==g&&g}}async function installDependencies(e,s,t=!1){fs.existsSync(path.join(e,"package.json"))||execSync("npm init -y",{stdio:"inherit",cwd:e}),s.forEach((e=>{}));const n=`npm install ${t?"--save-dev":""} ${s.join(" ")}`;execSync(n,{stdio:"inherit",cwd:e})}async function uninstallDependencies(e,s,t=!1){s.forEach((e=>{}));const n=`npm uninstall ${t?"--save-dev":"--save"} ${s.join(" ")}`;execSync(n,{stdio:"inherit",cwd:e})}function fetchPackageVersion(e){return new Promise(((s,t)=>{https.get(`https://registry.npmjs.org/${e}`,(e=>{let n="";e.on("data",(e=>n+=e)),e.on("end",(()=>{try{const e=JSON.parse(n);s(e["dist-tags"].latest)}catch(e){t(new Error("Failed to parse JSON response"))}}))})).on("error",(e=>t(e)))}))}const readJsonFile=e=>{const s=fs.readFileSync(e,"utf8");return JSON.parse(s)};function compareVersions(e,s){const t=e.split(".").map(Number),n=s.split(".").map(Number);for(let e=0;e<t.length;e++){if(t[e]>n[e])return 1;if(t[e]<n[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}}
3
+ async function main() {
4
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
5
+ try {
6
+ const args = process.argv.slice(2);
7
+ let projectName = args[0];
8
+ let answer = null;
9
+ if (projectName) {
10
+ let useBackendOnly = args.includes("--backend-only");
11
+ let useSwaggerDocs = args.includes("--swagger-docs");
12
+ let useTailwind = args.includes("--tailwindcss");
13
+ let useWebsocket = args.includes("--websocket");
14
+ let usePrisma = args.includes("--prisma");
15
+ let useDocker = args.includes("--docker");
16
+ const predefinedAnswers = {
17
+ projectName,
18
+ backendOnly: useBackendOnly,
19
+ swaggerDocs: useSwaggerDocs,
20
+ tailwindcss: useTailwind,
21
+ websocket: useWebsocket,
22
+ prisma: usePrisma,
23
+ docker: useDocker,
24
+ };
25
+ answer = await getAnswer(predefinedAnswers);
26
+ if (answer === null) {
27
+ console.log(chalk.red("Installation cancelled."));
28
+ return;
29
+ }
30
+ const currentDir = process.cwd();
31
+ const configPath = path.join(currentDir, "prisma-php.json");
32
+ const localSettings = readJsonFile(configPath);
33
+ let excludeFiles = [];
34
+ (_a = localSettings.excludeFiles) === null || _a === void 0
35
+ ? void 0
36
+ : _a.map((file) => {
37
+ const filePath = path.join(currentDir, file);
38
+ if (fs.existsSync(filePath))
39
+ excludeFiles.push(filePath.replace(/\\/g, "/"));
40
+ });
41
+ updateAnswer = {
42
+ projectName,
43
+ backendOnly:
44
+ (_b =
45
+ answer === null || answer === void 0
46
+ ? void 0
47
+ : answer.backendOnly) !== null && _b !== void 0
48
+ ? _b
49
+ : false,
50
+ swaggerDocs:
51
+ (_c =
52
+ answer === null || answer === void 0
53
+ ? void 0
54
+ : answer.swaggerDocs) !== null && _c !== void 0
55
+ ? _c
56
+ : false,
57
+ tailwindcss:
58
+ (_d =
59
+ answer === null || answer === void 0
60
+ ? void 0
61
+ : answer.tailwindcss) !== null && _d !== void 0
62
+ ? _d
63
+ : false,
64
+ websocket:
65
+ (_e =
66
+ answer === null || answer === void 0
67
+ ? void 0
68
+ : answer.websocket) !== null && _e !== void 0
69
+ ? _e
70
+ : false,
71
+ prisma:
72
+ (_f =
73
+ answer === null || answer === void 0 ? void 0 : answer.prisma) !==
74
+ null && _f !== void 0
75
+ ? _f
76
+ : false,
77
+ docker:
78
+ (_g =
79
+ answer === null || answer === void 0 ? void 0 : answer.docker) !==
80
+ null && _g !== void 0
81
+ ? _g
82
+ : false,
83
+ isUpdate: true,
84
+ excludeFiles:
85
+ (_h = localSettings.excludeFiles) !== null && _h !== void 0 ? _h : [],
86
+ excludeFilePath:
87
+ excludeFiles !== null && excludeFiles !== void 0 ? excludeFiles : [],
88
+ filePath: currentDir,
89
+ };
90
+ } else {
91
+ answer = await getAnswer();
92
+ }
93
+ if (answer === null) {
94
+ console.warn(chalk.red("Installation cancelled."));
95
+ return;
96
+ }
97
+ const latestVersionOfCreatePrismaPhpApp = await fetchPackageVersion(
98
+ "create-prisma-php-app"
99
+ );
100
+ const isCreatePrismaPhpAppInstalled = getInstalledPackageVersion(
101
+ "create-prisma-php-app"
102
+ );
103
+ if (isCreatePrismaPhpAppInstalled) {
104
+ if (
105
+ compareVersions(
106
+ isCreatePrismaPhpAppInstalled,
107
+ latestVersionOfCreatePrismaPhpApp
108
+ ) === -1
109
+ ) {
110
+ execSync(`npm uninstall -g create-prisma-php-app`, {
111
+ stdio: "inherit",
112
+ });
113
+ execSync(`npm install -g create-prisma-php-app`, {
114
+ stdio: "inherit",
115
+ });
116
+ }
117
+ } else {
118
+ execSync("npm install -g create-prisma-php-app", { stdio: "inherit" });
119
+ }
120
+ // Create the project directory
121
+ if (!projectName) fs.mkdirSync(answer.projectName);
122
+ const currentDir = process.cwd();
123
+ let projectPath = projectName
124
+ ? currentDir
125
+ : path.join(currentDir, answer.projectName);
126
+ if (!projectName) process.chdir(answer.projectName);
127
+ const dependencies = [
128
+ "typescript",
129
+ "@types/node",
130
+ "ts-node",
131
+ "http-proxy-middleware",
132
+ "chalk",
133
+ "npm-run-all",
134
+ "browser-sync",
135
+ ];
136
+ if (answer.swaggerDocs) {
137
+ dependencies.push("swagger-jsdoc");
138
+ }
139
+ if (answer.tailwindcss) {
140
+ dependencies.push(
141
+ "tailwindcss",
142
+ "autoprefixer",
143
+ "postcss",
144
+ "postcss-cli",
145
+ "cssnano"
146
+ );
147
+ }
148
+ if (answer.websocket) {
149
+ dependencies.push("chokidar-cli");
150
+ }
151
+ if (answer.prisma) {
152
+ dependencies.push("prisma", "@prisma/client");
153
+ }
154
+ await installDependencies(projectPath, dependencies, true);
155
+ if (!projectName) {
156
+ execSync(`npx tsc --init`, { stdio: "inherit" });
157
+ }
158
+ if (answer.tailwindcss)
159
+ execSync(`npx tailwindcss init -p`, { stdio: "inherit" });
160
+ if (answer.prisma) {
161
+ if (!fs.existsSync(path.join(projectPath, "prisma")))
162
+ execSync(`npx prisma init`, { stdio: "inherit" });
163
+ }
164
+ await createDirectoryStructure(projectPath, answer);
165
+ const publicDirPath = path.join(projectPath, "public");
166
+ if (!fs.existsSync(publicDirPath)) {
167
+ fs.mkdirSync(publicDirPath);
168
+ }
169
+ if (answer.swaggerDocs) {
170
+ const swaggerDocsPath = path.join(
171
+ projectPath,
172
+ "src",
173
+ "app",
174
+ "swagger-docs"
175
+ );
176
+ // Check if the directory exists, if not, create it
177
+ if (!fs.existsSync(swaggerDocsPath)) {
178
+ fs.mkdirSync(swaggerDocsPath, { recursive: true }); // 'recursive: true' creates parent directories if they don't exist
179
+ }
180
+ // Clone the Git repository into the swagger-docs directory
181
+ execSync(
182
+ `git clone https://github.com/TheSteelNinjaCode/prisma-php-swagger-docs.git ${swaggerDocsPath}`,
183
+ { stdio: "inherit" }
184
+ );
185
+ }
186
+ if (
187
+ updateAnswer === null || updateAnswer === void 0
188
+ ? void 0
189
+ : updateAnswer.isUpdate
190
+ ) {
191
+ const updateUninstallDependencies = [];
192
+ if (updateAnswer.backendOnly) {
193
+ nonBackendFiles.forEach((file) => {
194
+ const filePath = path.join(projectPath, "src", "app", file);
195
+ if (fs.existsSync(filePath)) {
196
+ fs.unlinkSync(filePath); // Delete each file if it exists
197
+ console.log(`${file} was deleted successfully.`);
198
+ } else {
199
+ console.log(`${file} does not exist.`);
200
+ }
201
+ });
202
+ const backendOnlyFolders = ["js", "css"];
203
+ backendOnlyFolders.forEach((folder) => {
204
+ const folderPath = path.join(projectPath, "src", "app", folder);
205
+ if (fs.existsSync(folderPath)) {
206
+ fs.rmSync(folderPath, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
207
+ console.log(`${folder} was deleted successfully.`);
208
+ } else {
209
+ console.log(`${folder} does not exist.`);
210
+ }
211
+ });
212
+ }
213
+ if (!updateAnswer.swaggerDocs) {
214
+ const swaggerDocsFolder = path.join(
215
+ projectPath,
216
+ "src",
217
+ "app",
218
+ "swagger-docs"
219
+ );
220
+ if (fs.existsSync(swaggerDocsFolder)) {
221
+ fs.rmSync(swaggerDocsFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
222
+ console.log(`swagger-docs was deleted successfully.`);
223
+ }
224
+ const swaggerFiles = ["swagger-setup.js"];
225
+ swaggerFiles.forEach((file) => {
226
+ const filePath = path.join(projectPath, "settings", file);
227
+ if (fs.existsSync(filePath)) {
228
+ fs.unlinkSync(filePath); // Delete each file if it exists
229
+ console.log(`${file} was deleted successfully.`);
230
+ } else {
231
+ console.log(`${file} does not exist.`);
232
+ }
233
+ });
234
+ updateUninstallDependencies.push("swagger-jsdoc");
235
+ }
236
+ if (!updateAnswer.tailwindcss) {
237
+ const tailwindFiles = ["postcss.config.js", "tailwind.config.js"];
238
+ tailwindFiles.forEach((file) => {
239
+ const filePath = path.join(projectPath, file);
240
+ if (fs.existsSync(filePath)) {
241
+ fs.unlinkSync(filePath); // Delete each file if it exists
242
+ console.log(`${file} was deleted successfully.`);
243
+ } else {
244
+ console.log(`${file} does not exist.`);
245
+ }
246
+ });
247
+ updateUninstallDependencies.push(
248
+ "tailwindcss",
249
+ "autoprefixer",
250
+ "postcss",
251
+ "postcss-cli",
252
+ "cssnano"
253
+ );
254
+ }
255
+ if (!updateAnswer.websocket) {
256
+ const websocketFiles = [
257
+ "restart-websocket.js",
258
+ "restart-websocket.bat",
259
+ ];
260
+ websocketFiles.forEach((file) => {
261
+ const filePath = path.join(projectPath, "settings", file);
262
+ if (fs.existsSync(filePath)) {
263
+ fs.unlinkSync(filePath); // Delete each file if it exists
264
+ console.log(`${file} was deleted successfully.`);
265
+ } else {
266
+ console.log(`${file} does not exist.`);
267
+ }
268
+ });
269
+ const websocketFolder = path.join(
270
+ projectPath,
271
+ "src",
272
+ "Lib",
273
+ "Websocket"
274
+ );
275
+ if (fs.existsSync(websocketFolder)) {
276
+ fs.rmSync(websocketFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
277
+ console.log(`Websocket folder was deleted successfully.`);
278
+ }
279
+ updateUninstallDependencies.push("chokidar-cli");
280
+ }
281
+ if (!updateAnswer.prisma) {
282
+ updateUninstallDependencies.push("prisma", "@prisma/client");
283
+ }
284
+ if (!updateAnswer.docker) {
285
+ const dockerFiles = [
286
+ ".dockerignore",
287
+ "docker-compose.yml",
288
+ "Dockerfile",
289
+ "apache.conf",
290
+ ];
291
+ dockerFiles.forEach((file) => {
292
+ const filePath = path.join(projectPath, file);
293
+ if (fs.existsSync(filePath)) {
294
+ fs.unlinkSync(filePath); // Delete each file if it exists
295
+ console.log(`${file} was deleted successfully.`);
296
+ } else {
297
+ console.log(`${file} does not exist.`);
298
+ }
299
+ });
300
+ }
301
+ if (updateUninstallDependencies.length > 0) {
302
+ await uninstallDependencies(
303
+ projectPath,
304
+ updateUninstallDependencies,
305
+ true
306
+ );
307
+ }
308
+ }
309
+ const projectPathModified = projectPath.replace(/\\/g, "\\");
310
+ const bsConfig = bsConfigUrls(projectPathModified);
311
+ const phpGenerateClassPath = answer.prisma ? "src/Lib/Prisma/Classes" : "";
312
+ const prismaPhpConfig = {
313
+ projectName: answer.projectName,
314
+ projectRootPath: projectPathModified,
315
+ phpEnvironment: "XAMPP",
316
+ phpRootPathExe: "C:\\xampp\\php\\php.exe",
317
+ phpGenerateClassPath,
318
+ bsTarget: bsConfig.bsTarget,
319
+ bsPathRewrite: bsConfig.bsPathRewrite,
320
+ backendOnly: answer.backendOnly,
321
+ swaggerDocs: answer.swaggerDocs,
322
+ tailwindcss: answer.tailwindcss,
323
+ websocket: answer.websocket,
324
+ prisma: answer.prisma,
325
+ docker: answer.docker,
326
+ ngrok: false,
327
+ version: latestVersionOfCreatePrismaPhpApp,
328
+ excludeFiles:
329
+ (_j =
330
+ updateAnswer === null || updateAnswer === void 0
331
+ ? void 0
332
+ : updateAnswer.excludeFiles) !== null && _j !== void 0
333
+ ? _j
334
+ : [],
335
+ };
336
+ fs.writeFileSync(
337
+ path.join(projectPath, "prisma-php.json"),
338
+ JSON.stringify(prismaPhpConfig, null, 2),
339
+ { flag: "w" }
340
+ );
341
+ if (
342
+ updateAnswer === null || updateAnswer === void 0
343
+ ? void 0
344
+ : updateAnswer.isUpdate
345
+ ) {
346
+ execSync(
347
+ `C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar update`,
348
+ {
349
+ stdio: "inherit",
350
+ }
351
+ );
352
+ } else {
353
+ execSync(
354
+ `C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar install`,
355
+ {
356
+ stdio: "inherit",
357
+ }
358
+ );
359
+ }
360
+ console.log(
361
+ `${chalk.green("Success!")} Prisma PHP project successfully created in ${
362
+ answer.projectName
363
+ }!`
364
+ );
365
+ } catch (error) {
366
+ console.error("Error while creating the project:", error);
367
+ process.exit(1);
368
+ }
369
+ }
370
+ main();
@@ -0,0 +1,75 @@
1
+ import { createProxyMiddleware } from "http-proxy-middleware";
2
+ import { readFileSync, writeFileSync } from "fs";
3
+ import chokidar from "chokidar";
4
+ import browserSync from "browser-sync";
5
+ // import prismaPhpConfig from "../prisma-php.json" assert { type: "json" };
6
+ import { generateFileListJson } from "./files-list.js";
7
+ import { join, dirname } from "path";
8
+ import { fileURLToPath } from "url";
9
+ const __filename = fileURLToPath(import.meta.url);
10
+ const __dirname = dirname(__filename);
11
+ const bs = browserSync.create();
12
+ const prismaPhpConfig = JSON.parse(readFileSync(join(__dirname, "..", "prisma-php.json")).toString("utf-8"));
13
+ // Watch for file changes (create, delete, save)
14
+ const watcher = chokidar.watch("src/app/**/*", {
15
+ ignored: /(^|[\/\\])\../, // Ignore dotfiles
16
+ persistent: true,
17
+ usePolling: true,
18
+ interval: 1000,
19
+ });
20
+ // Perform specific actions for file events
21
+ watcher
22
+ .on("add", (path) => {
23
+ generateFileListJson();
24
+ })
25
+ .on("change", (path) => {
26
+ generateFileListJson();
27
+ })
28
+ .on("unlink", (path) => {
29
+ generateFileListJson();
30
+ });
31
+ // BrowserSync initialization
32
+ bs.init({
33
+ proxy: "http://localhost:3000",
34
+ middleware: [
35
+ (req, res, next) => {
36
+ res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
37
+ res.setHeader("Pragma", "no-cache");
38
+ res.setHeader("Expires", "0");
39
+ next();
40
+ },
41
+ createProxyMiddleware({
42
+ target: prismaPhpConfig.bsTarget,
43
+ changeOrigin: true,
44
+ pathRewrite: prismaPhpConfig.ngrok ? {} : prismaPhpConfig.bsPathRewrite,
45
+ }),
46
+ ],
47
+ files: "src/**/*.*",
48
+ notify: false,
49
+ open: false,
50
+ ghostMode: false,
51
+ codeSync: true, // Disable synchronization of code changes across clients
52
+ watchOptions: {
53
+ usePolling: true,
54
+ interval: 1000,
55
+ },
56
+ }, (err, bsInstance) => {
57
+ if (err) {
58
+ console.error("BrowserSync failed to start:", err);
59
+ return;
60
+ }
61
+ // Retrieve the active URLs from the BrowserSync instance
62
+ const options = bsInstance.getOption("urls");
63
+ const localUrl = options.get("local");
64
+ const externalUrl = options.get("external");
65
+ const uiUrl = options.get("ui");
66
+ const uiExternalUrl = options.get("ui-external");
67
+ // Construct the URLs dynamically
68
+ const urls = {
69
+ local: localUrl,
70
+ external: externalUrl,
71
+ ui: uiUrl,
72
+ uiExternal: uiExternalUrl,
73
+ };
74
+ writeFileSync(join(__dirname, "bs-config.json"), JSON.stringify(urls, null, 2));
75
+ });
@@ -0,0 +1,43 @@
1
+ import fs from "fs";
2
+ import { join, sep, relative, dirname } from "path";
3
+ import { fileURLToPath } from "url";
4
+ const __filename = fileURLToPath(import.meta.url);
5
+ const __dirname = dirname(__filename);
6
+ // Define the directory and JSON file paths correctly
7
+ const dirPath = "src/app"; // Directory path
8
+ const jsonFilePath = "settings/files-list.json"; // Path to the JSON file
9
+ // Function to get all files in the directory
10
+ const getAllFiles = (dirPath) => {
11
+ const files = [];
12
+ // Check if directory exists before reading
13
+ if (!fs.existsSync(dirPath)) {
14
+ console.error(`Directory not found: ${dirPath}`);
15
+ return files; // Return an empty array if the directory doesn't exist
16
+ }
17
+ const items = fs.readdirSync(dirPath);
18
+ items.forEach((item) => {
19
+ const fullPath = join(dirPath, item);
20
+ if (fs.statSync(fullPath).isDirectory()) {
21
+ files.push(...getAllFiles(fullPath)); // Recursive call for subdirectories
22
+ }
23
+ else {
24
+ // Generate the relative path and ensure it starts with ./src
25
+ const relativePath = `.${sep}${relative(join(__dirname, ".."), fullPath)}`;
26
+ // Replace only the root backslashes with forward slashes and leave inner ones
27
+ files.push(relativePath.replace(/\\/g, "/").replace(/^\.\.\//, ""));
28
+ }
29
+ });
30
+ return files;
31
+ };
32
+ // Function to generate the files-list.json
33
+ export const generateFileListJson = () => {
34
+ const files = getAllFiles(dirPath);
35
+ // If files exist, generate JSON file
36
+ if (files.length > 0) {
37
+ fs.writeFileSync(jsonFilePath, JSON.stringify(files, null, 2));
38
+ // console.log(`File list has been saved to: ${jsonFilePath}`);
39
+ }
40
+ else {
41
+ console.error("No files found to save in the JSON file.");
42
+ }
43
+ };
@@ -0,0 +1,60 @@
1
+ import fs, { readFileSync } from "fs";
2
+ import { join, basename, dirname, normalize, sep } from "path";
3
+ import { fileURLToPath } from "url";
4
+ // import prismaPhpConfig from "../prisma-php.json" assert { type: "json" };
5
+ const __filename = fileURLToPath(import.meta.url);
6
+ const __dirname = dirname(__filename);
7
+ const prismaPhpConfig = JSON.parse(readFileSync(join(__dirname, "..", "prisma-php.json")).toString("utf-8"));
8
+ const newProjectName = basename(join(__dirname, ".."));
9
+ // Function to update the project name and paths in the JSON config
10
+ function updateProjectNameInConfig(filePath, newProjectName) {
11
+ const filePathDir = dirname(filePath);
12
+ // Update the projectName directly in the imported config
13
+ prismaPhpConfig.projectName = newProjectName;
14
+ // Update other paths
15
+ prismaPhpConfig.projectRootPath = filePathDir;
16
+ const targetPath = getTargetPath(filePathDir, prismaPhpConfig.phpEnvironment);
17
+ prismaPhpConfig.bsTarget = `http://localhost${targetPath}`;
18
+ prismaPhpConfig.bsPathRewrite["^/"] = targetPath;
19
+ // Save the updated config back to the JSON file
20
+ fs.writeFile(filePath, JSON.stringify(prismaPhpConfig, null, 2), "utf8", (err) => {
21
+ if (err) {
22
+ console.error("Error writing the updated JSON file:", err);
23
+ return;
24
+ }
25
+ console.log("The project name, PHP path, and other paths have been updated successfully.");
26
+ });
27
+ }
28
+ // Function to determine the target path for browser-sync
29
+ function getTargetPath(fullPath, environment) {
30
+ const normalizedPath = normalize(fullPath);
31
+ const webDirectories = {
32
+ XAMPP: join("htdocs"),
33
+ WAMP: join("www"),
34
+ MAMP: join("htdocs"),
35
+ LAMP: join("var", "www", "html"),
36
+ LEMP: join("usr", "share", "nginx", "html"),
37
+ AMPPS: join("www"),
38
+ UniformServer: join("www"),
39
+ EasyPHP: join("data", "localweb"),
40
+ };
41
+ const webDir = webDirectories[environment.toUpperCase()];
42
+ if (!webDir) {
43
+ throw new Error(`Unsupported environment: ${environment}`);
44
+ }
45
+ const indexOfWebDir = normalizedPath
46
+ .toLowerCase()
47
+ .indexOf(normalize(webDir).toLowerCase());
48
+ if (indexOfWebDir === -1) {
49
+ throw new Error(`Web directory not found in path: ${webDir}`);
50
+ }
51
+ const startIndex = indexOfWebDir + webDir.length;
52
+ const subPath = normalizedPath.slice(startIndex);
53
+ const safeSeparatorRegex = new RegExp(sep.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"), "g");
54
+ const finalPath = subPath.replace(safeSeparatorRegex, "/") + "/";
55
+ return finalPath;
56
+ }
57
+ // Path to your JSON configuration file (for saving changes)
58
+ const configFilePath = join(__dirname, "..", "prisma-php.json");
59
+ // Run the function with your config file path and the new project name
60
+ updateProjectNameInConfig(configFilePath, newProjectName);
@@ -86,7 +86,7 @@ $scriptName = dirname($_SERVER['SCRIPT_NAME']);
86
86
  /**
87
87
  * @var string $baseUrl - The base URL of the request.
88
88
  */
89
- $baseUrl = $protocol . $domainName . "$scriptName/src/app";
89
+ $baseUrl = $_prismaPHPSettings['ngrok'] ? 'src/app' : $protocol . $domainName . "$scriptName/src/app";
90
90
  /**
91
91
  * @var string $documentUrl - The document URL of the request.
92
92
  */
@@ -0,0 +1,40 @@
1
+ import { spawn } from "child_process";
2
+ import path, { dirname } from "path";
3
+ import chokidar from "chokidar";
4
+ import { fileURLToPath } from "url";
5
+ const __filename = fileURLToPath(import.meta.url);
6
+ const __dirname = dirname(__filename);
7
+ // Define paths
8
+ const phpPath = "php"; // Adjust if necessary to include the full path to PHP
9
+ const serverScriptPath = path.join(__dirname, "..", "src", "Lib", "Websocket", "server.php");
10
+ // Hold the server process
11
+ let serverProcess = null;
12
+ const restartServer = () => {
13
+ // If a server process already exists, kill it
14
+ if (serverProcess) {
15
+ console.log("Stopping WebSocket server...");
16
+ serverProcess.kill("SIGINT"); // Adjust the signal as necessary for your environment
17
+ serverProcess = null;
18
+ }
19
+ // Start a new WebSocket server process
20
+ console.log("Starting WebSocket server...");
21
+ serverProcess = spawn(phpPath, [serverScriptPath]);
22
+ serverProcess.stdout?.on("data", (data) => {
23
+ console.log(`WebSocket Server: ${data.toString()}`);
24
+ });
25
+ serverProcess.stderr?.on("data", (data) => {
26
+ console.error(`WebSocket Server Error: ${data.toString()}`);
27
+ });
28
+ serverProcess.on("close", (code) => {
29
+ console.log(`WebSocket server process exited with code ${code}`);
30
+ });
31
+ };
32
+ // Initial start
33
+ restartServer();
34
+ // Watch for changes and restart the server
35
+ chokidar
36
+ .watch(path.join(__dirname, "..", "src", "Lib", "Websocket", "**", "*"))
37
+ .on("change", (path) => {
38
+ console.log(`File changed: ${path}`);
39
+ restartServer();
40
+ });
@@ -0,0 +1,75 @@
1
+ import swaggerJsdoc from "swagger-jsdoc";
2
+ import { writeFileSync, readFileSync, existsSync } from "fs";
3
+ import { fileURLToPath } from "url";
4
+ import { join, dirname } from "path";
5
+ import chalk from "chalk";
6
+ const __filename = fileURLToPath(import.meta.url);
7
+ const __dirname = dirname(__filename);
8
+ // Define the output path for the swagger.json file
9
+ const outputPath = join(__dirname, "../src/app/swagger-docs/apis/pphp-swagger.json");
10
+ const bsConnectionInfo = join(__dirname, "bs-config.json");
11
+ // Default connection info
12
+ const defaultConnectionInfo = {
13
+ local: "http://localhost:3000",
14
+ external: "http://192.168.1.5:3000",
15
+ ui: "http://localhost:3001",
16
+ uiExternal: "http://192.168.1.5:3001",
17
+ };
18
+ let jsonData = defaultConnectionInfo;
19
+ if (existsSync(bsConnectionInfo)) {
20
+ try {
21
+ const data = readFileSync(bsConnectionInfo, "utf8");
22
+ jsonData = JSON.parse(data);
23
+ }
24
+ catch (error) {
25
+ console.error("Error parsing bs-output.json:", error);
26
+ }
27
+ }
28
+ else {
29
+ console.warn("bs-output.json not found, using default connection info.");
30
+ }
31
+ const options = {
32
+ definition: {
33
+ openapi: "3.0.0",
34
+ info: {
35
+ title: "Prisma PHP API Documentation",
36
+ version: "1.0.0",
37
+ description: "API documentation for the Prisma PHP project",
38
+ },
39
+ servers: [
40
+ {
41
+ url: jsonData.local, // For Development
42
+ description: "Development Server",
43
+ },
44
+ {
45
+ url: "your-production-domain", // For Production
46
+ description: "Production Server",
47
+ },
48
+ ],
49
+ components: {
50
+ securitySchemes: {
51
+ bearerAuth: {
52
+ type: "http",
53
+ scheme: "bearer",
54
+ bearerFormat: "JWT",
55
+ },
56
+ },
57
+ },
58
+ security: [
59
+ {
60
+ bearerAuth: [],
61
+ },
62
+ ],
63
+ },
64
+ apis: [join(__dirname, "../src/app/swagger-docs/apis/**/*.ts")], // Adjust to match TypeScript file paths
65
+ };
66
+ // Generate the Swagger specification
67
+ const swaggerSpec = JSON.stringify(swaggerJsdoc(options), null, 2);
68
+ // Always generate the swagger.json file
69
+ try {
70
+ writeFileSync(outputPath, swaggerSpec, "utf-8");
71
+ console.log(`Swagger JSON has been generated and saved to ${chalk.blue("src/app/swagger-docs/pphp-swagger.json")}`);
72
+ }
73
+ catch (error) {
74
+ console.error("Error saving Swagger JSON:", error);
75
+ }
@@ -106,6 +106,6 @@
106
106
  // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
107
107
  "skipLibCheck": true /* Skip type checking all .d.ts files. */
108
108
  },
109
- "include": ["src/**/*.ts", "settings/**/*.ts"],
109
+ "include": ["**/*.ts"],
110
110
  "exclude": ["node_modules", "vendor"]
111
111
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-prisma-php-app",
3
- "version": "1.22.4",
3
+ "version": "1.22.5",
4
4
  "description": "Prisma-PHP: A Revolutionary Library Bridging PHP with Prisma ORM",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -1,9 +0,0 @@
1
- module.exports = {
2
- proxy: "http://localhost",
3
- serveStatic: ["src/app"],
4
- files: "src/**/*.*",
5
- notify: false,
6
- open: false,
7
- ghostMode: false,
8
- codeSync: true, // Disable synchronization of code changes across clients
9
- };
@@ -1,61 +0,0 @@
1
- import { readdirSync, statSync, existsSync, writeFileSync } from "fs";
2
- import path, { dirname } from "path";
3
- import { fileURLToPath } from "url";
4
-
5
- // Define __dirname equivalent in ES modules
6
- const __filename = fileURLToPath(import.meta.url);
7
- const __dirname = dirname(__filename);
8
-
9
- const dirPath = path.join(__dirname, "..", "src", "app");
10
- const jsonFilePath = path.join(__dirname, "files-list.json");
11
-
12
- // Function to get all files in the directory
13
- const getAllFiles = (dirPath) => {
14
- const files = [];
15
-
16
- // Check if directory exists before reading
17
- if (!existsSync(dirPath)) {
18
- console.error(`Directory not found: ${dirPath}`);
19
- return files; // Return an empty array if the directory doesn't exist
20
- }
21
-
22
- const items = readdirSync(dirPath);
23
- items.forEach((item) => {
24
- const fullPath = path.join(dirPath, item);
25
- if (statSync(fullPath).isDirectory()) {
26
- files.push(...getAllFiles(fullPath)); // Recursive call for subdirectories
27
- } else {
28
- // Generate the relative path and ensure it starts with ./src
29
- const relativePath = `.${path.sep}${path.relative(
30
- path.join(__dirname, ".."),
31
- fullPath
32
- )}`;
33
- // Replace only the root backslashes with forward slashes and leave inner ones
34
- files.push(relativePath.replace(/\\/g, "\\").replace(/^\.\.\//, ""));
35
- }
36
- });
37
-
38
- return files;
39
- };
40
-
41
- // Function to generate the files-list.json
42
- const generateFileListJson = () => {
43
- const files = getAllFiles(dirPath);
44
-
45
- // If files exist, generate JSON file
46
- if (files.length > 0) {
47
- writeFileSync(jsonFilePath, JSON.stringify(files, null, 2));
48
- console.log(
49
- `File list has been saved to: settings/files-list.json`
50
- );
51
- } else {
52
- console.error("No files found to save in the JSON file.");
53
- }
54
- };
55
-
56
- // Main function
57
- async function processDirectory() {
58
- generateFileListJson();
59
- }
60
-
61
- processDirectory();
@@ -1,83 +0,0 @@
1
- const fs = require("fs");
2
- const path = require("path");
3
-
4
- // Path to your JSON configuration file
5
- const configFilePath = path.join(__dirname, "..", "prisma-php.json");
6
-
7
- // Use the parent directory name as the new project name
8
- const newProjectName = path.basename(path.join(__dirname, ".."));
9
-
10
- // Function to update the project name and paths in the JSON config
11
- function updateProjectNameInConfig(filePath, newProjectName) {
12
- const filePathDir = path.dirname(filePath);
13
- fs.readFile(filePath, "utf8", (err, data) => {
14
- if (err) {
15
- console.error("Error reading the JSON file:", err);
16
- return;
17
- }
18
-
19
- let config = JSON.parse(data);
20
-
21
- // Update the projectName
22
- config.projectName = newProjectName;
23
-
24
- // Update other paths
25
- config.projectRootPath = filePathDir;
26
-
27
- const targetPath = getTargetPath(filePathDir, config.phpEnvironment);
28
-
29
- config.bsTarget = `http://localhost${targetPath}`;
30
- config.bsPathRewrite["^/"] = targetPath;
31
-
32
- // Save the updated config back to the JSON file
33
- fs.writeFile(filePath, JSON.stringify(config, null, 2), "utf8", (err) => {
34
- if (err) {
35
- console.error("Error writing the updated JSON file:", err);
36
- return;
37
- }
38
- console.log(
39
- "The project name, PHP path, and other paths have been updated successfully."
40
- );
41
- });
42
- });
43
- }
44
-
45
- // Function to determine the target path for browser-sync
46
- function getTargetPath(fullPath, environment) {
47
- const normalizedPath = path.normalize(fullPath);
48
- const webDirectories = {
49
- XAMPP: path.join("htdocs"),
50
- WAMP: path.join("www"),
51
- MAMP: path.join("htdocs"),
52
- LAMP: path.join("var", "www", "html"),
53
- LEMP: path.join("usr", "share", "nginx", "html"),
54
- AMPPS: path.join("www"),
55
- UniformServer: path.join("www"),
56
- EasyPHP: path.join("data", "localweb"),
57
- };
58
-
59
- const webDir = webDirectories[environment.toUpperCase()];
60
- if (!webDir) {
61
- throw new Error(`Unsupported environment: ${environment}`);
62
- }
63
-
64
- const indexOfWebDir = normalizedPath
65
- .toLowerCase()
66
- .indexOf(path.normalize(webDir).toLowerCase());
67
- if (indexOfWebDir === -1) {
68
- throw new Error(`Web directory not found in path: ${webDir}`);
69
- }
70
-
71
- const startIndex = indexOfWebDir + webDir.length;
72
- const subPath = normalizedPath.slice(startIndex);
73
- const safeSeparatorRegex = new RegExp(
74
- path.sep.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"),
75
- "g"
76
- );
77
- const finalPath = subPath.replace(safeSeparatorRegex, "/") + "/";
78
-
79
- return finalPath;
80
- }
81
-
82
- // Run the function with your config file path and the new project name
83
- updateProjectNameInConfig(configFilePath, newProjectName);
@@ -1,53 +0,0 @@
1
- const { spawn } = require("child_process");
2
- const path = require("path");
3
-
4
- // Define paths
5
- const phpPath = "php"; // Adjust if necessary to include the full path to PHP
6
- const serverScriptPath = path.join(
7
- __dirname,
8
- "..",
9
- "src",
10
- "Lib",
11
- "Websocket",
12
- "server.php"
13
- );
14
-
15
- // Hold the server process
16
- let serverProcess = null;
17
-
18
- const restartServer = () => {
19
- // If a server process already exists, kill it
20
- if (serverProcess) {
21
- console.log("Stopping WebSocket server...");
22
- serverProcess.kill("SIGINT"); // Adjust the signal as necessary for your environment
23
- serverProcess = null;
24
- }
25
-
26
- // Start a new WebSocket server process
27
- console.log("Starting WebSocket server...");
28
- serverProcess = spawn(phpPath, [serverScriptPath]);
29
-
30
- serverProcess.stdout.on("data", (data) => {
31
- console.log(`WebSocket Server: ${data}`);
32
- });
33
-
34
- serverProcess.stderr.on("data", (data) => {
35
- console.error(`WebSocket Server Error: ${data}`);
36
- });
37
-
38
- serverProcess.on("close", (code) => {
39
- console.log(`WebSocket server process exited with code ${code}`);
40
- });
41
- };
42
-
43
- // Initial start
44
- restartServer();
45
-
46
- // Watch for changes and restart the server
47
- const chokidar = require("chokidar");
48
- chokidar
49
- .watch(path.join(__dirname, "..", "src", "Lib", "Websocket", "**", "*"))
50
- .on("change", (event, path) => {
51
- console.log(`${event}: ${path}`);
52
- restartServer();
53
- });
@@ -1,203 +0,0 @@
1
- import { exec, spawn } from "child_process";
2
- import chalk from "chalk";
3
- import { writeFileSync } from "fs";
4
- import readline from "readline";
5
-
6
- const BROWSERSYNC_PREFIX = "[Browsersync]";
7
- const REGEX_PATTERNS = {
8
- BROWSERSYNC: /^\[Browsersync\]\s*(.+)$/,
9
- PROXYING: /Proxying/,
10
- ACCESS_URLS: /Access URLs:/,
11
- LOCAL_URL: /Local:\s*(http:\/\/.+)/,
12
- EXTERNAL_URL: /External:\s*(http:\/\/\S+)/,
13
- UI_URL: /UI:\s*(http:\/\/.+)/,
14
- UI_EXTERNAL_URL: /UI External:\s*(http:\/\/.+)/,
15
- WATCHING_FILES: /Watching files/,
16
- };
17
-
18
- async function runCommand(command, options = {}) {
19
- return new Promise((resolve, reject) => {
20
- const process = exec(command, options);
21
-
22
- let stdout = "";
23
- let stderr = "";
24
-
25
- process.stdout.on("data", (data) => {
26
- stdout += data;
27
- });
28
-
29
- process.stderr.on("data", (data) => {
30
- stderr += data;
31
- });
32
-
33
- process.on("close", (code) => {
34
- if (code === 0) {
35
- resolve({ stdout, stderr });
36
- } else {
37
- reject(
38
- new Error(`Command "${command}" exited with code ${code}\n${stderr}`)
39
- );
40
- }
41
- });
42
- });
43
- }
44
-
45
- async function startDev() {
46
- let browserSync;
47
- let devProcess;
48
- try {
49
- // Step 1: Start projectName and wait for it to complete
50
- console.log("Starting projectName...");
51
- const projectName = await runCommand("npm run projectName");
52
- console.log(projectName.stdout);
53
-
54
- // Step 2: Start browserSync and process its output
55
- console.log("Starting browser-sync...");
56
- browserSync = spawn("npm", ["run", "browserSync"], { shell: true });
57
-
58
- const formattedLog = {
59
- local: "",
60
- external: "",
61
- ui: "",
62
- uiExternal: "",
63
- };
64
-
65
- const rl = readline.createInterface({
66
- input: browserSync.stdout,
67
- crlfDelay: Infinity,
68
- });
69
-
70
- let browserSyncReady = false;
71
-
72
- rl.on("line", (line) => {
73
- if (REGEX_PATTERNS.PROXYING.test(line)) {
74
- const match = line.match(REGEX_PATTERNS.BROWSERSYNC);
75
- if (match) {
76
- console.log(`${chalk.blue(BROWSERSYNC_PREFIX)} ${match[1]}`);
77
- }
78
- } else if (REGEX_PATTERNS.ACCESS_URLS.test(line)) {
79
- const match = line.match(REGEX_PATTERNS.BROWSERSYNC);
80
- if (match) {
81
- console.log(`${chalk.blue(BROWSERSYNC_PREFIX)} ${match[1]}`);
82
- }
83
- } else if (REGEX_PATTERNS.LOCAL_URL.test(line)) {
84
- const match = line.match(REGEX_PATTERNS.LOCAL_URL);
85
- if (match) {
86
- const localUrl = match[1];
87
- formattedLog.local = localUrl;
88
- console.log(`${chalk.white("Local: ")}${chalk.cyanBright(localUrl)}`);
89
- }
90
- } else if (/^ {4}External:/.test(line)) {
91
- const match = line.match(REGEX_PATTERNS.EXTERNAL_URL);
92
- if (match) {
93
- const externalUrl = match[1];
94
- formattedLog.external = externalUrl;
95
- console.log(
96
- `${chalk.white("External: ")}${chalk.magentaBright(externalUrl)}`
97
- );
98
- }
99
- } else if (REGEX_PATTERNS.UI_URL.test(line)) {
100
- const match = line.match(REGEX_PATTERNS.UI_URL);
101
- if (match) {
102
- const uiUrl = match[1];
103
- formattedLog.ui = uiUrl;
104
- console.log(`${chalk.yellow("UI: ")}${chalk.cyanBright(uiUrl)}`);
105
- }
106
- } else if (REGEX_PATTERNS.UI_EXTERNAL_URL.test(line)) {
107
- const match = line.match(REGEX_PATTERNS.UI_EXTERNAL_URL);
108
- if (match) {
109
- const uiExternalUrl = match[1];
110
- formattedLog.uiExternal = uiExternalUrl;
111
- console.log(
112
- `${chalk.yellow("UI External: ")}${chalk.magentaBright(
113
- uiExternalUrl
114
- )}`
115
- );
116
- }
117
- } else if (REGEX_PATTERNS.WATCHING_FILES.test(line)) {
118
- console.log(`${chalk.blue(BROWSERSYNC_PREFIX)} Watching files...`);
119
- const outputPath = "./settings/bs-output.json";
120
- writeFileSync(
121
- outputPath,
122
- JSON.stringify(formattedLog, null, 2),
123
- "utf-8"
124
- );
125
- console.log(`Browser-sync output saved to ${outputPath}`);
126
-
127
- if (!browserSyncReady) {
128
- browserSyncReady = true;
129
- // Start npmRunAll after browserSync is ready
130
- startDevProcess();
131
- }
132
- } else if (REGEX_PATTERNS.BROWSERSYNC.test(line)) {
133
- const match = line.match(REGEX_PATTERNS.BROWSERSYNC);
134
- if (match) {
135
- console.log(`${chalk.blue(BROWSERSYNC_PREFIX)} ${match[1]}`);
136
- }
137
- } else {
138
- // Print any other notifications
139
- console.log(line);
140
- }
141
- });
142
-
143
- browserSync.stderr.on("data", (data) => {
144
- console.error(`browser-sync error: ${data.toString()}`);
145
- });
146
-
147
- browserSync.on("error", (err) => {
148
- console.error(`Failed to start browserSync process: ${err.message}`);
149
- });
150
-
151
- // Function to start npmRunAll process
152
- function startDevProcess() {
153
- console.log("Starting npmRunAll...");
154
- devProcess = spawn("npm", ["run", "npmRunAll"], { shell: true });
155
-
156
- devProcess.stdout.on("data", (data) => {
157
- process.stdout.write(data);
158
- });
159
-
160
- devProcess.stderr.on("data", (data) => {
161
- process.stderr.write(data);
162
- });
163
-
164
- devProcess.on("close", (code) => {
165
- console.log(`Dev process exited with code ${code}`);
166
- });
167
-
168
- devProcess.on("error", (err) => {
169
- console.error(`Failed to start dev process: ${err.message}`);
170
- });
171
- }
172
-
173
- // Handle browserSync close event
174
- browserSync.on("close", (code) => {
175
- console.log(`browserSync process exited with code ${code}`);
176
- });
177
-
178
- // Handle process exit and cleanup
179
- function handleExit() {
180
- if (browserSync) {
181
- browserSync.kill();
182
- }
183
- if (devProcess) {
184
- devProcess.kill();
185
- }
186
- }
187
-
188
- process.on("exit", handleExit);
189
- process.on("SIGINT", () => {
190
- handleExit();
191
- process.exit();
192
- });
193
- process.on("SIGTERM", () => {
194
- handleExit();
195
- process.exit();
196
- });
197
- } catch (error) {
198
- console.error("An error occurred:", error.message);
199
- process.exit(1);
200
- }
201
- }
202
-
203
- startDev();
@@ -1,89 +0,0 @@
1
- import swaggerJsdoc from "swagger-jsdoc";
2
- import { writeFileSync, readFileSync, existsSync } from "fs";
3
- import { fileURLToPath } from "url";
4
- import { join, dirname } from "path";
5
- import chalk from "chalk";
6
-
7
- // Define __dirname equivalent in ES modules
8
- const __filename = fileURLToPath(import.meta.url);
9
- const __dirname = dirname(__filename);
10
-
11
- // Define the output path for the swagger.json file
12
- const outputPath = join(
13
- __dirname,
14
- "../src/app/swagger-docs/apis/pphp-swagger.json"
15
- );
16
-
17
- const bsConnectionInfo = join(__dirname, "bs-output.json");
18
-
19
- // Check if the bs-output.json file exists
20
- const defaultConnectionInfo = {
21
- local: "http://localhost:3000",
22
- external: "http://192.168.1.5:3000",
23
- ui: "http://localhost:3001",
24
- uiExternal: "http://192.168.1.5:3001",
25
- };
26
-
27
- let jsonData = defaultConnectionInfo;
28
-
29
- if (existsSync(bsConnectionInfo)) {
30
- try {
31
- const data = readFileSync(bsConnectionInfo, "utf8");
32
- jsonData = JSON.parse(data);
33
- } catch (error) {
34
- console.error("Error parsing bs-output.json:", error);
35
- }
36
- } else {
37
- console.warn("bs-output.json not found, using default connection info.");
38
- }
39
-
40
- const options = {
41
- definition: {
42
- openapi: "3.0.0",
43
- info: {
44
- title: "Prisma PHP API Documentation",
45
- version: "1.0.0",
46
- description: "API documentation for the Prisma PHP project",
47
- },
48
- servers: [
49
- {
50
- url: jsonData.local, // For Development
51
- description: "Development Server",
52
- },
53
- {
54
- url: "your-production-domain", // For Production
55
- description: "Production Server",
56
- },
57
- ],
58
- components: {
59
- securitySchemes: {
60
- bearerAuth: {
61
- type: "http",
62
- scheme: "bearer",
63
- bearerFormat: "JWT",
64
- },
65
- },
66
- },
67
- security: [
68
- {
69
- bearerAuth: [],
70
- },
71
- ],
72
- },
73
- apis: [join(__dirname, "../src/app/swagger-docs/apis/**/*.js")], // Path to your API routes
74
- };
75
-
76
- // Generate the Swagger specification
77
- const swaggerSpec = JSON.stringify(swaggerJsdoc(options), null, 2);
78
-
79
- // Always generate the swagger.json file
80
- try {
81
- writeFileSync(outputPath, swaggerSpec, "utf-8");
82
- console.log(
83
- `Swagger JSON has been generated and saved to ${chalk.blue(
84
- "src/app/swagger-docs/pphp-swagger.json"
85
- )}`
86
- );
87
- } catch (error) {
88
- console.error("Error saving Swagger JSON:", error);
89
- }