create-prisma-php-app 1.9.19 → 1.9.20

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