create-prisma-php-app 1.9.20 → 1.9.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,721 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import { execSync } from "child_process";
3
- import fs from "fs";
4
- import { fileURLToPath } from "url";
5
- import path from "path";
6
- import chalk from "chalk";
7
- import prompts from "prompts";
8
- import https from "https";
9
- const __filename = fileURLToPath(import.meta.url);
10
- const __dirname = path.dirname(__filename);
11
- let updateAnswer = null;
12
- function bsConfigUrls(projectSettings) {
13
- // Identify the base path dynamically up to and including 'htdocs'
14
- const htdocsIndex = projectSettings.PROJECT_ROOT_PATH.indexOf("\\htdocs\\");
15
- if (htdocsIndex === -1) {
16
- console.error("Invalid PROJECT_ROOT_PATH. The path does not contain \\htdocs\\");
17
- return {
18
- bsTarget: "",
19
- bsPathRewrite: {},
20
- };
21
- }
22
- // Extract the path up to and including 'htdocs\\'
23
- const basePathToRemove = projectSettings.PROJECT_ROOT_PATH.substring(0, htdocsIndex + "\\htdocs\\".length);
24
- // Escape backslashes for the regex pattern
25
- const escapedBasePathToRemove = basePathToRemove.replace(/\\/g, "\\\\");
26
- // Remove the base path and replace backslashes with forward slashes for URL compatibility
27
- const relativeWebPath = projectSettings.PROJECT_ROOT_PATH.replace(new RegExp(`^${escapedBasePathToRemove}`), "").replace(/\\/g, "/");
28
- // Construct the Browser Sync command with the correct proxy URL, being careful not to affect the protocol part
29
- let proxyUrl = `http://localhost/${relativeWebPath}`;
30
- // Ensure the proxy URL does not end with a slash before appending '/public'
31
- proxyUrl = proxyUrl.endsWith("/") ? proxyUrl.slice(0, -1) : proxyUrl;
32
- // Clean the URL by replacing "//" with "/" but not affecting "http://"
33
- // We replace instances of "//" that are not preceded by ":"
34
- const cleanUrl = proxyUrl.replace(/(?<!:)(\/\/+)/g, "/");
35
- const cleanRelativeWebPath = relativeWebPath.replace(/\/\/+/g, "/");
36
- // Correct the relativeWebPath to ensure it does not start with a "/"
37
- const adjustedRelativeWebPath = cleanRelativeWebPath.startsWith("/")
38
- ? cleanRelativeWebPath.substring(1)
39
- : cleanRelativeWebPath;
40
- return {
41
- bsTarget: `${cleanUrl}/`,
42
- bsPathRewrite: {
43
- "^/": `/${adjustedRelativeWebPath}/`,
44
- },
45
- };
46
- }
47
- function configureBrowserSyncCommand(baseDir, projectSettings) {
48
- // TypeScript content to write
49
- const bsConfigTsContent = `const { createProxyMiddleware } = require("http-proxy-middleware");
50
- const fs = require("fs");
51
-
52
- const jsonData = fs.readFileSync("prisma-php.json", "utf8");
53
- const config = JSON.parse(jsonData);
54
-
55
- module.exports = {
56
- // First middleware: Set Cache-Control headers
57
- function(req, res, next) {
58
- res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
59
- res.setHeader("Pragma", "no-cache");
60
- res.setHeader("Expires", "0");
61
- next();
62
- },
63
- // Use the 'middleware' option to create a proxy that masks the deep URL.
64
- middleware: [
65
- // This middleware intercepts requests to the root and proxies them to the deep path.
66
- createProxyMiddleware("/", {
67
- target: config.bsTarget,
68
- changeOrigin: true,
69
- pathRewrite: config.bsPathRewrite,
70
- }),
71
- ],
72
- proxy: "http://localhost:3000", // Proxy the BrowserSync server.
73
- files: "src/**/*.*",
74
- notify: false,
75
- open: false,
76
- ghostMode: false,
77
- };`;
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`;
83
- }
84
- async function updatePackageJson(baseDir, projectSettings, answer) {
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));
124
- }
125
- async function updateComposerJson(baseDir, answer) {
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.");
150
- }
151
- async function updateIndexJsForWebSocket(baseDir, answer) {
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 = `
161
- // WebSocket initialization
162
- const ws = new WebSocket("ws://localhost:8080");
163
- `;
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.");
168
- }
169
- // This function updates the .gitignore file
170
- async function createUpdateGitignoreFile(baseDir, additions) {
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");
178
- }
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);
187
- }
188
- // Recursive copy function
189
- function copyRecursiveSync(src, dest) {
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
- }
206
- }
207
- // Function to execute the recursive copy for entire directories
208
- async function executeCopy(baseDir, directoriesToCopy, answer) {
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
- });
216
- }
217
- function createOrUpdateTailwindConfig(baseDir) {
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."));
234
- }
235
- function modifyPostcssConfig(baseDir) {
236
- const filePath = path.join(baseDir, "postcss.config.js");
237
- if (checkExcludeFiles(filePath))
238
- return;
239
- const newContent = `export default {
240
- plugins: {
241
- tailwindcss: {},
242
- autoprefixer: {},
243
- cssnano: {},
244
- },
245
- };`;
246
- fs.writeFileSync(filePath, newContent, { flag: "w" });
247
- console.log(chalk.green("postcss.config.js updated successfully."));
248
- }
249
- function modifyLayoutPHP(baseDir, useTailwind) {
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
- }
268
- }
269
- // This function updates or creates the .env file
270
- async function createOrUpdateEnvFile(baseDir, content) {
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
- }
282
- }
283
- function checkExcludeFiles(destPath) {
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);
288
- }
289
- async function createDirectoryStructure(baseDir, answer, projectSettings) {
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
- }
303
- }
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
352
- AUTH_SECRET=uxsjXVPHN038DEYls2Kw0QUgBcXKUyrjv416nIFWPY4=
353
-
354
- # PHPMailer
355
- # SMTP_HOST=smtp.gmail.com or your SMTP host
356
- # SMTP_USERNAME=john.doe@gmail.com or your SMTP username
357
- # SMTP_PASSWORD=123456
358
- # SMTP_PORT=587 for TLS, 465 for SSL or your SMTP port
359
- # SMTP_ENCRYPTION=ssl or tls
360
- # MAIL_FROM=john.doe@gmail.com
361
- # MAIL_FROM_NAME="John Doe"`;
362
- await createOrUpdateEnvFile(baseDir, envContent);
363
- // Add vendor to .gitignore
364
- await createUpdateGitignoreFile(baseDir, ["vendor"]);
365
- }
366
- async function getAnswer(predefinedAnswers = {}) {
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
- });
377
- }
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);
413
- };
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
- }
433
- }
434
- /**
435
- * Install dependencies in the specified directory.
436
- * @param {string} baseDir - The base directory where to install the dependencies.
437
- * @param {string[]} dependencies - The list of dependencies to install.
438
- * @param {boolean} [isDev=false] - Whether to install the dependencies as devDependencies.
439
- */
440
- async function installDependencies(baseDir, dependencies, isDev = false) {
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,
457
- });
458
- }
459
- async function uninstallDependencies(baseDir, dependencies, isDev = false) {
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
- });
469
- }
470
- function fetchPackageVersion(packageName) {
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
- });
488
- }
489
- const readJsonFile = (filePath) => {
490
- const jsonData = fs.readFileSync(filePath, "utf8");
491
- return JSON.parse(jsonData);
492
- };
493
- async function main() {
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
- };
534
- }
535
- else {
536
- answer = await getAnswer();
537
- }
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}!`);
715
- }
716
- catch (error) {
717
- console.error("Error while creating the project:", error);
718
- process.exit(1);
719
- }
720
- }
721
- main();
2
+ import{execSync}from"child_process";import fs from"fs";import{fileURLToPath}from"url";import path from"path";import chalk from"chalk";import prompts from"prompts";import https from"https";const __filename=fileURLToPath(import.meta.url),__dirname=path.dirname(__filename);let updateAnswer=null;function bsConfigUrls(e){const s=e.PROJECT_ROOT_PATH.indexOf("\\htdocs\\");if(-1===s)return{bsTarget:"",bsPathRewrite:{}};const t=e.PROJECT_ROOT_PATH.substring(0,s+"\\htdocs\\".length).replace(/\\/g,"\\\\"),n=e.PROJECT_ROOT_PATH.replace(new RegExp(`^${t}`),"").replace(/\\/g,"/");let i=`http://localhost/${n}`;i=i.endsWith("/")?i.slice(0,-1):i;const c=i.replace(/(?<!:)(\/\/+)/g,"/"),r=n.replace(/\/\/+/g,"/");return{bsTarget:`${c}/`,bsPathRewrite:{"^/":`/${r.startsWith("/")?r.substring(1):r}/`}}}function configureBrowserSyncCommand(e,s){const t=path.join(e,"settings","bs-config.cjs");return fs.writeFileSync(t,'const { createProxyMiddleware } = require("http-proxy-middleware");\n const fs = require("fs");\n \n const jsonData = fs.readFileSync("prisma-php.json", "utf8");\n const config = JSON.parse(jsonData);\n \n module.exports = {\n // First middleware: Set Cache-Control headers\n function(req, res, next) {\n res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");\n res.setHeader("Pragma", "no-cache");\n res.setHeader("Expires", "0");\n next();\n },\n // Use the \'middleware\' option to create a proxy that masks the deep URL.\n middleware: [\n // This middleware intercepts requests to the root and proxies them to the deep path.\n createProxyMiddleware("/", {\n target: config.bsTarget,\n changeOrigin: true,\n pathRewrite: config.bsPathRewrite,\n }),\n ],\n proxy: "http://localhost:3000", // Proxy the BrowserSync server.\n files: "src/**/*.*",\n notify: false,\n open: false,\n ghostMode: false,\n };',"utf8"),"browser-sync start --config settings/bs-config.cjs"}async function updatePackageJson(e,s,t){const n=path.join(e,"package.json");if(checkExcludeFiles(n))return;const i=JSON.parse(fs.readFileSync(n,"utf8")),c=configureBrowserSyncCommand(e,s);i.scripts=Object.assign(Object.assign({},i.scripts),{projectName:"node settings/project-name.cjs"});let r=[];t.tailwindcss&&(i.scripts=Object.assign(Object.assign({},i.scripts),{tailwind:"postcss ./src/app/css/tailwind.css -o ./src/app/css/styles.css --watch"}),r.push("tailwind")),t.websocket&&(i.scripts=Object.assign(Object.assign({},i.scripts),{websocket:"node ./settings/restart-websocket.cjs"}),r.push("websocket"));const a=Object.assign({},i.scripts);a["browser-sync"]=c,a.dev=r.length>0?`npm-run-all --parallel projectName browser-sync ${r.join(" ")}`:"npm-run-all --parallel projectName browser-sync",i.scripts=a,i.type="module",t.prisma&&(i.prisma={seed:"node prisma/seed.js"}),fs.writeFileSync(n,JSON.stringify(i,null,2))}async function updateComposerJson(e,s){const t=path.join(e,"composer.json");if(checkExcludeFiles(t))return;let n;if(fs.existsSync(t)){{const e=fs.readFileSync(t,"utf8");n=JSON.parse(e)}s.websocket&&(n.require=Object.assign(Object.assign({},n.require),{"cboden/ratchet":"^0.4.4"})),s.prisma&&(n.require=Object.assign(Object.assign({},n.require),{"ramsey/uuid":"5.x-dev","hidehalo/nanoid-php":"1.x-dev"})),fs.writeFileSync(t,JSON.stringify(n,null,2))}}async function updateIndexJsForWebSocket(e,s){if(!s.websocket)return;const t=path.join(e,"src","app","js","index.js");if(checkExcludeFiles(t))return;let n=fs.readFileSync(t,"utf8");n+='\n// WebSocket initialization\nconst ws = new WebSocket("ws://localhost:8080");\n',fs.writeFileSync(t,n,"utf8")}async function createUpdateGitignoreFile(e,s){const t=path.join(e,".gitignore");if(checkExcludeFiles(t))return;let n="";fs.existsSync(t)&&(n=fs.readFileSync(t,"utf8")),s.forEach((e=>{n.includes(e)||(n+=`\n${e}`)})),n=n.trimStart(),fs.writeFileSync(t,n)}function copyRecursiveSync(e,s){const t=fs.existsSync(e),n=t&&fs.statSync(e);if(t&&n&&n.isDirectory())fs.mkdirSync(s,{recursive:!0}),fs.readdirSync(e).forEach((t=>{copyRecursiveSync(path.join(e,t),path.join(s,t))}));else{if(checkExcludeFiles(s))return;fs.copyFileSync(e,s,0)}}async function executeCopy(e,s,t){s.forEach((({srcDir:s,destDir:n})=>{if(!t.prisma&&"/prisma-client-php"===s)return;copyRecursiveSync(path.join(__dirname,s),path.join(e,n))}))}function createOrUpdateTailwindConfig(e){const s=path.join(e,"tailwind.config.js");if(checkExcludeFiles(s))return;let t=fs.readFileSync(s,"utf8");const n=["./src/app/**/*.{html,js,php}"].map((e=>` "${e}"`)).join(",\n");t=t.replace(/content: \[\],/g,`content: [\n${n}\n],`),fs.writeFileSync(s,t,{flag:"w"})}function modifyPostcssConfig(e){const s=path.join(e,"postcss.config.js");if(checkExcludeFiles(s))return;fs.writeFileSync(s,"export default {\n plugins: {\n tailwindcss: {},\n autoprefixer: {},\n cssnano: {},\n },\n};",{flag:"w"})}function modifyLayoutPHP(e,s){const t=path.join(e,"src","app","layout.php");if(!checkExcludeFiles(t))try{let e=fs.readFileSync(t,"utf8");const n='\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">',i=s?` <link href="<?php echo $baseUrl; ?>css/styles.css" rel="stylesheet"> ${n}`:` <script src="https://cdn.tailwindcss.com"><\/script> ${n}`;e=e.replace("</head>",`${i}\n</head>`),fs.writeFileSync(t,e,{flag:"w"})}catch(e){}}async function createOrUpdateEnvFile(e,s){const t=path.join(e,".env");if(checkExcludeFiles(t))return;let n=fs.existsSync(t)?fs.readFileSync(t,"utf8"):"";n.includes(s)||(n+=`${""!==n?"\n\n":""}${s}`,fs.writeFileSync(t,n,{flag:"w"}))}function checkExcludeFiles(e){var s,t;return!!(null==updateAnswer?void 0:updateAnswer.isUpdate)&&(null!==(t=null===(s=null==updateAnswer?void 0:updateAnswer.excludeFilePath)||void 0===s?void 0:s.includes(e.replace(/\\/g,"/")))&&void 0!==t&&t)}async function createDirectoryStructure(e,s,t){const n=[{src:"/bootstrap.php",dest:"/bootstrap.php"},{src:"/.htaccess",dest:"/.htaccess"},{src:"/../composer.json",dest:"/composer.json"}];(null==updateAnswer?void 0:updateAnswer.isUpdate)&&(n.push({src:"/.env",dest:"/.env"},{src:"/tsconfig.json",dest:"/tsconfig.json"}),updateAnswer.tailwindcss&&n.push({src:"/postcss.config.js",dest:"/postcss.config.js"},{src:"/tailwind.config.js",dest:"/tailwind.config.js"}));n.forEach((({src:s,dest:t})=>{const n=path.join(__dirname,s),i=path.join(e,t);if(checkExcludeFiles(i))return;const c=fs.readFileSync(n,"utf8");fs.writeFileSync(i,c,{flag:"w"})})),await executeCopy(e,[{srcDir:"/settings",destDir:"/settings"},{srcDir:"/prisma",destDir:"/prisma"},{srcDir:"/src",destDir:"/src"},{srcDir:"/../vendor",destDir:"/vendor"}],s),await updatePackageJson(e,t,s),await updateComposerJson(e,s),await updateIndexJsForWebSocket(e,s),s.tailwindcss?(createOrUpdateTailwindConfig(e),modifyLayoutPHP(e,!0),modifyPostcssConfig(e)):modifyLayoutPHP(e,!1);await createOrUpdateEnvFile(e,'# Prisma PHP Auth Secret Key For development only - Change this in production\nAUTH_SECRET=uxsjXVPHN038DEYls2Kw0QUgBcXKUyrjv416nIFWPY4= \n\n# PHPMailer\n# SMTP_HOST=smtp.gmail.com or your SMTP host\n# SMTP_USERNAME=john.doe@gmail.com or your SMTP username\n# SMTP_PASSWORD=123456\n# SMTP_PORT=587 for TLS, 465 for SSL or your SMTP port\n# SMTP_ENCRYPTION=ssl or tls\n# MAIL_FROM=john.doe@gmail.com\n# MAIL_FROM_NAME="John Doe"'),await createUpdateGitignoreFile(e,["vendor"])}async function getAnswer(e={}){var s,t,n,i;const c=[];e.projectName||c.push({type:"text",name:"projectName",message:"What is your project named?",initial:"my-app"}),e.tailwindcss||c.push({type:"toggle",name:"tailwindcss",message:`Would you like to use ${chalk.blue("Tailwind CSS")}?`,initial:!0,active:"Yes",inactive:"No"}),e.websocket||c.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!0,active:"Yes",inactive:"No"}),e.prisma||c.push({type:"toggle",name:"prisma",message:`Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,initial:!0,active:"Yes",inactive:"No"});const r=c,a=()=>{process.exit(0)};try{const c=await prompts(r,{onCancel:a});return 0===Object.keys(c).length?null:{projectName:c.projectName?String(c.projectName).trim().replace(/ /g,"-"):null!==(s=e.projectName)&&void 0!==s?s:"my-app",tailwindcss:null!==(t=c.tailwindcss)&&void 0!==t?t:e.tailwindcss,websocket:null!==(n=c.websocket)&&void 0!==n?n:e.websocket,prisma:null!==(i=c.prisma)&&void 0!==i?i:e.prisma}}catch(e){return null}}async function installDependencies(e,s,t=!1){fs.existsSync(path.join(e,"package.json"))||execSync("npm init -y",{stdio:"inherit",cwd:e}),s.forEach((e=>{}));const n=`npm install ${t?"--save-dev":""} ${s.join(" ")}`;execSync(n,{stdio:"inherit",cwd:e})}async function uninstallDependencies(e,s,t=!1){s.forEach((e=>{}));const n=`npm uninstall ${t?"--save-dev":"--save"} ${s.join(" ")}`;execSync(n,{stdio:"inherit",cwd:e})}function fetchPackageVersion(e){return new Promise(((s,t)=>{https.get(`https://registry.npmjs.org/${e}`,(e=>{let n="";e.on("data",(e=>n+=e)),e.on("end",(()=>{try{const e=JSON.parse(n);s(e["dist-tags"].latest)}catch(e){t(new Error("Failed to parse JSON response"))}}))})).on("error",(e=>t(e)))}))}const readJsonFile=e=>{const s=fs.readFileSync(e,"utf8");return JSON.parse(s)};async function main(){var e,s,t,n,i,c;try{const r=process.argv.slice(2);let a=r[0],o=null;if(a){const c={projectName:a,tailwindcss:r.includes("--tailwindcss"),websocket:r.includes("--websocket"),prisma:r.includes("--prisma")};if(o=await getAnswer(c),null===o)return;const p=process.cwd(),l=path.join(p,"prisma-php.json"),d=readJsonFile(l);let u=[];null===(e=d.excludeFiles)||void 0===e||e.map((e=>{const s=path.join(p,e);fs.existsSync(s)&&u.push(s.replace(/\\/g,"/"))})),updateAnswer={projectName:a,tailwindcss:null!==(s=null==o?void 0:o.tailwindcss)&&void 0!==s&&s,websocket:null!==(t=null==o?void 0:o.websocket)&&void 0!==t&&t,prisma:null!==(n=null==o?void 0:o.prisma)&&void 0!==n&&n,isUpdate:!0,excludeFiles:null!==(i=d.excludeFiles)&&void 0!==i?i:[],excludeFilePath:null!=u?u:[],filePath:p}}else o=await getAnswer();if(null===o)return;execSync("npm install -g create-prisma-php-app",{stdio:"inherit"}),execSync("npm install -g browser-sync",{stdio:"inherit"}),a||fs.mkdirSync(o.projectName);const p=process.cwd();let l=a?p:path.join(p,o.projectName);a||process.chdir(o.projectName);const d=["typescript","@types/node","ts-node","http-proxy-middleware@^2.0.6","npm-run-all"];o.tailwindcss&&d.push("tailwindcss","autoprefixer","postcss","postcss-cli","cssnano"),o.websocket&&d.push("chokidar-cli"),o.prisma&&d.push("prisma","@prisma/client"),await installDependencies(l,d,!0),a||execSync("npx tsc --init",{stdio:"inherit"}),o.tailwindcss&&execSync("npx tailwindcss init -p",{stdio:"inherit"}),o.prisma&&execSync("npx prisma init",{stdio:"inherit"});const u=l.replace(/\\/g,"\\"),h=o.prisma?"src/Lib/Prisma/Classes":"",f={PROJECT_NAME:o.projectName,PROJECT_ROOT_PATH:u,PHP_ROOT_PATH_EXE:"D:\\\\xampp\\\\php\\\\php.exe",PHP_GENERATE_CLASS_PATH:h};await createDirectoryStructure(l,o,f);const m=path.join(l,"public");if(fs.existsSync(m)||fs.mkdirSync(m),!o.tailwindcss){const e=path.join(l,"src","app","css");["tailwind.css","styles.css"].forEach((s=>{const t=path.join(e,s);fs.existsSync(t)&&fs.unlinkSync(t)}))}if(!o.websocket){const e=path.join(l,"src","Lib","Websocket");fs.existsSync(e)&&fs.rmSync(e,{recursive:!0,force:!0});const s=path.join(l,"settings");["restart-websocket.cjs","restart-websocket.bat"].forEach((e=>{const t=path.join(s,e);fs.existsSync(t)&&fs.unlinkSync(t)}))}if(!o.prisma){const e=path.join(l,"prisma"),s=path.join(l,"src","Lib","Prisma");fs.existsSync(e)&&fs.rmSync(e,{recursive:!0,force:!0}),fs.existsSync(s)&&fs.rmSync(s,{recursive:!0,force:!0})}if(null==updateAnswer?void 0:updateAnswer.isUpdate){const e=[];if(!updateAnswer.tailwindcss){["postcss.config.js","tailwind.config.js"].forEach((e=>{const s=path.join(l,e);fs.existsSync(s)&&fs.unlinkSync(s)})),e.push("tailwindcss","autoprefixer","postcss","postcss-cli","cssnano")}updateAnswer.websocket||e.push("chokidar-cli"),updateAnswer.prisma||e.push("prisma","@prisma/client"),e.length>0&&await uninstallDependencies(l,e,!0)}const w=await fetchPackageVersion("create-prisma-php-app"),y=bsConfigUrls(f),g=o.prisma?"src/Lib/Prisma/Classes":"",j={projectName:o.projectName,projectRootPath:u,phpEnvironment:"XAMPP",phpRootPathExe:"D:\\xampp\\php\\php.exe",phpGenerateClassPath:g,bsTarget:y.bsTarget,bsPathRewrite:y.bsPathRewrite,tailwindcss:o.tailwindcss,websocket:o.websocket,prisma:o.prisma,version:w,excludeFiles:null!==(c=null==updateAnswer?void 0:updateAnswer.excludeFiles)&&void 0!==c?c:[]};fs.writeFileSync(path.join(l,"prisma-php.json"),JSON.stringify(j,null,2),{flag:"w"})}catch(e){process.exit(1)}}main();
@@ -24,6 +24,33 @@ class Auth
24
24
  $this->logger = $logger;
25
25
  }
26
26
 
27
+ /**
28
+ * Authenticates a user and generates a JWT (JSON Web Token) based on the specified user role
29
+ * and token validity duration. The method first checks if the secret key is set, calculates
30
+ * the token's expiration time, sets the necessary payload, and encodes it into a JWT.
31
+ * If possible (HTTP headers not yet sent), it also sets cookies with the JWT for client-side storage.
32
+ *
33
+ * @param mixed $role A role identifier which can be a simple string or an instance of AuthRole.
34
+ * If an instance of AuthRole is provided, its `value` property will be used as the role in the token.
35
+ * @param string|null $tokenValidity Optional parameter specifying the duration the token is valid for (e.g., '10m', '1h').
36
+ * If null, the default validity period set in the class property is used.
37
+ * The format should be a number followed by a time unit ('s' for seconds, 'm' for minutes,
38
+ * 'h' for hours, 'd' for days), and this is parsed to calculate the exact expiration time.
39
+ *
40
+ * @return string Returns the encoded JWT as a string.
41
+ *
42
+ * @throws InvalidArgumentException Thrown if the secret key is not set or if the duration format is invalid.
43
+ *
44
+ * Example:
45
+ * $auth = new Authentication();
46
+ * $auth->setSecretKey('your_secret_key');
47
+ * try {
48
+ * $jwt = $auth->authenticate('Admin', '1h');
49
+ * echo "JWT: " . $jwt;
50
+ * } catch (\InvalidArgumentException $e) {
51
+ * echo "Error: " . $e->getMessage();
52
+ * }
53
+ */
27
54
  public function authenticate($role, string $tokenValidity = null): string
28
55
  {
29
56
  if (!$this->secretKey) {
@@ -54,6 +81,11 @@ class Auth
54
81
  return $jwt;
55
82
  }
56
83
 
84
+ public function isAuthenticated(): bool
85
+ {
86
+ return isset($_SESSION[self::PAYLOAD]);
87
+ }
88
+
57
89
  private function calculateExpirationTime(string $duration): int
58
90
  {
59
91
  $now = new DateTime();
@@ -16,8 +16,8 @@ enum AuthRole: string
16
16
  class AuthConfig
17
17
  {
18
18
  public const ROLE_IDENTIFIER = 'role';
19
- public const IS_ROLE_BASE = true;
20
- public const IS_TOKEN_AUTO_REFRESH = true;
19
+ public const IS_ROLE_BASE = false;
20
+ public const IS_TOKEN_AUTO_REFRESH = false;
21
21
 
22
22
  // An array listing the public routes that do not require authentication.
23
23
  // Example: public static $publicRoutes = ['/'];
@@ -1,5 +1,3 @@
1
- <?php require_once "../../bootstrap.php"; ?>
2
-
3
1
  <!DOCTYPE html>
4
2
  <html lang="en">
5
3
 
@@ -15,12 +13,6 @@
15
13
  </head>
16
14
 
17
15
  <body>
18
- <!-- don't place any HTML content here. This section is reserved to show the notFound content. -->
19
- <?php if (isset($notFound)) {
20
- echo $notFound;
21
- exit;
22
- } ?>
23
-
24
16
  <!-- Additional HTML content can go here. -->
25
17
  <?php echo $content; ?>
26
18
  <!-- Additional HTML content can go here. -->
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-prisma-php-app",
3
- "version": "1.9.20",
3
+ "version": "1.9.22",
4
4
  "description": "Prisma-PHP: A Revolutionary Library Bridging PHP with Prisma ORM",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",