create-prisma-php-app 1.26.526 → 1.26.528

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,366 +1,367 @@
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 t=e.substring(0,s+"\\htdocs\\".length).replace(/\\/g,"\\\\"),n=e.replace(new RegExp(`^${t}`),"").replace(/\\/g,"/");let c=`http://localhost/${n}`;c=c.endsWith("/")?c.slice(0,-1):c;const i=c.replace(/(?<!:)(\/\/+)/g,"/"),o=n.replace(/\/\/+/g,"/");return{bsTarget:`${i}/`,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={...n.scripts,projectName:"tsx settings/project-name.ts"};let c=[];if(s.tailwindcss&&(n.scripts={...n.scripts,tailwind:"postcss src/app/css/tailwind.css -o src/app/css/styles.css --watch"},c.push("tailwind")),s.websocket&&(n.scripts={...n.scripts,websocket:"tsx settings/restart-websocket.ts"},c.push("websocket")),s.docker&&(n.scripts={...n.scripts,docker:"docker-compose up"},c.push("docker")),s.swaggerDocs){const e=s.prisma?"tsx settings/auto-swagger-docs.ts":"tsx settings/swagger-config.ts";n.scripts={...n.scripts,"create-swagger-docs":e}}let i={...n.scripts};i.browserSync="tsx settings/bs-config.ts",i.dev=`npm-run-all projectName -p browserSync ${c.join(" ")}`,n.scripts=i,n.type="module",s.prisma&&(n.prisma={seed:"tsx prisma/seed.ts"}),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={...n.require,"cboden/ratchet":"^0.4.4"}),s.prisma&&(n.require={...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\nvar ws = new WebSocket("ws://localhost:8080");\n',fs.writeFileSync(t,n,"utf8")}function copyRecursiveSync(e,s,t){const n=fs.existsSync(e),c=n&&fs.statSync(e);if(n&&c&&c.isDirectory()){const n=s.toLowerCase();if(!t.websocket&&n.includes("src\\lib\\websocket"))return;if(!t.prisma&&n.includes("src\\lib\\prisma"))return;if(t.backendOnly&&n.includes("src\\app\\js")||t.backendOnly&&n.includes("src\\app\\css")||t.backendOnly&&n.includes("src\\app\\assets"))return;if(!t.swaggerDocs&&n.includes("src\\app\\swagger-docs"))return;const c=s.replace(/\\/g,"/");if(updateAnswer?.excludeFilePath?.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.ts")||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.backendOnly&&!t.swaggerDocs&&s.includes("layout.php"))return;if(!t.swaggerDocs&&s.includes("swagger-config.ts"))return;if(t.tailwindcss&&s.includes("index.css"))return;if((!t.swaggerDocs||!t.prisma)&&(s.includes("auto-swagger-docs.ts")||s.includes("prisma-sdk.ts")||s.includes("prisma-schema-config.json")||s.includes("prisma-schema.json")))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||(s.tailwindcss||(n='\n <link href="<?= Request::baseUrl; ?>/css/index.css" rel="stylesheet">'),n+='\n <script src="<?= Request::baseUrl; ?>/js/json5.min.js"><\/script>\n <script src="<?= Request::baseUrl; ?>/js/index.js"><\/script>');let c="";s.backendOnly||(c=s.tailwindcss?` <link href="<?= Request::baseUrl; ?>/css/styles.css" rel="stylesheet"> ${n}`:n);const i=c.length>0?"\n":"";e=e.replace("</head>",`${c}${i} \x3c!-- Dynamic Head --\x3e\n <?= MainLayout::outputHeadScripts() ?>\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){return!!updateAnswer?.isUpdate&&(updateAnswer?.excludeFilePath?.includes(e.replace(/\\/g,"/"))??!1)}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"},{src:"/app-gitignore",dest:"/.gitignore"}];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.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),c=path.join(e,t);if(checkExcludeFiles(c))return;const i=fs.readFileSync(n,"utf8");fs.writeFileSync(c,i,{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 c='# 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${c}`;await createOrUpdateEnvFile(e,s)}else await createOrUpdateEnvFile(e,c)}async function getAnswer(e={}){const s=[];e.projectName||s.push({type:"text",name:"projectName",message:"What is your project named?",initial:"my-app"}),e.backendOnly||s.push({type:"toggle",name:"backendOnly",message:`Would you like to create a ${chalk.blue("backend-only project")}?`,initial:!1,active:"Yes",inactive:"No"});const t=()=>{process.exit(0)},n=await prompts(s,{onCancel:t}),c=[];n.backendOnly||e.backendOnly?(e.swaggerDocs||c.push({type:"toggle",name:"swaggerDocs",message:`Would you like to use ${chalk.blue("Swagger Docs")}?`,initial:!1,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"}),e.docker||c.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"})):(e.swaggerDocs||c.push({type:"toggle",name:"swaggerDocs",message:`Would you like to use ${chalk.blue("Swagger Docs")}?`,initial:!1,active:"Yes",inactive:"No"}),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"}),e.docker||c.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"}));const i=await prompts(c,{onCancel:t});return{projectName:n.projectName?String(n.projectName).trim().replace(/ /g,"-"):e.projectName??"my-app",backendOnly:n.backendOnly??e.backendOnly??!1,swaggerDocs:i.swaggerDocs??e.swaggerDocs??!1,tailwindcss:i.tailwindcss??e.tailwindcss??!1,websocket:i.websocket??e.websocket??!1,prisma:i.prisma??e.prisma??!1,docker:i.docker??e.docker??!1}}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
- try {
36
- const args = process.argv.slice(2);
37
- let projectName = args[0];
38
- let answer = null;
39
- if (projectName) {
40
- let useBackendOnly = args.includes("--backend-only");
41
- let useSwaggerDocs = args.includes("--swagger-docs");
42
- let useTailwind = args.includes("--tailwindcss");
43
- let useWebsocket = args.includes("--websocket");
44
- let usePrisma = args.includes("--prisma");
45
- let useDocker = args.includes("--docker");
46
- const predefinedAnswers = {
47
- projectName,
48
- backendOnly: useBackendOnly,
49
- swaggerDocs: useSwaggerDocs,
50
- tailwindcss: useTailwind,
51
- websocket: useWebsocket,
52
- prisma: usePrisma,
53
- docker: useDocker,
54
- };
55
- answer = await getAnswer(predefinedAnswers);
56
- if (answer === null) {
57
- console.log(chalk.red("Installation cancelled."));
58
- return;
59
- }
60
- const currentDir = process.cwd();
61
- const configPath = path.join(currentDir, "prisma-php.json");
62
- const localSettings = readJsonFile(configPath);
63
- let excludeFiles = [];
64
- localSettings.excludeFiles?.map((file) => {
65
- const filePath = path.join(currentDir, file);
66
- if (fs.existsSync(filePath))
67
- excludeFiles.push(filePath.replace(/\\/g, "/"));
68
- });
69
- updateAnswer = {
70
- projectName,
71
- backendOnly: answer?.backendOnly ?? false,
72
- swaggerDocs: answer?.swaggerDocs ?? false,
73
- tailwindcss: answer?.tailwindcss ?? false,
74
- websocket: answer?.websocket ?? false,
75
- prisma: answer?.prisma ?? false,
76
- docker: answer?.docker ?? false,
77
- isUpdate: true,
78
- excludeFiles: localSettings.excludeFiles ?? [],
79
- excludeFilePath: excludeFiles ?? [],
80
- filePath: currentDir,
81
- };
82
- } else {
83
- answer = await getAnswer();
84
- }
85
- if (answer === null) {
86
- console.warn(chalk.red("Installation cancelled."));
87
- return;
88
- }
89
- const latestVersionOfCreatePrismaPhpApp = await fetchPackageVersion(
90
- "create-prisma-php-app"
91
- );
92
- const isCreatePrismaPhpAppInstalled = getInstalledPackageVersion(
93
- "create-prisma-php-app"
94
- );
95
- if (isCreatePrismaPhpAppInstalled) {
96
- if (
97
- compareVersions(
98
- isCreatePrismaPhpAppInstalled,
99
- latestVersionOfCreatePrismaPhpApp
100
- ) === -1
101
- ) {
102
- execSync(`npm uninstall -g create-prisma-php-app`, {
103
- stdio: "inherit",
104
- });
105
- execSync(`npm install -g create-prisma-php-app`, {
106
- stdio: "inherit",
107
- });
108
- }
109
- } else {
110
- execSync("npm install -g create-prisma-php-app", { stdio: "inherit" });
111
- }
112
- // Create the project directory
113
- if (!projectName) fs.mkdirSync(answer.projectName);
114
- const currentDir = process.cwd();
115
- let projectPath = projectName
116
- ? currentDir
117
- : path.join(currentDir, answer.projectName);
118
- if (!projectName) process.chdir(answer.projectName);
119
- const dependencies = [
120
- "typescript",
121
- "@types/node",
122
- "tsx",
123
- "ts-node",
124
- "http-proxy-middleware",
125
- "chalk",
126
- "npm-run-all",
127
- "browser-sync",
128
- ];
129
- if (answer.swaggerDocs) {
130
- dependencies.push("swagger-jsdoc", "@types/swagger-jsdoc");
131
- }
132
- if (answer.swaggerDocs && answer.prisma) {
133
- dependencies.push("prompts", "@types/prompts", "@prisma/internals");
134
- }
135
- if (answer.tailwindcss) {
136
- dependencies.push(
137
- "tailwindcss",
138
- "autoprefixer",
139
- "postcss",
140
- "postcss-cli",
141
- "cssnano"
142
- );
143
- }
144
- if (answer.websocket) {
145
- dependencies.push("chokidar-cli");
146
- }
147
- if (answer.prisma) {
148
- dependencies.push("prisma", "@prisma/client");
149
- }
150
- await installDependencies(projectPath, dependencies, true);
151
- if (!projectName) {
152
- execSync(`npx tsc --init`, { stdio: "inherit" });
153
- }
154
- if (answer.tailwindcss)
155
- execSync(`npx tailwindcss init -p`, { stdio: "inherit" });
156
- if (answer.prisma) {
157
- if (!fs.existsSync(path.join(projectPath, "prisma")))
158
- execSync(`npx prisma init`, { stdio: "inherit" });
159
- }
160
- await createDirectoryStructure(projectPath, answer);
161
- if (answer.swaggerDocs) {
162
- const swaggerDocsPath = path.join(
163
- projectPath,
164
- "src",
165
- "app",
166
- "swagger-docs"
167
- );
168
- // Check if the directory exists
169
- if (fs.existsSync(swaggerDocsPath)) {
170
- // If it exists and is not empty, remove it before cloning
171
- if (fs.readdirSync(swaggerDocsPath).length > 0) {
172
- console.log("Removing existing swagger-docs directory...");
173
- fs.rmSync(swaggerDocsPath, { recursive: true, force: true });
174
- }
175
- }
176
- // Clone the Git repository into the swagger-docs directory
177
- execSync(
178
- `git clone https://github.com/TheSteelNinjaCode/prisma-php-swagger-docs.git ${swaggerDocsPath}`,
179
- { stdio: "inherit" }
180
- );
181
- // delete the folder .git
182
- fs.rmSync(path.join(swaggerDocsPath, ".git"), {
183
- recursive: true,
184
- force: true,
185
- });
186
- }
187
- if (updateAnswer?.isUpdate) {
188
- const updateUninstallDependencies = [];
189
- if (updateAnswer.backendOnly) {
190
- nonBackendFiles.forEach((file) => {
191
- const filePath = path.join(projectPath, "src", "app", file);
192
- if (fs.existsSync(filePath)) {
193
- fs.unlinkSync(filePath); // Delete each file if it exists
194
- console.log(`${file} was deleted successfully.`);
195
- } else {
196
- console.log(`${file} does not exist.`);
197
- }
198
- });
199
- const backendOnlyFolders = ["js", "css"];
200
- backendOnlyFolders.forEach((folder) => {
201
- const folderPath = path.join(projectPath, "src", "app", folder);
202
- if (fs.existsSync(folderPath)) {
203
- fs.rmSync(folderPath, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
204
- console.log(`${folder} was deleted successfully.`);
205
- } else {
206
- console.log(`${folder} does not exist.`);
207
- }
208
- });
209
- }
210
- if (!updateAnswer.swaggerDocs) {
211
- const swaggerDocsFolder = path.join(
212
- projectPath,
213
- "src",
214
- "app",
215
- "swagger-docs"
216
- );
217
- if (fs.existsSync(swaggerDocsFolder)) {
218
- fs.rmSync(swaggerDocsFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
219
- console.log(`swagger-docs was deleted successfully.`);
220
- }
221
- const swaggerFiles = ["swagger-config.ts"];
222
- swaggerFiles.forEach((file) => {
223
- const filePath = path.join(projectPath, "settings", file);
224
- if (fs.existsSync(filePath)) {
225
- fs.unlinkSync(filePath); // Delete each file if it exists
226
- console.log(`${file} was deleted successfully.`);
227
- } else {
228
- console.log(`${file} does not exist.`);
229
- }
230
- });
231
- updateUninstallDependencies.push(
232
- "swagger-jsdoc",
233
- "@types/swagger-jsdoc",
234
- "prompts",
235
- "@types/prompts",
236
- "@prisma/internals"
237
- );
238
- }
239
- if (!updateAnswer.tailwindcss) {
240
- const tailwindFiles = ["postcss.config.js", "tailwind.config.js"];
241
- tailwindFiles.forEach((file) => {
242
- const filePath = path.join(projectPath, file);
243
- if (fs.existsSync(filePath)) {
244
- fs.unlinkSync(filePath); // Delete each file if it exists
245
- console.log(`${file} was deleted successfully.`);
246
- } else {
247
- console.log(`${file} does not exist.`);
248
- }
249
- });
250
- updateUninstallDependencies.push(
251
- "tailwindcss",
252
- "autoprefixer",
253
- "postcss",
254
- "postcss-cli",
255
- "cssnano"
256
- );
257
- }
258
- if (!updateAnswer.websocket) {
259
- const websocketFiles = [
260
- "restart-websocket.ts",
261
- "restart-websocket.bat",
262
- ];
263
- websocketFiles.forEach((file) => {
264
- const filePath = path.join(projectPath, "settings", file);
265
- if (fs.existsSync(filePath)) {
266
- fs.unlinkSync(filePath); // Delete each file if it exists
267
- console.log(`${file} was deleted successfully.`);
268
- } else {
269
- console.log(`${file} does not exist.`);
270
- }
271
- });
272
- const websocketFolder = path.join(
273
- projectPath,
274
- "src",
275
- "Lib",
276
- "Websocket"
277
- );
278
- if (fs.existsSync(websocketFolder)) {
279
- fs.rmSync(websocketFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
280
- console.log(`Websocket folder was deleted successfully.`);
281
- }
282
- updateUninstallDependencies.push("chokidar-cli");
283
- }
284
- if (!updateAnswer.prisma) {
285
- updateUninstallDependencies.push("prisma", "@prisma/client");
286
- }
287
- if (!updateAnswer.docker) {
288
- const dockerFiles = [
289
- ".dockerignore",
290
- "docker-compose.yml",
291
- "Dockerfile",
292
- "apache.conf",
293
- ];
294
- dockerFiles.forEach((file) => {
295
- const filePath = path.join(projectPath, file);
296
- if (fs.existsSync(filePath)) {
297
- fs.unlinkSync(filePath); // Delete each file if it exists
298
- console.log(`${file} was deleted successfully.`);
299
- } else {
300
- console.log(`${file} does not exist.`);
301
- }
302
- });
303
- }
304
- if (updateUninstallDependencies.length > 0) {
305
- await uninstallDependencies(
306
- projectPath,
307
- updateUninstallDependencies,
308
- true
309
- );
310
- }
311
- }
312
- const projectPathModified = projectPath.replace(/\\/g, "\\");
313
- const bsConfig = bsConfigUrls(projectPathModified);
314
- const phpGenerateClassPath = answer.prisma ? "src/Lib/Prisma/Classes" : "";
315
- const prismaPhpConfig = {
316
- projectName: answer.projectName,
317
- projectRootPath: projectPathModified,
318
- phpEnvironment: "XAMPP",
319
- phpRootPathExe: "C:\\xampp\\php\\php.exe",
320
- phpGenerateClassPath,
321
- bsTarget: bsConfig.bsTarget,
322
- bsPathRewrite: bsConfig.bsPathRewrite,
323
- backendOnly: answer.backendOnly,
324
- swaggerDocs: answer.swaggerDocs,
325
- tailwindcss: answer.tailwindcss,
326
- websocket: answer.websocket,
327
- prisma: answer.prisma,
328
- docker: answer.docker,
329
- version: latestVersionOfCreatePrismaPhpApp,
330
- excludeFiles: updateAnswer?.excludeFiles ?? [],
331
- };
332
- fs.writeFileSync(
333
- path.join(projectPath, "prisma-php.json"),
334
- JSON.stringify(prismaPhpConfig, null, 2),
335
- { flag: "w" }
336
- );
337
- if (updateAnswer?.isUpdate) {
338
- execSync(
339
- `C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar update`,
340
- {
341
- stdio: "inherit",
342
- }
343
- );
344
- } else {
345
- execSync(
346
- `C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar install`,
347
- {
348
- stdio: "inherit",
349
- }
350
- );
351
- }
352
- console.log("\n=========================\n");
353
- console.log(
354
- `${chalk.green(
355
- "Success!"
356
- )} Prisma PHP project successfully created in ${chalk.green(
357
- `${currentDir.replace(/\\/g, "/")}/${answer.projectName}`
358
- )}!`
359
- );
360
- console.log("\n=========================");
361
- } catch (error) {
362
- console.error("Error while creating the project:", error);
363
- process.exit(1);
364
- }
365
- }
366
- main();
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 t=e.substring(0,s+"\\htdocs\\".length).replace(/\\/g,"\\\\"),n=e.replace(new RegExp(`^${t}`),"").replace(/\\/g,"/");let c=`http://localhost/${n}`;c=c.endsWith("/")?c.slice(0,-1):c;const i=c.replace(/(?<!:)(\/\/+)/g,"/"),o=n.replace(/\/\/+/g,"/");return{bsTarget:`${i}/`,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={...n.scripts,projectName:"tsx settings/project-name.ts"};let c=[];if(s.tailwindcss&&(n.scripts={...n.scripts,tailwind:"postcss src/app/css/tailwind.css -o src/app/css/styles.css --watch"},c.push("tailwind")),s.websocket&&(n.scripts={...n.scripts,websocket:"tsx settings/restart-websocket.ts"},c.push("websocket")),s.docker&&(n.scripts={...n.scripts,docker:"docker-compose up"},c.push("docker")),s.swaggerDocs){const e=s.prisma?"tsx settings/auto-swagger-docs.ts":"tsx settings/swagger-config.ts";n.scripts={...n.scripts,"create-swagger-docs":e}}let i={...n.scripts};i.browserSync="tsx settings/bs-config.ts",i.dev=`npm-run-all projectName -p browserSync ${c.join(" ")}`,n.scripts=i,n.type="module",s.prisma&&(n.prisma={seed:"tsx prisma/seed.ts"}),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={...n.require,"cboden/ratchet":"^0.4.4"}),s.prisma&&(n.require={...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\nvar ws = new WebSocket("ws://localhost:8080");\n',fs.writeFileSync(t,n,"utf8")}function copyRecursiveSync(e,s,t){const n=fs.existsSync(e),c=n&&fs.statSync(e);if(n&&c&&c.isDirectory()){const n=s.toLowerCase();if(!t.websocket&&n.includes("src\\lib\\websocket"))return;if(!t.prisma&&n.includes("src\\lib\\prisma"))return;if(t.backendOnly&&n.includes("src\\app\\js")||t.backendOnly&&n.includes("src\\app\\css")||t.backendOnly&&n.includes("src\\app\\assets"))return;if(!t.swaggerDocs&&n.includes("src\\app\\swagger-docs"))return;const c=s.replace(/\\/g,"/");if(updateAnswer?.excludeFilePath?.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.ts")||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.backendOnly&&!t.swaggerDocs&&s.includes("layout.php"))return;if(!t.swaggerDocs&&s.includes("swagger-config.ts"))return;if(t.tailwindcss&&s.includes("index.css"))return;if((!t.swaggerDocs||!t.prisma)&&(s.includes("auto-swagger-docs.ts")||s.includes("prisma-sdk.ts")||s.includes("prisma-schema-config.json")||s.includes("prisma-schema.json")))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||(s.tailwindcss||(n='\n <link href="<?= Request::baseUrl; ?>/css/index.css" rel="stylesheet">'),n+='\n <script src="<?= Request::baseUrl; ?>/js/json5.min.js"><\/script>\n <script src="<?= Request::baseUrl; ?>/js/index.js"><\/script>');let c="";s.backendOnly||(c=s.tailwindcss?` <link href="<?= Request::baseUrl; ?>/css/styles.css" rel="stylesheet"> ${n}`:n);const i=c.length>0?"\n":"";e=e.replace("</head>",`${c}${i} \x3c!-- Dynamic Head --\x3e\n <?= MainLayout::outputHeadScripts() ?>\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){return!!updateAnswer?.isUpdate&&(updateAnswer?.excludeFilePath?.includes(e.replace(/\\/g,"/"))??!1)}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"},{src:"/app-gitignore",dest:"/.gitignore"}];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.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),c=path.join(e,t);if(checkExcludeFiles(c))return;const i=fs.readFileSync(n,"utf8");fs.writeFileSync(c,i,{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 c='# 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${c}`;await createOrUpdateEnvFile(e,s)}else await createOrUpdateEnvFile(e,c)}async function getAnswer(e={}){const s=[];e.projectName||s.push({type:"text",name:"projectName",message:"What is your project named?",initial:"my-app"}),e.backendOnly||s.push({type:"toggle",name:"backendOnly",message:`Would you like to create a ${chalk.blue("backend-only project")}?`,initial:!1,active:"Yes",inactive:"No"});const t=()=>{process.exit(0)},n=await prompts(s,{onCancel:t}),c=[];n.backendOnly||e.backendOnly?(e.swaggerDocs||c.push({type:"toggle",name:"swaggerDocs",message:`Would you like to use ${chalk.blue("Swagger Docs")}?`,initial:!1,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"}),e.docker||c.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"})):(e.swaggerDocs||c.push({type:"toggle",name:"swaggerDocs",message:`Would you like to use ${chalk.blue("Swagger Docs")}?`,initial:!1,active:"Yes",inactive:"No"}),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"}),e.docker||c.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"}));const i=await prompts(c,{onCancel:t});return{projectName:n.projectName?String(n.projectName).trim().replace(/ /g,"-"):e.projectName??"my-app",backendOnly:n.backendOnly??e.backendOnly??!1,swaggerDocs:i.swaggerDocs??e.swaggerDocs??!1,tailwindcss:i.tailwindcss??e.tailwindcss??!1,websocket:i.websocket??e.websocket??!1,prisma:i.prisma??e.prisma??!1,docker:i.docker??e.docker??!1}}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
+ try {
36
+ const args = process.argv.slice(2);
37
+ let projectName = args[0];
38
+ let answer = null;
39
+ if (projectName) {
40
+ let useBackendOnly = args.includes("--backend-only");
41
+ let useSwaggerDocs = args.includes("--swagger-docs");
42
+ let useTailwind = args.includes("--tailwindcss");
43
+ let useWebsocket = args.includes("--websocket");
44
+ let usePrisma = args.includes("--prisma");
45
+ let useDocker = args.includes("--docker");
46
+ const predefinedAnswers = {
47
+ projectName,
48
+ backendOnly: useBackendOnly,
49
+ swaggerDocs: useSwaggerDocs,
50
+ tailwindcss: useTailwind,
51
+ websocket: useWebsocket,
52
+ prisma: usePrisma,
53
+ docker: useDocker,
54
+ };
55
+ answer = await getAnswer(predefinedAnswers);
56
+ if (answer === null) {
57
+ console.log(chalk.red("Installation cancelled."));
58
+ return;
59
+ }
60
+ const currentDir = process.cwd();
61
+ const configPath = path.join(currentDir, "prisma-php.json");
62
+ const localSettings = readJsonFile(configPath);
63
+ let excludeFiles = [];
64
+ localSettings.excludeFiles?.map((file) => {
65
+ const filePath = path.join(currentDir, file);
66
+ if (fs.existsSync(filePath))
67
+ excludeFiles.push(filePath.replace(/\\/g, "/"));
68
+ });
69
+ updateAnswer = {
70
+ projectName,
71
+ backendOnly: answer?.backendOnly ?? false,
72
+ swaggerDocs: answer?.swaggerDocs ?? false,
73
+ tailwindcss: answer?.tailwindcss ?? false,
74
+ websocket: answer?.websocket ?? false,
75
+ prisma: answer?.prisma ?? false,
76
+ docker: answer?.docker ?? false,
77
+ isUpdate: true,
78
+ excludeFiles: localSettings.excludeFiles ?? [],
79
+ excludeFilePath: excludeFiles ?? [],
80
+ filePath: currentDir,
81
+ };
82
+ } else {
83
+ answer = await getAnswer();
84
+ }
85
+ if (answer === null) {
86
+ console.warn(chalk.red("Installation cancelled."));
87
+ return;
88
+ }
89
+ const latestVersionOfCreatePrismaPhpApp = await fetchPackageVersion(
90
+ "create-prisma-php-app"
91
+ );
92
+ const isCreatePrismaPhpAppInstalled = getInstalledPackageVersion(
93
+ "create-prisma-php-app"
94
+ );
95
+ if (isCreatePrismaPhpAppInstalled) {
96
+ if (
97
+ compareVersions(
98
+ isCreatePrismaPhpAppInstalled,
99
+ latestVersionOfCreatePrismaPhpApp
100
+ ) === -1
101
+ ) {
102
+ execSync(`npm uninstall -g create-prisma-php-app`, {
103
+ stdio: "inherit",
104
+ });
105
+ execSync(`npm install -g create-prisma-php-app`, {
106
+ stdio: "inherit",
107
+ });
108
+ }
109
+ } else {
110
+ execSync("npm install -g create-prisma-php-app", { stdio: "inherit" });
111
+ }
112
+ // Create the project directory
113
+ if (!projectName) fs.mkdirSync(answer.projectName);
114
+ const currentDir = process.cwd();
115
+ let projectPath = projectName
116
+ ? currentDir
117
+ : path.join(currentDir, answer.projectName);
118
+ if (!projectName) process.chdir(answer.projectName);
119
+ const dependencies = [
120
+ "typescript",
121
+ "@types/node",
122
+ "tsx",
123
+ "ts-node",
124
+ "http-proxy-middleware",
125
+ "chalk",
126
+ "npm-run-all",
127
+ "browser-sync",
128
+ "@types/browser-sync",
129
+ ];
130
+ if (answer.swaggerDocs) {
131
+ dependencies.push("swagger-jsdoc", "@types/swagger-jsdoc");
132
+ }
133
+ if (answer.swaggerDocs && answer.prisma) {
134
+ dependencies.push("prompts", "@types/prompts", "@prisma/internals");
135
+ }
136
+ if (answer.tailwindcss) {
137
+ dependencies.push(
138
+ "tailwindcss",
139
+ "autoprefixer",
140
+ "postcss",
141
+ "postcss-cli",
142
+ "cssnano"
143
+ );
144
+ }
145
+ if (answer.websocket) {
146
+ dependencies.push("chokidar-cli");
147
+ }
148
+ if (answer.prisma) {
149
+ dependencies.push("prisma", "@prisma/client");
150
+ }
151
+ await installDependencies(projectPath, dependencies, true);
152
+ if (!projectName) {
153
+ execSync(`npx tsc --init`, { stdio: "inherit" });
154
+ }
155
+ if (answer.tailwindcss)
156
+ execSync(`npx tailwindcss init -p`, { stdio: "inherit" });
157
+ if (answer.prisma) {
158
+ if (!fs.existsSync(path.join(projectPath, "prisma")))
159
+ execSync(`npx prisma init`, { stdio: "inherit" });
160
+ }
161
+ await createDirectoryStructure(projectPath, answer);
162
+ if (answer.swaggerDocs) {
163
+ const swaggerDocsPath = path.join(
164
+ projectPath,
165
+ "src",
166
+ "app",
167
+ "swagger-docs"
168
+ );
169
+ // Check if the directory exists
170
+ if (fs.existsSync(swaggerDocsPath)) {
171
+ // If it exists and is not empty, remove it before cloning
172
+ if (fs.readdirSync(swaggerDocsPath).length > 0) {
173
+ console.log("Removing existing swagger-docs directory...");
174
+ fs.rmSync(swaggerDocsPath, { recursive: true, force: true });
175
+ }
176
+ }
177
+ // Clone the Git repository into the swagger-docs directory
178
+ execSync(
179
+ `git clone https://github.com/TheSteelNinjaCode/prisma-php-swagger-docs.git ${swaggerDocsPath}`,
180
+ { stdio: "inherit" }
181
+ );
182
+ // delete the folder .git
183
+ fs.rmSync(path.join(swaggerDocsPath, ".git"), {
184
+ recursive: true,
185
+ force: true,
186
+ });
187
+ }
188
+ if (updateAnswer?.isUpdate) {
189
+ const updateUninstallDependencies = [];
190
+ if (updateAnswer.backendOnly) {
191
+ nonBackendFiles.forEach((file) => {
192
+ const filePath = path.join(projectPath, "src", "app", file);
193
+ if (fs.existsSync(filePath)) {
194
+ fs.unlinkSync(filePath); // Delete each file if it exists
195
+ console.log(`${file} was deleted successfully.`);
196
+ } else {
197
+ console.log(`${file} does not exist.`);
198
+ }
199
+ });
200
+ const backendOnlyFolders = ["js", "css"];
201
+ backendOnlyFolders.forEach((folder) => {
202
+ const folderPath = path.join(projectPath, "src", "app", folder);
203
+ if (fs.existsSync(folderPath)) {
204
+ fs.rmSync(folderPath, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
205
+ console.log(`${folder} was deleted successfully.`);
206
+ } else {
207
+ console.log(`${folder} does not exist.`);
208
+ }
209
+ });
210
+ }
211
+ if (!updateAnswer.swaggerDocs) {
212
+ const swaggerDocsFolder = path.join(
213
+ projectPath,
214
+ "src",
215
+ "app",
216
+ "swagger-docs"
217
+ );
218
+ if (fs.existsSync(swaggerDocsFolder)) {
219
+ fs.rmSync(swaggerDocsFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
220
+ console.log(`swagger-docs was deleted successfully.`);
221
+ }
222
+ const swaggerFiles = ["swagger-config.ts"];
223
+ swaggerFiles.forEach((file) => {
224
+ const filePath = path.join(projectPath, "settings", file);
225
+ if (fs.existsSync(filePath)) {
226
+ fs.unlinkSync(filePath); // Delete each file if it exists
227
+ console.log(`${file} was deleted successfully.`);
228
+ } else {
229
+ console.log(`${file} does not exist.`);
230
+ }
231
+ });
232
+ updateUninstallDependencies.push(
233
+ "swagger-jsdoc",
234
+ "@types/swagger-jsdoc",
235
+ "prompts",
236
+ "@types/prompts",
237
+ "@prisma/internals"
238
+ );
239
+ }
240
+ if (!updateAnswer.tailwindcss) {
241
+ const tailwindFiles = ["postcss.config.js", "tailwind.config.js"];
242
+ tailwindFiles.forEach((file) => {
243
+ const filePath = path.join(projectPath, file);
244
+ if (fs.existsSync(filePath)) {
245
+ fs.unlinkSync(filePath); // Delete each file if it exists
246
+ console.log(`${file} was deleted successfully.`);
247
+ } else {
248
+ console.log(`${file} does not exist.`);
249
+ }
250
+ });
251
+ updateUninstallDependencies.push(
252
+ "tailwindcss",
253
+ "autoprefixer",
254
+ "postcss",
255
+ "postcss-cli",
256
+ "cssnano"
257
+ );
258
+ }
259
+ if (!updateAnswer.websocket) {
260
+ const websocketFiles = [
261
+ "restart-websocket.ts",
262
+ "restart-websocket.bat",
263
+ ];
264
+ websocketFiles.forEach((file) => {
265
+ const filePath = path.join(projectPath, "settings", file);
266
+ if (fs.existsSync(filePath)) {
267
+ fs.unlinkSync(filePath); // Delete each file if it exists
268
+ console.log(`${file} was deleted successfully.`);
269
+ } else {
270
+ console.log(`${file} does not exist.`);
271
+ }
272
+ });
273
+ const websocketFolder = path.join(
274
+ projectPath,
275
+ "src",
276
+ "Lib",
277
+ "Websocket"
278
+ );
279
+ if (fs.existsSync(websocketFolder)) {
280
+ fs.rmSync(websocketFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
281
+ console.log(`Websocket folder was deleted successfully.`);
282
+ }
283
+ updateUninstallDependencies.push("chokidar-cli");
284
+ }
285
+ if (!updateAnswer.prisma) {
286
+ updateUninstallDependencies.push("prisma", "@prisma/client");
287
+ }
288
+ if (!updateAnswer.docker) {
289
+ const dockerFiles = [
290
+ ".dockerignore",
291
+ "docker-compose.yml",
292
+ "Dockerfile",
293
+ "apache.conf",
294
+ ];
295
+ dockerFiles.forEach((file) => {
296
+ const filePath = path.join(projectPath, file);
297
+ if (fs.existsSync(filePath)) {
298
+ fs.unlinkSync(filePath); // Delete each file if it exists
299
+ console.log(`${file} was deleted successfully.`);
300
+ } else {
301
+ console.log(`${file} does not exist.`);
302
+ }
303
+ });
304
+ }
305
+ if (updateUninstallDependencies.length > 0) {
306
+ await uninstallDependencies(
307
+ projectPath,
308
+ updateUninstallDependencies,
309
+ true
310
+ );
311
+ }
312
+ }
313
+ const projectPathModified = projectPath.replace(/\\/g, "\\");
314
+ const bsConfig = bsConfigUrls(projectPathModified);
315
+ const phpGenerateClassPath = answer.prisma ? "src/Lib/Prisma/Classes" : "";
316
+ const prismaPhpConfig = {
317
+ projectName: answer.projectName,
318
+ projectRootPath: projectPathModified,
319
+ phpEnvironment: "XAMPP",
320
+ phpRootPathExe: "C:\\xampp\\php\\php.exe",
321
+ phpGenerateClassPath,
322
+ bsTarget: bsConfig.bsTarget,
323
+ bsPathRewrite: bsConfig.bsPathRewrite,
324
+ backendOnly: answer.backendOnly,
325
+ swaggerDocs: answer.swaggerDocs,
326
+ tailwindcss: answer.tailwindcss,
327
+ websocket: answer.websocket,
328
+ prisma: answer.prisma,
329
+ docker: answer.docker,
330
+ version: latestVersionOfCreatePrismaPhpApp,
331
+ excludeFiles: updateAnswer?.excludeFiles ?? [],
332
+ };
333
+ fs.writeFileSync(
334
+ path.join(projectPath, "prisma-php.json"),
335
+ JSON.stringify(prismaPhpConfig, null, 2),
336
+ { flag: "w" }
337
+ );
338
+ if (updateAnswer?.isUpdate) {
339
+ execSync(
340
+ `C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar update`,
341
+ {
342
+ stdio: "inherit",
343
+ }
344
+ );
345
+ } else {
346
+ execSync(
347
+ `C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar install`,
348
+ {
349
+ stdio: "inherit",
350
+ }
351
+ );
352
+ }
353
+ console.log("\n=========================\n");
354
+ console.log(
355
+ `${chalk.green(
356
+ "Success!"
357
+ )} Prisma PHP project successfully created in ${chalk.green(
358
+ `${currentDir.replace(/\\/g, "/")}/${answer.projectName}`
359
+ )}!`
360
+ );
361
+ console.log("\n=========================");
362
+ } catch (error) {
363
+ console.error("Error while creating the project:", error);
364
+ process.exit(1);
365
+ }
366
+ }
367
+ main();