create-prisma-php-app 1.22.4 → 1.22.6
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/bootstrap.php +8 -7
- package/dist/index.js +403 -1
- package/dist/settings/bs-config.js +75 -0
- package/dist/settings/files-list.js +43 -0
- package/dist/settings/project-name.js +60 -0
- package/dist/settings/request-methods.php +2 -2
- package/dist/settings/restart-websocket.js +40 -0
- package/dist/settings/swagger-config.js +75 -0
- package/dist/tsconfig.json +1 -1
- package/package.json +1 -1
- package/dist/settings/bs-config.cjs +0 -9
- package/dist/settings/files-list-config.js +0 -61
- package/dist/settings/project-name.cjs +0 -83
- package/dist/settings/restart-websocket.cjs +0 -53
- package/dist/settings/start-dev.js +0 -203
- package/dist/settings/swagger-setup.js +0 -89
package/dist/bootstrap.php
CHANGED
|
@@ -37,7 +37,7 @@ function determineContentToInclude()
|
|
|
37
37
|
* ================================================
|
|
38
38
|
*/
|
|
39
39
|
|
|
40
|
-
$isDirectAccessToPrivateRoute = preg_match('
|
|
40
|
+
$isDirectAccessToPrivateRoute = preg_match('/_/', $uri);
|
|
41
41
|
if ($isDirectAccessToPrivateRoute) {
|
|
42
42
|
$sameSiteFetch = false;
|
|
43
43
|
$serverFetchSite = $_SERVER['HTTP_SEC_FETCH_SITE'] ?? '';
|
|
@@ -138,6 +138,8 @@ function getFilePrecedence()
|
|
|
138
138
|
|
|
139
139
|
function uriExtractor(string $scriptUrl): string
|
|
140
140
|
{
|
|
141
|
+
if ($_ENV['APP_ENV'] !== 'development') return "/";
|
|
142
|
+
|
|
141
143
|
global $_prismaPHPSettings;
|
|
142
144
|
|
|
143
145
|
$projectName = $_prismaPHPSettings['projectName'] ?? '';
|
|
@@ -335,9 +337,7 @@ function singleDynamicRoute($uriSegments, $routeSegments)
|
|
|
335
337
|
|
|
336
338
|
function checkForDuplicateRoutes()
|
|
337
339
|
{
|
|
338
|
-
if ($_ENV['APP_ENV'] !== 'development')
|
|
339
|
-
return;
|
|
340
|
-
}
|
|
340
|
+
if ($_ENV['APP_ENV'] !== 'development') return;
|
|
341
341
|
|
|
342
342
|
global $_filesListRoutes;
|
|
343
343
|
$normalizedRoutesMap = [];
|
|
@@ -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()
|
|
@@ -759,7 +760,7 @@ try {
|
|
|
759
760
|
$_isContentIncluded = true;
|
|
760
761
|
}
|
|
761
762
|
|
|
762
|
-
if (!empty($_contentToInclude)) {
|
|
763
|
+
if (!empty($_contentToInclude) && !empty($_fileToInclude)) {
|
|
763
764
|
if (!$_isParentLayout) {
|
|
764
765
|
ob_start();
|
|
765
766
|
require_once $_contentToInclude;
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,404 @@
|
|
|
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.js")||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 k=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=k.swaggerDocs)&&void 0!==i?i:e.swaggerDocs)&&void 0!==c&&c,tailwindcss:null!==(a=null!==(o=k.tailwindcss)&&void 0!==o?o:e.tailwindcss)&&void 0!==a&&a,websocket:null!==(l=null!==(r=k.websocket)&&void 0!==r?r:e.websocket)&&void 0!==l&&l,prisma:null!==(d=null!==(p=k.prisma)&&void 0!==p?p:e.prisma)&&void 0!==d&&d,docker:null!==(g=null!==(u=k.docker)&&void 0!==u?u:e.docker)&&void 0!==g&&g}}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
|
+
/**
|
|
4
|
+
* Install dependencies in the specified directory.
|
|
5
|
+
* @param {string} baseDir - The base directory where to install the dependencies.
|
|
6
|
+
* @param {string[]} dependencies - The list of dependencies to install.
|
|
7
|
+
* @param {boolean} [isDev=false] - Whether to install the dependencies as devDependencies.
|
|
8
|
+
*/
|
|
9
|
+
async function installDependencies(baseDir, dependencies, isDev = false) {
|
|
10
|
+
console.log("Initializing new Node.js project...");
|
|
11
|
+
// Initialize a package.json if it doesn't exist
|
|
12
|
+
if (!fs.existsSync(path.join(baseDir, "package.json")))
|
|
13
|
+
execSync("npm init -y", {
|
|
14
|
+
stdio: "inherit",
|
|
15
|
+
cwd: baseDir,
|
|
16
|
+
});
|
|
17
|
+
// Log the dependencies being installed
|
|
18
|
+
console.log(
|
|
19
|
+
`${
|
|
20
|
+
isDev ? "Installing development dependencies" : "Installing dependencies"
|
|
21
|
+
}:`
|
|
22
|
+
);
|
|
23
|
+
dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
|
|
24
|
+
// Prepare the npm install command with the appropriate flag for dev dependencies
|
|
25
|
+
const npmInstallCommand = `npm install ${
|
|
26
|
+
isDev ? "--save-dev" : ""
|
|
27
|
+
} ${dependencies.join(" ")}`;
|
|
28
|
+
// Execute the npm install command
|
|
29
|
+
execSync(npmInstallCommand, {
|
|
30
|
+
stdio: "inherit",
|
|
31
|
+
cwd: baseDir,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
async function main() {
|
|
35
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j;
|
|
36
|
+
try {
|
|
37
|
+
const args = process.argv.slice(2);
|
|
38
|
+
let projectName = args[0];
|
|
39
|
+
let answer = null;
|
|
40
|
+
if (projectName) {
|
|
41
|
+
let useBackendOnly = args.includes("--backend-only");
|
|
42
|
+
let useSwaggerDocs = args.includes("--swagger-docs");
|
|
43
|
+
let useTailwind = args.includes("--tailwindcss");
|
|
44
|
+
let useWebsocket = args.includes("--websocket");
|
|
45
|
+
let usePrisma = args.includes("--prisma");
|
|
46
|
+
let useDocker = args.includes("--docker");
|
|
47
|
+
const predefinedAnswers = {
|
|
48
|
+
projectName,
|
|
49
|
+
backendOnly: useBackendOnly,
|
|
50
|
+
swaggerDocs: useSwaggerDocs,
|
|
51
|
+
tailwindcss: useTailwind,
|
|
52
|
+
websocket: useWebsocket,
|
|
53
|
+
prisma: usePrisma,
|
|
54
|
+
docker: useDocker,
|
|
55
|
+
};
|
|
56
|
+
answer = await getAnswer(predefinedAnswers);
|
|
57
|
+
if (answer === null) {
|
|
58
|
+
console.log(chalk.red("Installation cancelled."));
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
const currentDir = process.cwd();
|
|
62
|
+
const configPath = path.join(currentDir, "prisma-php.json");
|
|
63
|
+
const localSettings = readJsonFile(configPath);
|
|
64
|
+
let excludeFiles = [];
|
|
65
|
+
(_a = localSettings.excludeFiles) === null || _a === void 0
|
|
66
|
+
? void 0
|
|
67
|
+
: _a.map((file) => {
|
|
68
|
+
const filePath = path.join(currentDir, file);
|
|
69
|
+
if (fs.existsSync(filePath))
|
|
70
|
+
excludeFiles.push(filePath.replace(/\\/g, "/"));
|
|
71
|
+
});
|
|
72
|
+
updateAnswer = {
|
|
73
|
+
projectName,
|
|
74
|
+
backendOnly:
|
|
75
|
+
(_b =
|
|
76
|
+
answer === null || answer === void 0
|
|
77
|
+
? void 0
|
|
78
|
+
: answer.backendOnly) !== null && _b !== void 0
|
|
79
|
+
? _b
|
|
80
|
+
: false,
|
|
81
|
+
swaggerDocs:
|
|
82
|
+
(_c =
|
|
83
|
+
answer === null || answer === void 0
|
|
84
|
+
? void 0
|
|
85
|
+
: answer.swaggerDocs) !== null && _c !== void 0
|
|
86
|
+
? _c
|
|
87
|
+
: false,
|
|
88
|
+
tailwindcss:
|
|
89
|
+
(_d =
|
|
90
|
+
answer === null || answer === void 0
|
|
91
|
+
? void 0
|
|
92
|
+
: answer.tailwindcss) !== null && _d !== void 0
|
|
93
|
+
? _d
|
|
94
|
+
: false,
|
|
95
|
+
websocket:
|
|
96
|
+
(_e =
|
|
97
|
+
answer === null || answer === void 0
|
|
98
|
+
? void 0
|
|
99
|
+
: answer.websocket) !== null && _e !== void 0
|
|
100
|
+
? _e
|
|
101
|
+
: false,
|
|
102
|
+
prisma:
|
|
103
|
+
(_f =
|
|
104
|
+
answer === null || answer === void 0 ? void 0 : answer.prisma) !==
|
|
105
|
+
null && _f !== void 0
|
|
106
|
+
? _f
|
|
107
|
+
: false,
|
|
108
|
+
docker:
|
|
109
|
+
(_g =
|
|
110
|
+
answer === null || answer === void 0 ? void 0 : answer.docker) !==
|
|
111
|
+
null && _g !== void 0
|
|
112
|
+
? _g
|
|
113
|
+
: false,
|
|
114
|
+
isUpdate: true,
|
|
115
|
+
excludeFiles:
|
|
116
|
+
(_h = localSettings.excludeFiles) !== null && _h !== void 0 ? _h : [],
|
|
117
|
+
excludeFilePath:
|
|
118
|
+
excludeFiles !== null && excludeFiles !== void 0 ? excludeFiles : [],
|
|
119
|
+
filePath: currentDir,
|
|
120
|
+
};
|
|
121
|
+
} else {
|
|
122
|
+
answer = await getAnswer();
|
|
123
|
+
}
|
|
124
|
+
if (answer === null) {
|
|
125
|
+
console.warn(chalk.red("Installation cancelled."));
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
const latestVersionOfCreatePrismaPhpApp = await fetchPackageVersion(
|
|
129
|
+
"create-prisma-php-app"
|
|
130
|
+
);
|
|
131
|
+
const isCreatePrismaPhpAppInstalled = getInstalledPackageVersion(
|
|
132
|
+
"create-prisma-php-app"
|
|
133
|
+
);
|
|
134
|
+
if (isCreatePrismaPhpAppInstalled) {
|
|
135
|
+
if (
|
|
136
|
+
compareVersions(
|
|
137
|
+
isCreatePrismaPhpAppInstalled,
|
|
138
|
+
latestVersionOfCreatePrismaPhpApp
|
|
139
|
+
) === -1
|
|
140
|
+
) {
|
|
141
|
+
execSync(`npm uninstall -g create-prisma-php-app`, {
|
|
142
|
+
stdio: "inherit",
|
|
143
|
+
});
|
|
144
|
+
execSync(`npm install -g create-prisma-php-app`, {
|
|
145
|
+
stdio: "inherit",
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
} else {
|
|
149
|
+
execSync("npm install -g create-prisma-php-app", { stdio: "inherit" });
|
|
150
|
+
}
|
|
151
|
+
// Create the project directory
|
|
152
|
+
if (!projectName) fs.mkdirSync(answer.projectName);
|
|
153
|
+
const currentDir = process.cwd();
|
|
154
|
+
let projectPath = projectName
|
|
155
|
+
? currentDir
|
|
156
|
+
: path.join(currentDir, answer.projectName);
|
|
157
|
+
if (!projectName) process.chdir(answer.projectName);
|
|
158
|
+
const dependencies = [
|
|
159
|
+
"typescript",
|
|
160
|
+
"@types/node",
|
|
161
|
+
"ts-node",
|
|
162
|
+
"http-proxy-middleware",
|
|
163
|
+
"chalk",
|
|
164
|
+
"npm-run-all",
|
|
165
|
+
"browser-sync",
|
|
166
|
+
];
|
|
167
|
+
if (answer.swaggerDocs) {
|
|
168
|
+
dependencies.push("swagger-jsdoc");
|
|
169
|
+
}
|
|
170
|
+
if (answer.tailwindcss) {
|
|
171
|
+
dependencies.push(
|
|
172
|
+
"tailwindcss",
|
|
173
|
+
"autoprefixer",
|
|
174
|
+
"postcss",
|
|
175
|
+
"postcss-cli",
|
|
176
|
+
"cssnano"
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
if (answer.websocket) {
|
|
180
|
+
dependencies.push("chokidar-cli");
|
|
181
|
+
}
|
|
182
|
+
if (answer.prisma) {
|
|
183
|
+
dependencies.push("prisma", "@prisma/client");
|
|
184
|
+
}
|
|
185
|
+
await installDependencies(projectPath, dependencies, true);
|
|
186
|
+
if (!projectName) {
|
|
187
|
+
execSync(`npx tsc --init`, { stdio: "inherit" });
|
|
188
|
+
}
|
|
189
|
+
if (answer.tailwindcss)
|
|
190
|
+
execSync(`npx tailwindcss init -p`, { stdio: "inherit" });
|
|
191
|
+
if (answer.prisma) {
|
|
192
|
+
if (!fs.existsSync(path.join(projectPath, "prisma")))
|
|
193
|
+
execSync(`npx prisma init`, { stdio: "inherit" });
|
|
194
|
+
}
|
|
195
|
+
await createDirectoryStructure(projectPath, answer);
|
|
196
|
+
const publicDirPath = path.join(projectPath, "public");
|
|
197
|
+
if (!fs.existsSync(publicDirPath)) {
|
|
198
|
+
fs.mkdirSync(publicDirPath);
|
|
199
|
+
}
|
|
200
|
+
if (answer.swaggerDocs) {
|
|
201
|
+
const swaggerDocsPath = path.join(
|
|
202
|
+
projectPath,
|
|
203
|
+
"src",
|
|
204
|
+
"app",
|
|
205
|
+
"swagger-docs"
|
|
206
|
+
);
|
|
207
|
+
// Check if the directory exists, if not, create it
|
|
208
|
+
if (!fs.existsSync(swaggerDocsPath)) {
|
|
209
|
+
fs.mkdirSync(swaggerDocsPath, { recursive: true }); // 'recursive: true' creates parent directories if they don't exist
|
|
210
|
+
}
|
|
211
|
+
// Clone the Git repository into the swagger-docs directory
|
|
212
|
+
execSync(
|
|
213
|
+
`git clone https://github.com/TheSteelNinjaCode/prisma-php-swagger-docs.git ${swaggerDocsPath}`,
|
|
214
|
+
{ stdio: "inherit" }
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
if (
|
|
218
|
+
updateAnswer === null || updateAnswer === void 0
|
|
219
|
+
? void 0
|
|
220
|
+
: updateAnswer.isUpdate
|
|
221
|
+
) {
|
|
222
|
+
const updateUninstallDependencies = [];
|
|
223
|
+
if (updateAnswer.backendOnly) {
|
|
224
|
+
nonBackendFiles.forEach((file) => {
|
|
225
|
+
const filePath = path.join(projectPath, "src", "app", file);
|
|
226
|
+
if (fs.existsSync(filePath)) {
|
|
227
|
+
fs.unlinkSync(filePath); // Delete each file if it exists
|
|
228
|
+
console.log(`${file} was deleted successfully.`);
|
|
229
|
+
} else {
|
|
230
|
+
console.log(`${file} does not exist.`);
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
const backendOnlyFolders = ["js", "css"];
|
|
234
|
+
backendOnlyFolders.forEach((folder) => {
|
|
235
|
+
const folderPath = path.join(projectPath, "src", "app", folder);
|
|
236
|
+
if (fs.existsSync(folderPath)) {
|
|
237
|
+
fs.rmSync(folderPath, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
|
|
238
|
+
console.log(`${folder} was deleted successfully.`);
|
|
239
|
+
} else {
|
|
240
|
+
console.log(`${folder} does not exist.`);
|
|
241
|
+
}
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
if (!updateAnswer.swaggerDocs) {
|
|
245
|
+
const swaggerDocsFolder = path.join(
|
|
246
|
+
projectPath,
|
|
247
|
+
"src",
|
|
248
|
+
"app",
|
|
249
|
+
"swagger-docs"
|
|
250
|
+
);
|
|
251
|
+
if (fs.existsSync(swaggerDocsFolder)) {
|
|
252
|
+
fs.rmSync(swaggerDocsFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
|
|
253
|
+
console.log(`swagger-docs was deleted successfully.`);
|
|
254
|
+
}
|
|
255
|
+
const swaggerFiles = ["swagger-setup.js"];
|
|
256
|
+
swaggerFiles.forEach((file) => {
|
|
257
|
+
const filePath = path.join(projectPath, "settings", file);
|
|
258
|
+
if (fs.existsSync(filePath)) {
|
|
259
|
+
fs.unlinkSync(filePath); // Delete each file if it exists
|
|
260
|
+
console.log(`${file} was deleted successfully.`);
|
|
261
|
+
} else {
|
|
262
|
+
console.log(`${file} does not exist.`);
|
|
263
|
+
}
|
|
264
|
+
});
|
|
265
|
+
updateUninstallDependencies.push("swagger-jsdoc");
|
|
266
|
+
}
|
|
267
|
+
if (!updateAnswer.tailwindcss) {
|
|
268
|
+
const tailwindFiles = ["postcss.config.js", "tailwind.config.js"];
|
|
269
|
+
tailwindFiles.forEach((file) => {
|
|
270
|
+
const filePath = path.join(projectPath, file);
|
|
271
|
+
if (fs.existsSync(filePath)) {
|
|
272
|
+
fs.unlinkSync(filePath); // Delete each file if it exists
|
|
273
|
+
console.log(`${file} was deleted successfully.`);
|
|
274
|
+
} else {
|
|
275
|
+
console.log(`${file} does not exist.`);
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
updateUninstallDependencies.push(
|
|
279
|
+
"tailwindcss",
|
|
280
|
+
"autoprefixer",
|
|
281
|
+
"postcss",
|
|
282
|
+
"postcss-cli",
|
|
283
|
+
"cssnano"
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
if (!updateAnswer.websocket) {
|
|
287
|
+
const websocketFiles = [
|
|
288
|
+
"restart-websocket.js",
|
|
289
|
+
"restart-websocket.bat",
|
|
290
|
+
];
|
|
291
|
+
websocketFiles.forEach((file) => {
|
|
292
|
+
const filePath = path.join(projectPath, "settings", 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
|
+
const websocketFolder = path.join(
|
|
301
|
+
projectPath,
|
|
302
|
+
"src",
|
|
303
|
+
"Lib",
|
|
304
|
+
"Websocket"
|
|
305
|
+
);
|
|
306
|
+
if (fs.existsSync(websocketFolder)) {
|
|
307
|
+
fs.rmSync(websocketFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
|
|
308
|
+
console.log(`Websocket folder was deleted successfully.`);
|
|
309
|
+
}
|
|
310
|
+
updateUninstallDependencies.push("chokidar-cli");
|
|
311
|
+
}
|
|
312
|
+
if (!updateAnswer.prisma) {
|
|
313
|
+
updateUninstallDependencies.push("prisma", "@prisma/client");
|
|
314
|
+
}
|
|
315
|
+
if (!updateAnswer.docker) {
|
|
316
|
+
const dockerFiles = [
|
|
317
|
+
".dockerignore",
|
|
318
|
+
"docker-compose.yml",
|
|
319
|
+
"Dockerfile",
|
|
320
|
+
"apache.conf",
|
|
321
|
+
];
|
|
322
|
+
dockerFiles.forEach((file) => {
|
|
323
|
+
const filePath = path.join(projectPath, file);
|
|
324
|
+
if (fs.existsSync(filePath)) {
|
|
325
|
+
fs.unlinkSync(filePath); // Delete each file if it exists
|
|
326
|
+
console.log(`${file} was deleted successfully.`);
|
|
327
|
+
} else {
|
|
328
|
+
console.log(`${file} does not exist.`);
|
|
329
|
+
}
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
if (updateUninstallDependencies.length > 0) {
|
|
333
|
+
await uninstallDependencies(
|
|
334
|
+
projectPath,
|
|
335
|
+
updateUninstallDependencies,
|
|
336
|
+
true
|
|
337
|
+
);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
const projectPathModified = projectPath.replace(/\\/g, "\\");
|
|
341
|
+
const bsConfig = bsConfigUrls(projectPathModified);
|
|
342
|
+
const phpGenerateClassPath = answer.prisma ? "src/Lib/Prisma/Classes" : "";
|
|
343
|
+
const prismaPhpConfig = {
|
|
344
|
+
projectName: answer.projectName,
|
|
345
|
+
projectRootPath: projectPathModified,
|
|
346
|
+
phpEnvironment: "XAMPP",
|
|
347
|
+
phpRootPathExe: "C:\\xampp\\php\\php.exe",
|
|
348
|
+
phpGenerateClassPath,
|
|
349
|
+
bsTarget: bsConfig.bsTarget,
|
|
350
|
+
bsPathRewrite: bsConfig.bsPathRewrite,
|
|
351
|
+
backendOnly: answer.backendOnly,
|
|
352
|
+
swaggerDocs: answer.swaggerDocs,
|
|
353
|
+
tailwindcss: answer.tailwindcss,
|
|
354
|
+
websocket: answer.websocket,
|
|
355
|
+
prisma: answer.prisma,
|
|
356
|
+
docker: answer.docker,
|
|
357
|
+
version: latestVersionOfCreatePrismaPhpApp,
|
|
358
|
+
excludeFiles:
|
|
359
|
+
(_j =
|
|
360
|
+
updateAnswer === null || updateAnswer === void 0
|
|
361
|
+
? void 0
|
|
362
|
+
: updateAnswer.excludeFiles) !== null && _j !== void 0
|
|
363
|
+
? _j
|
|
364
|
+
: [],
|
|
365
|
+
};
|
|
366
|
+
fs.writeFileSync(
|
|
367
|
+
path.join(projectPath, "prisma-php.json"),
|
|
368
|
+
JSON.stringify(prismaPhpConfig, null, 2),
|
|
369
|
+
{ flag: "w" }
|
|
370
|
+
);
|
|
371
|
+
if (
|
|
372
|
+
updateAnswer === null || updateAnswer === void 0
|
|
373
|
+
? void 0
|
|
374
|
+
: updateAnswer.isUpdate
|
|
375
|
+
) {
|
|
376
|
+
execSync(
|
|
377
|
+
`C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar update`,
|
|
378
|
+
{
|
|
379
|
+
stdio: "inherit",
|
|
380
|
+
}
|
|
381
|
+
);
|
|
382
|
+
} else {
|
|
383
|
+
execSync(
|
|
384
|
+
`C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar install`,
|
|
385
|
+
{
|
|
386
|
+
stdio: "inherit",
|
|
387
|
+
}
|
|
388
|
+
);
|
|
389
|
+
}
|
|
390
|
+
console.log("\n=========================\n");
|
|
391
|
+
console.log(
|
|
392
|
+
`${chalk.green(
|
|
393
|
+
"Success!"
|
|
394
|
+
)} Prisma PHP project successfully created in ${chalk.green(
|
|
395
|
+
answer.projectName
|
|
396
|
+
)}!`
|
|
397
|
+
);
|
|
398
|
+
console.log("\n=========================");
|
|
399
|
+
} catch (error) {
|
|
400
|
+
console.error("Error while creating the project:", error);
|
|
401
|
+
process.exit(1);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
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: {},
|
|
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
|
+
};
|