create-prisma-php-app 1.11.16 → 1.11.501

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