create-prisma-php-app 1.6.33 → 1.6.35

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