create-prisma-php-app 1.6.26 → 1.6.27

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