create-prisma-php-app 1.11.536 → 1.11.538

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.
Files changed (2) hide show
  1. package/dist/index.js +721 -601
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -10,43 +10,51 @@ const __filename = fileURLToPath(import.meta.url);
10
10
  const __dirname = path.dirname(__filename);
11
11
  let updateAnswer = null;
12
12
  function bsConfigUrls(projectSettings) {
13
- // Identify the base path dynamically up to and including 'htdocs'
14
- const htdocsIndex = projectSettings.PROJECT_ROOT_PATH.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 = projectSettings.PROJECT_ROOT_PATH.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 = projectSettings.PROJECT_ROOT_PATH.replace(new RegExp(`^${escapedBasePathToRemove}`), "").replace(/\\/g, "/");
28
- // Construct the Browser Sync command with the correct proxy URL, being careful not to affect the protocol part
29
- let proxyUrl = `http://localhost/${relativeWebPath}`;
30
- // Ensure the proxy URL does not end with a slash before appending '/public'
31
- proxyUrl = proxyUrl.endsWith("/") ? proxyUrl.slice(0, -1) : proxyUrl;
32
- // Clean the URL by replacing "//" with "/" but not affecting "http://"
33
- // We replace instances of "//" that are not preceded by ":"
34
- const cleanUrl = proxyUrl.replace(/(?<!:)(\/\/+)/g, "/");
35
- const cleanRelativeWebPath = relativeWebPath.replace(/\/\/+/g, "/");
36
- // Correct the relativeWebPath to ensure it does not start with a "/"
37
- const adjustedRelativeWebPath = cleanRelativeWebPath.startsWith("/")
38
- ? cleanRelativeWebPath.substring(1)
39
- : cleanRelativeWebPath;
13
+ // Identify the base path dynamically up to and including 'htdocs'
14
+ const htdocsIndex = projectSettings.PROJECT_ROOT_PATH.indexOf("\\htdocs\\");
15
+ if (htdocsIndex === -1) {
16
+ console.error(
17
+ "Invalid PROJECT_ROOT_PATH. The path does not contain \\htdocs\\"
18
+ );
40
19
  return {
41
- bsTarget: `${cleanUrl}/`,
42
- bsPathRewrite: {
43
- "^/": `/${adjustedRelativeWebPath}/`,
44
- },
20
+ bsTarget: "",
21
+ bsPathRewrite: {},
45
22
  };
23
+ }
24
+ // Extract the path up to and including 'htdocs\\'
25
+ const basePathToRemove = projectSettings.PROJECT_ROOT_PATH.substring(
26
+ 0,
27
+ htdocsIndex + "\\htdocs\\".length
28
+ );
29
+ // Escape backslashes for the regex pattern
30
+ const escapedBasePathToRemove = basePathToRemove.replace(/\\/g, "\\\\");
31
+ // Remove the base path and replace backslashes with forward slashes for URL compatibility
32
+ const relativeWebPath = projectSettings.PROJECT_ROOT_PATH.replace(
33
+ new RegExp(`^${escapedBasePathToRemove}`),
34
+ ""
35
+ ).replace(/\\/g, "/");
36
+ // Construct the Browser Sync command with the correct proxy URL, being careful not to affect the protocol part
37
+ let proxyUrl = `http://localhost/${relativeWebPath}`;
38
+ // Ensure the proxy URL does not end with a slash before appending '/public'
39
+ proxyUrl = proxyUrl.endsWith("/") ? proxyUrl.slice(0, -1) : proxyUrl;
40
+ // Clean the URL by replacing "//" with "/" but not affecting "http://"
41
+ // We replace instances of "//" that are not preceded by ":"
42
+ const cleanUrl = proxyUrl.replace(/(?<!:)(\/\/+)/g, "/");
43
+ const cleanRelativeWebPath = relativeWebPath.replace(/\/\/+/g, "/");
44
+ // Correct the relativeWebPath to ensure it does not start with a "/"
45
+ const adjustedRelativeWebPath = cleanRelativeWebPath.startsWith("/")
46
+ ? cleanRelativeWebPath.substring(1)
47
+ : cleanRelativeWebPath;
48
+ return {
49
+ bsTarget: `${cleanUrl}/`,
50
+ bsPathRewrite: {
51
+ "^/": `/${adjustedRelativeWebPath}/`,
52
+ },
53
+ };
46
54
  }
47
55
  function configureBrowserSyncCommand(baseDir) {
48
- // TypeScript content to write
49
- const bsConfigTsContent = `const { createProxyMiddleware } = require("http-proxy-middleware");
56
+ // TypeScript content to write
57
+ const bsConfigTsContent = `const { createProxyMiddleware } = require("http-proxy-middleware");
50
58
  const fs = require("fs");
51
59
 
52
60
  const jsonData = fs.readFileSync("prisma-php.json", "utf8");
@@ -72,291 +80,336 @@ module.exports = {
72
80
  open: false,
73
81
  ghostMode: false,
74
82
  };`;
75
- // Determine the path and write the bs-config.js
76
- const bsConfigPath = path.join(baseDir, "settings", "bs-config.cjs");
77
- fs.writeFileSync(bsConfigPath, bsConfigTsContent, "utf8");
78
- // Return the Browser Sync command string, using the cleaned URL
79
- return `browser-sync start --config settings/bs-config.cjs`;
83
+ // Determine the path and write the bs-config.js
84
+ const bsConfigPath = path.join(baseDir, "settings", "bs-config.cjs");
85
+ fs.writeFileSync(bsConfigPath, bsConfigTsContent, "utf8");
86
+ // Return the Browser Sync command string, using the cleaned URL
87
+ return `browser-sync start --config settings/bs-config.cjs`;
80
88
  }
81
89
  async function updatePackageJson(baseDir, answer) {
82
- const packageJsonPath = path.join(baseDir, "package.json");
83
- if (checkExcludeFiles(packageJsonPath))
84
- return;
85
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
86
- // Use the new function to configure the Browser Sync command
87
- const browserSyncCommand = configureBrowserSyncCommand(baseDir);
88
- packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), { projectName: "node settings/project-name.cjs" });
89
- let answersToInclude = [];
90
- if (answer.tailwindcss) {
91
- packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), { tailwind: "postcss ./src/app/css/tailwind.css -o ./src/app/css/styles.css --watch" });
92
- answersToInclude.push("tailwind");
93
- }
94
- if (answer.websocket) {
95
- packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), { websocket: "node ./settings/restart-websocket.cjs" });
96
- answersToInclude.push("websocket");
97
- }
98
- // if (answer.prisma) {
99
- // packageJson.scripts = {
100
- // ...packageJson.scripts,
101
- // postinstall: "prisma generate",
102
- // };
103
- // }
104
- // Initialize with existing scripts
105
- const updatedScripts = Object.assign({}, packageJson.scripts);
106
- // Conditionally add "browser-sync" command
107
- updatedScripts["browser-sync"] = browserSyncCommand;
108
- // Conditionally set the "dev" command
109
- updatedScripts.dev =
110
- answersToInclude.length > 0
111
- ? `npm-run-all --parallel projectName browser-sync ${answersToInclude.join(" ")}`
112
- : `npm-run-all --parallel projectName browser-sync`;
113
- // Finally, assign the updated scripts back to packageJson
114
- packageJson.scripts = updatedScripts;
115
- packageJson.type = "module";
116
- if (answer.prisma)
117
- packageJson.prisma = {
118
- seed: "node prisma/seed.js",
119
- };
120
- fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
90
+ const packageJsonPath = path.join(baseDir, "package.json");
91
+ if (checkExcludeFiles(packageJsonPath)) return;
92
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
93
+ // Use the new function to configure the Browser Sync command
94
+ const browserSyncCommand = configureBrowserSyncCommand(baseDir);
95
+ packageJson.scripts = Object.assign(Object.assign({}, packageJson.scripts), {
96
+ projectName: "node settings/project-name.cjs",
97
+ });
98
+ let answersToInclude = [];
99
+ if (answer.tailwindcss) {
100
+ packageJson.scripts = Object.assign(
101
+ Object.assign({}, packageJson.scripts),
102
+ {
103
+ tailwind:
104
+ "postcss ./src/app/css/tailwind.css -o ./src/app/css/styles.css --watch",
105
+ }
106
+ );
107
+ answersToInclude.push("tailwind");
108
+ }
109
+ if (answer.websocket) {
110
+ packageJson.scripts = Object.assign(
111
+ Object.assign({}, packageJson.scripts),
112
+ { websocket: "node ./settings/restart-websocket.cjs" }
113
+ );
114
+ answersToInclude.push("websocket");
115
+ }
116
+ // if (answer.prisma) {
117
+ // packageJson.scripts = {
118
+ // ...packageJson.scripts,
119
+ // postinstall: "prisma generate",
120
+ // };
121
+ // }
122
+ // Initialize with existing scripts
123
+ const updatedScripts = Object.assign({}, packageJson.scripts);
124
+ // Conditionally add "browser-sync" command
125
+ updatedScripts["browser-sync"] = browserSyncCommand;
126
+ // Conditionally set the "dev" command
127
+ updatedScripts.dev =
128
+ answersToInclude.length > 0
129
+ ? `npm-run-all --parallel projectName browser-sync ${answersToInclude.join(
130
+ " "
131
+ )}`
132
+ : `npm-run-all --parallel projectName browser-sync`;
133
+ // Finally, assign the updated scripts back to packageJson
134
+ packageJson.scripts = updatedScripts;
135
+ packageJson.type = "module";
136
+ if (answer.prisma)
137
+ packageJson.prisma = {
138
+ seed: "node prisma/seed.js",
139
+ };
140
+ fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
121
141
  }
122
142
  async function updateComposerJson(baseDir, answer) {
123
- const composerJsonPath = path.join(baseDir, "composer.json");
124
- if (checkExcludeFiles(composerJsonPath))
125
- return;
126
- let composerJson;
127
- // Check if the composer.json file exists
128
- if (fs.existsSync(composerJsonPath)) {
129
- // Read the current composer.json content
130
- const composerJsonContent = fs.readFileSync(composerJsonPath, "utf8");
131
- composerJson = JSON.parse(composerJsonContent);
132
- }
133
- else {
134
- console.error("composer.json does not exist.");
135
- return;
136
- }
137
- // Conditionally add WebSocket dependency
138
- if (answer.websocket) {
139
- composerJson.require = Object.assign(Object.assign({}, composerJson.require), { "cboden/ratchet": "^0.4.4" });
140
- }
141
- if (answer.prisma) {
142
- composerJson.require = Object.assign(Object.assign({}, composerJson.require), { "ramsey/uuid": "5.x-dev", "hidehalo/nanoid-php": "1.x-dev" });
143
- }
144
- // Write the modified composer.json back to the file
145
- fs.writeFileSync(composerJsonPath, JSON.stringify(composerJson, null, 2));
146
- console.log("composer.json updated successfully.");
143
+ const composerJsonPath = path.join(baseDir, "composer.json");
144
+ if (checkExcludeFiles(composerJsonPath)) return;
145
+ let composerJson;
146
+ // Check if the composer.json file exists
147
+ if (fs.existsSync(composerJsonPath)) {
148
+ // Read the current composer.json content
149
+ const composerJsonContent = fs.readFileSync(composerJsonPath, "utf8");
150
+ composerJson = JSON.parse(composerJsonContent);
151
+ } else {
152
+ console.error("composer.json does not exist.");
153
+ return;
154
+ }
155
+ // Conditionally add WebSocket dependency
156
+ if (answer.websocket) {
157
+ composerJson.require = Object.assign(
158
+ Object.assign({}, composerJson.require),
159
+ { "cboden/ratchet": "^0.4.4" }
160
+ );
161
+ }
162
+ if (answer.prisma) {
163
+ composerJson.require = Object.assign(
164
+ Object.assign({}, composerJson.require),
165
+ { "ramsey/uuid": "5.x-dev", "hidehalo/nanoid-php": "1.x-dev" }
166
+ );
167
+ }
168
+ // Write the modified composer.json back to the file
169
+ fs.writeFileSync(composerJsonPath, JSON.stringify(composerJson, null, 2));
170
+ console.log("composer.json updated successfully.");
147
171
  }
148
172
  async function updateIndexJsForWebSocket(baseDir, answer) {
149
- if (!answer.websocket) {
150
- return;
151
- }
152
- const indexPath = path.join(baseDir, "src", "app", "js", "index.js");
153
- if (checkExcludeFiles(indexPath))
154
- return;
155
- let indexContent = fs.readFileSync(indexPath, "utf8");
156
- // WebSocket initialization code to be appended
157
- const webSocketCode = `
173
+ if (!answer.websocket) {
174
+ return;
175
+ }
176
+ const indexPath = path.join(baseDir, "src", "app", "js", "index.js");
177
+ if (checkExcludeFiles(indexPath)) return;
178
+ let indexContent = fs.readFileSync(indexPath, "utf8");
179
+ // WebSocket initialization code to be appended
180
+ const webSocketCode = `
158
181
  // WebSocket initialization
159
182
  const ws = new WebSocket("ws://localhost:8080");
160
183
  `;
161
- // Append WebSocket code if user chose to use WebSocket
162
- indexContent += webSocketCode;
163
- fs.writeFileSync(indexPath, indexContent, "utf8");
164
- console.log("WebSocket code added to index.js successfully.");
184
+ // Append WebSocket code if user chose to use WebSocket
185
+ indexContent += webSocketCode;
186
+ fs.writeFileSync(indexPath, indexContent, "utf8");
187
+ console.log("WebSocket code added to index.js successfully.");
165
188
  }
166
189
  // This function updates the .gitignore file
167
190
  async function createUpdateGitignoreFile(baseDir, additions) {
168
- const gitignorePath = path.join(baseDir, ".gitignore");
169
- if (checkExcludeFiles(gitignorePath))
170
- return;
171
- // Check if the .gitignore file exists, create if it doesn't
172
- let gitignoreContent = "";
173
- if (fs.existsSync(gitignorePath)) {
174
- gitignoreContent = fs.readFileSync(gitignorePath, "utf8");
191
+ const gitignorePath = path.join(baseDir, ".gitignore");
192
+ if (checkExcludeFiles(gitignorePath)) return;
193
+ // Check if the .gitignore file exists, create if it doesn't
194
+ let gitignoreContent = "";
195
+ if (fs.existsSync(gitignorePath)) {
196
+ gitignoreContent = fs.readFileSync(gitignorePath, "utf8");
197
+ }
198
+ additions.forEach((addition) => {
199
+ if (!gitignoreContent.includes(addition)) {
200
+ gitignoreContent += `\n${addition}`;
175
201
  }
176
- additions.forEach((addition) => {
177
- if (!gitignoreContent.includes(addition)) {
178
- gitignoreContent += `\n${addition}`;
179
- }
180
- });
181
- // Ensure there's no leading newline if the file was just created
182
- gitignoreContent = gitignoreContent.trimStart();
183
- fs.writeFileSync(gitignorePath, gitignoreContent);
202
+ });
203
+ // Ensure there's no leading newline if the file was just created
204
+ gitignoreContent = gitignoreContent.trimStart();
205
+ fs.writeFileSync(gitignorePath, gitignoreContent);
184
206
  }
185
207
  // Recursive copy function
186
208
  function copyRecursiveSync(src, dest, answer) {
187
- console.log("🚀 ~ copyRecursiveSync ~ dest:", dest);
188
- console.log("🚀 ~ copyRecursiveSync ~ src:", src);
189
- const exists = fs.existsSync(src);
190
- const stats = exists && fs.statSync(src);
191
- const isDirectory = exists && stats && stats.isDirectory();
192
- if (isDirectory) {
193
- if (!fs.existsSync(dest))
194
- fs.mkdirSync(dest, { recursive: true });
195
- fs.readdirSync(src).forEach((childItemName) => {
196
- copyRecursiveSync(path.join(src, childItemName), path.join(dest, childItemName), answer);
197
- });
198
- }
199
- else {
200
- if (checkExcludeFiles(dest))
201
- return;
202
- if (!answer.tailwindcss &&
203
- (dest.includes("tailwind.css") || dest.includes("styles.css")))
204
- return;
205
- if (!answer.websocket &&
206
- (dest.includes("restart-websocket.cjs") ||
207
- dest.includes("restart-websocket.bat")))
208
- return;
209
- fs.copyFileSync(src, dest, 0);
210
- }
209
+ console.log("🚀 ~ copyRecursiveSync ~ dest:", dest);
210
+ console.log("🚀 ~ copyRecursiveSync ~ src:", src);
211
+ const exists = fs.existsSync(src);
212
+ const stats = exists && fs.statSync(src);
213
+ const isDirectory = exists && stats && stats.isDirectory();
214
+ if (isDirectory) {
215
+ const destLower = dest.toLowerCase();
216
+ console.log("🚀 ~ copyRecursiveSync ~ destLower:", destLower);
217
+ const destIncludeWebsocket = destLower.includes("src\\lib\\websocket");
218
+ console.log(
219
+ "🚀 ~ copyRecursiveSync ~ destIncludeWebsocket:",
220
+ destIncludeWebsocket
221
+ );
222
+ if (!answer.websocket && destLower.includes("src\\lib\\websocket")) return;
223
+ // if (!answer.prisma && dest.toLowerCase().includes("Prisma")) return;
224
+ if (!fs.existsSync(dest)) fs.mkdirSync(dest, { recursive: true });
225
+ fs.readdirSync(src).forEach((childItemName) => {
226
+ copyRecursiveSync(
227
+ path.join(src, childItemName),
228
+ path.join(dest, childItemName),
229
+ answer
230
+ );
231
+ });
232
+ } else {
233
+ if (checkExcludeFiles(dest)) return;
234
+ if (
235
+ !answer.tailwindcss &&
236
+ (dest.includes("tailwind.css") || dest.includes("styles.css"))
237
+ )
238
+ return;
239
+ if (
240
+ !answer.websocket &&
241
+ (dest.includes("restart-websocket.cjs") ||
242
+ dest.includes("restart-websocket.bat"))
243
+ )
244
+ return;
245
+ fs.copyFileSync(src, dest, 0);
246
+ }
211
247
  }
212
248
  // Function to execute the recursive copy for entire directories
213
249
  async function executeCopy(baseDir, directoriesToCopy, answer) {
214
- directoriesToCopy.forEach(({ srcDir, destDir }) => {
215
- const sourcePath = path.join(__dirname, srcDir);
216
- const destPath = path.join(baseDir, destDir);
217
- const destLower = destPath.toLowerCase();
218
- if (!answer.websocket &&
219
- (destLower.includes("src\\lib\\websocket") ||
220
- destLower.includes("src/lib/websocket")))
221
- return;
222
- // if (!answer.prisma && dest.toLowerCase().includes("Prisma")) return;
223
- copyRecursiveSync(sourcePath, destPath, answer);
224
- });
250
+ directoriesToCopy.forEach(({ srcDir, destDir }) => {
251
+ const sourcePath = path.join(__dirname, srcDir);
252
+ const destPath = path.join(baseDir, destDir);
253
+ copyRecursiveSync(sourcePath, destPath, answer);
254
+ });
225
255
  }
226
256
  function createOrUpdateTailwindConfig(baseDir) {
227
- console.log("🚀 ~ createOrUpdateTailwindConfig ~ baseDir:", baseDir);
228
- const filePath = path.join(baseDir, "tailwind.config.js");
229
- if (checkExcludeFiles(filePath))
230
- return;
231
- const newContent = [
232
- "./src/app/**/*.{html,js,php}",
233
- // Add more paths as needed
234
- ];
235
- let configData = fs.readFileSync(filePath, "utf8");
236
- console.log("🚀 ~ createOrUpdateTailwindConfig ~ configData:", configData);
237
- const contentArrayString = newContent
238
- .map((item) => ` "${item}"`)
239
- .join(",\n");
240
- configData = configData.replace(/content: \[\],/g, `content: [\n${contentArrayString}\n],`);
241
- fs.writeFileSync(filePath, configData, { flag: "w" });
242
- console.log(chalk.green("Tailwind configuration updated successfully."));
257
+ console.log("🚀 ~ createOrUpdateTailwindConfig ~ baseDir:", baseDir);
258
+ const filePath = path.join(baseDir, "tailwind.config.js");
259
+ if (checkExcludeFiles(filePath)) return;
260
+ const newContent = [
261
+ "./src/app/**/*.{html,js,php}",
262
+ // Add more paths as needed
263
+ ];
264
+ let configData = fs.readFileSync(filePath, "utf8");
265
+ console.log("🚀 ~ createOrUpdateTailwindConfig ~ configData:", configData);
266
+ const contentArrayString = newContent
267
+ .map((item) => ` "${item}"`)
268
+ .join(",\n");
269
+ configData = configData.replace(
270
+ /content: \[\],/g,
271
+ `content: [\n${contentArrayString}\n],`
272
+ );
273
+ fs.writeFileSync(filePath, configData, { flag: "w" });
274
+ console.log(chalk.green("Tailwind configuration updated successfully."));
243
275
  }
244
276
  function modifyPostcssConfig(baseDir) {
245
- const filePath = path.join(baseDir, "postcss.config.js");
246
- if (checkExcludeFiles(filePath))
247
- return;
248
- const newContent = `export default {
277
+ const filePath = path.join(baseDir, "postcss.config.js");
278
+ if (checkExcludeFiles(filePath)) return;
279
+ const newContent = `export default {
249
280
  plugins: {
250
281
  tailwindcss: {},
251
282
  autoprefixer: {},
252
283
  cssnano: {},
253
284
  },
254
285
  };`;
255
- fs.writeFileSync(filePath, newContent, { flag: "w" });
256
- console.log(chalk.green("postcss.config.js updated successfully."));
286
+ fs.writeFileSync(filePath, newContent, { flag: "w" });
287
+ console.log(chalk.green("postcss.config.js updated successfully."));
257
288
  }
258
289
  function modifyLayoutPHP(baseDir, useTailwind) {
259
- const layoutPath = path.join(baseDir, "src", "app", "layout.php");
260
- if (checkExcludeFiles(layoutPath))
261
- return;
262
- try {
263
- let indexContent = fs.readFileSync(layoutPath, "utf8");
264
- 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">`;
265
- // Tailwind CSS link or CDN script
266
- const tailwindLink = useTailwind
267
- ? ` <link href="<?php echo $baseUrl; ?>css/styles.css" rel="stylesheet"> ${stylesAndLinks}`
268
- : ` <script src="https://cdn.tailwindcss.com"></script> ${stylesAndLinks}`;
269
- // Insert before the closing </head> tag
270
- indexContent = indexContent.replace("</head>", `${tailwindLink}\n</head>`);
271
- fs.writeFileSync(layoutPath, indexContent, { flag: "w" });
272
- console.log(chalk.green(`index.php modified successfully for ${useTailwind ? "local Tailwind CSS" : "Tailwind CSS CDN"}.`));
273
- }
274
- catch (error) {
275
- console.error(chalk.red("Error modifying index.php:"), error);
276
- }
290
+ const layoutPath = path.join(baseDir, "src", "app", "layout.php");
291
+ if (checkExcludeFiles(layoutPath)) return;
292
+ try {
293
+ let indexContent = fs.readFileSync(layoutPath, "utf8");
294
+ 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">`;
295
+ // Tailwind CSS link or CDN script
296
+ const tailwindLink = useTailwind
297
+ ? ` <link href="<?php echo $baseUrl; ?>css/styles.css" rel="stylesheet"> ${stylesAndLinks}`
298
+ : ` <script src="https://cdn.tailwindcss.com"></script> ${stylesAndLinks}`;
299
+ // Insert before the closing </head> tag
300
+ indexContent = indexContent.replace("</head>", `${tailwindLink}\n</head>`);
301
+ fs.writeFileSync(layoutPath, indexContent, { flag: "w" });
302
+ console.log(
303
+ chalk.green(
304
+ `index.php modified successfully for ${
305
+ useTailwind ? "local Tailwind CSS" : "Tailwind CSS CDN"
306
+ }.`
307
+ )
308
+ );
309
+ } catch (error) {
310
+ console.error(chalk.red("Error modifying index.php:"), error);
311
+ }
277
312
  }
278
313
  // This function updates or creates the .env file
279
314
  async function createOrUpdateEnvFile(baseDir, content) {
280
- const envPath = path.join(baseDir, ".env");
281
- if (checkExcludeFiles(envPath))
282
- return;
283
- let envContent = fs.existsSync(envPath)
284
- ? fs.readFileSync(envPath, "utf8")
285
- : "";
286
- // Check if the content already exists in the .env file
287
- if (!envContent.includes(content)) {
288
- envContent += `${envContent !== "" ? "\n\n" : ""}${content}`;
289
- fs.writeFileSync(envPath, envContent, { flag: "w" });
290
- }
291
- else {
292
- console.log(".env file already contains the content.");
293
- }
315
+ const envPath = path.join(baseDir, ".env");
316
+ if (checkExcludeFiles(envPath)) return;
317
+ let envContent = fs.existsSync(envPath)
318
+ ? fs.readFileSync(envPath, "utf8")
319
+ : "";
320
+ // Check if the content already exists in the .env file
321
+ if (!envContent.includes(content)) {
322
+ envContent += `${envContent !== "" ? "\n\n" : ""}${content}`;
323
+ fs.writeFileSync(envPath, envContent, { flag: "w" });
324
+ } else {
325
+ console.log(".env file already contains the content.");
326
+ }
294
327
  }
295
328
  function checkExcludeFiles(destPath) {
296
- var _a, _b;
297
- if (!(updateAnswer === null || updateAnswer === void 0 ? void 0 : updateAnswer.isUpdate))
298
- return false;
299
- 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);
329
+ var _a, _b;
330
+ if (
331
+ !(updateAnswer === null || updateAnswer === void 0
332
+ ? void 0
333
+ : updateAnswer.isUpdate)
334
+ )
335
+ return false;
336
+ return (_b =
337
+ (_a =
338
+ updateAnswer === null || updateAnswer === void 0
339
+ ? void 0
340
+ : updateAnswer.excludeFilePath) === null || _a === void 0
341
+ ? void 0
342
+ : _a.includes(destPath.replace(/\\/g, "/"))) !== null && _b !== void 0
343
+ ? _b
344
+ : false;
300
345
  }
301
346
  async function createDirectoryStructure(baseDir, answer) {
302
- console.log("🚀 ~ baseDir:", baseDir);
303
- console.log("🚀 ~ answer:", answer);
304
- const filesToCopy = [
305
- { src: "/bootstrap.php", dest: "/bootstrap.php" },
306
- { src: "/.htaccess", dest: "/.htaccess" },
307
- { src: "/../composer.json", dest: "/composer.json" },
308
- ];
309
- if (updateAnswer === null || updateAnswer === void 0 ? void 0 : updateAnswer.isUpdate) {
310
- filesToCopy.push({ src: "/.env", dest: "/.env" }, { src: "/tsconfig.json", dest: "/tsconfig.json" });
311
- if (updateAnswer.tailwindcss) {
312
- filesToCopy.push({ src: "/postcss.config.js", dest: "/postcss.config.js" }, { src: "/tailwind.config.js", dest: "/tailwind.config.js" });
313
- }
347
+ console.log("🚀 ~ baseDir:", baseDir);
348
+ console.log("🚀 ~ answer:", answer);
349
+ const filesToCopy = [
350
+ { src: "/bootstrap.php", dest: "/bootstrap.php" },
351
+ { src: "/.htaccess", dest: "/.htaccess" },
352
+ { src: "/../composer.json", dest: "/composer.json" },
353
+ ];
354
+ if (
355
+ updateAnswer === null || updateAnswer === void 0
356
+ ? void 0
357
+ : updateAnswer.isUpdate
358
+ ) {
359
+ filesToCopy.push(
360
+ { src: "/.env", dest: "/.env" },
361
+ { src: "/tsconfig.json", dest: "/tsconfig.json" }
362
+ );
363
+ if (updateAnswer.tailwindcss) {
364
+ filesToCopy.push(
365
+ { src: "/postcss.config.js", dest: "/postcss.config.js" },
366
+ { src: "/tailwind.config.js", dest: "/tailwind.config.js" }
367
+ );
314
368
  }
315
- const directoriesToCopy = [
316
- {
317
- srcDir: "/settings",
318
- destDir: "/settings",
319
- },
320
- {
321
- srcDir: "/src",
322
- destDir: "/src",
323
- },
324
- ];
325
- if (answer.prisma) {
326
- directoriesToCopy.push({
327
- srcDir: "/prisma",
328
- destDir: "/prisma",
329
- });
330
- }
331
- console.log("🚀 ~ directoriesToCopy:", directoriesToCopy);
332
- filesToCopy.forEach(({ src, dest }) => {
333
- const sourcePath = path.join(__dirname, src);
334
- const destPath = path.join(baseDir, dest);
335
- if (checkExcludeFiles(destPath))
336
- return;
337
- const code = fs.readFileSync(sourcePath, "utf8");
338
- fs.writeFileSync(destPath, code, { flag: "w" });
369
+ }
370
+ const directoriesToCopy = [
371
+ {
372
+ srcDir: "/settings",
373
+ destDir: "/settings",
374
+ },
375
+ {
376
+ srcDir: "/src",
377
+ destDir: "/src",
378
+ },
379
+ ];
380
+ if (answer.prisma) {
381
+ directoriesToCopy.push({
382
+ srcDir: "/prisma",
383
+ destDir: "/prisma",
339
384
  });
340
- await executeCopy(baseDir, directoriesToCopy, answer);
341
- await updatePackageJson(baseDir, answer);
342
- await updateComposerJson(baseDir, answer);
343
- await updateIndexJsForWebSocket(baseDir, answer);
344
- if (answer.tailwindcss) {
345
- createOrUpdateTailwindConfig(baseDir);
346
- modifyLayoutPHP(baseDir, true);
347
- modifyPostcssConfig(baseDir);
348
- }
349
- else {
350
- modifyLayoutPHP(baseDir, false);
351
- }
352
- const prismaEnvContent = `# Environment variables declared in this file are automatically made available to Prisma.
385
+ }
386
+ console.log("🚀 ~ directoriesToCopy:", directoriesToCopy);
387
+ filesToCopy.forEach(({ src, dest }) => {
388
+ const sourcePath = path.join(__dirname, src);
389
+ const destPath = path.join(baseDir, dest);
390
+ if (checkExcludeFiles(destPath)) return;
391
+ const code = fs.readFileSync(sourcePath, "utf8");
392
+ fs.writeFileSync(destPath, code, { flag: "w" });
393
+ });
394
+ await executeCopy(baseDir, directoriesToCopy, answer);
395
+ await updatePackageJson(baseDir, answer);
396
+ await updateComposerJson(baseDir, answer);
397
+ await updateIndexJsForWebSocket(baseDir, answer);
398
+ if (answer.tailwindcss) {
399
+ createOrUpdateTailwindConfig(baseDir);
400
+ modifyLayoutPHP(baseDir, true);
401
+ modifyPostcssConfig(baseDir);
402
+ } else {
403
+ modifyLayoutPHP(baseDir, false);
404
+ }
405
+ const prismaEnvContent = `# Environment variables declared in this file are automatically made available to Prisma.
353
406
  # See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema
354
407
 
355
408
  # Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
356
409
  # See the documentation for all the connection string options: https://pris.ly/d/connection-strings
357
410
 
358
411
  DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"`;
359
- const prismaPHPEnvContent = `# Prisma PHP Auth Secret Key For development only - Change this in production
412
+ const prismaPHPEnvContent = `# Prisma PHP Auth Secret Key For development only - Change this in production
360
413
  AUTH_SECRET=uxsjXVPHN038DEYls2Kw0QUgBcXKUyrjv416nIFWPY4=
361
414
 
362
415
  # PHPMailer
@@ -367,84 +420,93 @@ AUTH_SECRET=uxsjXVPHN038DEYls2Kw0QUgBcXKUyrjv416nIFWPY4=
367
420
  # SMTP_ENCRYPTION=ssl or tls
368
421
  # MAIL_FROM=john.doe@gmail.com
369
422
  # MAIL_FROM_NAME="John Doe"`;
370
- let envContent = prismaPHPEnvContent;
371
- if (answer.prisma) {
372
- envContent = `${prismaEnvContent}\n\n${prismaPHPEnvContent}`;
373
- await createOrUpdateEnvFile(baseDir, envContent);
374
- }
375
- else {
376
- await createOrUpdateEnvFile(baseDir, envContent);
377
- }
378
- // Add vendor to .gitignore
379
- await createUpdateGitignoreFile(baseDir, ["vendor", ".env", "node_modules"]);
423
+ let envContent = prismaPHPEnvContent;
424
+ if (answer.prisma) {
425
+ envContent = `${prismaEnvContent}\n\n${prismaPHPEnvContent}`;
426
+ await createOrUpdateEnvFile(baseDir, envContent);
427
+ } else {
428
+ await createOrUpdateEnvFile(baseDir, envContent);
429
+ }
430
+ // Add vendor to .gitignore
431
+ await createUpdateGitignoreFile(baseDir, ["vendor", ".env", "node_modules"]);
380
432
  }
381
433
  async function getAnswer(predefinedAnswers = {}) {
382
- var _a, _b, _c, _d;
383
- console.log("🚀 ~ predefinedAnswers:", predefinedAnswers);
384
- const questionsArray = [];
385
- if (!predefinedAnswers.projectName) {
386
- questionsArray.push({
387
- type: "text",
388
- name: "projectName",
389
- message: "What is your project named?",
390
- initial: "my-app",
391
- });
392
- }
393
- if (!predefinedAnswers.tailwindcss) {
394
- questionsArray.push({
395
- type: "toggle",
396
- name: "tailwindcss",
397
- message: `Would you like to use ${chalk.blue("Tailwind CSS")}?`,
398
- initial: true,
399
- active: "Yes",
400
- inactive: "No",
401
- });
402
- }
403
- if (!predefinedAnswers.websocket) {
404
- questionsArray.push({
405
- type: "toggle",
406
- name: "websocket",
407
- message: `Would you like to use ${chalk.blue("Websocket")}?`,
408
- initial: true,
409
- active: "Yes",
410
- inactive: "No",
411
- });
412
- }
413
- if (!predefinedAnswers.prisma) {
414
- questionsArray.push({
415
- type: "toggle",
416
- name: "prisma",
417
- message: `Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,
418
- initial: true,
419
- active: "Yes",
420
- inactive: "No",
421
- });
434
+ var _a, _b, _c, _d;
435
+ console.log("🚀 ~ predefinedAnswers:", predefinedAnswers);
436
+ const questionsArray = [];
437
+ if (!predefinedAnswers.projectName) {
438
+ questionsArray.push({
439
+ type: "text",
440
+ name: "projectName",
441
+ message: "What is your project named?",
442
+ initial: "my-app",
443
+ });
444
+ }
445
+ if (!predefinedAnswers.tailwindcss) {
446
+ questionsArray.push({
447
+ type: "toggle",
448
+ name: "tailwindcss",
449
+ message: `Would you like to use ${chalk.blue("Tailwind CSS")}?`,
450
+ initial: true,
451
+ active: "Yes",
452
+ inactive: "No",
453
+ });
454
+ }
455
+ if (!predefinedAnswers.websocket) {
456
+ questionsArray.push({
457
+ type: "toggle",
458
+ name: "websocket",
459
+ message: `Would you like to use ${chalk.blue("Websocket")}?`,
460
+ initial: true,
461
+ active: "Yes",
462
+ inactive: "No",
463
+ });
464
+ }
465
+ if (!predefinedAnswers.prisma) {
466
+ questionsArray.push({
467
+ type: "toggle",
468
+ name: "prisma",
469
+ message: `Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,
470
+ initial: true,
471
+ active: "Yes",
472
+ inactive: "No",
473
+ });
474
+ }
475
+ const questions = questionsArray;
476
+ console.log("🚀 ~ questions:", questions);
477
+ const onCancel = () => {
478
+ console.log(chalk.red("Operation cancelled by the user."));
479
+ process.exit(0);
480
+ };
481
+ try {
482
+ const response = await prompts(questions, { onCancel });
483
+ console.log("🚀 ~ response:", response);
484
+ if (Object.keys(response).length === 0) {
485
+ return null;
422
486
  }
423
- const questions = questionsArray;
424
- console.log("🚀 ~ questions:", questions);
425
- const onCancel = () => {
426
- console.log(chalk.red("Operation cancelled by the user."));
427
- process.exit(0);
487
+ return {
488
+ projectName: response.projectName
489
+ ? String(response.projectName).trim().replace(/ /g, "-")
490
+ : (_a = predefinedAnswers.projectName) !== null && _a !== void 0
491
+ ? _a
492
+ : "my-app",
493
+ tailwindcss:
494
+ (_b = response.tailwindcss) !== null && _b !== void 0
495
+ ? _b
496
+ : predefinedAnswers.tailwindcss,
497
+ websocket:
498
+ (_c = response.websocket) !== null && _c !== void 0
499
+ ? _c
500
+ : predefinedAnswers.websocket,
501
+ prisma:
502
+ (_d = response.prisma) !== null && _d !== void 0
503
+ ? _d
504
+ : predefinedAnswers.prisma,
428
505
  };
429
- try {
430
- const response = await prompts(questions, { onCancel });
431
- console.log("🚀 ~ response:", response);
432
- if (Object.keys(response).length === 0) {
433
- return null;
434
- }
435
- return {
436
- projectName: response.projectName
437
- ? String(response.projectName).trim().replace(/ /g, "-")
438
- : (_a = predefinedAnswers.projectName) !== null && _a !== void 0 ? _a : "my-app",
439
- tailwindcss: (_b = response.tailwindcss) !== null && _b !== void 0 ? _b : predefinedAnswers.tailwindcss,
440
- websocket: (_c = response.websocket) !== null && _c !== void 0 ? _c : predefinedAnswers.websocket,
441
- prisma: (_d = response.prisma) !== null && _d !== void 0 ? _d : predefinedAnswers.prisma,
442
- };
443
- }
444
- catch (error) {
445
- console.error(chalk.red("Prompt error:"), error);
446
- return null;
447
- }
506
+ } catch (error) {
507
+ console.error(chalk.red("Prompt error:"), error);
508
+ return null;
509
+ }
448
510
  }
449
511
  /**
450
512
  * Install dependencies in the specified directory.
@@ -453,271 +515,329 @@ async function getAnswer(predefinedAnswers = {}) {
453
515
  * @param {boolean} [isDev=false] - Whether to install the dependencies as devDependencies.
454
516
  */
455
517
  async function installDependencies(baseDir, dependencies, isDev = false) {
456
- console.log("Initializing new Node.js project...");
457
- // Initialize a package.json if it doesn't exist
458
- if (!fs.existsSync(path.join(baseDir, "package.json")))
459
- execSync("npm init -y", {
460
- stdio: "inherit",
461
- cwd: baseDir,
462
- });
463
- // Log the dependencies being installed
464
- console.log(`${isDev ? "Installing development dependencies" : "Installing dependencies"}:`);
465
- dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
466
- // Prepare the npm install command with the appropriate flag for dev dependencies
467
- const npmInstallCommand = `npm install ${isDev ? "--save-dev" : ""} ${dependencies.join(" ")}`;
468
- // Execute the npm install command
469
- execSync(npmInstallCommand, {
470
- stdio: "inherit",
471
- cwd: baseDir,
518
+ console.log("Initializing new Node.js project...");
519
+ // Initialize a package.json if it doesn't exist
520
+ if (!fs.existsSync(path.join(baseDir, "package.json")))
521
+ execSync("npm init -y", {
522
+ stdio: "inherit",
523
+ cwd: baseDir,
472
524
  });
525
+ // Log the dependencies being installed
526
+ console.log(
527
+ `${
528
+ isDev ? "Installing development dependencies" : "Installing dependencies"
529
+ }:`
530
+ );
531
+ dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
532
+ // Prepare the npm install command with the appropriate flag for dev dependencies
533
+ const npmInstallCommand = `npm install ${
534
+ isDev ? "--save-dev" : ""
535
+ } ${dependencies.join(" ")}`;
536
+ // Execute the npm install command
537
+ execSync(npmInstallCommand, {
538
+ stdio: "inherit",
539
+ cwd: baseDir,
540
+ });
473
541
  }
474
542
  async function uninstallDependencies(baseDir, dependencies, isDev = false) {
475
- console.log("Uninstalling dependencies:");
476
- dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
477
- // Prepare the npm uninstall command with the appropriate flag for dev dependencies
478
- const npmUninstallCommand = `npm uninstall ${isDev ? "--save-dev" : "--save"} ${dependencies.join(" ")}`;
479
- // Execute the npm uninstall command
480
- execSync(npmUninstallCommand, {
481
- stdio: "inherit",
482
- cwd: baseDir,
483
- });
543
+ console.log("Uninstalling dependencies:");
544
+ dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
545
+ // Prepare the npm uninstall command with the appropriate flag for dev dependencies
546
+ const npmUninstallCommand = `npm uninstall ${
547
+ isDev ? "--save-dev" : "--save"
548
+ } ${dependencies.join(" ")}`;
549
+ // Execute the npm uninstall command
550
+ execSync(npmUninstallCommand, {
551
+ stdio: "inherit",
552
+ cwd: baseDir,
553
+ });
484
554
  }
485
555
  function fetchPackageVersion(packageName) {
486
- return new Promise((resolve, reject) => {
487
- https
488
- .get(`https://registry.npmjs.org/${packageName}`, (res) => {
489
- let data = "";
490
- res.on("data", (chunk) => (data += chunk));
491
- res.on("end", () => {
492
- try {
493
- const parsed = JSON.parse(data);
494
- resolve(parsed["dist-tags"].latest);
495
- }
496
- catch (error) {
497
- reject(new Error("Failed to parse JSON response"));
498
- }
499
- });
500
- })
501
- .on("error", (err) => reject(err));
502
- });
556
+ return new Promise((resolve, reject) => {
557
+ https
558
+ .get(`https://registry.npmjs.org/${packageName}`, (res) => {
559
+ let data = "";
560
+ res.on("data", (chunk) => (data += chunk));
561
+ res.on("end", () => {
562
+ try {
563
+ const parsed = JSON.parse(data);
564
+ resolve(parsed["dist-tags"].latest);
565
+ } catch (error) {
566
+ reject(new Error("Failed to parse JSON response"));
567
+ }
568
+ });
569
+ })
570
+ .on("error", (err) => reject(err));
571
+ });
503
572
  }
504
573
  const readJsonFile = (filePath) => {
505
- const jsonData = fs.readFileSync(filePath, "utf8");
506
- return JSON.parse(jsonData);
574
+ const jsonData = fs.readFileSync(filePath, "utf8");
575
+ return JSON.parse(jsonData);
507
576
  };
508
577
  async function main() {
509
- var _a, _b, _c, _d, _e, _f;
510
- try {
511
- const args = process.argv.slice(2);
512
- let projectName = args[0];
513
- let answer = null;
514
- if (projectName) {
515
- let useTailwind = args.includes("--tailwindcss");
516
- let useWebsocket = args.includes("--websocket");
517
- let usePrisma = args.includes("--prisma");
518
- const predefinedAnswers = {
519
- projectName,
520
- tailwindcss: useTailwind,
521
- websocket: useWebsocket,
522
- prisma: usePrisma,
523
- };
524
- console.log("🚀 ~ main ~ predefinedAnswers:", predefinedAnswers);
525
- answer = await getAnswer(predefinedAnswers);
526
- if (answer === null) {
527
- console.log(chalk.red("Installation cancelled."));
528
- return;
529
- }
530
- const currentDir = process.cwd();
531
- const configPath = path.join(currentDir, "prisma-php.json");
532
- const localSettings = readJsonFile(configPath);
533
- let excludeFiles = [];
534
- (_a = localSettings.excludeFiles) === null || _a === void 0 ? void 0 : _a.map((file) => {
535
- const filePath = path.join(currentDir, file);
536
- if (fs.existsSync(filePath))
537
- excludeFiles.push(filePath.replace(/\\/g, "/"));
538
- });
539
- updateAnswer = {
540
- projectName,
541
- tailwindcss: (_b = answer === null || answer === void 0 ? void 0 : answer.tailwindcss) !== null && _b !== void 0 ? _b : false,
542
- websocket: (_c = answer === null || answer === void 0 ? void 0 : answer.websocket) !== null && _c !== void 0 ? _c : false,
543
- prisma: (_d = answer === null || answer === void 0 ? void 0 : answer.prisma) !== null && _d !== void 0 ? _d : false,
544
- isUpdate: true,
545
- excludeFiles: (_e = localSettings.excludeFiles) !== null && _e !== void 0 ? _e : [],
546
- excludeFilePath: excludeFiles !== null && excludeFiles !== void 0 ? excludeFiles : [],
547
- filePath: currentDir,
548
- };
549
- }
550
- else {
551
- answer = await getAnswer();
552
- }
553
- if (answer === null) {
554
- console.log(chalk.red("Installation cancelled."));
555
- return;
556
- }
557
- execSync(`npm install -g create-prisma-php-app`, { stdio: "inherit" }); // TODO: Uncomment this line before publishing the package
558
- // Support for browser-sync
559
- execSync(`npm install -g browser-sync`, { stdio: "inherit" });
560
- // Create the project directory
561
- if (!projectName)
562
- fs.mkdirSync(answer.projectName);
563
- const currentDir = process.cwd();
564
- let projectPath = projectName
565
- ? currentDir
566
- : path.join(currentDir, answer.projectName);
567
- if (!projectName)
568
- process.chdir(answer.projectName);
569
- const dependencies = [
570
- "typescript",
571
- "@types/node",
572
- "ts-node",
573
- "http-proxy-middleware@^3.0.0",
574
- "npm-run-all",
575
- ];
576
- if (answer.tailwindcss) {
577
- dependencies.push("tailwindcss", "autoprefixer", "postcss", "postcss-cli", "cssnano");
578
- }
579
- if (answer.websocket) {
580
- dependencies.push("chokidar-cli");
581
- }
582
- if (answer.prisma) {
583
- dependencies.push("prisma", "@prisma/client");
584
- }
585
- await installDependencies(projectPath, dependencies, true);
586
- if (!projectName) {
587
- execSync(`npx tsc --init`, { stdio: "inherit" });
588
- }
589
- if (answer.tailwindcss)
590
- execSync(`npx tailwindcss init -p`, { stdio: "inherit" });
591
- if (answer.prisma) {
592
- if (!fs.existsSync(path.join(projectPath, "prisma")))
593
- execSync(`npx prisma init`, { stdio: "inherit" });
594
- }
595
- await createDirectoryStructure(projectPath, answer);
596
- const publicDirPath = path.join(projectPath, "public");
597
- if (!fs.existsSync(publicDirPath)) {
598
- fs.mkdirSync(publicDirPath);
599
- }
600
- // if (!answer.tailwindcss) {
601
- // const cssPath = path.join(projectPath, "src", "app", "css");
602
- // const tailwindFiles = ["tailwind.css", "styles.css"];
603
- // tailwindFiles.forEach((file) => {
604
- // const filePath = path.join(cssPath, file);
605
- // if (fs.existsSync(filePath)) {
606
- // fs.unlinkSync(filePath); // Delete each file if it exists
607
- // console.log(`${file} was deleted successfully.`);
608
- // } else {
609
- // console.log(`${file} does not exist.`);
610
- // }
611
- // });
612
- // }
613
- // Update websocket if not chosen by the user
614
- // if (!answer.websocket) {
615
- // const wsPath = path.join(projectPath, "src", "Lib", "Websocket");
616
- // // Check if the websocket directory exists
617
- // if (fs.existsSync(wsPath)) {
618
- // // Use fs.rmSync with recursive option set to true to delete the directory and its contents
619
- // fs.rmSync(wsPath, { recursive: true, force: true }); // force option is not necessary but can be used to ensure deletion
620
- // console.log("Websocket directory was deleted successfully.");
621
- // } else {
622
- // console.log("Websocket directory does not exist.");
623
- // }
624
- // // Update settings directory if websocket is not chosen
625
- // const settingsPath = path.join(projectPath, "settings");
626
- // const websocketFiles = ["restart-websocket.cjs", "restart-websocket.bat"];
627
- // websocketFiles.forEach((file) => {
628
- // const filePath = path.join(settingsPath, file);
629
- // if (fs.existsSync(filePath)) {
630
- // fs.unlinkSync(filePath); // Delete each file if it exists
631
- // console.log(`${file} was deleted successfully.`);
632
- // } else {
633
- // console.log(`${file} does not exist.`);
634
- // }
635
- // });
636
- // }
637
- if (!answer.prisma) {
638
- const prismaPath = path.join(projectPath, "prisma");
639
- const prismClassPath = path.join(projectPath, "src", "Lib", "Prisma");
640
- // Check if the prisma directory exists
641
- if (fs.existsSync(prismaPath)) {
642
- // Use fs.rmSync with recursive option set to true to delete the directory and its contents
643
- fs.rmSync(prismaPath, { recursive: true, force: true }); // force option is not necessary but can be used to ensure deletion
644
- console.log("Prisma directory was deleted successfully.");
645
- }
646
- else {
647
- console.log("Prisma directory does not exist.");
648
- }
649
- // Check if the prisma class directory exists
650
- if (fs.existsSync(prismClassPath)) {
651
- // Use fs.rmSync with recursive option set to true to delete the directory and its contents
652
- fs.rmSync(prismClassPath, { recursive: true, force: true }); // force option is not necessary but can be used to ensure deletion
653
- console.log("Prisma class directory was deleted successfully.");
654
- }
655
- else {
656
- console.log("Prisma class directory does not exist.");
657
- }
658
- }
659
- if (updateAnswer === null || updateAnswer === void 0 ? void 0 : updateAnswer.isUpdate) {
660
- const updateUninstallDependencies = [];
661
- if (!updateAnswer.tailwindcss) {
662
- const tailwindFiles = ["postcss.config.js", "tailwind.config.js"];
663
- tailwindFiles.forEach((file) => {
664
- const filePath = path.join(projectPath, file);
665
- if (fs.existsSync(filePath)) {
666
- fs.unlinkSync(filePath); // Delete each file if it exists
667
- console.log(`${file} was deleted successfully.`);
668
- }
669
- else {
670
- console.log(`${file} does not exist.`);
671
- }
672
- });
673
- updateUninstallDependencies.push("tailwindcss", "autoprefixer", "postcss", "postcss-cli", "cssnano");
674
- }
675
- if (!updateAnswer.websocket) {
676
- updateUninstallDependencies.push("chokidar-cli");
677
- }
678
- if (!updateAnswer.prisma) {
679
- updateUninstallDependencies.push("prisma", "@prisma/client");
680
- }
681
- if (updateUninstallDependencies.length > 0) {
682
- await uninstallDependencies(projectPath, updateUninstallDependencies, true);
683
- }
684
- }
685
- const version = await fetchPackageVersion("create-prisma-php-app");
686
- const projectPathModified = projectPath.replace(/\\/g, "\\");
687
- const PHP_GENERATE_CLASS_PATH = answer.prisma
688
- ? "src/Lib/Prisma/Classes"
689
- : "";
690
- const projectSettings = {
691
- PROJECT_NAME: answer.projectName,
692
- PROJECT_ROOT_PATH: projectPathModified,
693
- PHP_ROOT_PATH_EXE: "C:\\\\xampp\\\\php\\\\php.exe",
694
- PHP_GENERATE_CLASS_PATH,
695
- };
696
- const bsConfig = bsConfigUrls(projectSettings);
697
- const phpGenerateClassPath = answer.prisma ? "src/Lib/Prisma/Classes" : "";
698
- const prismaPhpConfig = {
699
- projectName: answer.projectName,
700
- projectRootPath: projectPathModified,
701
- phpEnvironment: "XAMPP",
702
- phpRootPathExe: "C:\\xampp\\php\\php.exe",
703
- phpGenerateClassPath,
704
- bsTarget: bsConfig.bsTarget,
705
- bsPathRewrite: bsConfig.bsPathRewrite,
706
- tailwindcss: answer.tailwindcss,
707
- websocket: answer.websocket,
708
- prisma: answer.prisma,
709
- version,
710
- excludeFiles: (_f = updateAnswer === null || updateAnswer === void 0 ? void 0 : updateAnswer.excludeFiles) !== null && _f !== void 0 ? _f : [],
711
- };
712
- fs.writeFileSync(path.join(projectPath, "prisma-php.json"), JSON.stringify(prismaPhpConfig, null, 2), { flag: "w" });
713
- execSync(`D:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar install`, {
714
- stdio: "inherit",
715
- });
716
- console.log(`${chalk.green("Success!")} Prisma PHP project successfully created in ${answer.projectName}!`);
578
+ var _a, _b, _c, _d, _e, _f;
579
+ try {
580
+ const args = process.argv.slice(2);
581
+ let projectName = args[0];
582
+ let answer = null;
583
+ if (projectName) {
584
+ let useTailwind = args.includes("--tailwindcss");
585
+ let useWebsocket = args.includes("--websocket");
586
+ let usePrisma = args.includes("--prisma");
587
+ const predefinedAnswers = {
588
+ projectName,
589
+ tailwindcss: useTailwind,
590
+ websocket: useWebsocket,
591
+ prisma: usePrisma,
592
+ };
593
+ console.log("🚀 ~ main ~ predefinedAnswers:", predefinedAnswers);
594
+ answer = await getAnswer(predefinedAnswers);
595
+ if (answer === null) {
596
+ console.log(chalk.red("Installation cancelled."));
597
+ return;
598
+ }
599
+ const currentDir = process.cwd();
600
+ const configPath = path.join(currentDir, "prisma-php.json");
601
+ const localSettings = readJsonFile(configPath);
602
+ let excludeFiles = [];
603
+ (_a = localSettings.excludeFiles) === null || _a === void 0
604
+ ? void 0
605
+ : _a.map((file) => {
606
+ const filePath = path.join(currentDir, file);
607
+ if (fs.existsSync(filePath))
608
+ excludeFiles.push(filePath.replace(/\\/g, "/"));
609
+ });
610
+ updateAnswer = {
611
+ projectName,
612
+ tailwindcss:
613
+ (_b =
614
+ answer === null || answer === void 0
615
+ ? void 0
616
+ : answer.tailwindcss) !== null && _b !== void 0
617
+ ? _b
618
+ : false,
619
+ websocket:
620
+ (_c =
621
+ answer === null || answer === void 0
622
+ ? void 0
623
+ : answer.websocket) !== null && _c !== void 0
624
+ ? _c
625
+ : false,
626
+ prisma:
627
+ (_d =
628
+ answer === null || answer === void 0 ? void 0 : answer.prisma) !==
629
+ null && _d !== void 0
630
+ ? _d
631
+ : false,
632
+ isUpdate: true,
633
+ excludeFiles:
634
+ (_e = localSettings.excludeFiles) !== null && _e !== void 0 ? _e : [],
635
+ excludeFilePath:
636
+ excludeFiles !== null && excludeFiles !== void 0 ? excludeFiles : [],
637
+ filePath: currentDir,
638
+ };
639
+ } else {
640
+ answer = await getAnswer();
641
+ }
642
+ if (answer === null) {
643
+ console.log(chalk.red("Installation cancelled."));
644
+ return;
645
+ }
646
+ execSync(`npm install -g create-prisma-php-app`, { stdio: "inherit" }); // TODO: Uncomment this line before publishing the package
647
+ // Support for browser-sync
648
+ execSync(`npm install -g browser-sync`, { stdio: "inherit" });
649
+ // Create the project directory
650
+ if (!projectName) fs.mkdirSync(answer.projectName);
651
+ const currentDir = process.cwd();
652
+ let projectPath = projectName
653
+ ? currentDir
654
+ : path.join(currentDir, answer.projectName);
655
+ if (!projectName) process.chdir(answer.projectName);
656
+ const dependencies = [
657
+ "typescript",
658
+ "@types/node",
659
+ "ts-node",
660
+ "http-proxy-middleware@^3.0.0",
661
+ "npm-run-all",
662
+ ];
663
+ if (answer.tailwindcss) {
664
+ dependencies.push(
665
+ "tailwindcss",
666
+ "autoprefixer",
667
+ "postcss",
668
+ "postcss-cli",
669
+ "cssnano"
670
+ );
671
+ }
672
+ if (answer.websocket) {
673
+ dependencies.push("chokidar-cli");
674
+ }
675
+ if (answer.prisma) {
676
+ dependencies.push("prisma", "@prisma/client");
717
677
  }
718
- catch (error) {
719
- console.error("Error while creating the project:", error);
720
- process.exit(1);
678
+ await installDependencies(projectPath, dependencies, true);
679
+ if (!projectName) {
680
+ execSync(`npx tsc --init`, { stdio: "inherit" });
721
681
  }
682
+ if (answer.tailwindcss)
683
+ execSync(`npx tailwindcss init -p`, { stdio: "inherit" });
684
+ if (answer.prisma) {
685
+ if (!fs.existsSync(path.join(projectPath, "prisma")))
686
+ execSync(`npx prisma init`, { stdio: "inherit" });
687
+ }
688
+ await createDirectoryStructure(projectPath, answer);
689
+ const publicDirPath = path.join(projectPath, "public");
690
+ if (!fs.existsSync(publicDirPath)) {
691
+ fs.mkdirSync(publicDirPath);
692
+ }
693
+ // if (!answer.tailwindcss) {
694
+ // const cssPath = path.join(projectPath, "src", "app", "css");
695
+ // const tailwindFiles = ["tailwind.css", "styles.css"];
696
+ // tailwindFiles.forEach((file) => {
697
+ // const filePath = path.join(cssPath, file);
698
+ // if (fs.existsSync(filePath)) {
699
+ // fs.unlinkSync(filePath); // Delete each file if it exists
700
+ // console.log(`${file} was deleted successfully.`);
701
+ // } else {
702
+ // console.log(`${file} does not exist.`);
703
+ // }
704
+ // });
705
+ // }
706
+ // Update websocket if not chosen by the user
707
+ // if (!answer.websocket) {
708
+ // const wsPath = path.join(projectPath, "src", "Lib", "Websocket");
709
+ // // Check if the websocket directory exists
710
+ // if (fs.existsSync(wsPath)) {
711
+ // // Use fs.rmSync with recursive option set to true to delete the directory and its contents
712
+ // fs.rmSync(wsPath, { recursive: true, force: true }); // force option is not necessary but can be used to ensure deletion
713
+ // console.log("Websocket directory was deleted successfully.");
714
+ // } else {
715
+ // console.log("Websocket directory does not exist.");
716
+ // }
717
+ // // Update settings directory if websocket is not chosen
718
+ // const settingsPath = path.join(projectPath, "settings");
719
+ // const websocketFiles = ["restart-websocket.cjs", "restart-websocket.bat"];
720
+ // websocketFiles.forEach((file) => {
721
+ // const filePath = path.join(settingsPath, file);
722
+ // if (fs.existsSync(filePath)) {
723
+ // fs.unlinkSync(filePath); // Delete each file if it exists
724
+ // console.log(`${file} was deleted successfully.`);
725
+ // } else {
726
+ // console.log(`${file} does not exist.`);
727
+ // }
728
+ // });
729
+ // }
730
+ if (!answer.prisma) {
731
+ const prismaPath = path.join(projectPath, "prisma");
732
+ const prismClassPath = path.join(projectPath, "src", "Lib", "Prisma");
733
+ // Check if the prisma directory exists
734
+ if (fs.existsSync(prismaPath)) {
735
+ // Use fs.rmSync with recursive option set to true to delete the directory and its contents
736
+ fs.rmSync(prismaPath, { recursive: true, force: true }); // force option is not necessary but can be used to ensure deletion
737
+ console.log("Prisma directory was deleted successfully.");
738
+ } else {
739
+ console.log("Prisma directory does not exist.");
740
+ }
741
+ // Check if the prisma class directory exists
742
+ if (fs.existsSync(prismClassPath)) {
743
+ // Use fs.rmSync with recursive option set to true to delete the directory and its contents
744
+ fs.rmSync(prismClassPath, { recursive: true, force: true }); // force option is not necessary but can be used to ensure deletion
745
+ console.log("Prisma class directory was deleted successfully.");
746
+ } else {
747
+ console.log("Prisma class directory does not exist.");
748
+ }
749
+ }
750
+ if (
751
+ updateAnswer === null || updateAnswer === void 0
752
+ ? void 0
753
+ : updateAnswer.isUpdate
754
+ ) {
755
+ const updateUninstallDependencies = [];
756
+ if (!updateAnswer.tailwindcss) {
757
+ const tailwindFiles = ["postcss.config.js", "tailwind.config.js"];
758
+ tailwindFiles.forEach((file) => {
759
+ const filePath = path.join(projectPath, file);
760
+ if (fs.existsSync(filePath)) {
761
+ fs.unlinkSync(filePath); // Delete each file if it exists
762
+ console.log(`${file} was deleted successfully.`);
763
+ } else {
764
+ console.log(`${file} does not exist.`);
765
+ }
766
+ });
767
+ updateUninstallDependencies.push(
768
+ "tailwindcss",
769
+ "autoprefixer",
770
+ "postcss",
771
+ "postcss-cli",
772
+ "cssnano"
773
+ );
774
+ }
775
+ if (!updateAnswer.websocket) {
776
+ updateUninstallDependencies.push("chokidar-cli");
777
+ }
778
+ if (!updateAnswer.prisma) {
779
+ updateUninstallDependencies.push("prisma", "@prisma/client");
780
+ }
781
+ if (updateUninstallDependencies.length > 0) {
782
+ await uninstallDependencies(
783
+ projectPath,
784
+ updateUninstallDependencies,
785
+ true
786
+ );
787
+ }
788
+ }
789
+ const version = await fetchPackageVersion("create-prisma-php-app");
790
+ const projectPathModified = projectPath.replace(/\\/g, "\\");
791
+ const PHP_GENERATE_CLASS_PATH = answer.prisma
792
+ ? "src/Lib/Prisma/Classes"
793
+ : "";
794
+ const projectSettings = {
795
+ PROJECT_NAME: answer.projectName,
796
+ PROJECT_ROOT_PATH: projectPathModified,
797
+ PHP_ROOT_PATH_EXE: "C:\\\\xampp\\\\php\\\\php.exe",
798
+ PHP_GENERATE_CLASS_PATH,
799
+ };
800
+ const bsConfig = bsConfigUrls(projectSettings);
801
+ const phpGenerateClassPath = answer.prisma ? "src/Lib/Prisma/Classes" : "";
802
+ const prismaPhpConfig = {
803
+ projectName: answer.projectName,
804
+ projectRootPath: projectPathModified,
805
+ phpEnvironment: "XAMPP",
806
+ phpRootPathExe: "C:\\xampp\\php\\php.exe",
807
+ phpGenerateClassPath,
808
+ bsTarget: bsConfig.bsTarget,
809
+ bsPathRewrite: bsConfig.bsPathRewrite,
810
+ tailwindcss: answer.tailwindcss,
811
+ websocket: answer.websocket,
812
+ prisma: answer.prisma,
813
+ version,
814
+ excludeFiles:
815
+ (_f =
816
+ updateAnswer === null || updateAnswer === void 0
817
+ ? void 0
818
+ : updateAnswer.excludeFiles) !== null && _f !== void 0
819
+ ? _f
820
+ : [],
821
+ };
822
+ fs.writeFileSync(
823
+ path.join(projectPath, "prisma-php.json"),
824
+ JSON.stringify(prismaPhpConfig, null, 2),
825
+ { flag: "w" }
826
+ );
827
+ execSync(
828
+ `D:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar install`,
829
+ {
830
+ stdio: "inherit",
831
+ }
832
+ );
833
+ console.log(
834
+ `${chalk.green("Success!")} Prisma PHP project successfully created in ${
835
+ answer.projectName
836
+ }!`
837
+ );
838
+ } catch (error) {
839
+ console.error("Error while creating the project:", error);
840
+ process.exit(1);
841
+ }
722
842
  }
723
843
  main();