create-prisma-php-app 1.26.14 → 1.26.16
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 +367 -366
- package/dist/src/app/js/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,366 +1,367 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
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;const nonBackendFiles=["favicon.ico","\\src\\app\\index.php","metadata.php","not-found.php"],dockerFiles=[".dockerignore","docker-compose.yml","Dockerfile","apache.conf"];function bsConfigUrls(e){const s=e.indexOf("\\htdocs\\");if(-1===s)return{bsTarget:"",bsPathRewrite:{}};const t=e.substring(0,s+"\\htdocs\\".length).replace(/\\/g,"\\\\"),n=e.replace(new RegExp(`^${t}`),"").replace(/\\/g,"/");let c=`http://localhost/${n}`;c=c.endsWith("/")?c.slice(0,-1):c;const i=c.replace(/(?<!:)(\/\/+)/g,"/"),o=n.replace(/\/\/+/g,"/");return{bsTarget:`${i}/`,bsPathRewrite:{"^/":`/${o.startsWith("/")?o.substring(1):o}/`}}}async function updatePackageJson(e,s){const t=path.join(e,"package.json");if(checkExcludeFiles(t))return;const n=JSON.parse(fs.readFileSync(t,"utf8"));n.scripts={...n.scripts,projectName:"tsx settings/project-name.ts"};let c=[];if(s.tailwindcss&&(n.scripts={...n.scripts,tailwind:"postcss src/app/css/tailwind.css -o src/app/css/styles.css --watch"},c.push("tailwind")),s.websocket&&(n.scripts={...n.scripts,websocket:"tsx settings/restart-websocket.ts"},c.push("websocket")),s.docker&&(n.scripts={...n.scripts,docker:"docker-compose up"},c.push("docker")),s.swaggerDocs){const e=s.prisma?"tsx settings/auto-swagger-docs.ts":"tsx settings/swagger-config.ts";n.scripts={...n.scripts,"create-swagger-docs":e}}let i={...n.scripts};i.browserSync="tsx settings/bs-config.ts",i.dev=`npm-run-all projectName -p browserSync ${c.join(" ")}`,n.scripts=i,n.type="module",s.prisma&&(n.prisma={seed:"tsx prisma/seed.ts"}),fs.writeFileSync(t,JSON.stringify(n,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={...n.require,"cboden/ratchet":"^0.4.4"}),s.prisma&&(n.require={...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\nvar ws = new WebSocket("ws://localhost:8080");\n',fs.writeFileSync(t,n,"utf8")}function copyRecursiveSync(e,s,t){const n=fs.existsSync(e),c=n&&fs.statSync(e);if(n&&c&&c.isDirectory()){const n=s.toLowerCase();if(!t.websocket&&n.includes("src\\lib\\websocket"))return;if(!t.prisma&&n.includes("src\\lib\\prisma"))return;if(t.backendOnly&&n.includes("src\\app\\js")||t.backendOnly&&n.includes("src\\app\\css")||t.backendOnly&&n.includes("src\\app\\assets"))return;if(!t.swaggerDocs&&n.includes("src\\app\\swagger-docs"))return;const c=s.replace(/\\/g,"/");if(updateAnswer?.excludeFilePath?.includes(c))return;fs.existsSync(s)||fs.mkdirSync(s,{recursive:!0}),fs.readdirSync(e).forEach((n=>{copyRecursiveSync(path.join(e,n),path.join(s,n),t)}))}else{if(checkExcludeFiles(s))return;if(!t.tailwindcss&&(s.includes("tailwind.css")||s.includes("styles.css")))return;if(!t.websocket&&(s.includes("restart-websocket.ts")||s.includes("restart-websocket.bat")))return;if(!t.docker&&dockerFiles.some((e=>s.includes(e))))return;if(t.backendOnly&&nonBackendFiles.some((e=>s.includes(e))))return;if(!t.backendOnly&&s.includes("route.php"))return;if(t.backendOnly&&!t.swaggerDocs&&s.includes("layout.php"))return;if(!t.swaggerDocs&&s.includes("swagger-config.ts"))return;if(t.tailwindcss&&s.includes("index.css"))return;if((!t.swaggerDocs||!t.prisma)&&(s.includes("auto-swagger-docs.ts")||s.includes("prisma-sdk.ts")||s.includes("prisma-schema-config.json")||s.includes("prisma-schema.json")))return;fs.copyFileSync(e,s,0)}}async function executeCopy(e,s,t){s.forEach((({src:s,dest:n})=>{copyRecursiveSync(path.join(__dirname,s),path.join(e,n),t)}))}function createOrUpdateTailwindConfig(e){const s=path.join(e,"tailwind.config.js");if(checkExcludeFiles(s))return;let t=fs.readFileSync(s,"utf8");const n=["./src/**/*.{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"),n="";s.backendOnly||(s.tailwindcss||(n='\n <link href="<?= Request::baseUrl; ?>/css/index.css" rel="stylesheet">'),n+='\n <script src="<?= Request::baseUrl; ?>/js/json5.min.js"><\/script>\n <script src="<?= Request::baseUrl; ?>/js/index.js"><\/script>');let c="";s.backendOnly||(c=s.tailwindcss?` <link href="<?= Request::baseUrl; ?>/css/styles.css" rel="stylesheet"> ${n}`:n);const i=c.length>0?"\n":"";e=e.replace("</head>",`${c}${i} \x3c!-- Dynamic Head --\x3e\n <?= MainLayout::outputHeadScripts() ?>\n</head>`),fs.writeFileSync(t,e,{flag:"w"})}catch(e){}}async function createOrUpdateEnvFile(e,s){const t=path.join(e,".env");checkExcludeFiles(t)||fs.writeFileSync(t,s,{flag:"w"})}function checkExcludeFiles(e){return!!updateAnswer?.isUpdate&&(updateAnswer?.excludeFilePath?.includes(e.replace(/\\/g,"/"))??!1)}async function createDirectoryStructure(e,s){const t=[{src:"/bootstrap.php",dest:"/bootstrap.php"},{src:"/.htaccess",dest:"/.htaccess"},{src:"/../composer.json",dest:"/composer.json"},{src:"/tsconfig.json",dest:"/tsconfig.json"},{src:"/app-gitignore",dest:"/.gitignore"}];s.tailwindcss&&t.push({src:"/postcss.config.js",dest:"/postcss.config.js"},{src:"/tailwind.config.js",dest:"/tailwind.config.js"});const n=[{src:"/settings",dest:"/settings"},{src:"/src",dest:"/src"}];s.prisma&&n.push({src:"/prisma",dest:"/prisma"}),s.docker&&n.push({src:"/.dockerignore",dest:"/.dockerignore"},{src:"/docker-compose.yml",dest:"/docker-compose.yml"},{src:"/Dockerfile",dest:"/Dockerfile"},{src:"/apache.conf",dest:"/apache.conf"}),t.forEach((({src:s,dest:t})=>{const n=path.join(__dirname,s),c=path.join(e,t);if(checkExcludeFiles(c))return;const i=fs.readFileSync(n,"utf8");fs.writeFileSync(c,i,{flag:"w"})})),await executeCopy(e,n,s),await updatePackageJson(e,s),await updateComposerJson(e,s),s.backendOnly||await updateIndexJsForWebSocket(e,s),s.tailwindcss&&(createOrUpdateTailwindConfig(e),modifyPostcssConfig(e)),(s.tailwindcss||!s.backendOnly||s.swaggerDocs)&&modifyLayoutPHP(e,s);const c='# 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"\n\n# SHOW ERRORS - Set to true to show errors in the browser for development only - Change this in production to false\nSHOW_ERRORS=true\n\n# APP TIMEZONE - Set your application timezone - Default is "UTC"\nAPP_TIMEZONE="UTC"\n\n# APP ENV - Set your application environment - Default is "development" - Change this in production to "production"\nAPP_ENV=development';if(s.prisma){const s=`${'# Environment variables declared in this file are automatically made available to Prisma.\n# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema\n\n# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.\n# See the documentation for all the connection string options: https://pris.ly/d/connection-strings\n\nDATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"'}\n\n${c}`;await createOrUpdateEnvFile(e,s)}else await createOrUpdateEnvFile(e,c)}async function getAnswer(e={}){const s=[];e.projectName||s.push({type:"text",name:"projectName",message:"What is your project named?",initial:"my-app"}),e.backendOnly||s.push({type:"toggle",name:"backendOnly",message:`Would you like to create a ${chalk.blue("backend-only project")}?`,initial:!1,active:"Yes",inactive:"No"});const t=()=>{process.exit(0)},n=await prompts(s,{onCancel:t}),c=[];n.backendOnly||e.backendOnly?(e.swaggerDocs||c.push({type:"toggle",name:"swaggerDocs",message:`Would you like to use ${chalk.blue("Swagger Docs")}?`,initial:!1,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"}),e.docker||c.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"})):(e.swaggerDocs||c.push({type:"toggle",name:"swaggerDocs",message:`Would you like to use ${chalk.blue("Swagger Docs")}?`,initial:!1,active:"Yes",inactive:"No"}),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"}),e.docker||c.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"}));const i=await prompts(c,{onCancel:t});return{projectName:n.projectName?String(n.projectName).trim().replace(/ /g,"-"):e.projectName??"my-app",backendOnly:n.backendOnly??e.backendOnly??!1,swaggerDocs:i.swaggerDocs??e.swaggerDocs??!1,tailwindcss:i.tailwindcss??e.tailwindcss??!1,websocket:i.websocket??e.websocket??!1,prisma:i.prisma??e.prisma??!1,docker:i.docker??e.docker??!1}}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)};function compareVersions(e,s){const t=e.split(".").map(Number),n=s.split(".").map(Number);for(let e=0;e<t.length;e++){if(t[e]>n[e])return 1;if(t[e]<n[e])return-1}return 0}function getInstalledPackageVersion(e){try{const s=execSync(`npm list -g ${e} --depth=0`).toString().match(new RegExp(`${e}@(\\d+\\.\\d+\\.\\d+)`));return s?s[1]:null}catch(e){return null}}
|
|
3
|
-
/**
|
|
4
|
-
* Install dependencies in the specified directory.
|
|
5
|
-
* @param {string} baseDir - The base directory where to install the dependencies.
|
|
6
|
-
* @param {string[]} dependencies - The list of dependencies to install.
|
|
7
|
-
* @param {boolean} [isDev=false] - Whether to install the dependencies as devDependencies.
|
|
8
|
-
*/
|
|
9
|
-
async function installDependencies(baseDir, dependencies, isDev = false) {
|
|
10
|
-
console.log("Initializing new Node.js project...");
|
|
11
|
-
// Initialize a package.json if it doesn't exist
|
|
12
|
-
if (!fs.existsSync(path.join(baseDir, "package.json")))
|
|
13
|
-
execSync("npm init -y", {
|
|
14
|
-
stdio: "inherit",
|
|
15
|
-
cwd: baseDir,
|
|
16
|
-
});
|
|
17
|
-
// Log the dependencies being installed
|
|
18
|
-
console.log(
|
|
19
|
-
`${
|
|
20
|
-
isDev ? "Installing development dependencies" : "Installing dependencies"
|
|
21
|
-
}:`
|
|
22
|
-
);
|
|
23
|
-
dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
|
|
24
|
-
// Prepare the npm install command with the appropriate flag for dev dependencies
|
|
25
|
-
const npmInstallCommand = `npm install ${
|
|
26
|
-
isDev ? "--save-dev" : ""
|
|
27
|
-
} ${dependencies.join(" ")}`;
|
|
28
|
-
// Execute the npm install command
|
|
29
|
-
execSync(npmInstallCommand, {
|
|
30
|
-
stdio: "inherit",
|
|
31
|
-
cwd: baseDir,
|
|
32
|
-
});
|
|
33
|
-
}
|
|
34
|
-
async function main() {
|
|
35
|
-
try {
|
|
36
|
-
const args = process.argv.slice(2);
|
|
37
|
-
let projectName = args[0];
|
|
38
|
-
let answer = null;
|
|
39
|
-
if (projectName) {
|
|
40
|
-
let useBackendOnly = args.includes("--backend-only");
|
|
41
|
-
let useSwaggerDocs = args.includes("--swagger-docs");
|
|
42
|
-
let useTailwind = args.includes("--tailwindcss");
|
|
43
|
-
let useWebsocket = args.includes("--websocket");
|
|
44
|
-
let usePrisma = args.includes("--prisma");
|
|
45
|
-
let useDocker = args.includes("--docker");
|
|
46
|
-
const predefinedAnswers = {
|
|
47
|
-
projectName,
|
|
48
|
-
backendOnly: useBackendOnly,
|
|
49
|
-
swaggerDocs: useSwaggerDocs,
|
|
50
|
-
tailwindcss: useTailwind,
|
|
51
|
-
websocket: useWebsocket,
|
|
52
|
-
prisma: usePrisma,
|
|
53
|
-
docker: useDocker,
|
|
54
|
-
};
|
|
55
|
-
answer = await getAnswer(predefinedAnswers);
|
|
56
|
-
if (answer === null) {
|
|
57
|
-
console.log(chalk.red("Installation cancelled."));
|
|
58
|
-
return;
|
|
59
|
-
}
|
|
60
|
-
const currentDir = process.cwd();
|
|
61
|
-
const configPath = path.join(currentDir, "prisma-php.json");
|
|
62
|
-
const localSettings = readJsonFile(configPath);
|
|
63
|
-
let excludeFiles = [];
|
|
64
|
-
localSettings.excludeFiles?.map((file) => {
|
|
65
|
-
const filePath = path.join(currentDir, file);
|
|
66
|
-
if (fs.existsSync(filePath))
|
|
67
|
-
excludeFiles.push(filePath.replace(/\\/g, "/"));
|
|
68
|
-
});
|
|
69
|
-
updateAnswer = {
|
|
70
|
-
projectName,
|
|
71
|
-
backendOnly: answer?.backendOnly ?? false,
|
|
72
|
-
swaggerDocs: answer?.swaggerDocs ?? false,
|
|
73
|
-
tailwindcss: answer?.tailwindcss ?? false,
|
|
74
|
-
websocket: answer?.websocket ?? false,
|
|
75
|
-
prisma: answer?.prisma ?? false,
|
|
76
|
-
docker: answer?.docker ?? false,
|
|
77
|
-
isUpdate: true,
|
|
78
|
-
excludeFiles: localSettings.excludeFiles ?? [],
|
|
79
|
-
excludeFilePath: excludeFiles ?? [],
|
|
80
|
-
filePath: currentDir,
|
|
81
|
-
};
|
|
82
|
-
} else {
|
|
83
|
-
answer = await getAnswer();
|
|
84
|
-
}
|
|
85
|
-
if (answer === null) {
|
|
86
|
-
console.warn(chalk.red("Installation cancelled."));
|
|
87
|
-
return;
|
|
88
|
-
}
|
|
89
|
-
const latestVersionOfCreatePrismaPhpApp = await fetchPackageVersion(
|
|
90
|
-
"create-prisma-php-app"
|
|
91
|
-
);
|
|
92
|
-
const isCreatePrismaPhpAppInstalled = getInstalledPackageVersion(
|
|
93
|
-
"create-prisma-php-app"
|
|
94
|
-
);
|
|
95
|
-
if (isCreatePrismaPhpAppInstalled) {
|
|
96
|
-
if (
|
|
97
|
-
compareVersions(
|
|
98
|
-
isCreatePrismaPhpAppInstalled,
|
|
99
|
-
latestVersionOfCreatePrismaPhpApp
|
|
100
|
-
) === -1
|
|
101
|
-
) {
|
|
102
|
-
execSync(`npm uninstall -g create-prisma-php-app`, {
|
|
103
|
-
stdio: "inherit",
|
|
104
|
-
});
|
|
105
|
-
execSync(`npm install -g create-prisma-php-app`, {
|
|
106
|
-
stdio: "inherit",
|
|
107
|
-
});
|
|
108
|
-
}
|
|
109
|
-
} else {
|
|
110
|
-
execSync("npm install -g create-prisma-php-app", { stdio: "inherit" });
|
|
111
|
-
}
|
|
112
|
-
// Create the project directory
|
|
113
|
-
if (!projectName) fs.mkdirSync(answer.projectName);
|
|
114
|
-
const currentDir = process.cwd();
|
|
115
|
-
let projectPath = projectName
|
|
116
|
-
? currentDir
|
|
117
|
-
: path.join(currentDir, answer.projectName);
|
|
118
|
-
if (!projectName) process.chdir(answer.projectName);
|
|
119
|
-
const dependencies = [
|
|
120
|
-
"typescript",
|
|
121
|
-
"@types/node",
|
|
122
|
-
"tsx",
|
|
123
|
-
"ts-node",
|
|
124
|
-
"http-proxy-middleware",
|
|
125
|
-
"chalk",
|
|
126
|
-
"npm-run-all",
|
|
127
|
-
"browser-sync",
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
"
|
|
139
|
-
"
|
|
140
|
-
"postcss
|
|
141
|
-
"
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
"
|
|
166
|
-
"
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
if
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
backendOnlyFolders
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
"
|
|
215
|
-
"
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
swaggerFiles
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
"
|
|
234
|
-
"
|
|
235
|
-
"
|
|
236
|
-
"@
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
tailwindFiles.
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
"
|
|
253
|
-
"
|
|
254
|
-
"postcss
|
|
255
|
-
"
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
"restart-websocket.
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
"
|
|
276
|
-
"
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
"
|
|
291
|
-
"
|
|
292
|
-
"
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
const
|
|
314
|
-
const
|
|
315
|
-
const
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
console.log(
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
}
|
|
366
|
-
|
|
1
|
+
#!/usr/bin/env node
|
|
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;const nonBackendFiles=["favicon.ico","\\src\\app\\index.php","metadata.php","not-found.php"],dockerFiles=[".dockerignore","docker-compose.yml","Dockerfile","apache.conf"];function bsConfigUrls(e){const s=e.indexOf("\\htdocs\\");if(-1===s)return{bsTarget:"",bsPathRewrite:{}};const t=e.substring(0,s+"\\htdocs\\".length).replace(/\\/g,"\\\\"),n=e.replace(new RegExp(`^${t}`),"").replace(/\\/g,"/");let c=`http://localhost/${n}`;c=c.endsWith("/")?c.slice(0,-1):c;const i=c.replace(/(?<!:)(\/\/+)/g,"/"),o=n.replace(/\/\/+/g,"/");return{bsTarget:`${i}/`,bsPathRewrite:{"^/":`/${o.startsWith("/")?o.substring(1):o}/`}}}async function updatePackageJson(e,s){const t=path.join(e,"package.json");if(checkExcludeFiles(t))return;const n=JSON.parse(fs.readFileSync(t,"utf8"));n.scripts={...n.scripts,projectName:"tsx settings/project-name.ts"};let c=[];if(s.tailwindcss&&(n.scripts={...n.scripts,tailwind:"postcss src/app/css/tailwind.css -o src/app/css/styles.css --watch"},c.push("tailwind")),s.websocket&&(n.scripts={...n.scripts,websocket:"tsx settings/restart-websocket.ts"},c.push("websocket")),s.docker&&(n.scripts={...n.scripts,docker:"docker-compose up"},c.push("docker")),s.swaggerDocs){const e=s.prisma?"tsx settings/auto-swagger-docs.ts":"tsx settings/swagger-config.ts";n.scripts={...n.scripts,"create-swagger-docs":e}}let i={...n.scripts};i.browserSync="tsx settings/bs-config.ts",i.dev=`npm-run-all projectName -p browserSync ${c.join(" ")}`,n.scripts=i,n.type="module",s.prisma&&(n.prisma={seed:"tsx prisma/seed.ts"}),fs.writeFileSync(t,JSON.stringify(n,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={...n.require,"cboden/ratchet":"^0.4.4"}),s.prisma&&(n.require={...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\nvar ws = new WebSocket("ws://localhost:8080");\n',fs.writeFileSync(t,n,"utf8")}function copyRecursiveSync(e,s,t){const n=fs.existsSync(e),c=n&&fs.statSync(e);if(n&&c&&c.isDirectory()){const n=s.toLowerCase();if(!t.websocket&&n.includes("src\\lib\\websocket"))return;if(!t.prisma&&n.includes("src\\lib\\prisma"))return;if(t.backendOnly&&n.includes("src\\app\\js")||t.backendOnly&&n.includes("src\\app\\css")||t.backendOnly&&n.includes("src\\app\\assets"))return;if(!t.swaggerDocs&&n.includes("src\\app\\swagger-docs"))return;const c=s.replace(/\\/g,"/");if(updateAnswer?.excludeFilePath?.includes(c))return;fs.existsSync(s)||fs.mkdirSync(s,{recursive:!0}),fs.readdirSync(e).forEach((n=>{copyRecursiveSync(path.join(e,n),path.join(s,n),t)}))}else{if(checkExcludeFiles(s))return;if(!t.tailwindcss&&(s.includes("tailwind.css")||s.includes("styles.css")))return;if(!t.websocket&&(s.includes("restart-websocket.ts")||s.includes("restart-websocket.bat")))return;if(!t.docker&&dockerFiles.some((e=>s.includes(e))))return;if(t.backendOnly&&nonBackendFiles.some((e=>s.includes(e))))return;if(!t.backendOnly&&s.includes("route.php"))return;if(t.backendOnly&&!t.swaggerDocs&&s.includes("layout.php"))return;if(!t.swaggerDocs&&s.includes("swagger-config.ts"))return;if(t.tailwindcss&&s.includes("index.css"))return;if((!t.swaggerDocs||!t.prisma)&&(s.includes("auto-swagger-docs.ts")||s.includes("prisma-sdk.ts")||s.includes("prisma-schema-config.json")||s.includes("prisma-schema.json")))return;fs.copyFileSync(e,s,0)}}async function executeCopy(e,s,t){s.forEach((({src:s,dest:n})=>{copyRecursiveSync(path.join(__dirname,s),path.join(e,n),t)}))}function createOrUpdateTailwindConfig(e){const s=path.join(e,"tailwind.config.js");if(checkExcludeFiles(s))return;let t=fs.readFileSync(s,"utf8");const n=["./src/**/*.{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"),n="";s.backendOnly||(s.tailwindcss||(n='\n <link href="<?= Request::baseUrl; ?>/css/index.css" rel="stylesheet">'),n+='\n <script src="<?= Request::baseUrl; ?>/js/json5.min.js"><\/script>\n <script src="<?= Request::baseUrl; ?>/js/index.js"><\/script>');let c="";s.backendOnly||(c=s.tailwindcss?` <link href="<?= Request::baseUrl; ?>/css/styles.css" rel="stylesheet"> ${n}`:n);const i=c.length>0?"\n":"";e=e.replace("</head>",`${c}${i} \x3c!-- Dynamic Head --\x3e\n <?= MainLayout::outputHeadScripts() ?>\n</head>`),fs.writeFileSync(t,e,{flag:"w"})}catch(e){}}async function createOrUpdateEnvFile(e,s){const t=path.join(e,".env");checkExcludeFiles(t)||fs.writeFileSync(t,s,{flag:"w"})}function checkExcludeFiles(e){return!!updateAnswer?.isUpdate&&(updateAnswer?.excludeFilePath?.includes(e.replace(/\\/g,"/"))??!1)}async function createDirectoryStructure(e,s){const t=[{src:"/bootstrap.php",dest:"/bootstrap.php"},{src:"/.htaccess",dest:"/.htaccess"},{src:"/../composer.json",dest:"/composer.json"},{src:"/tsconfig.json",dest:"/tsconfig.json"},{src:"/app-gitignore",dest:"/.gitignore"}];s.tailwindcss&&t.push({src:"/postcss.config.js",dest:"/postcss.config.js"},{src:"/tailwind.config.js",dest:"/tailwind.config.js"});const n=[{src:"/settings",dest:"/settings"},{src:"/src",dest:"/src"}];s.prisma&&n.push({src:"/prisma",dest:"/prisma"}),s.docker&&n.push({src:"/.dockerignore",dest:"/.dockerignore"},{src:"/docker-compose.yml",dest:"/docker-compose.yml"},{src:"/Dockerfile",dest:"/Dockerfile"},{src:"/apache.conf",dest:"/apache.conf"}),t.forEach((({src:s,dest:t})=>{const n=path.join(__dirname,s),c=path.join(e,t);if(checkExcludeFiles(c))return;const i=fs.readFileSync(n,"utf8");fs.writeFileSync(c,i,{flag:"w"})})),await executeCopy(e,n,s),await updatePackageJson(e,s),await updateComposerJson(e,s),s.backendOnly||await updateIndexJsForWebSocket(e,s),s.tailwindcss&&(createOrUpdateTailwindConfig(e),modifyPostcssConfig(e)),(s.tailwindcss||!s.backendOnly||s.swaggerDocs)&&modifyLayoutPHP(e,s);const c='# 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"\n\n# SHOW ERRORS - Set to true to show errors in the browser for development only - Change this in production to false\nSHOW_ERRORS=true\n\n# APP TIMEZONE - Set your application timezone - Default is "UTC"\nAPP_TIMEZONE="UTC"\n\n# APP ENV - Set your application environment - Default is "development" - Change this in production to "production"\nAPP_ENV=development';if(s.prisma){const s=`${'# Environment variables declared in this file are automatically made available to Prisma.\n# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema\n\n# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.\n# See the documentation for all the connection string options: https://pris.ly/d/connection-strings\n\nDATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"'}\n\n${c}`;await createOrUpdateEnvFile(e,s)}else await createOrUpdateEnvFile(e,c)}async function getAnswer(e={}){const s=[];e.projectName||s.push({type:"text",name:"projectName",message:"What is your project named?",initial:"my-app"}),e.backendOnly||s.push({type:"toggle",name:"backendOnly",message:`Would you like to create a ${chalk.blue("backend-only project")}?`,initial:!1,active:"Yes",inactive:"No"});const t=()=>{process.exit(0)},n=await prompts(s,{onCancel:t}),c=[];n.backendOnly||e.backendOnly?(e.swaggerDocs||c.push({type:"toggle",name:"swaggerDocs",message:`Would you like to use ${chalk.blue("Swagger Docs")}?`,initial:!1,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"}),e.docker||c.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"})):(e.swaggerDocs||c.push({type:"toggle",name:"swaggerDocs",message:`Would you like to use ${chalk.blue("Swagger Docs")}?`,initial:!1,active:"Yes",inactive:"No"}),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"}),e.docker||c.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"}));const i=await prompts(c,{onCancel:t});return{projectName:n.projectName?String(n.projectName).trim().replace(/ /g,"-"):e.projectName??"my-app",backendOnly:n.backendOnly??e.backendOnly??!1,swaggerDocs:i.swaggerDocs??e.swaggerDocs??!1,tailwindcss:i.tailwindcss??e.tailwindcss??!1,websocket:i.websocket??e.websocket??!1,prisma:i.prisma??e.prisma??!1,docker:i.docker??e.docker??!1}}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)};function compareVersions(e,s){const t=e.split(".").map(Number),n=s.split(".").map(Number);for(let e=0;e<t.length;e++){if(t[e]>n[e])return 1;if(t[e]<n[e])return-1}return 0}function getInstalledPackageVersion(e){try{const s=execSync(`npm list -g ${e} --depth=0`).toString().match(new RegExp(`${e}@(\\d+\\.\\d+\\.\\d+)`));return s?s[1]:null}catch(e){return null}}
|
|
3
|
+
/**
|
|
4
|
+
* Install dependencies in the specified directory.
|
|
5
|
+
* @param {string} baseDir - The base directory where to install the dependencies.
|
|
6
|
+
* @param {string[]} dependencies - The list of dependencies to install.
|
|
7
|
+
* @param {boolean} [isDev=false] - Whether to install the dependencies as devDependencies.
|
|
8
|
+
*/
|
|
9
|
+
async function installDependencies(baseDir, dependencies, isDev = false) {
|
|
10
|
+
console.log("Initializing new Node.js project...");
|
|
11
|
+
// Initialize a package.json if it doesn't exist
|
|
12
|
+
if (!fs.existsSync(path.join(baseDir, "package.json")))
|
|
13
|
+
execSync("npm init -y", {
|
|
14
|
+
stdio: "inherit",
|
|
15
|
+
cwd: baseDir,
|
|
16
|
+
});
|
|
17
|
+
// Log the dependencies being installed
|
|
18
|
+
console.log(
|
|
19
|
+
`${
|
|
20
|
+
isDev ? "Installing development dependencies" : "Installing dependencies"
|
|
21
|
+
}:`
|
|
22
|
+
);
|
|
23
|
+
dependencies.forEach((dep) => console.log(`- ${chalk.blue(dep)}`));
|
|
24
|
+
// Prepare the npm install command with the appropriate flag for dev dependencies
|
|
25
|
+
const npmInstallCommand = `npm install ${
|
|
26
|
+
isDev ? "--save-dev" : ""
|
|
27
|
+
} ${dependencies.join(" ")}`;
|
|
28
|
+
// Execute the npm install command
|
|
29
|
+
execSync(npmInstallCommand, {
|
|
30
|
+
stdio: "inherit",
|
|
31
|
+
cwd: baseDir,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
async function main() {
|
|
35
|
+
try {
|
|
36
|
+
const args = process.argv.slice(2);
|
|
37
|
+
let projectName = args[0];
|
|
38
|
+
let answer = null;
|
|
39
|
+
if (projectName) {
|
|
40
|
+
let useBackendOnly = args.includes("--backend-only");
|
|
41
|
+
let useSwaggerDocs = args.includes("--swagger-docs");
|
|
42
|
+
let useTailwind = args.includes("--tailwindcss");
|
|
43
|
+
let useWebsocket = args.includes("--websocket");
|
|
44
|
+
let usePrisma = args.includes("--prisma");
|
|
45
|
+
let useDocker = args.includes("--docker");
|
|
46
|
+
const predefinedAnswers = {
|
|
47
|
+
projectName,
|
|
48
|
+
backendOnly: useBackendOnly,
|
|
49
|
+
swaggerDocs: useSwaggerDocs,
|
|
50
|
+
tailwindcss: useTailwind,
|
|
51
|
+
websocket: useWebsocket,
|
|
52
|
+
prisma: usePrisma,
|
|
53
|
+
docker: useDocker,
|
|
54
|
+
};
|
|
55
|
+
answer = await getAnswer(predefinedAnswers);
|
|
56
|
+
if (answer === null) {
|
|
57
|
+
console.log(chalk.red("Installation cancelled."));
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
const currentDir = process.cwd();
|
|
61
|
+
const configPath = path.join(currentDir, "prisma-php.json");
|
|
62
|
+
const localSettings = readJsonFile(configPath);
|
|
63
|
+
let excludeFiles = [];
|
|
64
|
+
localSettings.excludeFiles?.map((file) => {
|
|
65
|
+
const filePath = path.join(currentDir, file);
|
|
66
|
+
if (fs.existsSync(filePath))
|
|
67
|
+
excludeFiles.push(filePath.replace(/\\/g, "/"));
|
|
68
|
+
});
|
|
69
|
+
updateAnswer = {
|
|
70
|
+
projectName,
|
|
71
|
+
backendOnly: answer?.backendOnly ?? false,
|
|
72
|
+
swaggerDocs: answer?.swaggerDocs ?? false,
|
|
73
|
+
tailwindcss: answer?.tailwindcss ?? false,
|
|
74
|
+
websocket: answer?.websocket ?? false,
|
|
75
|
+
prisma: answer?.prisma ?? false,
|
|
76
|
+
docker: answer?.docker ?? false,
|
|
77
|
+
isUpdate: true,
|
|
78
|
+
excludeFiles: localSettings.excludeFiles ?? [],
|
|
79
|
+
excludeFilePath: excludeFiles ?? [],
|
|
80
|
+
filePath: currentDir,
|
|
81
|
+
};
|
|
82
|
+
} else {
|
|
83
|
+
answer = await getAnswer();
|
|
84
|
+
}
|
|
85
|
+
if (answer === null) {
|
|
86
|
+
console.warn(chalk.red("Installation cancelled."));
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
const latestVersionOfCreatePrismaPhpApp = await fetchPackageVersion(
|
|
90
|
+
"create-prisma-php-app"
|
|
91
|
+
);
|
|
92
|
+
const isCreatePrismaPhpAppInstalled = getInstalledPackageVersion(
|
|
93
|
+
"create-prisma-php-app"
|
|
94
|
+
);
|
|
95
|
+
if (isCreatePrismaPhpAppInstalled) {
|
|
96
|
+
if (
|
|
97
|
+
compareVersions(
|
|
98
|
+
isCreatePrismaPhpAppInstalled,
|
|
99
|
+
latestVersionOfCreatePrismaPhpApp
|
|
100
|
+
) === -1
|
|
101
|
+
) {
|
|
102
|
+
execSync(`npm uninstall -g create-prisma-php-app`, {
|
|
103
|
+
stdio: "inherit",
|
|
104
|
+
});
|
|
105
|
+
execSync(`npm install -g create-prisma-php-app`, {
|
|
106
|
+
stdio: "inherit",
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
} else {
|
|
110
|
+
execSync("npm install -g create-prisma-php-app", { stdio: "inherit" });
|
|
111
|
+
}
|
|
112
|
+
// Create the project directory
|
|
113
|
+
if (!projectName) fs.mkdirSync(answer.projectName);
|
|
114
|
+
const currentDir = process.cwd();
|
|
115
|
+
let projectPath = projectName
|
|
116
|
+
? currentDir
|
|
117
|
+
: path.join(currentDir, answer.projectName);
|
|
118
|
+
if (!projectName) process.chdir(answer.projectName);
|
|
119
|
+
const dependencies = [
|
|
120
|
+
"typescript",
|
|
121
|
+
"@types/node",
|
|
122
|
+
"tsx",
|
|
123
|
+
"ts-node",
|
|
124
|
+
"http-proxy-middleware",
|
|
125
|
+
"chalk",
|
|
126
|
+
"npm-run-all",
|
|
127
|
+
"browser-sync",
|
|
128
|
+
"@types/browser-sync",
|
|
129
|
+
];
|
|
130
|
+
if (answer.swaggerDocs) {
|
|
131
|
+
dependencies.push("swagger-jsdoc", "@types/swagger-jsdoc");
|
|
132
|
+
}
|
|
133
|
+
if (answer.swaggerDocs && answer.prisma) {
|
|
134
|
+
dependencies.push("prompts", "@types/prompts", "@prisma/internals");
|
|
135
|
+
}
|
|
136
|
+
if (answer.tailwindcss) {
|
|
137
|
+
dependencies.push(
|
|
138
|
+
"tailwindcss",
|
|
139
|
+
"autoprefixer",
|
|
140
|
+
"postcss",
|
|
141
|
+
"postcss-cli",
|
|
142
|
+
"cssnano"
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
if (answer.websocket) {
|
|
146
|
+
dependencies.push("chokidar-cli");
|
|
147
|
+
}
|
|
148
|
+
if (answer.prisma) {
|
|
149
|
+
dependencies.push("prisma", "@prisma/client");
|
|
150
|
+
}
|
|
151
|
+
await installDependencies(projectPath, dependencies, true);
|
|
152
|
+
if (!projectName) {
|
|
153
|
+
execSync(`npx tsc --init`, { stdio: "inherit" });
|
|
154
|
+
}
|
|
155
|
+
if (answer.tailwindcss)
|
|
156
|
+
execSync(`npx tailwindcss init -p`, { stdio: "inherit" });
|
|
157
|
+
if (answer.prisma) {
|
|
158
|
+
if (!fs.existsSync(path.join(projectPath, "prisma")))
|
|
159
|
+
execSync(`npx prisma init`, { stdio: "inherit" });
|
|
160
|
+
}
|
|
161
|
+
await createDirectoryStructure(projectPath, answer);
|
|
162
|
+
if (answer.swaggerDocs) {
|
|
163
|
+
const swaggerDocsPath = path.join(
|
|
164
|
+
projectPath,
|
|
165
|
+
"src",
|
|
166
|
+
"app",
|
|
167
|
+
"swagger-docs"
|
|
168
|
+
);
|
|
169
|
+
// Check if the directory exists
|
|
170
|
+
if (fs.existsSync(swaggerDocsPath)) {
|
|
171
|
+
// If it exists and is not empty, remove it before cloning
|
|
172
|
+
if (fs.readdirSync(swaggerDocsPath).length > 0) {
|
|
173
|
+
console.log("Removing existing swagger-docs directory...");
|
|
174
|
+
fs.rmSync(swaggerDocsPath, { recursive: true, force: true });
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
// Clone the Git repository into the swagger-docs directory
|
|
178
|
+
execSync(
|
|
179
|
+
`git clone https://github.com/TheSteelNinjaCode/prisma-php-swagger-docs.git ${swaggerDocsPath}`,
|
|
180
|
+
{ stdio: "inherit" }
|
|
181
|
+
);
|
|
182
|
+
// delete the folder .git
|
|
183
|
+
fs.rmSync(path.join(swaggerDocsPath, ".git"), {
|
|
184
|
+
recursive: true,
|
|
185
|
+
force: true,
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
if (updateAnswer?.isUpdate) {
|
|
189
|
+
const updateUninstallDependencies = [];
|
|
190
|
+
if (updateAnswer.backendOnly) {
|
|
191
|
+
nonBackendFiles.forEach((file) => {
|
|
192
|
+
const filePath = path.join(projectPath, "src", "app", file);
|
|
193
|
+
if (fs.existsSync(filePath)) {
|
|
194
|
+
fs.unlinkSync(filePath); // Delete each file if it exists
|
|
195
|
+
console.log(`${file} was deleted successfully.`);
|
|
196
|
+
} else {
|
|
197
|
+
console.log(`${file} does not exist.`);
|
|
198
|
+
}
|
|
199
|
+
});
|
|
200
|
+
const backendOnlyFolders = ["js", "css"];
|
|
201
|
+
backendOnlyFolders.forEach((folder) => {
|
|
202
|
+
const folderPath = path.join(projectPath, "src", "app", folder);
|
|
203
|
+
if (fs.existsSync(folderPath)) {
|
|
204
|
+
fs.rmSync(folderPath, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
|
|
205
|
+
console.log(`${folder} was deleted successfully.`);
|
|
206
|
+
} else {
|
|
207
|
+
console.log(`${folder} does not exist.`);
|
|
208
|
+
}
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
if (!updateAnswer.swaggerDocs) {
|
|
212
|
+
const swaggerDocsFolder = path.join(
|
|
213
|
+
projectPath,
|
|
214
|
+
"src",
|
|
215
|
+
"app",
|
|
216
|
+
"swagger-docs"
|
|
217
|
+
);
|
|
218
|
+
if (fs.existsSync(swaggerDocsFolder)) {
|
|
219
|
+
fs.rmSync(swaggerDocsFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
|
|
220
|
+
console.log(`swagger-docs was deleted successfully.`);
|
|
221
|
+
}
|
|
222
|
+
const swaggerFiles = ["swagger-config.ts"];
|
|
223
|
+
swaggerFiles.forEach((file) => {
|
|
224
|
+
const filePath = path.join(projectPath, "settings", file);
|
|
225
|
+
if (fs.existsSync(filePath)) {
|
|
226
|
+
fs.unlinkSync(filePath); // Delete each file if it exists
|
|
227
|
+
console.log(`${file} was deleted successfully.`);
|
|
228
|
+
} else {
|
|
229
|
+
console.log(`${file} does not exist.`);
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
updateUninstallDependencies.push(
|
|
233
|
+
"swagger-jsdoc",
|
|
234
|
+
"@types/swagger-jsdoc",
|
|
235
|
+
"prompts",
|
|
236
|
+
"@types/prompts",
|
|
237
|
+
"@prisma/internals"
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
if (!updateAnswer.tailwindcss) {
|
|
241
|
+
const tailwindFiles = ["postcss.config.js", "tailwind.config.js"];
|
|
242
|
+
tailwindFiles.forEach((file) => {
|
|
243
|
+
const filePath = path.join(projectPath, file);
|
|
244
|
+
if (fs.existsSync(filePath)) {
|
|
245
|
+
fs.unlinkSync(filePath); // Delete each file if it exists
|
|
246
|
+
console.log(`${file} was deleted successfully.`);
|
|
247
|
+
} else {
|
|
248
|
+
console.log(`${file} does not exist.`);
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
updateUninstallDependencies.push(
|
|
252
|
+
"tailwindcss",
|
|
253
|
+
"autoprefixer",
|
|
254
|
+
"postcss",
|
|
255
|
+
"postcss-cli",
|
|
256
|
+
"cssnano"
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
if (!updateAnswer.websocket) {
|
|
260
|
+
const websocketFiles = [
|
|
261
|
+
"restart-websocket.ts",
|
|
262
|
+
"restart-websocket.bat",
|
|
263
|
+
];
|
|
264
|
+
websocketFiles.forEach((file) => {
|
|
265
|
+
const filePath = path.join(projectPath, "settings", file);
|
|
266
|
+
if (fs.existsSync(filePath)) {
|
|
267
|
+
fs.unlinkSync(filePath); // Delete each file if it exists
|
|
268
|
+
console.log(`${file} was deleted successfully.`);
|
|
269
|
+
} else {
|
|
270
|
+
console.log(`${file} does not exist.`);
|
|
271
|
+
}
|
|
272
|
+
});
|
|
273
|
+
const websocketFolder = path.join(
|
|
274
|
+
projectPath,
|
|
275
|
+
"src",
|
|
276
|
+
"Lib",
|
|
277
|
+
"Websocket"
|
|
278
|
+
);
|
|
279
|
+
if (fs.existsSync(websocketFolder)) {
|
|
280
|
+
fs.rmSync(websocketFolder, { recursive: true, force: true }); // Use fs.rmSync instead of fs.rmdirSync
|
|
281
|
+
console.log(`Websocket folder was deleted successfully.`);
|
|
282
|
+
}
|
|
283
|
+
updateUninstallDependencies.push("chokidar-cli");
|
|
284
|
+
}
|
|
285
|
+
if (!updateAnswer.prisma) {
|
|
286
|
+
updateUninstallDependencies.push("prisma", "@prisma/client");
|
|
287
|
+
}
|
|
288
|
+
if (!updateAnswer.docker) {
|
|
289
|
+
const dockerFiles = [
|
|
290
|
+
".dockerignore",
|
|
291
|
+
"docker-compose.yml",
|
|
292
|
+
"Dockerfile",
|
|
293
|
+
"apache.conf",
|
|
294
|
+
];
|
|
295
|
+
dockerFiles.forEach((file) => {
|
|
296
|
+
const filePath = path.join(projectPath, file);
|
|
297
|
+
if (fs.existsSync(filePath)) {
|
|
298
|
+
fs.unlinkSync(filePath); // Delete each file if it exists
|
|
299
|
+
console.log(`${file} was deleted successfully.`);
|
|
300
|
+
} else {
|
|
301
|
+
console.log(`${file} does not exist.`);
|
|
302
|
+
}
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
if (updateUninstallDependencies.length > 0) {
|
|
306
|
+
await uninstallDependencies(
|
|
307
|
+
projectPath,
|
|
308
|
+
updateUninstallDependencies,
|
|
309
|
+
true
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
const projectPathModified = projectPath.replace(/\\/g, "\\");
|
|
314
|
+
const bsConfig = bsConfigUrls(projectPathModified);
|
|
315
|
+
const phpGenerateClassPath = answer.prisma ? "src/Lib/Prisma/Classes" : "";
|
|
316
|
+
const prismaPhpConfig = {
|
|
317
|
+
projectName: answer.projectName,
|
|
318
|
+
projectRootPath: projectPathModified,
|
|
319
|
+
phpEnvironment: "XAMPP",
|
|
320
|
+
phpRootPathExe: "C:\\xampp\\php\\php.exe",
|
|
321
|
+
phpGenerateClassPath,
|
|
322
|
+
bsTarget: bsConfig.bsTarget,
|
|
323
|
+
bsPathRewrite: bsConfig.bsPathRewrite,
|
|
324
|
+
backendOnly: answer.backendOnly,
|
|
325
|
+
swaggerDocs: answer.swaggerDocs,
|
|
326
|
+
tailwindcss: answer.tailwindcss,
|
|
327
|
+
websocket: answer.websocket,
|
|
328
|
+
prisma: answer.prisma,
|
|
329
|
+
docker: answer.docker,
|
|
330
|
+
version: latestVersionOfCreatePrismaPhpApp,
|
|
331
|
+
excludeFiles: updateAnswer?.excludeFiles ?? [],
|
|
332
|
+
};
|
|
333
|
+
fs.writeFileSync(
|
|
334
|
+
path.join(projectPath, "prisma-php.json"),
|
|
335
|
+
JSON.stringify(prismaPhpConfig, null, 2),
|
|
336
|
+
{ flag: "w" }
|
|
337
|
+
);
|
|
338
|
+
if (updateAnswer?.isUpdate) {
|
|
339
|
+
execSync(
|
|
340
|
+
`C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar update`,
|
|
341
|
+
{
|
|
342
|
+
stdio: "inherit",
|
|
343
|
+
}
|
|
344
|
+
);
|
|
345
|
+
} else {
|
|
346
|
+
execSync(
|
|
347
|
+
`C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar install`,
|
|
348
|
+
{
|
|
349
|
+
stdio: "inherit",
|
|
350
|
+
}
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
console.log("\n=========================\n");
|
|
354
|
+
console.log(
|
|
355
|
+
`${chalk.green(
|
|
356
|
+
"Success!"
|
|
357
|
+
)} Prisma PHP project successfully created in ${chalk.green(
|
|
358
|
+
`${currentDir.replace(/\\/g, "/")}/${answer.projectName}`
|
|
359
|
+
)}!`
|
|
360
|
+
);
|
|
361
|
+
console.log("\n=========================");
|
|
362
|
+
} catch (error) {
|
|
363
|
+
console.error("Error while creating the project:", error);
|
|
364
|
+
process.exit(1);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
main();
|
package/dist/src/app/js/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const eventAttributesB6B56=new Set(["onclick","ondblclick","onmousedown","onmouseup","onmouseover","onmousemove","onmouseout","onwheel","onkeypress","onkeydown","onkeyup","onfocus","onblur","onchange","oninput","onselect","onsubmit","onreset","onresize","onscroll","onload","onunload","onabort","onerror","onbeforeunload","oncopy","oncut","onpaste","ondrag","ondragstart","ondragend","ondragover","ondragenter","ondragleave","ondrop","oncontextmenu","ontouchstart","ontouchmove","ontouchend","ontouchcancel","onpointerdown","onpointerup","onpointermove","onpointerover","onpointerout","onpointerenter","onpointerleave","onpointercancel"]),stateA129A={checkedElements:new Set};let responseDataDEAC2=null;var store=null;let isNavigatingA12E1=!1;const redirectRegex3AE99=/redirect_7F834\s*=\s*(\/[^\s]*)/,existingScripts=new Set;function observeDOMChanges(){new MutationObserver((e=>{for(const t of e)"childList"===t.type&&t.addedNodes.length>0&&attachWireFunctionEvents()})).observe(document.body,{childList:!0,subtree:!0})}function attachWireFunctionEvents(){handleHiddenAttribute();document.querySelectorAll("button, input, select, textarea, a, form, label, div, span").forEach((e=>{if(handleAnchorTag(e),Array.from(e.attributes).filter((e=>eventAttributesB6B56.has(e.name))).forEach((t=>{const n=t.name.slice(2),o=t.value;o&&(e.removeAttribute(t.name),handleDebounce(e,n,o))})),e instanceof HTMLFormElement){const t=e.getAttribute("onsubmit");t&&(e.removeAttribute("onsubmit"),handleDebounce(e,"submit",t))}}))}function handleHiddenAttribute(){const e=document.querySelectorAll("[pp-visibility]"),t=document.querySelectorAll("[pp-display]");e.forEach((e=>handleVisibilityElementAttribute(e,"pp-visibility",handleElementVisibility))),t.forEach((e=>handleVisibilityElementAttribute(e,"pp-display",handleElementDisplay)))}function handleVisibilityElementAttribute(e,t,n){const o=e.getAttribute(t);if(o)if(isJsonLike(o)){n(e,parseJson(o))}else{const n=parseTime(o);if(n>0){const o="pp-visibility"===t?"visibility":"display";scheduleChange(e,n,o,"visibility"===o?"hidden":"none")}}}function isJsonLike(e){return"string"==typeof e&&((e=e.trim()).startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]"))}function handleElementVisibility(e,t){handleElementChange(e,t,"visibility","hidden","visible")}function handleElementDisplay(e,t){handleElementChange(e,t,"display","none","block")}function handleElementChange(e,t,n,o,s){const a=t.start?parseTime(t.start):0,r=t.end?parseTime(t.end):0;a>0?(e.style[n]=o,scheduleChange(e,a,n,s),r>0&&scheduleChange(e,a+r,n,o)):r>0&&scheduleChange(e,r,n,o)}function scheduleChange(e,t,n,o){setTimeout((()=>{requestAnimationFrame((()=>{e.style[n]=o}))}),t)}function parseTime(e){if("number"==typeof e)return e;const t=e.match(/^(\d+)(ms|s|m)?$/);if(t){const e=parseInt(t[1],10);switch(t[2]||"ms"){case"ms":return e;case"s":return 1e3*e;case"m":return 60*e*1e3;default:return e}}return 0}async function handleDebounce(e,t,n){e.removeEventListener(t,(()=>{}));const o=e.getAttribute("pp-debounce")||"",s=e.getAttribute("pp-before-request")||"",a=e.getAttribute("pp-after-request")||"",r=async t=>{t.preventDefault();try{s&&await invokeHandler(e,s,t),await invokeHandler(e,n,t),a&&"@close"!==a&&await invokeHandler(e,a,t),handlerAutofocusAttribute()}catch(e){}};if(o){const n=debounce(r,parseTime(o));e instanceof HTMLFormElement&&"submit"===t?e.addEventListener(t,(e=>{e.preventDefault(),n(e)})):e.addEventListener(t,n)}else e.addEventListener(t,r)}function handlerAutofocusAttribute(){const e=document.querySelectorAll("[pp-autofocus]");let t=!1;e.forEach((e=>{if(t)return;const n=e.getAttribute("pp-autofocus");if(!n||!isJsonLike(n))return;const o=parseJson(n);if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){const t=["text","search","tel","url","password"];if(e instanceof HTMLInputElement)if(t.includes(e.type))if("number"===e.type){e.type="text";const t=e.value.length||0;e.setSelectionRange(t,t),e.type="number"}else setCursorPosition(e,o);else;else e instanceof HTMLTextAreaElement&&setCursorPosition(e,o)}e.focus(),t=!0}))}function setCursorPosition(e,t){if(t.start)e.setSelectionRange(0,0);else if(t.end){const t=e.value.length||0;e.setSelectionRange(t,t)}else if(t.length){const n=parseInt(t.length,10)||0;e.setSelectionRange(n,n)}}async function invokeHandler(e,t,n){try{const o=t.match(/^(\w+(\.\w+)*)\((.*)\)$/);if(o){const s=o[1].split("."),{context:a,methodName:r}=resolveContext(s);"function"==typeof a[r]?new Function("event",t).call(e,n):await handleParsedCallback(e,t)}else await handleParsedCallback(e,t)}catch(e){}}function resolveContext(e){let t=window;for(let n=0;n<e.length-1;n++)if(t=t[e[n]],!t)throw new Error(`Cannot find object ${e[n]} in the context.`);return{context:t,methodName:e[e.length-1]}}async function handleParsedCallback(e,t){const{funcName:n,data:o}=parseCallback(e,t);if(!n)return;const s=window[n];if("function"==typeof s){const t=e.hasAttribute("pp-after-request"),n=Array.isArray(o.args)?o.args:[],a=responseDataDEAC2?parseJson(responseDataDEAC2):{response:responseDataDEAC2};let r={args:n,element:e,data:o};t&&(r={...r,...a}),await s(r)}else responseDataDEAC2=null,responseDataDEAC2=await handleUndefinedFunction(e,n,o)}function handleAnchorTag(e){e instanceof HTMLAnchorElement&&e.addEventListener("click",(async e=>{const t=e.currentTarget,n=t.getAttribute("href"),o=t.getAttribute("target");if(n&&"_blank"!==o&&!e.metaKey&&!e.ctrlKey&&(e.preventDefault(),!isNavigatingA12E1)){isNavigatingA12E1=!0;try{if(/^(https?:)?\/\//i.test(n)&&!n.startsWith(window.location.origin))window.location.href=n;else{const e=t.getAttribute("pp-append-params");if(n.startsWith("?")&&"true"===e){const e=new URL(window.location.href),t=new URLSearchParams(e.search);let o="";const[s,a]=n.split("#");a&&(o=`#${a}`);new URLSearchParams(s.split("?")[1]).forEach(((e,n)=>{t.set(n,e)}));const r=`${e.pathname}?${t.toString()}${o}`;history.pushState(null,"",r)}else{const[e,t]=n.split("#"),o=`${e}${t?`#${t}`:""}`;history.pushState(null,"",o)}const o=n.indexOf("#");if(-1!==o){const e=n.slice(o+1),t=document.getElementById(e);if(t)t.scrollIntoView({behavior:"smooth"});else{await handleNavigation();const t=document.getElementById(e);t&&t.scrollIntoView({behavior:"smooth"})}}else await handleNavigation()}}catch(e){}finally{isNavigatingA12E1=!1}}}))}async function handleNavigation(){try{const e=e=>{const t=e.querySelector("[pp-loading-transition]")?.getAttribute("pp-loading-transition");let n=250,o=250;if(t)try{const e=parseJson(t);n=parseTime(e.fadeIn||n),o=parseTime(e.fadeOut||o)}catch(e){}return{fadeIn:n,fadeOut:o}},t=(e,t)=>new Promise((n=>{e.style.transition=`opacity ${t}ms ease-out`,e.style.opacity="0",setTimeout((()=>{e.style.transition="",n()}),t)})),n=(e,t)=>{e.style.transition=`opacity ${t}ms ease-in`,e.style.opacity="1",setTimeout((()=>{e.style.transition=""}),t)},o=async o=>{const s=document.querySelector("[pp-loading-content='true']")||document.body;if(s){const{fadeIn:a,fadeOut:r}=e(o);await t(s,r),s.innerHTML=o.innerHTML,n(s,a)}},s=window.location.pathname,a=document.getElementById("loading-file-1B87E");if(a){let e=a.querySelector(`div[pp-loading-url='${s}']`);e||(e=a.querySelector("div[pp-loading-url='/']")),e&&await o(e)}const r=await pphpFetch(window.location.href),i=r.match(redirectRegex3AE99);if(i&&i[1]){const e=i[1];await handleRedirect(e)}else updateDocumentContent(r)}catch(e){}}function onUrlChange(){}async function updateBodyContent(e){const t=saveScrollPositions();saveState();const n=(new DOMParser).parseFromString(e,"text/html");await appendCallbackResponse(n),restoreState(),restoreScrollPositions(t),document.dispatchEvent(new Event("PPBodyLoaded"))}async function appendCallbackResponse(e){const t=e.getElementById("afterbegin-8D95D");if(t){const e=document.getElementById("afterbegin-8D95D");e?e.innerHTML=t.innerHTML:document.body.insertAdjacentHTML("afterbegin",t.outerHTML)}await populateDocumentBody(e)}async function updateDocumentContent(e){const t=saveScrollPositions(),n=(new DOMParser).parseFromString(e,"text/html"),o="pp-dynamic-script",s="pp-dynamic-link";document.head.querySelectorAll("[pp-dynamic-meta]").forEach((e=>e.remove()));document.head.querySelectorAll("[pp-dynamic-link]").forEach((e=>e.remove()));document.head.querySelectorAll("[pp-dynamic-script]").forEach((e=>e.remove()));await(async e=>{Array.from(e.head.children).forEach((e=>{const t=e.tagName;if("SCRIPT"===t&&e.hasAttribute(o)){const t=document.createElement("script");Array.from(e.attributes).forEach((e=>t.setAttribute(e.name,e.value))),e.textContent&&(t.textContent=e.textContent),document.head.appendChild(t)}else if("META"===t){if(e.getAttribute("charset")||"viewport"===e.getAttribute("name"))return;const t=e.name,n=e.getAttribute("property"),o=document.head.querySelector(t?`meta[name="${t}"]`:`meta[property="${n}"]`);o?document.head.replaceChild(e.cloneNode(!0),o):document.head.appendChild(e.cloneNode(!0))}else if("TITLE"===t){const t=document.head.querySelector("title");t?document.head.replaceChild(e.cloneNode(!0),t):document.head.appendChild(e.cloneNode(!0))}else if("LINK"===t){const t=t=>{const n=document.head.querySelector('link[rel="icon"]');if(n)document.head.replaceChild(e.cloneNode(!0),n);else{const e=document.createElement("link");e.rel="icon",e.href=t,document.head.appendChild(e)}};if("icon"===e.getAttribute("rel")){t(e.href)}else if(e.hasAttribute(s)){const t=e.cloneNode(!0);document.head.appendChild(t)}}})),await populateDocumentBody(e)})(n),restoreScrollPositions(t),document.dispatchEvent(new Event("PPBodyLoaded"))}async function populateDocumentBody(e){const t=e.body.cloneNode(!0);document.body.querySelectorAll("script").forEach((e=>{e.src?existingScripts.add(e.src):e.textContent&&existingScripts.add(e.textContent.trim())}));t.querySelectorAll("script").forEach((e=>{const t=e.src||e.textContent?.trim();if(t&&existingScripts.has(t))return;t&&existingScripts.add(t);const n=document.createElement("script");Array.from(e.attributes).forEach((e=>{n.setAttribute(e.name,e.value)})),e.hasAttribute("src")||(n.textContent=e.textContent),e.parentNode?.replaceChild(n,e)})),document.body.replaceWith(t)}function saveState(){const e=document.activeElement;stateA129A.focusId=e?.id||e?.name,stateA129A.focusValue=e?.value,stateA129A.focusChecked=e?.checked,stateA129A.focusType=e?.type,stateA129A.focusSelectionStart=e?.selectionStart,stateA129A.focusSelectionEnd=e?.selectionEnd,stateA129A.isSuspense=e.hasAttribute("pp-suspense"),stateA129A.checkedElements.clear(),document.querySelectorAll('input[type="checkbox"]:checked').forEach((e=>{stateA129A.checkedElements.add(e.id||e.name)})),document.querySelectorAll('input[type="radio"]:checked').forEach((e=>{stateA129A.checkedElements.add(e.id||e.name)}))}function restoreState(){if(stateA129A.focusId){const e=document.getElementById(stateA129A.focusId)||document.querySelector(`[name="${stateA129A.focusId}"]`);if(e instanceof HTMLInputElement){const t=e.value.length||0;void 0!==stateA129A.focusSelectionStart&&null!==stateA129A.focusSelectionEnd&&e.setSelectionRange(t,t),stateA129A.focusValue&&("checkbox"===e.type||"radio"===e.type?e.checked=!!stateA129A.focusChecked:"number"===e.type||"email"===e.type?(e.type="text",e.setSelectionRange(t,t),e.type="number"===e.type?"number":"email"):"date"===e.type||"month"===e.type||"week"===e.type||"time"===e.type||"datetime-local"===e.type||"color"===e.type||"file"===e.type||""!==e.value&&(e.value=stateA129A.focusValue)),e.focus()}else if(e instanceof HTMLTextAreaElement){const t=e.value.length||0;void 0!==stateA129A.focusSelectionStart&&null!==stateA129A.focusSelectionEnd&&e.setSelectionRange(t,t),stateA129A.focusValue&&""!==e.value&&(e.value=stateA129A.focusValue),e.focus()}else e instanceof HTMLSelectElement&&(stateA129A.focusValue&&""!==e.value&&(e.value=stateA129A.focusValue),e.focus())}stateA129A.checkedElements.forEach((e=>{const t=document.getElementById(e);t&&(t.checked=!0)}))}function saveScrollPositions(){const e={window:{scrollTop:window.scrollY||document.documentElement.scrollTop,scrollLeft:window.scrollX||document.documentElement.scrollLeft}};return document.querySelectorAll("*").forEach((t=>{(t.scrollTop||t.scrollLeft)&&(e[getElementKey(t)]={scrollTop:t.scrollTop,scrollLeft:t.scrollLeft})})),e}function restoreScrollPositions(e){requestAnimationFrame((()=>{const t=e.window;t&&window.scrollTo(t.scrollLeft,t.scrollTop),document.querySelectorAll("*").forEach((t=>{const n=getElementKey(t);e[n]&&(t.scrollTop=e[n].scrollTop,t.scrollLeft=e[n].scrollLeft)}))}))}function getElementKey(e){return e.id||e.className||e.tagName}async function pphpFetch(e,t){const n=await fetch(e,{...t,headers:{...t?.headers,"X-Requested-With":"XMLHttpRequest"}});return await n.text()}function parseCallback(e,t){let n={};const o=e.closest("form");if(o){new FormData(o).forEach(((e,t)=>{n[t]?Array.isArray(n[t])?n[t].push(e):n[t]=[n[t],e]:n[t]=e}))}else e instanceof HTMLInputElement?n=handleInputElement(e):(e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(n[e.name]=e.value);const s=t.match(/(\w+)\((.*)\)/);if(s){const e=s[1];let t=s[2].trim();if(t.startsWith("{")&&t.endsWith("}"))try{const e=parseJson(t);"object"==typeof e&&null!==e&&(n={...n,...e})}catch(e){}else{const e=t.split(/,(?=(?:[^'"]*['"][^'"]*['"])*[^'"]*$)/).map((e=>e.trim().replace(/^['"]|['"]$/g,"")));n.args=e}return{funcName:e,data:n}}return{funcName:t,data:n}}function handleInputElement(e){let t={};if(e.name)if("checkbox"===e.type)t[e.name]={value:e.value,checked:e.checked};else if("radio"===e.type){const n=document.querySelector(`input[name="${e.name}"]:checked`);t[e.name]=n?n.value:null}else t[e.name]=e.value;else"checkbox"===e.type||"radio"===e.type?t.value=e.checked:t.value=e.value;return t}function updateElementAttributes(e,t){for(const n in t)if(t.hasOwnProperty(n))switch(n){case"innerHTML":case"outerHTML":case"textContent":case"innerText":e[n]=decodeHTML(t[n]);break;case"insertAdjacentHTML":e.insertAdjacentHTML(t.position||"beforeend",decodeHTML(t[n].html));break;case"insertAdjacentText":e.insertAdjacentText(t.position||"beforeend",decodeHTML(t[n].text));break;case"setAttribute":e.setAttribute(t.attrName,decodeHTML(t[n]));break;case"removeAttribute":e.removeAttribute(t[n]);break;case"className":e.className=decodeHTML(t[n]);break;case"classList.add":e.classList.add(...decodeHTML(t[n]).split(","));break;case"classList.remove":e.classList.remove(...decodeHTML(t[n]).split(","));break;case"classList.toggle":e.classList.toggle(decodeHTML(t[n]));break;case"classList.replace":const[o,s]=decodeHTML(t[n]).split(",");e.classList.replace(o,s);break;case"dataset":e.dataset[t.attrName]=decodeHTML(t[n]);break;case"style":Object.assign(e.style,t[n]);break;case"value":e.value=decodeHTML(t[n]);break;case"checked":e.checked=t[n];break;default:e.setAttribute(n,decodeHTML(t[n]))}}function decodeHTML(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}function saveElementOriginalState(e){if(e.hasAttribute("pp-suspense")&&!e.hasAttribute("pp-original-state")){const t={};e.textContent&&(t.textContent=e.textContent.trim()),e.innerHTML&&(t.innerHTML=e.innerHTML.trim()),(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(t.value=e.value);for(let n=0;n<e.attributes.length;n++){const o=e.attributes[n];t[o.name]=o.value}e.setAttribute("pp-original-state",JSON.stringify(t))}e.querySelectorAll("[pp-suspense]").forEach((e=>saveElementOriginalState(e)))}async function handleSuspenseElement(e){let t=e.getAttribute("pp-suspense")||"";const n=(e,t)=>{for(const n in t)if(t.hasOwnProperty(n))for(const t of e.elements)if(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){const e=t.getAttribute("pp-suspense")||"";if(e)if(isJsonLike(e)){const n=parseJson(e);"disabled"!==n.onsubmit&&updateElementAttributes(t,n),n.targets&&n.targets.forEach((e=>{const{id:t,...n}=e,o=document.querySelector(t);o&&s(o,n)}))}else o(t,e)}},o=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},s=(e,t)=>{e instanceof HTMLFormElement?n(e,t):updateElementAttributes(e,t)};try{if(t&&isJsonLike(t)){const o=parseJson(t);if(o)if(e instanceof HTMLFormElement){const t=new FormData(e),s={};t.forEach(((e,t)=>{s[t]=e})),o.disabled&&toggleFormElements(e,!0);const{disabled:a,...r}=o;updateElementAttributes(e,r),n(e,s)}else if(o.targets){o.targets.forEach((e=>{const{id:t,...n}=e,o=document.querySelector(t);o&&s(o,n)}));const{targets:t,...n}=o;updateElementAttributes(e,n)}else{if("disabled"===o.empty&&""===e.value)return;const{empty:t,...n}=o;updateElementAttributes(e,n)}}else if(t)o(e,t);else if(e instanceof HTMLFormElement){const t=new FormData(e),o={};t.forEach(((e,t)=>{o[t]=e})),n(e,o)}}catch(e){}}function restoreSuspenseElement(e){const t=e.getAttribute("pp-original-state");if(e.hasAttribute("pp-suspense")&&t){const n=(e,t)=>{for(const n in t)t.hasOwnProperty(n)&&("textContent"===n?e.textContent=t[n]:"innerHTML"===n?e.innerHTML=t[n]:"disabled"===n?!0===t[n]?e.setAttribute("disabled","true"):e.removeAttribute("disabled"):e.setAttribute(n,t[n]));for(const n of Array.from(e.attributes))t.hasOwnProperty(n.name)||e.removeAttribute(n.name)},o=(e,t)=>{for(const o in t)if(t.hasOwnProperty(o))for(const t of Array.from(e.elements))if(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){const e=t.getAttribute("pp-original-state")||"";if(e){if(isJsonLike(e)){const o=parseJson(e);n(t,o)}else s(t,e);t.removeAttribute("pp-original-state")}}},s=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},a=(e,t)=>{e instanceof HTMLFormElement?o(e,t):n(e,t)};try{const s=parseJson(t);if(s)if(e instanceof HTMLFormElement){const t=new FormData(e),n={};if(t.forEach(((e,t)=>{n[t]=e})),o(e,n),e.hasAttribute("pp-suspense")){const t=e.getAttribute("pp-suspense")||"";if(parseJson(t).disabled)for(const t of Array.from(e.elements))(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&t.removeAttribute("disabled")}}else if(s.targets){s.targets.forEach((e=>{const{id:t,...n}=e,o=document.querySelector(t);o&&a(o,n)}));const{targets:t,...o}=s;n(e,o)}else{const{empty:t,...o}=s;n(e,o)}}catch(e){}}e.querySelectorAll("[pp-suspense]").forEach((e=>restoreSuspenseElement(e))),e.removeAttribute("pp-original-state")}function parseJson(e){try{return JSON5.parse(e)}catch(e){return null}}function toggleFormElements(e,t){Array.from(e.elements).forEach((e=>{(e instanceof HTMLInputElement||e instanceof HTMLButtonElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(e.disabled=t)}))}async function pphpFetchFile(e,t,n){const o=new FormData,s=n.files;if(s)for(let e=0;e<s.length;e++)o.append("file[]",s[e]);o.append("callback",t);const a=await fetch(e,{method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:o});return await a.text()}function getUrlParams(){const e={};return new URLSearchParams(window.location.search).forEach(((t,n)=>{e[n]=t})),e}async function handleUndefinedFunction(e,t,n){const o=createFetchOptions({callback:t,...n}),s=createFetchOptions({secondRequestC69CD:!0,...getUrlParams()});try{saveElementOriginalState(e),handleSuspenseElement(e);const n=new URL(window.location.href);let a="",r="",i={success:!1};const c=e.querySelector("input[type='file']");if(c){if(a=await pphpFetchFile(n.href,t,c),r=extractJson(a)||"",r)try{i=parseJson(r)}catch(e){}}else if(a=await pphpFetch(n.href,o),r=extractJson(a)||"",r)try{i=parseJson(r)}catch(e){}const l=e.getAttribute("pp-before-request")||"",u=e.getAttribute("pp-after-request")||"";if((l||u&&i.success)&&restoreSuspenseElement(e),l||u){let e="";if(i.success){e=a.replace(r,"")}else e=a;if(appendAfterbegin(e),!u&&!i.success)return}if(u&&i.success){handleAfterRequest(u,r);return appendAfterbegin(a.replace(r,"")),r}if("@close"===u)return i.success?r:void 0;const d=await pphpFetch(n.href,s);await handleResponseRedirectOrUpdate(a,d,r,i)}catch(e){}}function createFetchOptions(e){return{method:"POST",headers:{"Content-Type":"application/json",HTTP_PPHP_WIRE_REQUEST:"true"},body:JSON.stringify(e)}}function getRedirectUrl(e){const t=e.match(redirectRegex3AE99);return t?t[1]:null}function getUpdatedHTMLContent(e,t,n){const o=document.createElement("div");if(o.id="afterbegin-8D95D",n&&t?.success){const t=e.replace(n,"");o.innerHTML=t}else o.innerHTML=e;return o.innerHTML?o:null}async function handleResponseRedirectOrUpdate(e,t,n,o){const s=getRedirectUrl(e);if(s)await handleRedirect(s);else{const s=getUpdatedHTMLContent(e,n,o),a=(new DOMParser).parseFromString(t,"text/html");s&&a.body.insertAdjacentElement("afterbegin",s),updateBodyContent(a.body.outerHTML)}}function appendAfterbegin(e){if(!e)return;const t="afterbegin-8D95D";let n=document.getElementById(t);n?(n.innerHTML=e,document.body.insertAdjacentElement("afterbegin",n)):(n=document.createElement("div"),n.id=t,n.innerHTML=e,document.body.insertAdjacentElement("afterbegin",n))}function extractJson(e){const t=e?.match(/\{[\s\S]*\}/);return t?t[0]:null}function handleAfterRequest(e,t){if(!isJsonLike(e))return;const n=parseJson(e),o=t?parseJson(t):null,s=n.targets;Array.isArray(s)&&s.forEach((e=>{const{id:t,...n}=e,s=document.querySelector(t);let a={};if(o){for(const t in n)if(n.hasOwnProperty(t))switch(t){case"innerHTML":case"outerHTML":case"textContent":case"innerText":"response"===n[t]&&(a[t]=e.responseKey?o[e.responseKey]:o.response);break;default:a[t]=n[t];break}}else a=n;s&&updateElementAttributes(s,a)}))}async function handleRedirect(e){if(e)try{const t=new URL(e,window.location.origin);t.origin!==window.location.origin?window.location.href=e:(history.pushState(null,"",e),await handleNavigation())}catch(e){}}function debounce(e,t=300,n=!1){let o;return function(...s){const a=this;o&&clearTimeout(o),o=setTimeout((()=>{o=null,n||e.apply(a,s)}),t),n&&!o&&e.apply(a,s)}}function copyCode(e,t,n,o,s="img",a=2e3){if(!(e instanceof HTMLElement))return;const r=e.closest(`.${t}`)?.querySelector("pre code"),i=r?.textContent?.trim()||"";i?navigator.clipboard.writeText(i).then((()=>{const t=e.querySelector(s);if(t)for(const[e,n]of Object.entries(o))e in t?t[e]=n:t.setAttribute(e,n);setTimeout((()=>{if(t)for(const[e,o]of Object.entries(n))e in t?t[e]=o:t.setAttribute(e,o)}),a)}),(()=>{alert("Failed to copy command to clipboard")})):alert("Failed to find the code block to copy")}if((e=>{const t=e.pushState,n=e.replaceState;e.pushState=function(n,o,s){const a=t.apply(e,arguments);return window.dispatchEvent(new Event("urlchange")),a},e.replaceState=function(t,o,s){const a=n.apply(e,arguments);return window.dispatchEvent(new Event("urlchange")),a}})(window.history),document.addEventListener("PPBodyLoaded",(()=>{attachWireFunctionEvents(),observeDOMChanges()})),document.addEventListener("DOMContentLoaded",(()=>{document.dispatchEvent(new Event("PPBodyLoaded"))})),window.addEventListener("popstate",(async()=>{await handleNavigation()})),window.addEventListener("urlchange",(()=>{})),null===store){class e{static instance=null;state;listeners;constructor(e={}){this.state=e,this.listeners=[]}static getInstance(t={}){return e.instance||(e.instance=new e(t),e.instance.loadState()),e.instance}setState(e){this.state={...this.state,...e},this.listeners.forEach((e=>e(this.state))),this.saveState()}subscribe(e){return this.listeners.push(e),e(this.state),()=>{this.listeners=this.listeners.filter((t=>t!==e))}}saveState(){localStorage.setItem("appState_59E13",JSON.stringify(this.state))}loadState(){const e=localStorage.getItem("appState_59E13");e&&(this.state=parseJson(e),this.listeners.forEach((e=>e(this.state))))}resetState(e){e?(delete this.state[e],this.saveState()):(this.state={},localStorage.removeItem("appState_59E13")),this.listeners.forEach((e=>e(this.state)))}}store=e.getInstance()}
|
|
1
|
+
const eventAttributesB6B56=new Set(["onclick","ondblclick","onmousedown","onmouseup","onmouseover","onmousemove","onmouseout","onwheel","onkeypress","onkeydown","onkeyup","onfocus","onblur","onchange","oninput","onselect","onsubmit","onreset","onresize","onscroll","onload","onunload","onabort","onerror","onbeforeunload","oncopy","oncut","onpaste","ondrag","ondragstart","ondragend","ondragover","ondragenter","ondragleave","ondrop","oncontextmenu","ontouchstart","ontouchmove","ontouchend","ontouchcancel","onpointerdown","onpointerup","onpointermove","onpointerover","onpointerout","onpointerenter","onpointerleave","onpointercancel"]);(()=>{const e=EventTarget.prototype.addEventListener,t=EventTarget.prototype.removeEventListener,n=new Map;EventTarget.prototype.addEventListener=function(t,o,s){n.has(this)||n.set(this,new Map);const a=n.get(this).get(t)||new Set;a.add(o),n.get(this).set(t,a),e.call(this,t,o,s)},EventTarget.prototype.removeEventListener=function(e,o,s){if(n.has(this)&&n.get(this).has(e)){const t=n.get(this).get(e);t&&(t.delete(o),0===t.size&&n.get(this).delete(e))}t.call(this,e,o,s)},EventTarget.prototype.removeAllEventListeners=function(e){if(n.has(this)&&n.get(this).has(e)){const o=n.get(this).get(e);o&&(o.forEach((n=>{t.call(this,e,n)})),n.get(this).delete(e))}}})();const stateA129A={checkedElements:new Set};let responseDataDEAC2=null;var store=null;let isNavigatingA12E1=!1;const redirectRegex3AE99=/redirect_7F834\s*=\s*(\/[^\s]*)/;function observeDOMChanges(){new MutationObserver((e=>{for(const t of e)"childList"===t.type&&t.addedNodes.length>0&&attachWireFunctionEvents()})).observe(document.body,{childList:!0,subtree:!0})}function attachWireFunctionEvents(){handleHiddenAttribute();document.querySelectorAll("button, input, select, textarea, a, form, label, div, span").forEach((e=>{if(handleAnchorTag(e),Array.from(e.attributes).filter((e=>eventAttributesB6B56.has(e.name))).forEach((t=>{const n=t.name.slice(2),o=t.value;o&&(e.removeAttribute(t.name),handleDebounce(e,n,o))})),e instanceof HTMLFormElement){const t=e.getAttribute("onsubmit");t&&(e.removeAttribute("onsubmit"),handleDebounce(e,"submit",t))}}))}function handleHiddenAttribute(){const e=document.querySelectorAll("[pp-visibility]"),t=document.querySelectorAll("[pp-display]");e.forEach((e=>handleVisibilityElementAttribute(e,"pp-visibility",handleElementVisibility))),t.forEach((e=>handleVisibilityElementAttribute(e,"pp-display",handleElementDisplay)))}function handleVisibilityElementAttribute(e,t,n){const o=e.getAttribute(t);if(o)if(isJsonLike(o)){n(e,parseJson(o))}else{const n=parseTime(o);if(n>0){const o="pp-visibility"===t?"visibility":"display";scheduleChange(e,n,o,"visibility"===o?"hidden":"none")}}}function isJsonLike(e){return"string"==typeof e&&((e=e.trim()).startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]"))}function handleElementVisibility(e,t){handleElementChange(e,t,"visibility","hidden","visible")}function handleElementDisplay(e,t){handleElementChange(e,t,"display","none","block")}function handleElementChange(e,t,n,o,s){const a=t.start?parseTime(t.start):0,r=t.end?parseTime(t.end):0;a>0?(e.style[n]=o,scheduleChange(e,a,n,s),r>0&&scheduleChange(e,a+r,n,o)):r>0&&scheduleChange(e,r,n,o)}function scheduleChange(e,t,n,o){setTimeout((()=>{requestAnimationFrame((()=>{e.style[n]=o}))}),t)}function parseTime(e){if("number"==typeof e)return e;const t=e.match(/^(\d+)(ms|s|m)?$/);if(t){const e=parseInt(t[1],10);switch(t[2]||"ms"){case"ms":return e;case"s":return 1e3*e;case"m":return 60*e*1e3;default:return e}}return 0}async function handleDebounce(e,t,n){e.removeEventListener(t,(()=>{}));const o=e.getAttribute("pp-debounce")||"",s=e.getAttribute("pp-before-request")||"",a=e.getAttribute("pp-after-request")||"",r=async t=>{t.preventDefault();try{s&&await invokeHandler(e,s,t),await invokeHandler(e,n,t),a&&"@close"!==a&&await invokeHandler(e,a,t),handlerAutofocusAttribute()}catch(e){}};if(o){const n=debounce(r,parseTime(o));e instanceof HTMLFormElement&&"submit"===t?e.addEventListener(t,(e=>{e.preventDefault(),n(e)})):e.addEventListener(t,n)}else e.addEventListener(t,r)}function handlerAutofocusAttribute(){const e=document.querySelectorAll("[pp-autofocus]");let t=!1;e.forEach((e=>{if(t)return;const n=e.getAttribute("pp-autofocus");if(!n||!isJsonLike(n))return;const o=parseJson(n);if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){const t=["text","search","tel","url","password"];if(e instanceof HTMLInputElement)if(t.includes(e.type))if("number"===e.type){e.type="text";const t=e.value.length||0;e.setSelectionRange(t,t),e.type="number"}else setCursorPosition(e,o);else;else e instanceof HTMLTextAreaElement&&setCursorPosition(e,o)}e.focus(),t=!0}))}function setCursorPosition(e,t){if(t.start)e.setSelectionRange(0,0);else if(t.end){const t=e.value.length||0;e.setSelectionRange(t,t)}else if(t.length){const n=parseInt(t.length,10)||0;e.setSelectionRange(n,n)}}async function invokeHandler(e,t,n){try{const o=t.match(/^(\w+(\.\w+)*)\((.*)\)$/);if(o){const s=o[1].split("."),{context:a,methodName:r}=resolveContext(s);"function"==typeof a[r]?new Function("event",t).call(e,n):await handleParsedCallback(e,t)}else await handleParsedCallback(e,t)}catch(e){}}function resolveContext(e){let t=window;for(let n=0;n<e.length-1;n++)if(t=t[e[n]],!t)throw new Error(`Cannot find object ${e[n]} in the context.`);return{context:t,methodName:e[e.length-1]}}async function handleParsedCallback(e,t){const{funcName:n,data:o}=parseCallback(e,t);if(!n)return;const s=window[n];if("function"==typeof s){const t=e.hasAttribute("pp-after-request"),n=Array.isArray(o.args)?o.args:[],a=responseDataDEAC2?parseJson(responseDataDEAC2):{response:responseDataDEAC2};let r={args:n,element:e,data:o};t&&(r={...r,...a}),await s(r)}else responseDataDEAC2=null,responseDataDEAC2=await handleUndefinedFunction(e,n,o)}function handleAnchorTag(e){e instanceof HTMLAnchorElement&&e.addEventListener("click",(async e=>{const t=e.currentTarget,n=t.getAttribute("href"),o=t.getAttribute("target");if(n&&"_blank"!==o&&!e.metaKey&&!e.ctrlKey&&(e.preventDefault(),!isNavigatingA12E1)){isNavigatingA12E1=!0;try{if(/^(https?:)?\/\//i.test(n)&&!n.startsWith(window.location.origin))window.location.href=n;else{const e=t.getAttribute("pp-append-params");if(n.startsWith("?")&&"true"===e){const e=new URL(window.location.href),t=new URLSearchParams(e.search);let o="";const[s,a]=n.split("#");a&&(o=`#${a}`);new URLSearchParams(s.split("?")[1]).forEach(((e,n)=>{t.set(n,e)}));const r=`${e.pathname}?${t.toString()}${o}`;history.pushState(null,"",r)}else{const[e,t]=n.split("#"),o=`${e}${t?`#${t}`:""}`;history.pushState(null,"",o)}const o=n.indexOf("#");if(-1!==o){const e=n.slice(o+1),t=document.getElementById(e);if(t)t.scrollIntoView({behavior:"smooth"});else{await handleNavigation();const t=document.getElementById(e);t&&t.scrollIntoView({behavior:"smooth"})}}else await handleNavigation()}}catch(e){}finally{isNavigatingA12E1=!1}}}))}async function handleNavigation(){try{const e=e=>{const t=e.querySelector("[pp-loading-transition]")?.getAttribute("pp-loading-transition");let n=250,o=250;if(t)try{const e=parseJson(t);n=parseTime(e.fadeIn||n),o=parseTime(e.fadeOut||o)}catch(e){}return{fadeIn:n,fadeOut:o}},t=(e,t)=>new Promise((n=>{e.style.transition=`opacity ${t}ms ease-out`,e.style.opacity="0",setTimeout((()=>{e.style.transition="",n()}),t)})),n=(e,t)=>{e.style.transition=`opacity ${t}ms ease-in`,e.style.opacity="1",setTimeout((()=>{e.style.transition=""}),t)},o=async o=>{const s=document.querySelector("[pp-loading-content='true']")||document.body;if(s){const{fadeIn:a,fadeOut:r}=e(o);await t(s,r),s.innerHTML=o.innerHTML,n(s,a)}},s=window.location.pathname,a=document.getElementById("loading-file-1B87E");if(a){let e=a.querySelector(`div[pp-loading-url='${s}']`);e||(e=a.querySelector("div[pp-loading-url='/']")),e&&await o(e)}const r=await pphpFetch(window.location.href),i=r.match(redirectRegex3AE99);if(i&&i[1]){const e=i[1];await handleRedirect(e)}else updateDocumentContent(r)}catch(e){}}function onUrlChange(){}async function updateBodyContent(e){const t=saveScrollPositions();saveState();const n=(new DOMParser).parseFromString(e,"text/html");document.removeAllEventListeners("PPBodyLoaded"),await appendCallbackResponse(n),restoreState(),restoreScrollPositions(t),attachWireFunctionEvents(),document.dispatchEvent(new Event("PPBodyLoaded"))}async function appendCallbackResponse(e){const t=e.getElementById("afterbegin-8D95D");if(t){const e=document.getElementById("afterbegin-8D95D");e?e.innerHTML=t.innerHTML:document.body.insertAdjacentHTML("afterbegin",t.outerHTML)}await populateDocumentBody(e)}async function updateDocumentContent(e){const t=saveScrollPositions(),n=(new DOMParser).parseFromString(e,"text/html"),o="pp-dynamic-script",s="pp-dynamic-link";document.head.querySelectorAll("[pp-dynamic-meta]").forEach((e=>e.remove()));document.head.querySelectorAll("[pp-dynamic-link]").forEach((e=>e.remove()));document.head.querySelectorAll("[pp-dynamic-script]").forEach((e=>e.remove()));document.removeAllEventListeners("PPBodyLoaded"),await(async e=>{Array.from(e.head.children).forEach((e=>{const t=e.tagName;if("SCRIPT"===t&&e.hasAttribute(o)){const t=document.createElement("script");Array.from(e.attributes).forEach((e=>t.setAttribute(e.name,e.value))),e.textContent&&(t.textContent=e.textContent),document.head.appendChild(t)}else if("META"===t){if(e.getAttribute("charset")||"viewport"===e.getAttribute("name"))return;const t=e.name,n=e.getAttribute("property"),o=document.head.querySelector(t?`meta[name="${t}"]`:`meta[property="${n}"]`);o?document.head.replaceChild(e.cloneNode(!0),o):document.head.appendChild(e.cloneNode(!0))}else if("TITLE"===t){const t=document.head.querySelector("title");t?document.head.replaceChild(e.cloneNode(!0),t):document.head.appendChild(e.cloneNode(!0))}else if("LINK"===t){const t=t=>{const n=document.head.querySelector('link[rel="icon"]');if(n)document.head.replaceChild(e.cloneNode(!0),n);else{const e=document.createElement("link");e.rel="icon",e.href=t,document.head.appendChild(e)}};if("icon"===e.getAttribute("rel")){t(e.href)}else if(e.hasAttribute(s)){const t=e.cloneNode(!0);document.head.appendChild(t)}}})),await populateDocumentBody(e)})(n),restoreScrollPositions(t),attachWireFunctionEvents(),document.dispatchEvent(new Event("PPBodyLoaded"))}async function populateDocumentBody(e){try{const t=e.body.cloneNode(!0);t.querySelectorAll("script").forEach((e=>{const t=document.createElement("script");Array.from(e.attributes).forEach((e=>{t.setAttribute(e.name,e.value)})),e.hasAttribute("src")||(t.textContent=e.textContent),e.parentNode?.replaceChild(t,e)})),document.body.replaceWith(t)}catch(e){}}function saveState(){const e=document.activeElement;stateA129A.focusId=e?.id||e?.name,stateA129A.focusValue=e?.value,stateA129A.focusChecked=e?.checked,stateA129A.focusType=e?.type,stateA129A.focusSelectionStart=e?.selectionStart,stateA129A.focusSelectionEnd=e?.selectionEnd,stateA129A.isSuspense=e.hasAttribute("pp-suspense"),stateA129A.checkedElements.clear(),document.querySelectorAll('input[type="checkbox"]:checked').forEach((e=>{stateA129A.checkedElements.add(e.id||e.name)})),document.querySelectorAll('input[type="radio"]:checked').forEach((e=>{stateA129A.checkedElements.add(e.id||e.name)}))}function restoreState(){if(stateA129A.focusId){const e=document.getElementById(stateA129A.focusId)||document.querySelector(`[name="${stateA129A.focusId}"]`);if(e instanceof HTMLInputElement){const t=e.value.length||0;void 0!==stateA129A.focusSelectionStart&&null!==stateA129A.focusSelectionEnd&&e.setSelectionRange(t,t),stateA129A.focusValue&&("checkbox"===e.type||"radio"===e.type?e.checked=!!stateA129A.focusChecked:"number"===e.type||"email"===e.type?(e.type="text",e.setSelectionRange(t,t),e.type="number"===e.type?"number":"email"):"date"===e.type||"month"===e.type||"week"===e.type||"time"===e.type||"datetime-local"===e.type||"color"===e.type||"file"===e.type||""!==e.value&&(e.value=stateA129A.focusValue)),e.focus()}else if(e instanceof HTMLTextAreaElement){const t=e.value.length||0;void 0!==stateA129A.focusSelectionStart&&null!==stateA129A.focusSelectionEnd&&e.setSelectionRange(t,t),stateA129A.focusValue&&""!==e.value&&(e.value=stateA129A.focusValue),e.focus()}else e instanceof HTMLSelectElement&&(stateA129A.focusValue&&""!==e.value&&(e.value=stateA129A.focusValue),e.focus())}stateA129A.checkedElements.forEach((e=>{const t=document.getElementById(e);t&&(t.checked=!0)}))}function saveScrollPositions(){const e={window:{scrollTop:window.scrollY||document.documentElement.scrollTop,scrollLeft:window.scrollX||document.documentElement.scrollLeft}};return document.querySelectorAll("*").forEach((t=>{(t.scrollTop||t.scrollLeft)&&(e[getElementKey(t)]={scrollTop:t.scrollTop,scrollLeft:t.scrollLeft})})),e}function restoreScrollPositions(e){requestAnimationFrame((()=>{const t=e.window;t&&window.scrollTo(t.scrollLeft,t.scrollTop),document.querySelectorAll("*").forEach((t=>{const n=getElementKey(t);e[n]&&(t.scrollTop=e[n].scrollTop,t.scrollLeft=e[n].scrollLeft)}))}))}function getElementKey(e){return e.id||e.className||e.tagName}async function pphpFetch(e,t){const n=await fetch(e,{...t,headers:{...t?.headers,"X-Requested-With":"XMLHttpRequest"}});return await n.text()}function parseCallback(e,t){let n={};const o=e.closest("form");if(o){new FormData(o).forEach(((e,t)=>{n[t]?Array.isArray(n[t])?n[t].push(e):n[t]=[n[t],e]:n[t]=e}))}else e instanceof HTMLInputElement?n=handleInputElement(e):(e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(n[e.name]=e.value);const s=t.match(/(\w+)\((.*)\)/);if(s){const e=s[1];let t=s[2].trim();if(t.startsWith("{")&&t.endsWith("}"))try{const e=parseJson(t);"object"==typeof e&&null!==e&&(n={...n,...e})}catch(e){}else{const e=t.split(/,(?=(?:[^'"]*['"][^'"]*['"])*[^'"]*$)/).map((e=>e.trim().replace(/^['"]|['"]$/g,"")));n.args=e}return{funcName:e,data:n}}return{funcName:t,data:n}}function handleInputElement(e){let t={};if(e.name)if("checkbox"===e.type)t[e.name]={value:e.value,checked:e.checked};else if("radio"===e.type){const n=document.querySelector(`input[name="${e.name}"]:checked`);t[e.name]=n?n.value:null}else t[e.name]=e.value;else"checkbox"===e.type||"radio"===e.type?t.value=e.checked:t.value=e.value;return t}function updateElementAttributes(e,t){for(const n in t)if(t.hasOwnProperty(n))switch(n){case"innerHTML":case"outerHTML":case"textContent":case"innerText":e[n]=decodeHTML(t[n]);break;case"insertAdjacentHTML":e.insertAdjacentHTML(t.position||"beforeend",decodeHTML(t[n].html));break;case"insertAdjacentText":e.insertAdjacentText(t.position||"beforeend",decodeHTML(t[n].text));break;case"setAttribute":e.setAttribute(t.attrName,decodeHTML(t[n]));break;case"removeAttribute":e.removeAttribute(t[n]);break;case"className":e.className=decodeHTML(t[n]);break;case"classList.add":e.classList.add(...decodeHTML(t[n]).split(","));break;case"classList.remove":e.classList.remove(...decodeHTML(t[n]).split(","));break;case"classList.toggle":e.classList.toggle(decodeHTML(t[n]));break;case"classList.replace":const[o,s]=decodeHTML(t[n]).split(",");e.classList.replace(o,s);break;case"dataset":e.dataset[t.attrName]=decodeHTML(t[n]);break;case"style":Object.assign(e.style,t[n]);break;case"value":e.value=decodeHTML(t[n]);break;case"checked":e.checked=t[n];break;default:e.setAttribute(n,decodeHTML(t[n]))}}function decodeHTML(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}function saveElementOriginalState(e){if(e.hasAttribute("pp-suspense")&&!e.hasAttribute("pp-original-state")){const t={};e.textContent&&(t.textContent=e.textContent.trim()),e.innerHTML&&(t.innerHTML=e.innerHTML.trim()),(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(t.value=e.value);for(let n=0;n<e.attributes.length;n++){const o=e.attributes[n];t[o.name]=o.value}e.setAttribute("pp-original-state",JSON.stringify(t))}e.querySelectorAll("[pp-suspense]").forEach((e=>saveElementOriginalState(e)))}async function handleSuspenseElement(e){let t=e.getAttribute("pp-suspense")||"";const n=(e,t)=>{for(const n in t)if(t.hasOwnProperty(n))for(const t of e.elements)if(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){const e=t.getAttribute("pp-suspense")||"";if(e)if(isJsonLike(e)){const n=parseJson(e);"disabled"!==n.onsubmit&&updateElementAttributes(t,n),n.targets&&n.targets.forEach((e=>{const{id:t,...n}=e,o=document.querySelector(t);o&&s(o,n)}))}else o(t,e)}},o=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},s=(e,t)=>{e instanceof HTMLFormElement?n(e,t):updateElementAttributes(e,t)};try{if(t&&isJsonLike(t)){const o=parseJson(t);if(o)if(e instanceof HTMLFormElement){const t=new FormData(e),s={};t.forEach(((e,t)=>{s[t]=e})),o.disabled&&toggleFormElements(e,!0);const{disabled:a,...r}=o;updateElementAttributes(e,r),n(e,s)}else if(o.targets){o.targets.forEach((e=>{const{id:t,...n}=e,o=document.querySelector(t);o&&s(o,n)}));const{targets:t,...n}=o;updateElementAttributes(e,n)}else{if("disabled"===o.empty&&""===e.value)return;const{empty:t,...n}=o;updateElementAttributes(e,n)}}else if(t)o(e,t);else if(e instanceof HTMLFormElement){const t=new FormData(e),o={};t.forEach(((e,t)=>{o[t]=e})),n(e,o)}}catch(e){}}function restoreSuspenseElement(e){const t=e.getAttribute("pp-original-state");if(e.hasAttribute("pp-suspense")&&t){const n=(e,t)=>{for(const n in t)t.hasOwnProperty(n)&&("textContent"===n?e.textContent=t[n]:"innerHTML"===n?e.innerHTML=t[n]:"disabled"===n?!0===t[n]?e.setAttribute("disabled","true"):e.removeAttribute("disabled"):e.setAttribute(n,t[n]));for(const n of Array.from(e.attributes))t.hasOwnProperty(n.name)||e.removeAttribute(n.name)},o=(e,t)=>{for(const o in t)if(t.hasOwnProperty(o))for(const t of Array.from(e.elements))if(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){const e=t.getAttribute("pp-original-state")||"";if(e){if(isJsonLike(e)){const o=parseJson(e);n(t,o)}else s(t,e);t.removeAttribute("pp-original-state")}}},s=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},a=(e,t)=>{e instanceof HTMLFormElement?o(e,t):n(e,t)};try{const s=parseJson(t);if(s)if(e instanceof HTMLFormElement){const t=new FormData(e),n={};if(t.forEach(((e,t)=>{n[t]=e})),o(e,n),e.hasAttribute("pp-suspense")){const t=e.getAttribute("pp-suspense")||"";if(parseJson(t).disabled)for(const t of Array.from(e.elements))(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&t.removeAttribute("disabled")}}else if(s.targets){s.targets.forEach((e=>{const{id:t,...n}=e,o=document.querySelector(t);o&&a(o,n)}));const{targets:t,...o}=s;n(e,o)}else{const{empty:t,...o}=s;n(e,o)}}catch(e){}}e.querySelectorAll("[pp-suspense]").forEach((e=>restoreSuspenseElement(e))),e.removeAttribute("pp-original-state")}function parseJson(e){try{return JSON5.parse(e)}catch(e){return null}}function toggleFormElements(e,t){Array.from(e.elements).forEach((e=>{(e instanceof HTMLInputElement||e instanceof HTMLButtonElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(e.disabled=t)}))}async function pphpFetchFile(e,t,n){const o=new FormData,s=n.files;if(s)for(let e=0;e<s.length;e++)o.append("file[]",s[e]);o.append("callback",t);const a=await fetch(e,{method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:o});return await a.text()}function getUrlParams(){const e={};return new URLSearchParams(window.location.search).forEach(((t,n)=>{e[n]=t})),e}async function handleUndefinedFunction(e,t,n){const o=createFetchOptions({callback:t,...n}),s=createFetchOptions({secondRequestC69CD:!0,...getUrlParams()});try{saveElementOriginalState(e),handleSuspenseElement(e);const n=new URL(window.location.href);let a="",r="",i={success:!1};const c=e.querySelector("input[type='file']");if(c){if(a=await pphpFetchFile(n.href,t,c),r=extractJson(a)||"",r)try{i=parseJson(r)}catch(e){}}else if(a=await pphpFetch(n.href,o),r=extractJson(a)||"",r)try{i=parseJson(r)}catch(e){}const l=e.getAttribute("pp-before-request")||"",u=e.getAttribute("pp-after-request")||"";if((l||u&&i.success)&&restoreSuspenseElement(e),l||u){let e="";if(i.success){e=a.replace(r,"")}else e=a;if(appendAfterbegin(e),!u&&!i.success)return}if(u&&i.success){handleAfterRequest(u,r);return appendAfterbegin(a.replace(r,"")),r}if("@close"===u)return i.success?r:void 0;const d=await pphpFetch(n.href,s);await handleResponseRedirectOrUpdate(a,d,r,i)}catch(e){}}function createFetchOptions(e){return{method:"POST",headers:{"Content-Type":"application/json",HTTP_PPHP_WIRE_REQUEST:"true"},body:JSON.stringify(e)}}function getRedirectUrl(e){const t=e.match(redirectRegex3AE99);return t?t[1]:null}function getUpdatedHTMLContent(e,t,n){const o=document.createElement("div");if(o.id="afterbegin-8D95D",n&&t?.success){const t=e.replace(n,"");o.innerHTML=t}else o.innerHTML=e;return o.innerHTML?o:null}async function handleResponseRedirectOrUpdate(e,t,n,o){const s=getRedirectUrl(e);if(s)await handleRedirect(s);else{const s=getUpdatedHTMLContent(e,n,o),a=(new DOMParser).parseFromString(t,"text/html");s&&a.body.insertAdjacentElement("afterbegin",s),updateBodyContent(a.body.outerHTML)}}function appendAfterbegin(e){if(!e)return;const t="afterbegin-8D95D";let n=document.getElementById(t);n?(n.innerHTML=e,document.body.insertAdjacentElement("afterbegin",n)):(n=document.createElement("div"),n.id=t,n.innerHTML=e,document.body.insertAdjacentElement("afterbegin",n))}function extractJson(e){const t=e?.match(/\{[\s\S]*\}/);return t?t[0]:null}function handleAfterRequest(e,t){if(!isJsonLike(e))return;const n=parseJson(e),o=t?parseJson(t):null,s=n.targets;Array.isArray(s)&&s.forEach((e=>{const{id:t,...n}=e,s=document.querySelector(t);let a={};if(o){for(const t in n)if(n.hasOwnProperty(t))switch(t){case"innerHTML":case"outerHTML":case"textContent":case"innerText":"response"===n[t]&&(a[t]=e.responseKey?o[e.responseKey]:o.response);break;default:a[t]=n[t];break}}else a=n;s&&updateElementAttributes(s,a)}))}async function handleRedirect(e){if(e)try{const t=new URL(e,window.location.origin);t.origin!==window.location.origin?window.location.href=e:(history.pushState(null,"",e),await handleNavigation())}catch(e){}}function debounce(e,t=300,n=!1){let o;return function(...s){const a=this;o&&clearTimeout(o),o=setTimeout((()=>{o=null,n||e.apply(a,s)}),t),n&&!o&&e.apply(a,s)}}function copyCode(e,t,n,o,s="img",a=2e3){if(!(e instanceof HTMLElement))return;const r=e.closest(`.${t}`)?.querySelector("pre code"),i=r?.textContent?.trim()||"";i?navigator.clipboard.writeText(i).then((()=>{const t=e.querySelector(s);if(t)for(const[e,n]of Object.entries(o))e in t?t[e]=n:t.setAttribute(e,n);setTimeout((()=>{if(t)for(const[e,o]of Object.entries(n))e in t?t[e]=o:t.setAttribute(e,o)}),a)}),(()=>{alert("Failed to copy command to clipboard")})):alert("Failed to find the code block to copy")}if((e=>{const t=e.pushState,n=e.replaceState;e.pushState=function(n,o,s){const a=t.apply(e,arguments);return window.dispatchEvent(new Event("urlchange")),a},e.replaceState=function(t,o,s){const a=n.apply(e,arguments);return window.dispatchEvent(new Event("urlchange")),a}})(window.history),document.addEventListener("PPBodyLoaded",(()=>{attachWireFunctionEvents(),observeDOMChanges()})),document.addEventListener("DOMContentLoaded",(()=>{document.dispatchEvent(new Event("PPBodyLoaded"))})),window.addEventListener("popstate",(async()=>{await handleNavigation()})),window.addEventListener("urlchange",(()=>{})),null===store){class e{static instance=null;state;listeners;constructor(e={}){this.state=e,this.listeners=[]}static getInstance(t={}){return e.instance||(e.instance=new e(t),e.instance.loadState()),e.instance}setState(e){this.state={...this.state,...e},this.listeners.forEach((e=>e(this.state))),this.saveState()}subscribe(e){return this.listeners.push(e),e(this.state),()=>{this.listeners=this.listeners.filter((t=>t!==e))}}saveState(){localStorage.setItem("appState_59E13",JSON.stringify(this.state))}loadState(){const e=localStorage.getItem("appState_59E13");e&&(this.state=parseJson(e),this.listeners.forEach((e=>e(this.state))))}resetState(e){e?(delete this.state[e],this.saveState()):(this.state={},localStorage.removeItem("appState_59E13")),this.listeners.forEach((e=>e(this.state)))}}store=e.getInstance()}
|