create-prisma-php-app 3.2.5 → 3.3.0
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 +88 -22
- package/dist/src/app/js/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
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";import{randomBytes}from"crypto";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","error.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 o=c.replace(/(?<!:)(\/\/+)/g,"/"),i=n.replace(/\/\/+/g,"/");return{bsTarget:`${o}/`,bsPathRewrite:{"^/":`/${i.startsWith("/")?i.substring(1):i}/`}}}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","tailwind:build":"postcss src/app/css/tailwind.css -o src/app/css/styles.css"},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 o={...n.scripts};o.browserSync="tsx settings/bs-config.ts",o["browserSync:build"]="tsx settings/build.ts",o.dev=`npm-run-all projectName -p browserSync ${c.join(" ")}`,o.build=`npm-run-all${s.tailwindcss?" tailwind:build":""} browserSync:build`,n.scripts=o,n.type="module",fs.writeFileSync(t,JSON.stringify(n,null,2))}async function updateComposerJson(e){const s=path.join(e,"composer.json");if(checkExcludeFiles(s))return;let t;if(fs.existsSync(s)){{const e=fs.readFileSync(s,"utf8");t=JSON.parse(e)}t.autoload={"psr-4":{"":"src/"}},t.version="1.0.0",fs.writeFileSync(s,JSON.stringify(t,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 generateAuthSecret(){return randomBytes(33).toString("base64")}function generateHexEncodedKey(e=16){return randomBytes(e).toString("hex")}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.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-schema-config.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 modifyPostcssConfig(e){const s=path.join(e,"postcss.config.js");if(checkExcludeFiles(s))return;fs.writeFileSync(s,'export default {\n plugins: {\n "@tailwindcss/postcss": {},\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/morphdom-umd.min.js"><\/script>\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),e=e.replace("</head>",`${c}\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:"/tsconfig.json",dest:"/tsconfig.json"},{src:"/app-gitignore",dest:"/.gitignore"}];s.tailwindcss&&t.push({src:"/postcss.config.js",dest:"/postcss.config.js"});const n=[{src:"/settings",dest:"/settings"},{src:"/src",dest:"/src"}];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 o=fs.readFileSync(n,"utf8");fs.writeFileSync(c,o,{flag:"w"})})),await executeCopy(e,n,s),await updatePackageJson(e,s),await updateComposerJson(e),s.backendOnly||await updateIndexJsForWebSocket(e,s),s.tailwindcss&&modifyPostcssConfig(e),(s.tailwindcss||!s.backendOnly||s.swaggerDocs)&&modifyLayoutPHP(e,s);const c=generateAuthSecret(),o=generateHexEncodedKey(),i=`# Authentication secret key for JWT or session encryption.\nAUTH_SECRET="${c}"\n# Name of the authentication cookie.\nAUTH_COOKIE_NAME="${generateHexEncodedKey(8)}"\n\n# PHPMailer SMTP configuration (uncomment and set as needed)\n# SMTP_HOST="smtp.gmail.com" # Your SMTP host\n# SMTP_USERNAME="john.doe@gmail.com" # Your SMTP username\n# SMTP_PASSWORD="123456" # Your SMTP password\n# SMTP_PORT="587" # 587 for TLS, 465 for SSL, or your SMTP port\n# SMTP_ENCRYPTION="ssl" # ssl or tls\n# MAIL_FROM="john.doe@gmail.com" # Sender email address\n# MAIL_FROM_NAME="John Doe" # Sender name\n\n# Show errors in the browser (development only). Set to false in production.\nSHOW_ERRORS="true"\n\n# Application timezone (default: UTC)\nAPP_TIMEZONE="UTC"\n\n# Application environment (development or production)\nAPP_ENV="development"\n\n# Enable or disable application cache (default: false)\nCACHE_ENABLED="false"\n# Cache time-to-live in seconds (default: 600)\nCACHE_TTL="600"\n\n# Local storage key for browser storage (auto-generated if not set).\n# Spaces will be replaced with underscores and converted to lowercase.\nLOCALSTORE_KEY="${o}"\n\n# Secret key for encrypting function calls.\nFUNCTION_CALL_SECRET="${generateHexEncodedKey(32)}"`;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${i}`;await createOrUpdateEnvFile(e,s)}else await createOrUpdateEnvFile(e,i)}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:!1,active:"Yes",inactive:"No"}),e.websocket||c.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!1,active:"Yes",inactive:"No"}),e.prisma||c.push({type:"toggle",name:"prisma",message:`Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,initial:!1,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 o=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:o.swaggerDocs??e.swaggerDocs??!1,tailwindcss:o.tailwindcss??e.tailwindcss??!1,websocket:o.websocket??e.websocket??!1,prisma:o.prisma??e.prisma??!1,docker:o.docker??e.docker??!1}}async function uninstallNpmDependencies(e,s,t=!1){s.forEach((e=>{}));const n=`npm uninstall ${t?"--save-dev":"--save"} ${s.join(" ")}`;execSync(n,{stdio:"inherit",cwd:e})}async function uninstallComposerDependencies(e,s){s.forEach((e=>{}));const t=`C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar remove ${s.join(" ")}`;execSync(t,{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}}
|
|
2
|
+
import{execSync,spawnSync}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";import{randomBytes}from"crypto";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","error.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 o=c.replace(/(?<!:)(\/\/+)/g,"/"),i=n.replace(/\/\/+/g,"/");return{bsTarget:`${o}/`,bsPathRewrite:{"^/":`/${i.startsWith("/")?i.substring(1):i}/`}}}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","tailwind:build":"postcss src/app/css/tailwind.css -o src/app/css/styles.css"},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 o={...n.scripts};o.browserSync="tsx settings/bs-config.ts",o["browserSync:build"]="tsx settings/build.ts",o.dev=`npm-run-all projectName -p browserSync ${c.join(" ")}`,o.build=`npm-run-all${s.tailwindcss?" tailwind:build":""} browserSync:build`,n.scripts=o,n.type="module",fs.writeFileSync(t,JSON.stringify(n,null,2))}async function updateComposerJson(e){checkExcludeFiles(path.join(e,"composer.json"))}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 generateAuthSecret(){return randomBytes(33).toString("base64")}function generateHexEncodedKey(e=16){return randomBytes(e).toString("hex")}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.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-schema-config.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 modifyPostcssConfig(e){const s=path.join(e,"postcss.config.js");if(checkExcludeFiles(s))return;fs.writeFileSync(s,'export default {\n plugins: {\n "@tailwindcss/postcss": {},\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/morphdom-umd.min.js"><\/script>\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),e=e.replace("</head>",`${c}\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:"/tsconfig.json",dest:"/tsconfig.json"},{src:"/app-gitignore",dest:"/.gitignore"}];s.tailwindcss&&t.push({src:"/postcss.config.js",dest:"/postcss.config.js"});const n=[{src:"/settings",dest:"/settings"},{src:"/src",dest:"/src"}];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 o=fs.readFileSync(n,"utf8");fs.writeFileSync(c,o,{flag:"w"})})),await executeCopy(e,n,s),await updatePackageJson(e,s),await updateComposerJson(e),s.backendOnly||await updateIndexJsForWebSocket(e,s),s.tailwindcss&&modifyPostcssConfig(e),(s.tailwindcss||!s.backendOnly||s.swaggerDocs)&&modifyLayoutPHP(e,s);const c=generateAuthSecret(),o=generateHexEncodedKey(),i=`# Authentication secret key for JWT or session encryption.\nAUTH_SECRET="${c}"\n# Name of the authentication cookie.\nAUTH_COOKIE_NAME="${generateHexEncodedKey(8)}"\n\n# PHPMailer SMTP configuration (uncomment and set as needed)\n# SMTP_HOST="smtp.gmail.com" # Your SMTP host\n# SMTP_USERNAME="john.doe@gmail.com" # Your SMTP username\n# SMTP_PASSWORD="123456" # Your SMTP password\n# SMTP_PORT="587" # 587 for TLS, 465 for SSL, or your SMTP port\n# SMTP_ENCRYPTION="ssl" # ssl or tls\n# MAIL_FROM="john.doe@gmail.com" # Sender email address\n# MAIL_FROM_NAME="John Doe" # Sender name\n\n# Show errors in the browser (development only). Set to false in production.\nSHOW_ERRORS="true"\n\n# Application timezone (default: UTC)\nAPP_TIMEZONE="UTC"\n\n# Application environment (development or production)\nAPP_ENV="development"\n\n# Enable or disable application cache (default: false)\nCACHE_ENABLED="false"\n# Cache time-to-live in seconds (default: 600)\nCACHE_TTL="600"\n\n# Local storage key for browser storage (auto-generated if not set).\n# Spaces will be replaced with underscores and converted to lowercase.\nLOCALSTORE_KEY="${o}"\n\n# Secret key for encrypting function calls.\nFUNCTION_CALL_SECRET="${generateHexEncodedKey(32)}"`;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${i}`;await createOrUpdateEnvFile(e,s)}else await createOrUpdateEnvFile(e,i)}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||updateAnswer?.isUpdate||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??!1?(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:!1,active:"Yes",inactive:"No"}),e.websocket||c.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!1,active:"Yes",inactive:"No"}),e.prisma||c.push({type:"toggle",name:"prisma",message:`Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,initial:!1,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 o=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:o.swaggerDocs??e.swaggerDocs??!1,tailwindcss:o.tailwindcss??e.tailwindcss??!1,websocket:o.websocket??e.websocket??!1,prisma:o.prisma??e.prisma??!1,docker:o.docker??e.docker??!1}}async function uninstallNpmDependencies(e,s,t=!1){s.forEach((e=>{}));const n=`npm uninstall ${t?"--save-dev":"--save"} ${s.join(" ")}`;execSync(n,{stdio:"inherit",cwd:e})}async function uninstallComposerDependencies(e,s){s.forEach((e=>{}));const t=`C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar remove ${s.join(" ")}`;execSync(t,{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
3
|
/**
|
|
4
4
|
* Install dependencies in the specified directory.
|
|
5
5
|
* @param {string} baseDir - The base directory where to install the dependencies.
|
|
@@ -32,35 +32,99 @@ async function installNpmDependencies(baseDir, dependencies, isDev = false) {
|
|
|
32
32
|
cwd: baseDir,
|
|
33
33
|
});
|
|
34
34
|
}
|
|
35
|
-
|
|
35
|
+
function getComposerCmd() {
|
|
36
|
+
try {
|
|
37
|
+
execSync("composer --version", { stdio: "ignore" });
|
|
38
|
+
return { cmd: "composer", baseArgs: [] };
|
|
39
|
+
} catch {
|
|
40
|
+
return {
|
|
41
|
+
cmd: "C:\\xampp\\php\\php.exe",
|
|
42
|
+
baseArgs: ["C:\\ProgramData\\ComposerSetup\\bin\\composer.phar"],
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
export async function installComposerDependencies(baseDir, dependencies) {
|
|
47
|
+
const { cmd, baseArgs } = getComposerCmd();
|
|
48
|
+
const composerJsonPath = path.join(baseDir, "composer.json");
|
|
49
|
+
const existsAlready = fs.existsSync(composerJsonPath);
|
|
36
50
|
console.log(
|
|
37
51
|
chalk.green(
|
|
38
52
|
`Composer project initialization: ${
|
|
39
|
-
|
|
40
|
-
? "Updating existing project..."
|
|
41
|
-
: "Setting up new project..."
|
|
53
|
+
existsAlready ? "Updating existing project…" : "Setting up new project…"
|
|
42
54
|
}`
|
|
43
55
|
)
|
|
44
56
|
);
|
|
45
|
-
|
|
46
|
-
|
|
57
|
+
/* ------------------------------------------------------------------ */
|
|
58
|
+
/* 1. Try composer init (quietly fall back if it fails) */
|
|
59
|
+
/* ------------------------------------------------------------------ */
|
|
60
|
+
if (!existsAlready) {
|
|
61
|
+
const initArgs = [
|
|
62
|
+
...baseArgs,
|
|
63
|
+
"init",
|
|
64
|
+
"--no-interaction",
|
|
65
|
+
"--name",
|
|
66
|
+
"tsnc/prisma-php-app",
|
|
67
|
+
"--require",
|
|
68
|
+
"php:^8.2",
|
|
69
|
+
"--type",
|
|
70
|
+
"project",
|
|
71
|
+
"--version",
|
|
72
|
+
"1.0.0",
|
|
73
|
+
];
|
|
74
|
+
const res = spawnSync(cmd, initArgs, { cwd: baseDir });
|
|
75
|
+
if (res.status !== 0) {
|
|
76
|
+
// Silent fallback: no logs, just write a minimal composer.json
|
|
77
|
+
fs.writeFileSync(
|
|
78
|
+
composerJsonPath,
|
|
79
|
+
JSON.stringify(
|
|
80
|
+
{
|
|
81
|
+
name: "tsnc/prisma-php-app",
|
|
82
|
+
type: "project",
|
|
83
|
+
version: "1.0.0",
|
|
84
|
+
require: { php: "^8.2" },
|
|
85
|
+
autoload: { "psr-4": { "": "src/" } },
|
|
86
|
+
},
|
|
87
|
+
null,
|
|
88
|
+
2
|
|
89
|
+
)
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/* 2. Ensure PSR-4 autoload entry ---------------------------------- */
|
|
94
|
+
const json = JSON.parse(fs.readFileSync(composerJsonPath, "utf8"));
|
|
95
|
+
json.autoload ??= {};
|
|
96
|
+
json.autoload["psr-4"] ??= {};
|
|
97
|
+
json.autoload["psr-4"][""] ??= "src/";
|
|
98
|
+
fs.writeFileSync(composerJsonPath, JSON.stringify(json, null, 2));
|
|
99
|
+
/* 3. Install dependencies ----------------------------------------- */
|
|
100
|
+
if (dependencies.length) {
|
|
101
|
+
console.log("Installing Composer dependencies:");
|
|
102
|
+
dependencies.forEach((d) => console.log(`- ${chalk.blue(d)}`));
|
|
47
103
|
execSync(
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
104
|
+
`${cmd} ${[
|
|
105
|
+
...baseArgs,
|
|
106
|
+
"require",
|
|
107
|
+
"--no-interaction",
|
|
108
|
+
...dependencies,
|
|
109
|
+
].join(" ")}`,
|
|
52
110
|
{ stdio: "inherit", cwd: baseDir }
|
|
53
111
|
);
|
|
54
112
|
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
113
|
+
/* 4. Refresh lock when updating ----------------------------------- */
|
|
114
|
+
if (existsAlready) {
|
|
115
|
+
execSync(
|
|
116
|
+
`${cmd} ${[
|
|
117
|
+
...baseArgs,
|
|
118
|
+
"update",
|
|
119
|
+
"--lock",
|
|
120
|
+
"--no-install",
|
|
121
|
+
"--no-interaction",
|
|
122
|
+
].join(" ")}`,
|
|
123
|
+
{ stdio: "inherit", cwd: baseDir }
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
/* 5. Regenerate autoloader ---------------------------------------- */
|
|
127
|
+
execSync(`${cmd} ${[...baseArgs, "dump-autoload", "--quiet"].join(" ")}`, {
|
|
64
128
|
stdio: "inherit",
|
|
65
129
|
cwd: baseDir,
|
|
66
130
|
});
|
|
@@ -68,7 +132,7 @@ async function installComposerDependencies(baseDir, dependencies) {
|
|
|
68
132
|
const npmPinnedVersions = {
|
|
69
133
|
"@tailwindcss/postcss": "^4.1.11",
|
|
70
134
|
"@types/browser-sync": "^2.29.0",
|
|
71
|
-
"@types/node": "^24.0.
|
|
135
|
+
"@types/node": "^24.0.13",
|
|
72
136
|
"@types/prompts": "^2.4.9",
|
|
73
137
|
"browser-sync": "^3.0.4",
|
|
74
138
|
chalk: "^5.4.1",
|
|
@@ -76,7 +140,7 @@ const npmPinnedVersions = {
|
|
|
76
140
|
cssnano: "^7.0.7",
|
|
77
141
|
"http-proxy-middleware": "^3.0.5",
|
|
78
142
|
"npm-run-all": "^4.1.5",
|
|
79
|
-
"php-parser": "^3.2.
|
|
143
|
+
"php-parser": "^3.2.5",
|
|
80
144
|
postcss: "^8.5.6",
|
|
81
145
|
"postcss-cli": "^11.0.1",
|
|
82
146
|
prompts: "^2.4.2",
|
|
@@ -96,6 +160,7 @@ const composerPinnedVersions = {
|
|
|
96
160
|
"symfony/uid": "^7.2.0",
|
|
97
161
|
"brick/math": "^0.13.1",
|
|
98
162
|
"cboden/ratchet": "^0.4.4",
|
|
163
|
+
"tsnc/prisma-php": "^1.0.0",
|
|
99
164
|
};
|
|
100
165
|
function composerPkg(name) {
|
|
101
166
|
return composerPinnedVersions[name]
|
|
@@ -208,6 +273,7 @@ async function main() {
|
|
|
208
273
|
composerPkg("ezyang/htmlpurifier"),
|
|
209
274
|
composerPkg("symfony/uid"),
|
|
210
275
|
composerPkg("brick/math"),
|
|
276
|
+
composerPkg("tsnc/prisma-php"),
|
|
211
277
|
];
|
|
212
278
|
if (answer.swaggerDocs) {
|
|
213
279
|
npmDependencies.push(
|
package/dist/src/app/js/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{const e=EventTarget.prototype.addEventListener,t=EventTarget.prototype.removeEventListener,n=new Map,s=new Set(["wheel","mousewheel","touchstart","touchmove","touchend","touchcancel","scroll"]);EventTarget.prototype.addEventListener=function(t,r,i){let o=i;s.has(t)&&(void 0===o?o={passive:!0}:"boolean"==typeof o?o={capture:o,passive:!0}:o&&void 0===o.passive&&(o={...o,passive:!0})),n.has(this)||n.set(this,new Map);const a=n.get(this),c=a.get(t)||new Set;c.add(r),a.set(t,c),e.call(this,t,r,o)},EventTarget.prototype.removeEventListener=function(e,s,r){if(n.has(this)&&n.get(this).has(e)){const t=n.get(this).get(e);t.delete(s),0===t.size&&n.get(this).delete(e)}t.call(this,e,s,r)},EventTarget.prototype.removeAllEventListeners=function(e){if(n.has(this)){if(e){const s=n.get(this).get(e);if(!s)return;return s.forEach((n=>t.call(this,e,n))),void n.get(this).delete(e)}n.get(this).forEach(((e,n)=>{e.forEach((e=>t.call(this,n,e)))})),n.delete(this)}}})(),function(){const e=console.log;console.log=(...t)=>{const n=t.map((e=>"function"==typeof e&&e.__isReactiveProxy?e():e));e.apply(console,n)}}();class PPHP{props={};_isNavigating=!1;_responseData=null;_elementState={checkedElements:new Set};_activeAbortController=null;_reservedWords;_declaredStateRoots=new Set;_arrayMethodCache=new WeakMap;_updateScheduled=!1;_pendingBindings=new Set;_effects=new Set;_pendingEffects=new Set;_processedPhpScripts=new WeakSet;_bindings=[];_templateStore=new WeakMap;_inlineDepth=0;_proxyCache=new WeakMap;_rawProps={};_refs=new Map;_wheelHandlersStashed=!1;_evaluatorCache=new Map;_depsCache=new Map;_dirtyDeps=new Set;_handlerCache=new Map;_handlerProxyCache=new WeakMap;_sharedStateMap=new Set;_processedLoops=new WeakSet;_hydrated=!1;_currentProcessingHierarchy=null;_stateHierarchy=new Map;_currentTemplateHierarchy=null;_inlineModuleFns=new Map;_currentExecutionScope=null;_transitionStyleInjected=!1;_eventHandlers;_redirectRegex=/redirect_7F834\s*=\s*(\/[^\s]*)/;_assignmentRe=/^\s*[\w.]+\s*=(?!=)/;_mustacheRe=/\{\{\s*([\s\S]+?)\s*\}\}/gu;_mutators;_boolAttrs=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected","truespeed"]);static _instance;static _effectCleanups;static _debounceTimers=new Map;static _shared=new Map;static _cryptoKey=null;static _cancelableEvents=new Set(["click","submit","change"]);static _mustacheTest=/\{\{\s*[\s\S]+?\s*\}\}/;static _mustachePattern=/\{\{\s*([\s\S]+?)\s*\}\}/g;static _passiveEvents=new Set(["wheel","mousewheel","touchstart","touchmove","touchend","touchcancel","scroll"]);constructor(){const e=Object.getOwnPropertyNames(HTMLElement.prototype).filter((e=>e.startsWith("on"))),t=Object.getOwnPropertyNames(Document.prototype).filter((e=>e.startsWith("on"))),n=Object.getOwnPropertyNames(Window.prototype).filter((e=>e.startsWith("on")));this._eventHandlers=new Set([...e,...t,...n].map((e=>e.toLowerCase()))),this._reservedWords=new Set(["null","undefined","true","false","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","finally","for","function","if","import","in","instanceof","let","new","return","super","switch","this","throw","try","typeof","var","void","while","with","yield","async","await","implements","interface","event","NaN","Infinity","Number","String","Boolean","Object","Array","Function","Date","RegExp","Error","JSON","Math","Map","Set"]),this._mutators=new Set(["push","pop","shift","unshift","splice","sort","reverse","copyWithin","fill"]),this.handlePopState(),this._proxyCache=new WeakMap,this._evaluatorCache.clear(),this._depsCache.clear(),this.props=this.makeReactive(this._rawProps),this.scheduleInitialHydration()}static get instance(){return PPHP._instance||(PPHP._instance=new PPHP),PPHP._instance}debugProps(){console.group("%cPPHP Debug Snapshot","font-weight:bold; color:teal"),console.groupCollapsed("📦 Raw props"),console.log(JSON.stringify(this.props,null,2)),console.groupEnd(),console.groupCollapsed("🔖 State hierarchy"),console.table(Array.from(this._stateHierarchy.entries()).map((([e,t])=>({scopedKey:e,originalKey:t.originalKey,level:t.level,value:this.formatValue(this.getNested(this.props,e)),path:t.hierarchy.join(" → ")})))),console.groupEnd(),console.groupCollapsed("⚙️ Reactive internals"),console.log("Bindings total:",this._bindings.length),console.log("Pending bindings:",this._pendingBindings.size),console.log("Effects:",this._effects.size),console.log("Pending effects:",this._pendingEffects.size),console.log("Dirty deps:",Array.from(this._dirtyDeps).join(", ")||"(none)"),console.groupEnd(),console.groupCollapsed("🔗 Refs"),console.table(Array.from(this._refs.entries()).map((([e,t])=>({key:e,count:t.length,selectors:t.map((e=>e.tagName.toLowerCase())).join(", ")})))),console.groupEnd(),console.groupCollapsed("📦 Inline modules"),this._inlineModuleFns.forEach(((e,t)=>{console.log(`${t}:`,[...e.keys()])})),console.groupEnd(),console.log("Hydrated:",this._hydrated),console.groupCollapsed("🔀 Conditionals (pp-if chains)");Array.from(document.querySelectorAll("[pp-if], [pp-elseif], [pp-else]")).forEach(((e,t)=>{const n=e.hasAttribute("pp-if")?"if":e.hasAttribute("pp-elseif")?"elseif":"else",s=e.getAttribute(`pp-${n}`)??null;let r=null;if(s){const t=s.replace(/^{\s*|\s*}$/g,""),n=this.detectElementHierarchy(e);try{r=!!this.makeScopedEvaluator(t,n)(this._createScopedPropsContext(n))}catch{r=null}}console.log(`#${t}`,{element:e.tagName+(e.id?`#${e.id}`:""),type:n,expr:s,visible:!e.hasAttribute("hidden"),result:r})})),console.groupEnd(),console.groupCollapsed("🔁 Loops (pp-for)");const e=Array.from(document.querySelectorAll("template[pp-for]"));if(0===e.length)console.log("(none)");else{const t=e.map(((e,t)=>{const{itemName:n,idxName:s,arrExpr:r}=this.parseForExpression(e);let i=0;const o=e.previousSibling;if(o?.nodeType===Node.COMMENT_NODE&&"pp-for"===o.data){let e=o.nextSibling;for(;e&&!(e instanceof HTMLTemplateElement&&e.hasAttribute("pp-for"));)i+=1,e=e.nextSibling}return{"#":t,"(expr)":r,item:n||"(default)",idx:s||"(—)",rendered:i}}));console.table(t)}console.groupEnd(),console.groupEnd()}scheduleInitialHydration(){const e=()=>new Promise((e=>setTimeout(e,0))),t=async()=>{try{await Promise.all([this.initRefs(),this.bootstrapDeclarativeState(),this.processInlineModuleScripts(),this._hydrated=!0]),await e(),await this.initializeAllReferencedProps(),await e(),await this.manageAttributeBindings(),await e(),await this.processIfChains(),await e(),await this.initLoopBindings(),await e(),await this.attachWireFunctionEvents();const t=250;for(let n=0;n<this._bindings.length;n+=t)this._bindings.slice(n,n+t).forEach((e=>{try{e.update()}catch(e){console.error("Initial binding update error:",e)}})),await e();document.body.removeAttribute("hidden")}catch(e){console.error("Hydration failed:",e),document.body.removeAttribute("hidden")}};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t,{once:!0}):t()}async initCryptoKey(){const e=document.cookie.split("; ").find((e=>e.startsWith("pphp_function_call_jwt=")))?.split("=",2)[1];if(!e)throw new Error("Missing function-call token");const[,t]=e.split("."),n=atob(t.replace(/-/g,"+").replace(/_/g,"/")),{k:s,exp:r}=JSON.parse(n);if(Date.now()/1e3>r)throw new Error("Function-call token expired");const i=Uint8Array.from(atob(s),(e=>e.charCodeAt(0)));PPHP._cryptoKey=await crypto.subtle.importKey("raw",i,{name:"AES-CBC"},!1,["encrypt","decrypt"])}async encryptCallbackName(e){await this.initCryptoKey();const t=crypto.getRandomValues(new Uint8Array(16)),n=(new TextEncoder).encode(e),s=await crypto.subtle.encrypt({name:"AES-CBC",iv:t},PPHP._cryptoKey,n);return`${btoa(String.fromCharCode(...t))}:${btoa(String.fromCharCode(...new Uint8Array(s)))}`}async decryptCallbackName(e){await this.initCryptoKey();const[t,n]=e.split(":",2),s=Uint8Array.from(atob(t),(e=>e.charCodeAt(0))),r=Uint8Array.from(atob(n),(e=>e.charCodeAt(0))).buffer,i=await crypto.subtle.decrypt({name:"AES-CBC",iv:s},PPHP._cryptoKey,r);return(new TextDecoder).decode(i)}qsa(e,t){try{if(e)return e.querySelectorAll(t)}catch(e){console.error("qsa() failed:",e)}return document.createDocumentFragment().querySelectorAll(t)}async bootstrapDeclarativeState(e=document.body){this.qsa(e,"[pp-init-state]").forEach((e=>{let t,n=e.getAttribute("pp-init-state").trim();if(!n)return void e.removeAttribute("pp-init-state");try{t=JSON5.parse(n)}catch(e){return void console.error("Bad pp-init-state JSON:",n)}const s=this.detectElementHierarchy(e),r=this._currentProcessingHierarchy;this._currentProcessingHierarchy=s,Object.entries(t).forEach((([e,t])=>{this.state(e,t)})),this._currentProcessingHierarchy=r,e.removeAttribute("pp-init-state")}))}detectComponentHierarchy(e){const t=[];let n=e;for(;n&&n!==document.documentElement;){const e=n.getAttribute("pp-component");e&&t.unshift(e),n=n.parentElement}return 0===t.length?(console.warn('PPHP: No component hierarchy found - ensure <body data-component="app"> exists'),["app"]):t}detectElementHierarchy(e){const t=[];let n=e;for(;n&&n!==document.documentElement;){const e=n.getAttribute("pp-component");e&&t.unshift(e),n=n.parentElement}return t.length>0?t:["app"]}generateScopedKey(e,t){return e.join(".")+"."+t}ref(e,t){const n=this._refs.get(e)??[];if(null!=t){const s=n[t];if(!s)throw new Error(`pphp.ref('${e}', ${t}) — no element at that index`);return s}if(0===n.length)throw new Error(`pphp.ref('${e}') failed — no element was found`);return 1===n.length?n[0]:n}effect(e,t){const n=Array.isArray(t),s=n?t:[],r=n&&0===s.length,i=this._currentProcessingHierarchy||["app"],o=s.map((e=>{if("function"==typeof e){const t=e.__pphp_key;if(t)return t;try{const t=e.toString().match(/([a-zA-Z_$][a-zA-Z0-9_$]*(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*)*)/);if(t){const e=t[1];return this.resolveDependencyPath(e,i)}}catch(e){}return null}return"string"==typeof e?this.resolveDependencyPath(e,i):null})).filter((e=>Boolean(e))),a=s.filter((e=>"function"==typeof e&&!e.__pphp_key)),c=new Set(o),l=new Map;for(const e of o)try{l.set(e,this.getResolvedValue(e))}catch(t){l.set(e,void 0)}const h=new Map;for(const e of a)try{const t=e();h.set(e,t)}catch(t){h.set(e,Symbol("error"))}let d=0,p=0;PPHP._effectCleanups||(PPHP._effectCleanups=new WeakMap);const u=PPHP._effectCleanups,f=()=>{const t=u.get(f);if(t){try{t()}catch(e){console.error("cleanup error:",e)}u.delete(f)}const s=performance.now();if(s-p<16)requestAnimationFrame((()=>{performance.now()-p>=16&&f()}));else{if(p=s,++d>100)throw console.error("PPHP: effect exceeded 100 runs - possible infinite loop"),console.error("Effect function:",e.toString()),console.error("Dependencies:",Array.from(c)),new Error("PPHP: effect ran >100 times — possible loop");if(!r){let e=!1;const t=[];if(o.length>0)for(const n of o)try{const s=this.getResolvedValue(n),r=l.get(n);this.hasValueChanged(s,r)&&(e=!0,t.push(n),l.set(n,s))}catch(s){e=!0,t.push(n),l.set(n,void 0)}for(const n of a)try{const s=n(),r=h.get(n);this.hasValueChanged(s,r)&&(e=!0,t.push("(function)"),h.set(n,s))}catch(s){h.get(n)!==Symbol("error")&&(e=!0,t.push("(function-error)"),h.set(n,Symbol("error")))}if(n&&(o.length>0||a.length>0)&&!e)return}try{const t=e();"function"==typeof t&&u.set(f,t),d=0}catch(t){console.error("effect error:",t),console.error("Effect function:",e.toString())}}};Object.assign(f,{__deps:c,__static:r,__functionDeps:a,__hierarchy:i,__isEffect:!0});try{const t=e();"function"==typeof t&&u.set(f,t),d=0}catch(e){console.error("effect error (initial):",e)}const m=n&&this._inlineDepth>0?this._pendingEffects:this._effects;return r?this._effects.add(f):m.add(f),()=>{const e=u.get(f);if(e){try{e()}catch(e){console.error("cleanup error:",e)}u.delete(f)}this._effects.delete(f),this._pendingEffects.delete(f)}}resolveDependencyPath(e,t){const n=e.startsWith("app.")?e.substring(4):e,s=n.split(".")[0];if(PPHP._shared.has(s))return n;const r=t.join(".")+"."+e;if(this.hasNested(this.props,r))return r;if(this.hasNested(this.props,e))return e;for(let n=t.length-1;n>=0;n--){const s=t.slice(0,n).join("."),r=s?s+"."+e:e;if(this.hasNested(this.props,r))return r}return e}getResolvedValue(e){e.split(".")[0];const t=(e.startsWith("app.")?e.substring(4):e).split("."),n=t[0],s=PPHP._shared.get(n);if(s){if(1===t.length)return s.getter();{const e=s.getter(),n=t.slice(1).join(".");return this.getNested(e,n)}}return this.getNested(this.props,e)}hasValueChanged(e,t){if(e===t)return!1;if(null==e||null==t)return e!==t;if("object"!=typeof e||"object"!=typeof t)return e!==t;try{return JSON.stringify(e)!==JSON.stringify(t)}catch(e){return!0}}resetProps(){this._isNavigating=!1,this._activeAbortController&&this._activeAbortController.abort(),this._activeAbortController=null,this._responseData=null,Object.keys(this._rawProps).forEach((e=>{if(window.hasOwnProperty(e)){const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable&&delete window[e]}})),this._rawProps={},this.clearShare(),this._proxyCache=new WeakMap,this._templateStore=new WeakMap,this._arrayMethodCache=new WeakMap,this._handlerProxyCache=new WeakMap,this._processedLoops=new WeakSet,this._depsCache.clear(),this._dirtyDeps.clear(),this._evaluatorCache.clear(),this._handlerCache.clear(),this._sharedStateMap.clear(),this._processedPhpScripts=new WeakSet,this._declaredStateRoots.clear(),this._inlineModuleFns.clear(),this._inlineDepth=0,this._currentProcessingHierarchy=null,this._currentTemplateHierarchy=null,this._currentExecutionScope=null,this._stateHierarchy.clear(),this._bindings=[],this._pendingBindings.clear(),this._effects.clear(),this._pendingEffects.clear(),PPHP._effectCleanups=new WeakMap,this._refs.clear(),PPHP._debounceTimers.forEach((e=>clearTimeout(e))),PPHP._debounceTimers.clear(),this._updateScheduled=!1,this._wheelHandlersStashed=!1;try{const e=window;Object.getOwnPropertyNames(e).forEach((t=>{if(t.startsWith("__pphp_")||t.startsWith("_temp_"))try{delete e[t]}catch(e){}}))}catch(e){}this.props=this.makeReactive(this._rawProps),this._hydrated=!1;const e=document.createNodeIterator(document.body,NodeFilter.SHOW_COMMENT,{acceptNode:e=>"pp-for"===e.data?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT});let t;for(;t=e.nextNode();){let e=t.nextSibling;for(;e&&!(e instanceof HTMLTemplateElement&&e.hasAttribute("pp-for"));){const t=e.nextSibling;e.parentNode?.removeChild(e),e=t}t.parentNode?.removeChild(t)}}async initReactiveOn(e=document.body){const t=()=>new Promise((e=>setTimeout(e,0)));await Promise.all([this.initRefs(e),this.bootstrapDeclarativeState(e),this.processInlineModuleScripts(e),this._hydrated=!0]),await t(),await this.initializeAllReferencedProps(e),await t(),await this.manageAttributeBindings(e),await t(),await this.processIfChains(e),await t(),await this.initLoopBindings(e),await t();for(let e=0;e<this._bindings.length;e+=250)this._bindings.slice(e,e+250).forEach((e=>e.update())),await t()}async removeAllEventListenersOnNavigation(){document.removeAllEventListeners(),this._refs.forEach((e=>e.forEach((e=>e.removeAllEventListeners?.())))),document.querySelectorAll("*").forEach((e=>e.removeAllEventListeners?.()))}async initLoopBindings(e=document.body){this.qsa(e,"template[pp-for]").forEach((e=>{this._processedLoops.has(e)||(this._processedLoops.add(e),this.registerLoop(e))}))}registerLoop(e){const t=this.parseForExpression(e),{marker:n,parent:s,templateHierarchy:r}=this.setupLoopMarker(e),i=this.initializeLoopState(),o=this.createLoopUpdater(e,t,n,s,r,i),a={dependencies:this.extractComprehensiveLoopDependencies(e,t,r),update:o,__isLoop:!0};this._bindings.push(a)}processIfChainsInFragment(e,t,n,s,r,i){const o=new WeakSet;e.querySelectorAll("[pp-if]").forEach((e=>{if(o.has(e))return;const a=[];let c=e;for(;c;){if(c.hasAttribute("pp-if"))a.push({el:c,expr:c.getAttribute("pp-if")});else if(c.hasAttribute("pp-elseif"))a.push({el:c,expr:c.getAttribute("pp-elseif")});else{if(!c.hasAttribute("pp-else"))break;a.push({el:c,expr:null})}o.add(c),c=c.nextElementSibling}a.forEach((e=>{if(null!==e.expr){const i=e.expr.replace(/^{\s*|\s*}$/g,"");e.deps=this.extractScopedDependencies(i,n);const o=this.makeScopedEvaluator(i,n);e.evaluate=()=>{const e={...this._createScopedPropsContext(n),[t.itemName]:s};return t.idxName&&(e[t.idxName]=r),!!o(e)}}}));let l=!1;for(const{el:e,expr:t,evaluate:n}of a)!l&&null!==t&&n()?(e.removeAttribute("hidden"),l=!0):l||null!==t?e.setAttribute("hidden",""):(e.removeAttribute("hidden"),l=!0);const h=new Set;a.forEach((e=>e.deps?.forEach((e=>h.add(e)))));const d=n.join("."),p=d?`${d}.${t.arrExpr}`:t.arrExpr;h.add(p);i.push({dependencies:h,update:()=>{const e=this.makeScopedEvaluator(t.arrExpr,n)(this._createScopedPropsContext(n));if(Array.isArray(e)){const i=this.getItemKey(s,r),o=this.findItemByKey(e,i,s),c=e.findIndex((t=>this.getItemKey(t,e.indexOf(t))===i));if(o&&-1!==c){let e=!1;for(const{el:s,expr:r,evaluate:i}of a)if(null!==r){const i=this.makeScopedEvaluator(r.replace(/^{\s*|\s*}$/g,""),n),a={...this._createScopedPropsContext(n),[t.itemName]:o};t.idxName&&(a[t.idxName]=c);const l=!!i(a);!e&&l?(s.removeAttribute("hidden"),e=!0):s.setAttribute("hidden","")}else e?s.setAttribute("hidden",""):(s.removeAttribute("hidden"),e=!0)}}},__isLoop:!0})}))}extractComprehensiveLoopDependencies(e,t,n){const s=new Set;let r=null;for(let e=n.length;e>=0;e--){const s=n.slice(0,e),i=s.length>0?`${s.join(".")}.${t.arrExpr}`:t.arrExpr;try{const e=this.getNested(this.props,i);if(Array.isArray(e)){r=i;break}}catch{}}if(!r)try{const e=this.getNested(this.props,t.arrExpr);Array.isArray(e)&&(r=t.arrExpr)}catch{r=n.length>0?`${n.join(".")}.${t.arrExpr}`:t.arrExpr}const i=r;null!==i&&s.add(i);const o=this.extractItemPropertiesFromTemplate(e,t);for(const e of o)if(s.add(`${i}.*`),s.add(`${i}.*.${e}`),"string"==typeof i){const t=this.getNested(this.props,i);if(Array.isArray(t))for(let n=0;n<t.length;n++)s.add(`${i}.${n}.${e}`)}return Array.from(s).some((e=>e.includes("*")))||s.add(`${i}.*`),s}extractItemPropertiesFromTemplate(e,t){const n=new Set,s=new RegExp(`\\b${t.itemName}\\.(\\w+(?:\\.\\w+)*)`,"g"),r=document.createTreeWalker(e.content,NodeFilter.SHOW_ALL,null);for(;r.nextNode();){const e=r.currentNode;let t="";if(e.nodeType===Node.TEXT_NODE)t=e.nodeValue||"";else if(e.nodeType===Node.ELEMENT_NODE){const n=e;for(const e of Array.from(n.attributes))t+=" "+e.value}const i=t.matchAll(s);for(const e of i)n.add(e[1])}return n}parseForExpression(e){const t=e.getAttribute("pp-for").trim(),[n,s]=t.split(/\s+in\s+/),[r,i]=n.replace(/^\(|\)$/g,"").split(",").map((e=>e.trim()));return{forExpr:t,vars:n,arrExpr:s,itemName:r,idxName:i}}setupLoopMarker(e){const t=e.parentNode,n=document.createComment("pp-for"),s=this.detectElementHierarchy(e);return t.insertBefore(n,e),t.removeChild(e),{marker:n,parent:t,templateHierarchy:s}}initializeLoopState(){return{previousList:[],renderedItems:new Map}}createItemNodes(e,t,n,s,r){this._currentTemplateHierarchy=r;const i={...this._createScopedPropsContext(r),[s.itemName]:t};s.idxName&&(i[s.idxName]=n);const o=e.content.cloneNode(!0),a=[],c=this.getItemKey(t,n);return this.processTextNodesInFragment(o,s,r,c,t,n,a),this.processElementBindingsInFragment(o,s,r,c,t,n,a),this.processEventHandlersInFragment(o,s,r,t,n),this.processIfChainsInFragment(o,s,r,t,n,a),a.forEach((e=>{e.__isLoop=!0,this._bindings.push(e)})),this._currentTemplateHierarchy=null,{nodes:Array.from(o.childNodes),bindings:a}}processTextNodesInFragment(e,t,n,s,r,i,o){const a=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);for(;a.nextNode();){const e=a.currentNode,c=e.nodeValue||"";if(PPHP._mustacheTest.test(c)){const a=new Set,l=n.join("."),h=l?`${l}.${t.arrExpr}`:t.arrExpr;a.add(h);for(const e of c.matchAll(PPHP._mustachePattern))this.extractScopedDependencies(e[1],n).forEach((e=>a.add(e)));const d=this.createTextNodeUpdaterWithItemKey(e,c,t,n,s,r);o.push({dependencies:a,update:d}),this.renderTextNode(e,c,t,n,r,i)}}}createTextNodeUpdaterWithItemKey(e,t,n,s,r,i){const o=this.makeScopedEvaluator(n.arrExpr,s);return()=>{const a=o(this._createScopedPropsContext(s));if(Array.isArray(a)){const o=this.findItemByKey(a,r,i),c=a.findIndex((e=>this.getItemKey(e,a.indexOf(e))===r));if(o&&-1!==c){const r={...this._createScopedPropsContext(s),[n.itemName]:o};n.idxName&&(r[n.idxName]=c);const i=this.renderMustacheText(t,s,r);e.nodeValue!==i&&(e.nodeValue=i)}}}}findItemByKey(e,t,n){for(let n=0;n<e.length;n++){const s=e[n];if(this.getItemKey(s,n)===t)return s}return n&&"object"==typeof n&&n.id?e.find((e=>e&&e.id===n.id)):null}processElementBindingsInFragment(e,t,n,s,r,i,o){e.querySelectorAll("*").forEach((e=>{this.processElementBindings(e,t,n,s,r,i,o)}))}processElementBindings(e,t,n,s,r,i,o){const a=new Set,c=new Set;for(const{name:t,value:n}of Array.from(e.attributes))if(PPHP._mustacheTest.test(n)&&!t.startsWith("pp-bind"))a.add(t);else if(t.startsWith("pp-bind-")){const e=t.replace(/^pp-bind-/,"");c.add(e)}for(const{name:c,value:l}of Array.from(e.attributes))if("pp-bind"===c)this.createElementBindingWithItemKey(e,l,"text",t,n,s,r,i,o);else if("pp-bind-expr"===c){const a=this.decodeEntities(l);this.createElementBindingWithItemKey(e,a,"text",t,n,s,r,i,o)}else if(c.startsWith("pp-bind-")){const h=c.replace(/^pp-bind-/,"");if(a.has(h)){if(!this._boolAttrs.has(h))continue;e.removeAttribute(h)}this.createElementBindingWithItemKey(e,l,h,t,n,s,r,i,o)}else PPHP._mustacheTest.test(l)&&this.createElementAttributeTemplateBindingWithItemKey(e,c,l,t,n,s,r,i,o)}createElementAttributeTemplateBindingWithItemKey(e,t,n,s,r,i,o,a,c){const l=new Set,h=r.join("."),d=h?`${h}.${s.arrExpr}`:s.arrExpr;l.add(d);for(const e of n.matchAll(PPHP._mustachePattern))this.extractScopedDependencies(e[1],r).forEach((e=>l.add(e)));const p=this.createAttributeTemplateUpdaterWithItemKey(e,t,n,s,r,i,o);c.push({dependencies:l,update:p}),this.renderAttributeTemplate(e,t,n,s,r,o,a)}createAttributeTemplateUpdaterWithItemKey(e,t,n,s,r,i,o){const a=this.makeScopedEvaluator(s.arrExpr,r);return()=>{const c=a(this._createScopedPropsContext(r));if(Array.isArray(c)){const a=this.findItemByKey(c,i,o),l=c.findIndex((e=>this.getItemKey(e,c.indexOf(e))===i));a&&-1!==l&&this.renderAttributeTemplate(e,t,n,s,r,a,l)}}}renderAttributeTemplate(e,t,n,s,r,i,o){const a={...this._createScopedPropsContext(r),[s.itemName]:i};s.idxName&&(a[s.idxName]=o);const c=n.replace(PPHP._mustachePattern,((e,t)=>{try{const e=this.makeScopedEvaluator(t,r);return this.formatValue(e(a))}catch(e){return console.error("PPHP: mustache token error:",t,e),""}}));e.getAttribute(t)!==c&&e.setAttribute(t,c)}createElementBindingWithItemKey(e,t,n,s,r,i,o,a,c){const l=new Set,h=r.join("."),d=h?`${h}.${s.arrExpr}`:s.arrExpr;l.add(d),this.extractScopedDependencies(t,r).forEach((e=>l.add(e)));const p=this.createElementBindingUpdaterWithItemKey(e,t,n,s,r,i,o);c.push({dependencies:l,update:p}),this.renderElementBinding(e,t,n,s,r,o,a)}createElementBindingUpdaterWithItemKey(e,t,n,s,r,i,o){const a=this.makeScopedEvaluator(s.arrExpr,r);return()=>{const c=a(this._createScopedPropsContext(r));if(Array.isArray(c)){const a=this.findItemByKey(c,i,o),l=c.findIndex((e=>this.getItemKey(e,c.indexOf(e))===i));if(a&&-1!==l){const i={...this._createScopedPropsContext(r),[s.itemName]:a};s.idxName&&(i[s.idxName]=l),this.updateElementBinding(e,t,n,r,i)}}}}getItemKey(e,t){if(e&&"object"==typeof e){if("id"in e&&null!=e.id)return`id_${e.id}`;if("key"in e&&null!=e.key)return`key_${e.key}`;if("_id"in e&&null!=e._id)return`_id_${e._id}`;const t=Object.keys(e).filter((t=>(t.toLowerCase().includes("id")||t.toLowerCase().includes("uuid"))&&null!=e[t]&&("string"==typeof e[t]||"number"==typeof e[t])));if(t.length>0){const n=t[0];return`${n}_${e[n]}`}}return`idx_${t}`}renderTextNode(e,t,n,s,r,i){const o={...this._createScopedPropsContext(s),[n.itemName]:r};n.idxName&&(o[n.idxName]=i),e.nodeValue=this.renderMustacheText(t,s,o)}renderMustacheText(e,t,n){return e.replace(PPHP._mustachePattern,((e,s)=>{try{const e=this.makeScopedEvaluator(s,t);return this.formatValue(e(n))}catch{return""}}))}updateElementBinding(e,t,n,s,r){const i=this.makeScopedEvaluator(t,s)(r);if("text"===n){const t=this.formatValue(i);e.textContent!==t&&(e.textContent=t)}else this.applyAttributeBinding(e,n,i)}renderElementBinding(e,t,n,s,r,i,o){const a={...this._createScopedPropsContext(r),[s.itemName]:i};s.idxName&&(a[s.idxName]=o),this.updateElementBinding(e,t,n,r,a)}applyAttributeBinding(e,t,n){if(this._boolAttrs.has(t)){const s=!!n;s!==e.hasAttribute(t)&&(s?e.setAttribute(t,""):e.removeAttribute(t)),t in e&&e[t]!==s&&(e[t]=s)}else{const s=String(n);t in e&&e[t]!==s&&(e[t]=s),e.getAttribute(t)!==s&&e.setAttribute(t,s)}}processEventHandlersInFragment(e,t,n,s,r){e.querySelectorAll("*").forEach((e=>{for(const{name:r,value:i}of Array.from(e.attributes)){const o=r.toLowerCase();if(!this._eventHandlers.has(o))continue;let a=i;const c=t=>{try{if(t&&"object"==typeof t&&!Array.isArray(t)){const n=`__pphp_data_${Date.now()}_${Math.random().toString(36).slice(2,7)}`;return e[n]=t,`(event.currentTarget.${n} || event.target.${n})`}return JSON.stringify(t)}catch(e){return console.error("Failed to serialize item:",e),"null"}};if(a=a.replace(new RegExp(`\\b${t.itemName}\\b`,"g"),c(s)),t.idxName){const e=`(globalThis.pphp._idxOf(${c(s)}, '${t.arrExpr}', ${JSON.stringify(n)}))`;a=a.replace(new RegExp(`\\b${t.idxName}\\b`,"g"),e)}e.setAttribute(r,a)}}))}_idxOf(e,t,n){try{const s=this.makeScopedEvaluator(t,n)(this._createScopedPropsContext(n));if(!Array.isArray(s))return-1;let r=s.findIndex((t=>t===e));if(-1!==r)return r;const i=this.getItemKey(e,-1);return r=s.findIndex(((e,t)=>this.getItemKey(e,t)===i)),r}catch{return-1}}updateItemNodes(e,t,n,s,r,i){if(t===n)return;if("object"==typeof t&&"object"==typeof n&&JSON.stringify(t)===JSON.stringify(n))return;this._currentTemplateHierarchy=i;const o={...this._createScopedPropsContext(i),[r.itemName]:n};r.idxName&&(o[r.idxName]=s),this.updateNodesContent(e,i,o),this.updateConditionalNodes(e,i,o),this._currentTemplateHierarchy=null}updateConditionalNodes(e,t,n){e.forEach((e=>{if(e.nodeType===Node.ELEMENT_NODE){e.querySelectorAll("[pp-if], [pp-elseif], [pp-else]").forEach((e=>{const s=e.getAttribute("pp-if")||e.getAttribute("pp-elseif");if(s){const r=s.replace(/^{\s*|\s*}$/g,"");try{const s=this.makeScopedEvaluator(r,t);!!s(n)?e.removeAttribute("hidden"):e.setAttribute("hidden","")}catch(e){console.error("Error evaluating pp-if condition:",r,e)}}else if(e.hasAttribute("pp-else")){const t=e.previousElementSibling;t&&t.hasAttribute("hidden")?e.removeAttribute("hidden"):e.setAttribute("hidden","")}}))}}))}updateNodesContent(e,t,n){e.forEach((e=>{e.nodeType===Node.ELEMENT_NODE&&this.updateElementContent(e,t,n)}))}updateElementContent(e,t,n){const s=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>{const t=e.nodeValue||"";return t.includes("{{")&&t.includes("}}")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT}});for(;s.nextNode();){const e=s.nextNode(),r=e.nodeValue||"",i=this.renderMustacheText(r,t,n);e.nodeValue!==i&&(e.nodeValue=i)}e.querySelectorAll("*").forEach((e=>{this.updateElementBindingsContent(e,t,n),this.updateElementTemplateAttributes(e,t,n)}))}updateElementTemplateAttributes(e,t,n){for(const{name:s,value:r}of Array.from(e.attributes))if(!s.startsWith("pp-bind")&&PPHP._mustacheTest.test(r)){const i=r.replace(PPHP._mustachePattern,((e,s)=>{try{const e=this.makeScopedEvaluator(s,t);return this.formatValue(e(n))}catch(e){return console.error("PPHP: mustache token error:",s,e),""}}));e.getAttribute(s)!==i&&e.setAttribute(s,i)}}updateElementBindingsContent(e,t,n){for(const{name:s,value:r}of Array.from(e.attributes))if("pp-bind"===s)this.updateElementBinding(e,r,"text",t,n);else if(s.startsWith("pp-bind-")){const i=s.replace(/^pp-bind-/,"");this.updateElementBinding(e,r,i,t,n)}}createLoopUpdater(e,t,n,s,r,i){let o;for(let e=r.length;e>=0;e--){const n=r.slice(0,e);try{const e=this.makeScopedEvaluator(t.arrExpr,n),s=e(this._createScopedPropsContext(n));if(Array.isArray(s)){o=e;break}}catch{}}return o=this.makeScopedEvaluator(t.arrExpr,r),()=>{this.performLoopUpdate(e,t,n,s,r,i,o)}}captureFocusState(e){const t=document.activeElement,n=t&&e.contains(t),s=n?t.closest("[key]")?.getAttribute("key"):null;return{active:t,hadFocus:n,focusKey:s,caretPos:n&&t instanceof HTMLInputElement?t.selectionStart:null}}restoreFocusState(e,t){if(e.focusKey){const n=t.querySelector(`[key="${e.focusKey}"]`),s=n?.querySelector("input,textarea");if(s&&(s.focus({preventScroll:!0}),null!==e.caretPos&&s instanceof HTMLInputElement)){const t=Math.min(e.caretPos,s.value.length);s.setSelectionRange(t,t)}}}calculateLoopDiff(e,t){const n=new Map,s=new Map;e.forEach(((e,t)=>{const s=this.getItemKey(e,t);n.set(s,{item:e,index:t})})),t.forEach(((e,t)=>{const n=this.getItemKey(e,t);s.set(n,{item:e,index:t})}));const r=new Set,i=new Map,o=new Map;for(const[e]of n)s.has(e)||r.add(e);for(const[e,{item:t,index:r}]of s)if(n.has(e)){const s=n.get(e);s.item===t&&s.index===r||o.set(e,{oldItem:s.item,newItem:t,newIndex:r,oldIndex:s.index})}else i.set(e,{item:t,index:r});return{toDelete:r,toInsert:i,toUpdate:o}}applyLoopChanges(e,t,n,s,r,i,o){this.applyLoopDeletions(e.toDelete,t),this.applyLoopUpdates(e.toUpdate,t,n,i),this.applyLoopInsertions(e.toInsert,t,n,s,r,i,o)}applyLoopUpdates(e,t,n,s){for(const[r,{oldItem:i,newItem:o,newIndex:a,oldIndex:c}]of e){const e=t.renderedItems.get(r);e&&(this.updateItemNodes(e.nodes,i,o,a,n,s),e.item=o,e.index=a,e.bindings.forEach((e=>{e.update()})))}}applyLoopInsertions(e,t,n,s,r,i,o){if(0===e.size)return;const a=Array.from(e.entries()).sort((([,e],[,t])=>e.index-t.index));for(const[e,{item:c,index:l}]of a){if(t.renderedItems.has(e)){console.warn(`Item with key ${e} already exists, skipping insertion`);continue}const{nodes:a,bindings:h}=this.createItemNodes(o,c,l,n,i);let d=s;const p=Array.from(t.renderedItems.entries()).map((([e,t])=>({key:e,...t}))).sort(((e,t)=>e.index-t.index));for(let e=p.length-1;e>=0;e--)if(p[e].index<l){d=p[e].nodes[p[e].nodes.length-1];break}a.forEach((e=>{r.insertBefore(e,d.nextSibling),d=e})),t.renderedItems.set(e,{nodes:a,item:c,index:l,bindings:h})}}performLoopUpdate(e,t,n,s,r,i,o){const a=this.captureFocusState(s);let c,l=[];for(let e=r.length;e>=0;e--){const t=r.slice(0,e);try{c=this._createScopedPropsContext(t);const e=o(c);if(Array.isArray(e)&&e.length>=0){l=e;break}}catch(e){console.log("🔥 Debug: Failed to evaluate at hierarchy:",t,e)}}if(!c){c=this._createScopedPropsContext(r);const e=o(c);l=Array.isArray(e)?e:[]}if(!Array.isArray(l))return void console.warn("Loop expression did not return an array:",l);const h=this.calculateLoopDiff(i.previousList,l);this.applyLoopChanges(h,i,t,n,s,r,e),i.previousList=[...l],this.restoreFocusState(a,s),this.attachWireFunctionEvents()}applyLoopDeletions(e,t){for(const n of e){const e=t.renderedItems.get(n);e&&(e.bindings.forEach((e=>{const t=this._bindings.indexOf(e);t>-1&&this._bindings.splice(t,1)})),e.nodes.forEach((e=>{e.parentNode&&e.parentNode.removeChild(e)})),t.renderedItems.delete(n))}}async initRefs(e=document.body){this.qsa(e,"[pp-ref]").forEach((e=>{const t=e.getAttribute("pp-ref"),n=this._refs.get(t)??[];n.push(e),this._refs.set(t,n),e.removeAttribute("pp-ref")}))}scheduleBindingUpdate(e){this._pendingBindings.add(e),this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this.flushBindings()})))}makeReactive(e,t=[]){if(e instanceof Date||e instanceof RegExp||e instanceof Error||e instanceof URLSearchParams||e instanceof URL||e instanceof Promise)return e;const n=this._proxyCache.get(e);if(n)return n;if(e instanceof Map||e instanceof Set||"object"!=typeof e||null===e)return e;if(e.__isReactiveProxy)return e;const s=this,r=new Proxy(e,{get(e,n,r){if("__isReactiveProxy"===n)return!0;const i=Reflect.get(e,n,r);if(Array.isArray(e)&&"string"==typeof n&&s._mutators.has(n)){let o=s._arrayMethodCache.get(e);if(o||(o=new Map,s._arrayMethodCache.set(e,o)),!o.has(n)){const e=i.bind(r),a=t.join("."),c=function(...t){const n=e(...t);return queueMicrotask((()=>{s._bindings.forEach((e=>{const t=s.getBindingType(e);for(const n of e.dependencies)if(s.dependencyMatches(a,n,t)){s.scheduleBindingUpdate(e);break}}))})),n};o.set(n,c)}return o.get(n)}if(null!==i&&"object"==typeof i&&!i.__isReactiveProxy)return s.makeReactive(i,[...t,n]);if(Array.isArray(e)&&"function"==typeof i){let t=s._arrayMethodCache.get(e);return t||(t=new Map,s._arrayMethodCache.set(e,t)),t.has(n)||t.set(n,i.bind(e)),t.get(n)}return i},set(e,n,r,i){if("__isReactiveProxy"===n)return!0;let o=r;null===r||"object"!=typeof r||r.__isReactiveProxy||(o=s.makeReactive(r,[...t,n]));const a=e[n],c=Reflect.set(e,n,o,i);if(a===o)return c;const l=[...t,n].join(".");if(s._dirtyDeps.add(l),l.startsWith("app.")){const e=l.substring(4),t=e.split(".")[0];PPHP._shared.has(t)&&s._dirtyDeps.add(e)}if(Array.isArray(e)&&/^\d+$/.test(String(n))){const e=t.join(".");if(s._dirtyDeps.add(`${e}.*`),e.startsWith("app.")){const t=e.substring(4),n=t.split(".")[0];PPHP._shared.has(n)&&s._dirtyDeps.add(`${t}.*`)}o&&"object"==typeof o&&Object.keys(o).forEach((t=>{if(s._dirtyDeps.add(`${e}.*.${t}`),e.startsWith("app.")){const n=e.substring(4),r=n.split(".")[0];PPHP._shared.has(r)&&s._dirtyDeps.add(`${n}.*.${t}`)}}))}if(t.length>=2&&/^\d+$/.test(t[t.length-1])){const e=t.slice(0,-1).join(".");if(s._dirtyDeps.add(`${e}.*.${String(n)}`),e.startsWith("app.")){const t=e.substring(4),r=t.split(".")[0];PPHP._shared.has(r)&&s._dirtyDeps.add(`${t}.*.${String(n)}`)}}return s._bindings.forEach((e=>{const t=s.getBindingType(e);for(const n of e.dependencies){if(s.dependencyMatches(l,n,t)){s.scheduleBindingUpdate(e);break}if(l.startsWith("app.")){const r=l.substring(4),i=r.split(".")[0];if(PPHP._shared.has(i)&&s.dependencyMatches(r,n,t)){s.scheduleBindingUpdate(e);break}}}})),s._hydrated&&s.scheduleFlush(),c}});return this._proxyCache.set(e,r),r}getBindingType(e){if(e.__isEffect)return"effect";if(e.__isLoop)return"loop";for(const t of e.dependencies)if(t.includes("*")||t.match(/\.\d+\./)||t.endsWith(".*"))return"loop";for(const t of e.dependencies)try{const e=this.getNested(this.props,t);if(Array.isArray(e))return"loop"}catch{}return"binding"}makeAttrTemplateUpdater(e,t,n,s){let r=this._templateStore.get(e);r||(r=new Map,this._templateStore.set(e,r)),r.has(t)||r.set(t,e.getAttribute(t)||"");const i=s??r.get(t),o=this.detectElementHierarchy(e);return(i.match(this._mustacheRe)||[]).forEach((e=>{const t=e.replace(/^\{\{\s*|\s*\}\}$/g,"");this.extractScopedDependencies(t,o).forEach((e=>n.add(e)))})),()=>{try{const n=i.replace(this._mustacheRe,((e,t)=>{try{const e=this.makeScopedEvaluator(t,o),n=this._createScopedPropsContext(o);return this.formatValue(e(n))}catch(e){return console.error("PPHP: mustache token error:",t,e),""}}));e.getAttribute(t)!==n&&e.setAttribute(t,n)}catch(e){console.error(`PPHP: failed to render attribute "${t}" with template "${i}"`,e)}}}formatValue(e){if(e instanceof Date)return e.toISOString();if("function"==typeof e){if(e.__isReactiveProxy)try{return this.formatValue(e())}catch{}return""}if(e&&"object"==typeof e){if(e.__isReactiveProxy&&"value"in e)try{return this.formatValue(e.value)}catch{return String(e)}if(e.__isReactiveProxy)try{const t={};for(const n in e)if("__isReactiveProxy"!==n&&"__pphp_key"!==n)try{t[n]=e[n]}catch{}return Object.keys(t).length?JSON.stringify(t,null,2):""}catch{return String(e)}try{return JSON.stringify(e,((e,t)=>{if("__isReactiveProxy"!==e&&"__pphp_key"!==e)return t&&"object"==typeof t&&t.__isReactiveProxy?"function"==typeof t&&"value"in t?t.value:"[Reactive Object]":t}),2)}catch{return String(e)}}return null!==e&&"object"==typeof e&&1===Object.keys(e).length&&Object.prototype.hasOwnProperty.call(e,"value")?this.formatValue(e.value):"boolean"==typeof e?e?"true":"false":Array.isArray(e)?e.map((e=>"object"==typeof e&&null!==e?(()=>{try{return JSON.stringify(e)}catch{return String(e)}})():String(e))).join(", "):e?.toString()??""}registerBinding(e,t,n="text",s){if(this._assignmentRe.test(t))return;const r=this.detectElementHierarchy(e),i=this.extractScopedDependencies(t,r),o=this.makeScopedEvaluator(t,r);if("value"===s||"checked"===s){const t=()=>{try{const t=this._createScopedPropsContext(r),n=o(t),i=this.formatValue(n);let a=!1;if("value"===s){const t=e;"value"in e&&t.value!==i?(t.value=i,a=!0):"value"in e||(e.setAttribute("value",i),a=!0)}else{const t=e,n="true"===i;"checked"in e&&t.checked!==n?(t.checked=n,a=!0):"checked"in e||(e.setAttribute("checked",i),a=!0)}if(!a||!this._hydrated||e instanceof HTMLInputElement&&("hidden"===e.type||e.disabled||e.readOnly))return;const c={};this._eventHandlers.forEach((e=>{if(e.startsWith("on")){const t=e.slice(2);c[t]=t}})),c.value="input",c.checked="change";const l=c[s]||s,h="click"===l?new MouseEvent(l,{bubbles:!0,cancelable:!0}):new Event(l,{bubbles:!0});e.dispatchEvent(h)}catch(e){console.error(`Error evaluating attribute "${s}":`,e)}};return void this._bindings.push({dependencies:i,update:t})}if(s){const n=s.toLowerCase();if(this._boolAttrs.has(n)){e.removeAttribute(n);const a=()=>{try{const t=this._createScopedPropsContext(r),i=!!o(t);e[s]!==i&&(e[s]=i),i?e.setAttribute(n,""):e.removeAttribute(n)}catch(e){console.error(`PPHP: error evaluating boolean attribute ${s}="${t}"`,e)}};return void this._bindings.push({dependencies:i,update:a})}const a=e.getAttribute(s)??"";if(this._mustacheRe.test(t)||this._mustacheRe.test(a)){const t=this.makeAttrTemplateUpdater(e,s,i,a);return void this._bindings.push({dependencies:i,update:t})}const c=()=>{try{const t=this._createScopedPropsContext(r),n=o(t),i=this.formatValue(n);s in e&&(e[s]=i),e.setAttribute(s,i)}catch(e){console.error(`Error evaluating attribute ${s}="${t}"`,e)}};return void this._bindings.push({dependencies:i,update:c})}const a={text(e,t){e.textContent!==t&&(e.textContent=t)},value(e,t){e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement?e.value!==t&&(e.value=t):e.setAttribute("value",t)},checked(e,t){e instanceof HTMLInputElement?e.checked="true"===t:e.setAttribute("checked",t)},attr(e,t){e.setAttribute("attr",t)}};this._bindings.push({dependencies:i,update:()=>{try{const t=this._createScopedPropsContext(r),s=o(t),i=this.formatValue(s);a[n](e,i)}catch(e){console.error(`Error evaluating expression "${t}"`,e)}}})}makeSafeEvaluator(e){const t=e.trim(),n=`\n try {\n with (ctx) {\n ${/^\s*[\w.]+\s*=(?!=)/.test(t)?`${t}; return "";`:`return (${t});`}\n }\n } catch {\n return "";\n }\n `;let s;try{s=new Function("ctx",n)}catch(t){const n=JSON.stringify(e);s=new Function("ctx",`try { return ${n}; } catch { return ""; }`)}return e=>{try{const t=s(e);return null==t?"":t}catch{return""}}}makeScopedEvaluator(e,t){const n=e.trim(),s=`\n try {\n with (ctx) {\n ${/^\s*[\w.]+\s*=(?!=)/.test(n)?`${n}; return "";`:`return (${n});`}\n }\n } catch {\n return "";\n }\n `;let r;try{r=new Function("ctx",s)}catch(t){const n=JSON.stringify(e);r=new Function("ctx",`try { return ${n}; } catch { return ""; }`)}return n=>{try{for(let s=t.length;s>=0;s--){const i=t.slice(0,s);try{const t=this._createScopedPropsContext(i,n),s=r(t);if(Array.isArray(s)&&"voucherItems"===e)return s;if(null!=s&&""!==s&&"voucherItems"!==e)return s}catch{}}const s=this._createScopedPropsContext(t,n),i=r(s);return null==i?"":i}catch{return""}}}_createScopedPropsContext(e,t={}){const n=e.join("."),s=this.getNested(this.props,n)||{},r=this;return new Proxy(t,{get(t,n,i){if("string"==typeof n){const e=Reflect.get(t,n,i);if("function"==typeof e&&e.__isReactiveProxy)try{return e()}catch{}}if(n in t)return Reflect.get(t,n,i);const o=r.getScopedFunction(n,e);if(o)return o;if(s&&n in s)return s[n];for(let t=e.length-1;t>=0;t--){const s=e.slice(0,t).join("."),i=r.getScopedFunction(n,e.slice(0,t));if(i)return i;const o=s?r.getNested(r.props,s):r.props;if(o&&n in o)return o[n]}return n in globalThis?globalThis[n]:void 0},set(t,s,i,o){if("string"!=typeof s)return Reflect.set(t,s,i,o);if(s in t)return Reflect.set(t,s,i,o);for(let t=e.length;t>=0;t--){const n=e.slice(0,t).join("."),o=n?`${n}.${s}`:s;if(r.hasNested(r.props,o))return r.setNested(r.props,o,i),r._dirtyDeps.add(o),r.scheduleFlush(),!0}const a=n?`${n}.${s}`:s;return r.setNested(r.props,a,i),r._dirtyDeps.add(a),r.scheduleFlush(),!0},has:(t,n)=>"string"==typeof n&&(n in t||!!r.getScopedFunction(n,e)||s&&n in s||n in globalThis||e.some(((t,s)=>{const i=e.slice(0,s).join("."),o=i?r.getNested(r.props,i):r.props;return o&&n in o})))})}extractScopedDependencies(e,t){const n=this.extractDependencies(e),s=new Set,r=t.join(".");for(const e of n){if(this._reservedWords.has(e.split(".")[0]))continue;const n=r+"."+e;if(this._stateHierarchy.has(n)){s.add(n);continue}if(this.hasNested(this.props,n)){s.add(n);continue}let i=!1;for(let n=t.length-1;n>=0&&!i;n--){const r=t.slice(0,n).join("."),o=r?r+"."+e:e;this._stateHierarchy.has(o)?(s.add(o),i=!0):this.hasNested(this.props,o)&&(s.add(o),i=!0)}if(!i){const t=r+"."+e;s.add(t)}}return s}async processIfChains(e=document.body){const t=new WeakSet;this.qsa(e,"[pp-if]").forEach((e=>{if(t.has(e))return;const n=this.detectElementHierarchy(e),s=[];let r=e;for(;r;){if(r.hasAttribute("pp-if"))s.push({el:r,expr:r.getAttribute("pp-if")});else if(r.hasAttribute("pp-elseif"))s.push({el:r,expr:r.getAttribute("pp-elseif")});else{if(!r.hasAttribute("pp-else"))break;s.push({el:r,expr:null})}t.add(r),r=r.nextElementSibling}s.forEach((e=>{if(null!==e.expr){const t=e.expr.replace(/^{\s*|\s*}$/g,"");e.deps=this.extractScopedDependencies(t,n);const s=this.makeScopedEvaluator(t,n);e.evaluate=()=>{const e=this._createScopedPropsContext(n);return!!s(e)}}}));const i=new Set;s.forEach((e=>e.deps?.forEach((e=>i.add(e)))));this._bindings.push({dependencies:i,update:()=>{let e=!1;for(const{el:t,expr:n,evaluate:r}of s)!e&&null!==n&&r()?(t.removeAttribute("hidden"),e=!0):e||null!==n?t.setAttribute("hidden",""):(t.removeAttribute("hidden"),e=!0)}})}))}async manageAttributeBindings(e=document.body){this.qsa(e,"*").forEach((e=>{const t=new Map;Array.from(e.attributes).forEach((e=>{if(e.name.startsWith("pp-bind"))return;const n=this.decodeEntities(e.value);PPHP._mustacheTest.test(n)&&t.set(e.name.toLowerCase(),n)})),["pp-bind","pp-bind-expr"].forEach((t=>{const n=e.getAttribute(t);n&&this.registerBinding(e,n,"text")})),Array.from(e.attributes).forEach((t=>{const n=t.name.toLowerCase(),s=t.value.trim();this._boolAttrs.has(n)&&!t.name.startsWith("pp-bind-")&&/^[A-Za-z_$][\w$]*$/.test(s)&&(e.removeAttribute(t.name),this.registerBinding(e,s,"text",n))})),Array.from(e.attributes).forEach((n=>{if(!n.name.startsWith("pp-bind-"))return;if(["pp-bind","pp-bind-expr","pp-bind-spread"].includes(n.name))return;const s=n.name.replace(/^pp-bind-/,"").toLowerCase(),r=this.decodeEntities(n.value).replace(/^{{\s*|\s*}}$/g,""),i="value"===s?"value":"checked"===s?"checked":"text";if(t.has(s)){const o=t.get(s).replace(PPHP._mustachePattern,"").trim(),a=o.length>0?`\`${o} \${${r}}\``:r;e.setAttribute(n.name,a);try{const t=this._createScopedPropsContext(this.detectElementHierarchy(e)),n=this.formatValue(this.makeScopedEvaluator(a,this.detectElementHierarchy(e))(t));e.setAttribute(s,n)}catch{}return this.registerBinding(e,a,i,s),void t.delete(s)}this.registerBinding(e,r,i,s)})),Array.from(e.attributes).forEach((t=>{if("pp-bind-spread"!==t.name)return;const n=this.detectElementHierarchy(e),s=this.decodeEntities(t.value).split(",").map((e=>e.trim())).filter(Boolean),r=new Set;s.forEach((e=>this.extractScopedDependencies(e,n).forEach((e=>r.add(e)))));const i=new Set;this._bindings.push({dependencies:r,update:()=>{try{const t={},r=this._createScopedPropsContext(n);s.forEach((e=>Object.assign(t,this.makeScopedEvaluator(e,n)(r)??{}))),i.forEach((n=>{n in t||e.hasAttribute(n)||(e.removeAttribute(n),i.delete(n))})),Object.entries(t).forEach((([t,n])=>{if(!i.has(t)&&e.hasAttribute(t))return;if(null==n||!1===n)return void(i.has(t)&&(e.removeAttribute(t),i.delete(t)));const s="object"==typeof n?JSON.stringify(n):String(n);e.getAttribute(t)!==s&&e.setAttribute(t,s),i.add(t)}))}catch(e){console.error("pp-bind-spread error:",e)}}})})),t.forEach(((t,n)=>{this.registerBinding(e,t,"text",n)}))}))}callInlineModule(e,...t){const n=this._currentProcessingHierarchy||["app"],s=this.getScopedFunction(e,n);if(!s)throw new Error(`PPHP: no inline module named "${e}" in scope ${n.join(".")}`);return s(...t)}getScopedFunction(e,t){if("string"!=typeof e)return null;for(let n=t.length;n>=0;n--){const s=t.slice(0,n).join("."),r=this._inlineModuleFns.get(s);if(r&&r.has(e))return r.get(e)}if(e.startsWith("set")){const n=e.charAt(3).toLowerCase()+e.slice(4);if(PPHP._shared.has(n)){const e=PPHP._shared.get(n);return e?.setter||null}for(let e=t.length;e>=0;e--){const s=t.slice(0,e).join("."),r=s?`${s}.${n}`:n;if(this.hasNested(this.props,r))return e=>{this.setNested(this.props,r,e),this._dirtyDeps.add(r),this.scheduleFlush()}}}return null}async processInlineModuleScripts(e=document.body){this._inlineDepth++;try{const t=Array.from(this.qsa(e,'script[type="text/php"]:not([src])')).filter((e=>!this._processedPhpScripts.has(e)));if(0===t.length)return;const n=t.map(((e,t)=>{const n=this.detectComponentHierarchy(e);(e.textContent||"").trim().substring(0,100);return{script:e,hierarchy:n,depth:n.length}})).sort(((e,t)=>e.depth-t.depth));for(const{script:e,hierarchy:t}of n){this._currentProcessingHierarchy=t;const n=t.join(".");let s=(e.textContent||"").trim();s=this.decodeEntities(s),s=this.stripComments(s),s=this.transformStateDeclarations(s),s=this.injectScopedVariables(s,t);const r=this.extractSetters(s);if(r.length){s+="\n\n";for(const e of r)s+=`pphp._registerScopedFunction('${n}', '${e}', ${e});\n`}s=s=this.stateDeclarations(s);const i=[];for(const[,e]of[...s.matchAll(/export\s+function\s+([A-Za-z_$]\w*)/g),...s.matchAll(/export\s+const\s+([A-Za-z_$]\w*)/g)])i.push(`pphp._registerScopedFunction('${n}', '${e}', ${e});`);i.length&&(s+="\n\n"+i.join("\n"));const o=new Blob([s],{type:"application/javascript"}),a=URL.createObjectURL(o);try{const e=await import(a);this._inlineModuleFns.has(n)||this._inlineModuleFns.set(n,new Map);const t=this._inlineModuleFns.get(n);for(const[n,s]of Object.entries(e))"function"!=typeof s||t.has(n)||t.set(n,s)}catch(e){console.error("❌ Inline module import failed:",e),console.error("📄 Generated source:",s)}finally{URL.revokeObjectURL(a),this._processedPhpScripts.add(e),this._currentProcessingHierarchy=null}}}finally{this._inlineDepth--,0===this._inlineDepth&&requestAnimationFrame((()=>{this._pendingEffects.forEach((e=>this._effects.add(e))),this._pendingEffects.clear()}))}}stateDeclarations(e){const t="pphp.",n=["state","share"];let s=e;for(const e of n){let n=0;for(;-1!==(n=s.indexOf(`${t}${e}(`,n));){const t=n+5+e.length+1,r=s.slice(t).match(/^(['"])([^'" ]+)\1\s*,/);if(r){const[e,s,i]=r;n=t+e.length}else{const e=s.slice(t),r=e.indexOf(",");if(-1===r)break;{const i=`'${e.slice(0,r).trim()}', `;s=s.slice(0,t)+i+s.slice(t),n=t+i.length+r}}}}return s}injectScopedVariables(e,t){const n=this.extractVariableReferences(e),s=this.extractDeclaredVariables(e),r=this.extractStateVariables(e),i=new Set([...s,...r]),o=[],a=new Set;for(const e of n)if(!a.has(e)&&!i.has(e)&&this.hasInScopedContext(e,t)){const n=this.findScopedKeyForVariable(e,t);o.push(`\nconst ${e} = (() => {\n const fn = () => {\n const ctx = globalThis.pphp._createScopedPropsContext(${JSON.stringify(t)});\n return ctx.${e};\n };\n \n fn.__isReactiveProxy = true;\n fn.__pphp_key = '${n}';\n \n Object.defineProperty(fn, 'value', {\n get() {\n const ctx = globalThis.pphp._createScopedPropsContext(${JSON.stringify(t)});\n return ctx.${e};\n },\n configurable: true\n });\n \n fn.valueOf = function() { return this.value; };\n fn.toString = function() { return String(this.value); };\n \n return fn;\n})();`),a.add(e);const s=`set${e.charAt(0).toUpperCase()}${e.slice(1)}`;this.hasInScopedContext(s,t)&&!i.has(s)&&(o.push(`\nconst ${s} = (...args) => {\n const ctx = globalThis.pphp._createScopedPropsContext(${JSON.stringify(t)});\n return ctx.${s}(...args);\n};`),a.add(s))}return o.length>0?o.join("\n")+"\n\n"+e:e}extractStateVariables(e){const t=new Set,n=/\b(?:const|let|var)\s+\[\s*([^,\]]+)(?:\s*,\s*([^,\]]+))?\s*\]\s*=\s*pphp\.state/g;let s;for(;null!==(s=n.exec(e));){const e=s[1]?.trim(),n=s[2]?.trim();e&&t.add(e),n&&t.add(n)}const r=/pphp\.state\s*\(\s*['"]([^'"]+)['"]/g;for(;null!==(s=r.exec(e));){const e=s[1];if(e){t.add(e);const n=`set${e.charAt(0).toUpperCase()}${e.slice(1)}`;t.add(n)}}return t}extractDeclaredVariables(e){const t=new Set;let n=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"").replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g,"");const s=[/\b(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,/\b(?:const|let|var)\s+\[\s*([^\]]+?)\s*\]/g,/\b(?:const|let|var)\s+\{\s*([^}]+?)\s*\}/g,/\bfunction\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,/\b(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*(?:\([^)]*\))?\s*=>/g,/\bexport\s+(?:function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)|(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*))/g];for(const e of s){let s;for(;null!==(s=e.exec(n));){const n=s[1]||s[2];if(e.source.includes("\\[")&&!e.source.includes("\\{")){const e=n.split(",").map((e=>e.trim())).filter(Boolean).map((e=>e.startsWith("...")?e.substring(3).trim():e));for(const n of e)/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(n)&&t.add(n)}else if(e.source.includes("\\{")&&!e.source.includes("\\[")){const e=n.split(",").map((e=>e.trim())).filter(Boolean).map((e=>{const t=e.indexOf(":");return-1!==t?e.substring(t+1).trim():e.startsWith("...")?e.substring(3).trim():e}));for(const n of e)/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(n)&&t.add(n)}else n&&t.add(n)}}return t}findScopedKeyForVariable(e,t){const n=t.join("."),s=this.getNested(this.props,n)||{};if(s&&e in s)return`${n}.${e}`;for(let n=t.length-1;n>=0;n--){const s=t.slice(0,n).join("."),r=s?this.getNested(this.props,s):this.props;if(r&&"object"==typeof r&&e in r)return s?`${s}.${e}`:e}return`${n}.${e}`}extractVariableReferences(e){const t=new Set;let n=e.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/.*$/gm," ").replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g," ");const s=/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g;let r;for(;null!==(r=s.exec(n));){const e=r[1],s=r.index;if(this._reservedWords.has(e))continue;const i=n.substring(Math.max(0,s-50),s),o=n.substring(s+e.length,s+e.length+10);/\b(?:const|let|var|function|class|export)\s+$/.test(i)||(s>0&&"."===n[s-1]||/^\s*:/.test(o)||this.isActualFunctionParameter(n,s,e)||this.isInDestructuringDeclaration(n,s,e)||t.add(e))}return t}isActualFunctionParameter(e,t,n){let s=-1,r=-1,i=0;for(let n=t-1;n>=0;n--){const t=e[n];if(")"===t)i++;else if("("===t){if(0===i){s=n;break}i--}}if(-1===s)return!1;i=0;for(let s=t+n.length;s<e.length;s++){const t=e[s];if("("===t)i++;else if(")"===t){if(0===i){r=s;break}i--}}if(-1===r)return!1;const o=e.substring(Math.max(0,s-20),s).trim(),a=e.substring(r+1,Math.min(e.length,r+10)).trim(),c=/\bfunction(?:\s+[a-zA-Z_$]\w*)?\s*$/.test(o),l=a.startsWith("=>");if(c||l){e.substring(s+1,r);const i=e.substring(t+n.length,r);return!i.includes("=>")&&!i.includes("{")}return!1}isInDestructuringDeclaration(e,t,n){const s=e.substring(Math.max(0,t-100),t);if(s.match(/\b(?:const|let|var)\s+\[\s*[^\]]*$/)){const s=e.substring(t+n.length,Math.min(e.length,t+n.length+100));if(/[^\]]*\]\s*=/.test(s))return!0}if(s.match(/\b(?:const|let|var)\s+\{\s*[^}]*$/)){const s=e.substring(t+n.length,Math.min(e.length,t+n.length+100));if(/[^}]*\}\s*=/.test(s))return!0}return!1}hasInScopedContext(e,t){if(this.getScopedFunction(e,t))return!0;const n=t.join("."),s=this.getNested(this.props,n)||{};if(s&&e in s)return!0;for(let n=t.length-1;n>=0;n--){const s=t.slice(0,n),r=s.join(".");if(this.getScopedFunction(e,s))return!0;const i=r?this.getNested(this.props,r):this.props;if(i&&"object"==typeof i&&e in i)return!0;const o=r?`${r}.${e}`:e;if(this._stateHierarchy.has(o))return!0}return!1}_registerScopedFunction(e,t,n){this._inlineModuleFns.has(e)||this._inlineModuleFns.set(e,new Map);this._inlineModuleFns.get(e).set(t,((...s)=>{const r=this._currentExecutionScope;this._currentExecutionScope=e;try{return t.startsWith("set")&&s.length>0?n(s[0]):n(...s)}finally{this._currentExecutionScope=r}}))}extractSetters(e){const t=[],n=/\[\s*([A-Za-z_$]\w*)\s*,\s*([A-Za-z_$]\w*)\s*\]\s*=\s*pphp\.(state|share)\(/g;let s;for(;s=n.exec(e);){const[,e,n,r]=s;"share"===r&&this.markShared(e),this._sharedStateMap.has(e)||t.push(n)}return t}markShared(e){this._sharedStateMap.add(e)}transformStateDeclarations(e){return e=(e=(e=e.replace(/(\b(?:const|let|var)\s+\[\s*)([A-Za-z_$]\w*)\s*,\s*([A-Za-z_$]\w*)\s*(\]\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,n,s,r)=>`${t}${n}, ${s}${r}'${n}', `))).replace(/(\b(?:const|let|var)\s+\[\s*)([A-Za-z_$]\w*)(\s*\]\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,n,s)=>`${t}${n}${s}'${n}', `))).replace(/(\b(?:const|let|var)\s+)([A-Za-z_$]\w*)(\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,n,s)=>`${t}[${n}] = pphp.state('${n}', `))}stripComments(e){let t="",n=0,s=!1,r="",i=!1;for(;n<e.length;){const o=e[n],a=e[n+1];if(i||"'"!==o&&'"'!==o&&"`"!==o||"\\"===e[n-1])if(s)t+=o,n++;else if(i||"/"!==o||"*"!==a)if(i)"*"===o&&"/"===a?(i=!1,n+=2):n++;else if("/"!==o||"/"!==a)t+=o,n++;else for(;n<e.length&&"\n"!==e[n];)n++;else i=!0,n+=2;else s=!s,r=s?o:"",t+=o,n++}return t}flushBindings(){const e=new Set(this._dirtyDeps);this._bindings.forEach((t=>{let n=!1;const s=this.getBindingType(t);for(const r of t.dependencies){for(const t of e)if(this.dependencyMatches(t,r,s)){n=!0;break}if(n)break}if(n)try{t.update()}catch(e){console.error("Binding update error:",e)}})),this._pendingBindings.forEach((e=>{try{e.update()}catch(e){console.error("Pending binding update error:",e)}})),this._pendingBindings.clear(),this._dirtyDeps.clear(),this._updateScheduled=!1,this._effects.forEach((t=>{if(t.__static)return;const n=t.__deps||new Set,s=t.__functionDeps||[];if(0===n.size&&0===s.length){try{t()}catch(e){console.error("effect error:",e)}return}const r=[...n].some((t=>[...e].some((e=>this.dependencyMatches(e,t,"effect"))))),i=s.length>0;if(r||i)try{t()}catch(e){console.error("effect error:",e)}}))}static ARRAY_INTRINSICS=(()=>{const e=new Set(["push","pop","shift","unshift","splice","sort","reverse","copyWithin","fill"]);return new Set(Object.getOwnPropertyNames(Array.prototype).filter((t=>!e.has(t))))})();static headMatch(e,t){return e===t||e.startsWith(t+".")}dependencyMatches(e,t,n="binding"){const s=e=>{if(e.startsWith("app.")){const t=e.slice(4),n=t.split(".")[0];if(PPHP._shared.has(n))return t}return e},r=s(e),i=s(t);if(r===i||e===t)return!0;const o=i.split(".");if(o.length>1&&PPHP.ARRAY_INTRINSICS.has(o.at(-1))&&PPHP.headMatch(r,o.slice(0,-1).join(".")))return!0;switch(n){case"effect":return this.matchEffectDependency(r,i);case"loop":return!(!PPHP.headMatch(r,i)&&!PPHP.headMatch(i,r))||!(!i.includes("*")&&!this.matchesArrayIndexPattern(r,i))&&this.matchLoopDependency(r,i);default:return!!PPHP.headMatch(r,i)||!(!i.includes("*")&&!this.matchesArrayIndexPattern(r,i))&&this.matchBindingDependency(r,i)}}matchEffectDependency(e,t){if(e.startsWith(t+".")){return!e.substring(t.length+1).includes(".")}return!!t.includes("*")&&this.matchesWildcardPattern(e,t)}matchLoopDependency(e,t){return!(!e.startsWith(t+".")&&!t.startsWith(e+"."))||(!(!this.isArrayPath(t)||!this.isArrayItemPath(e,t))||(t.includes("*")?this.matchesWildcardPattern(e,t):this.matchesArrayIndexPattern(e,t)))}isArrayPath(e){try{const t=this.getNested(this.props,e);return Array.isArray(t)}catch{return!1}}isArrayItemPath(e,t){return new RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\.\\d+($|\\.)`).test(e)}matchBindingDependency(e,t){if(e.startsWith(t+".")){return e.substring(t.length+1).split(".").length<=2}return t.includes("*")?this.matchesWildcardPattern(e,t):this.matchesArrayIndexPattern(e,t)}matchesWildcardPattern(e,t){const n=e.split("."),s=t.split(".");if(n.length!==s.length)return!1;for(let e=0;e<s.length;e++){const t=s[e],r=n[e];if("*"!==t&&t!==r)return!1}return!0}matchesArrayIndexPattern(e,t){const n=e.split("."),s=t.split(".");if(n.length!==s.length)return!1;for(let e=0;e<s.length;e++){const t=n[e],r=s[e];if(t!==r&&(!/^\d+$/.test(t)||!/^\d+$/.test(r)))return!1}return!0}scheduleFlush(){this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this._updateScheduled=!1,this.flushBindings()})))}getNested(e,t){return t.split(".").reduce(((e,t)=>e?e[t]:void 0),e)}setNested(e,t,n){const s=t.split("."),r=s.pop(),i=s.reduce(((e,t)=>e[t]??={}),e);null===n||"object"!=typeof n||Array.isArray(n)||n.__isReactiveProxy?i[r]=n:i[r]=this.makeReactive(n,s.concat(r))}hasNested(e,t){const n=t.split(".");let s=e;for(let e=0;e<n.length;e++){const t=n[e];if(null==s||"object"!=typeof s)return!1;if(!(t in s))return!1;s=s[t]}return!0}share(e,t){if("string"!=typeof e||""===e.trim())throw new Error("PPHP.share: key must be a non-empty string.");if(this._reservedWords.has(e))throw new Error(`'${e}' is reserved – choose another share key.`);const n=PPHP._shared.get(e);if(n)return[n.getter,n.setter];const[s,r]=this.state(e,t);return PPHP._shared.set(e,{getter:s,setter:r}),[s,r]}clearShare=e=>{e?PPHP._shared.delete(e):PPHP._shared.clear()};state(e,t){if("string"!=typeof e||""===e.trim())throw new Error("PPHP.state: missing or invalid key—make sure the build-time injector rewrote your declaration to pphp.state('foo', 0).");if(arguments.length<2&&(t=void 0),this._reservedWords.has(e))throw new Error(`'${e}' is reserved – choose another state key.`);const n=this._currentProcessingHierarchy||["app"],s=this.generateScopedKey(n,e);this._stateHierarchy.set(s,{originalKey:e,hierarchy:[...n],level:n.length}),this.hasNested(this.props,s)||this.setNested(this.props,s,t);const r=()=>this.getNested(this.props,s),i=e=>{const t=r(),n="function"==typeof e?e(t):e;this.setNested(this.props,s,n),this._dirtyDeps.add(s),n&&"object"==typeof n&&this.markNestedPropertiesDirty(s,n),this.scheduleFlush()},o=()=>r();Object.defineProperty(o,"value",{get:()=>r(),set:e=>i(e)}),Object.defineProperties(o,{valueOf:{value:()=>r()},toString:{value:()=>String(r())},__isReactiveProxy:{value:!0,writable:!1}}),o.__pphp_key=s;const a=r();if(null===a||"object"!=typeof a)return[o,i];const c=this;return[new Proxy(o,{apply:(e,t,n)=>Reflect.apply(e,t,n),get(e,t,n){if("value"===t)return r();if("__pphp_key"===t)return s;if("__isReactiveProxy"===t)return!0;if("valueOf"===t||"toString"===t)return Reflect.get(e,t,n);if("string"==typeof t){const n=r();if(n&&"object"==typeof n){const r=Object.prototype.hasOwnProperty.call(n,t),i=t in e&&void 0!==e[t];if(r||!i){let e=n[t];return e&&"object"==typeof e&&!e.__isReactiveProxy&&(e=c.makeReactive(e,[...s.split("."),t])),e}}}if(t in e)return Reflect.get(e,t,n);const i=r();return i&&"object"==typeof i?i[t]:void 0},set(e,t,n){if("value"===t)return i(n),!0;if("__isReactiveProxy"===t)return!0;const o=r();return o&&"object"==typeof o&&(o[t]=n,c._dirtyDeps.add(`${s}.${String(t)}`),c.scheduleFlush()),!0},has(e,t){if("value"===t||"__isReactiveProxy"===t||t in o)return!0;const n=r();return n&&"object"==typeof n&&t in n}}),i]}markNestedPropertiesDirty(e,t,n=new WeakSet){t&&"object"==typeof t&&!n.has(t)&&(n.add(t),Object.keys(t).forEach((s=>{const r=`${e}.${s}`;this._dirtyDeps.add(r);const i=t[s];i&&"object"==typeof i&&!n.has(i)&&this.markNestedPropertiesDirty(r,i,n)})))}static _isBuiltIn=(()=>{const e=new Map,t=[Object.prototype,Function.prototype,Array.prototype,String.prototype,Number.prototype,Boolean.prototype,Date.prototype,RegExp.prototype,Map.prototype,Set.prototype,WeakMap.prototype,WeakSet.prototype,Error.prototype,Promise.prototype];return n=>{const s=e.get(n);if(void 0!==s)return s;const r=n in globalThis||t.some((e=>n in e));return e.set(n,r),r}})();extractDependencies(e){const t=e.trim();if(this.isPlainText(t))return new Set;let n=e.replace(/\?\./g,".");const s=new Set,r=/(?:^|[^\w$])(?:\(\s*([^)]*?)\s*\)|([A-Za-z_$][\w$]*))\s*=>/g;for(let e;e=r.exec(n);)(e[1]??e[2]??"").split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>s.add(e)));const i=/function\s*(?:[A-Za-z_$][\w$]*\s*)?\(\s*([^)]*?)\s*\)/g;for(let e;e=i.exec(n);)e[1].split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>s.add(e)));const o=e=>{let t="",n=0;for(;n<e.length;)if("`"===e[n])for(n++;n<e.length;)if("\\"===e[n])n+=2;else if("$"===e[n]&&"{"===e[n+1]){n+=2;let s=1,r=n;for(;n<e.length&&s;)"{"===e[n]?s++:"}"===e[n]&&s--,n++;t+=o(e.slice(r,n-1))+" "}else{if("`"===e[n]){n++;break}n++}else t+=e[n++];return t};n=o(n),n=n.replace(/(['"])(?:\\.|[^\\])*?\1/g,""),n=n.replace(/\/(?:\\.|[^\/\\])+\/[gimsuy]*/g,"");const a=new Set,c=/\b[A-Za-z_$]\w*(?:\.[A-Za-z_$]\w*)*\b/g;for(const t of n.match(c)??[]){const[n,...r]=t.split(".");s.has(n)||(0===r.length&&PPHP._isBuiltIn(n)&&new RegExp(`\\.${n}\\b`).test(e)||0===r.length&&new RegExp(`\\b${t}\\s*\\(`).test(e)&&n in globalThis&&"function"==typeof globalThis[n]||a.add(t))}return a}isPlainText(e){const t=e.trim();if(/^['"`]/.test(t))return!1;return![/[+\-*/%=<>!&|?:]/,/\.\w+/,/\[\s*\w+\s*\]/,/\(\s*[^)]*\s*\)/,/=>/,/\b(true|false|null|undefined|typeof|new|delete|void|in|of|instanceof)\b/,/\?\./,/\?\?/,/\.\.\./,/\{[^}]*\}/,/\[[^\]]*\]/].some((e=>e.test(t)))&&(!!t.includes(" ")&&(!/\w+\.\w+/.test(t)&&!/\w+\[\w+\]/.test(t)))}async initializeAllReferencedProps(e=document.body){const t=PPHP._mustachePattern,n=PPHP._mustacheTest,s=this.props,r=new Set;this.qsa(e,"*").forEach((e=>{const s=this.detectElementHierarchy(e);for(const{name:i,value:o}of Array.from(e.attributes))if(o){if(n.test(o))for(const e of o.matchAll(t))this.extractScopedDependencies(e[1],s).forEach((e=>r.add(e)));("pp-if"===i||"pp-elseif"===i||i.startsWith("pp-bind"))&&this.extractScopedDependencies(o,s).forEach((e=>r.add(e)))}}));const i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>n.test(e.nodeValue??"")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT});for(;;){const e=i.nextNode();if(!e)break;const n=e.parentElement;if(!n)continue;const s=this.detectElementHierarchy(n);for(const n of e.nodeValue.matchAll(t))this.extractScopedDependencies(n[1],s).forEach((e=>r.add(e)))}const o=Array.from(r).sort(((e,t)=>t.split(".").length-e.split(".").length));for(const e of o){const t=e.split(".");let n=s;for(let e=0;e<t.length;e++){const s=t[e],r=e===t.length-1,i=t.slice(0,e+1).join(".");if(!(s in n)||!r&&(null==n[s]||"object"!=typeof n[s])){const e=this._stateHierarchy.has(i);r&&e||(n[s]=r?void 0:{})}n=n[s]}}}async updateDocumentContent(e){const t=this.saveScrollPositions(),n=(new DOMParser).parseFromString(this.sanitizePassiveHandlers(e),"text/html");this.scrubTemplateValueAttributes(n),this.reconcileHead(n),this.resetProps(),await this.removeAllEventListenersOnNavigation(),this.ensurePageTransitionStyles();const s=async()=>{document.body.replaceWith(n.body),await this.initReactiveOn(),this.restoreScrollPositions(t),this.attachWireFunctionEvents(),this.handlerAutofocusAttribute()};"startViewTransition"in document?await document.startViewTransition(s).finished:(await this.fadeOutBody(),await s(),await this.fadeInBody()),document.body.removeAttribute("hidden")}ensurePageTransitionStyles(){if(this._transitionStyleInjected)return;const e=document.createElement("style");e.id="pphp-page-transition-style",e.textContent="\n /* Fallback ↓ (no View‑Transitions API) */\n body.pphp-fade-out { opacity: 0; transform: translateY(8px); }\n body.pphp-fade-in { opacity: 1; transform: translateY(0); }\n body.pphp-fade-in,\n body.pphp-fade-out { transition: opacity .25s ease, transform .25s ease; }\n ",document.head.appendChild(e),this._transitionStyleInjected=!0}async fadeOutBody(e=document.body){e.classList.add("pphp-fade-out");const t=e.getAnimations()[0];return t&&t.finished?t.finished.then((()=>{})):new Promise((e=>setTimeout(e,250)))}async fadeInBody(e=document.body){e.classList.remove("pphp-fade-out"),e.classList.add("pphp-fade-in");const t=e.getAnimations()[0];t&&t.finished?await t.finished:await new Promise((e=>setTimeout(e,250))),e.classList.remove("pphp-fade-in")}reconcileHead(e){const t="pp-dynamic-script",n="pp-dynamic-link";document.head.querySelectorAll("[pp-dynamic-meta]").forEach((e=>e.remove())),document.head.querySelectorAll(`[${n}]`).forEach((e=>e.remove())),document.head.querySelectorAll(`[${t}]`).forEach((e=>e.remove())),Array.from(e.head.children).forEach((e=>{switch(e.tagName){case"SCRIPT":if(e.hasAttribute(t)){const t=document.createElement("script");Array.from(e.attributes).forEach((e=>t.setAttribute(e.name,e.value))),t.textContent=e.textContent,document.head.appendChild(t)}break;case"META":{const t=e;if(t.getAttribute("charset")||"viewport"===t.name)break;const n=t.name?`meta[name="${t.name}"]`:`meta[property="${t.getAttribute("property")}"]`,s=t.cloneNode(!0),r=document.head.querySelector(n);r?document.head.replaceChild(s,r):document.head.insertBefore(s,document.head.querySelector("title")?.nextSibling||null);break}case"TITLE":{const t=e.cloneNode(!0),n=document.head.querySelector("title");n?document.head.replaceChild(t,n):document.head.appendChild(t);break}case"LINK":{const t=e;if("icon"===t.rel){const e=t.cloneNode(!0),n=document.head.querySelector('link[rel="icon"]');n?document.head.replaceChild(e,n):document.head.appendChild(e)}else t.hasAttribute(n)&&document.head.appendChild(t.cloneNode(!0));break}}}))}scrubTemplateValueAttributes(e){e.querySelectorAll('input[value*="{{"], textarea[value*="{{"], select[value*="{{"],[checked*="{{"], [selected*="{{"]').forEach((e=>{e.hasAttribute("value")&&e.removeAttribute("value"),e.hasAttribute("checked")&&e.removeAttribute("checked"),e.hasAttribute("selected")&&e.removeAttribute("selected")}))}restoreScrollPositions(e){requestAnimationFrame((()=>{const t=e.window;t&&window.scrollTo(t.scrollLeft,t.scrollTop),document.querySelectorAll("*").forEach((t=>{const n=this.getElementKey(t);e[n]&&(t.scrollTop=e[n].scrollTop,t.scrollLeft=e[n].scrollLeft)}))}))}PRESERVE_HANDLERS={DETAILS:(e,t)=>(t.open=e.open,!0),INPUT(e,t){const n=e,s=t;return n.value!==s.value&&(s.value=n.value),s.checked=n.checked,document.activeElement!==n||(null!=n.selectionStart&&(s.selectionStart=n.selectionStart,s.selectionEnd=n.selectionEnd),!1)},TEXTAREA(e,t){const n=e,s=t;return n.value!==s.value&&(s.value=n.value),document.activeElement!==n||(s.selectionStart=n.selectionStart,s.selectionEnd=n.selectionEnd,!1)},SELECT(e,t){const n=e;return t.selectedIndex=n.selectedIndex,document.activeElement!==n},VIDEO(e,t){const n=e,s=t;return s.currentTime=n.currentTime,n.paused?s.pause():s.play(),!0},AUDIO:(e,t)=>this.PRESERVE_HANDLERS.VIDEO(e,t),CANVAS:()=>!1};async populateDocumentBody(e){try{const t=document.body,n=e instanceof Document?e.body:e;this._wheelHandlersStashed||(document.querySelectorAll("[onwheel]").forEach((e=>{const t=e.getAttribute("onwheel").trim();if(e.removeAttribute("onwheel"),t){const n=new Function("event",t);e.addEventListener("wheel",n,{passive:!0})}})),this._wheelHandlersStashed=!0);const s=this.PRESERVE_HANDLERS;morphdom(t,n,{getNodeKey(e){if(e.nodeType!==Node.ELEMENT_NODE)return;const t=e;return t.hasAttribute("pp-sync-script")?`pp-sync-script:${t.getAttribute("pp-sync-script")}`:t.getAttribute("key")||void 0},onBeforeElUpdated(e,t){const n=e.tagName;if("SCRIPT"===n||e.hasAttribute("data-nomorph"))return!1;const r=s[n];return!r||r(e,t)},onBeforeNodeDiscarded:e=>(e instanceof HTMLElement&&e.dataset.timerId&&clearTimeout(Number(e.dataset.timerId)),!0)})}catch(e){console.error("Error populating document body:",e)}}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[this.getElementKey(t)]={scrollTop:t.scrollTop,scrollLeft:t.scrollLeft})})),e}async attachWireFunctionEvents(){this.handleHiddenAttribute(),this.handleAnchorTag();const e=Array.from(this._eventHandlers).map((e=>`[${e}]`)).join(","),t=this.qsa(document.body,e);for(const e of t)for(const t of this._eventHandlers){const n=e.getAttribute(t);if(!n)continue;const s=this.decodeEntities(n).trim();if(!s){e.removeAttribute(t);continue}const r=`(event) => { ${this.unwrapArrowBody(this.buildHandlerFromRawBody(s))} }`;e.removeAttribute(t);const i=t.slice(2);e instanceof HTMLInputElement&&this.handleInputAppendParams(e,i),this.handleDebounce(e,i,r)}return this.handlePassiveWheelStashes(document),Promise.resolve()}decodeEntities=e=>{const t=document.createElement("textarea");t.innerHTML=e;let n=t.value;for(;n.includes("&");){t.innerHTML=n;const e=t.value;if(e===n)break;n=e}return n};unwrapArrowBody=e=>{if(!e.trim())return"";const t=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>\s*\{([\s\S]*)\}\s*$/);if(t){let e=t[1].trim();return e&&!e.endsWith(";")&&(e+=";"),e}const n=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>\s*/);if(n){let t=e.substring(n[0].length).trim();return t&&!t.endsWith(";")&&(t+=";"),t}let s=e.trim();return s&&!s.endsWith(";")&&(s+=";"),s};buildHandlerFromRawBody(e){let t=e.trim();t=t.replace(/([A-Za-z_$][\w$]*)->([A-Za-z_$][\w$]*)\s*\(\s*([^)]*?)\s*\)/g,((e,t,n,s)=>{const r=`${t}->${n}(${s.trim()})`;return`await pphp.handleParsedCallback(this, ${JSON.stringify(r)}, event);`})),t=t.replace(/([A-Za-z_$][\w$]*)::([A-Za-z_$][\w$]*)\s*\(\s*([^)]*?)\s*\)/g,((e,t,n,s)=>{const r=`${t}::${n}(${s.trim()})`;return`await pphp.handleParsedCallback(this, ${JSON.stringify(r)}, event);`}));const{normalized:n,originalParam:s}=this.normalizeToArrow(t),r=this.renameEventParam(n,s);return this.replaceThisReferences(r)}replaceThisReferences(e){return e.replace(/\bthis\./g,"event.target.")}normalizeToArrow(e){const t=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>/);if(!t)return{normalized:`() => { ${e} }`,originalParam:null};const n=t[0].replace(/\s*=>\s*$/,"").trim().replace(/^\(|\)$/g,"").trim();return{normalized:e,originalParam:/^[A-Za-z_$]\w*$/.test(n)?n:null}}renameEventParam(e,t){if(!t||"event"===t)return e;const n=new RegExp(`\\b${this.escapeRegex(t)}\\b`,"g");return e.replace(n,((e,t,n)=>{const s=n[t-1],r=n[t+e.length];return s&&/[\w$]/.test(s)||r&&/[\w$]/.test(r)?e:"event"}))}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async handleDebounce(e,t,n){const s=e.getAttribute("pp-debounce"),r=s?this.parseTime(s):0,i=e.getAttribute("pp-before-request")??"",o=e.getAttribute("pp-after-request")??"",a=PPHP._cancelableEvents,c=async s=>{a.has(t)&&s.cancelable&&s.preventDefault();try{i&&await this.invokeHandler(e,i,s),await this.invokeHandler(e,n,s),o&&!o.startsWith("@close")&&await this.invokeHandler(e,o,s),this.handlerAutofocusAttribute()}catch(e){console.error("Error in debounced handler:",e)}},l={passive:PPHP._passiveEvents.has(t)&&!a.has(t)},h=`${t}::${e.__pphpId||e.tagName}`,d=e=>{if(r>0){const t=PPHP._debounceTimers.get(h);t&&clearTimeout(t);const n=setTimeout((()=>{PPHP._debounceTimers.delete(h),c(e)}),r);PPHP._debounceTimers.set(h,n)}else c(e)};e instanceof HTMLFormElement&&"submit"===t?e.addEventListener("submit",(e=>{e.cancelable&&e.preventDefault(),d(e)}),l):e.addEventListener(t,d,l)}debounce(e,t=300,n=!1){let s;return function(...r){const i=this;s&&clearTimeout(s),s=setTimeout((()=>{s=null,n||e.apply(i,r)}),t),n&&!s&&e.apply(i,r)}}handlerAutofocusAttribute(){const e=document.querySelector("dialog[open]");let t=null;if(e&&(t=e.querySelector("[pp-autofocus]")),t||(t=document.querySelector("[pp-autofocus]")),!t)return;const n=t.getAttribute("pp-autofocus");if(!this.isJsonLike(n))return;const s=this.parseJson(n);requestAnimationFrame((()=>{t.focus(),(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&"function"==typeof this.setCursorPosition&&(t instanceof HTMLInputElement&&"number"===t.type?(t.type="text",this.setCursorPosition(t,s),t.type="number"):this.setCursorPosition(t,s))}))}async invokeHandler(e,t,n){try{const s=t.trim();let r=this._handlerCache.get(s);r||(r=this.parseHandler(s),this._handlerCache.set(s,r)),await this.executeHandler(r,e,n,s)}catch(n){this.handleInvokeError(n,t,e)}finally{this.scheduleFlush()}}parseHandler(e){const t=e.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").trim();if(this.isArrowFunction(t))return this.parseArrowFunction(t);const n=t.match(/^(\w+(?:\.\w+)*)\s*\(\s*(.*?)\s*\)$/s);if(n)return{type:"call",name:n[1],args:n[2],isAsync:this.isAsyncFunction(n[1])};const s=t.match(/^(\w+)$/);return s?{type:"simple",name:s[1],isAsync:this.isAsyncFunction(s[1])}:{type:"complex",body:t,isAsync:!1}}isArrowFunction(e){let t=!1,n="",s=0;for(let r=0;r<e.length-1;r++){const i=e[r],o=e[r+1];if(t||'"'!==i&&"'"!==i&&"`"!==i){if(t&&i===n&&"\\"!==e[r-1])t=!1,n="";else if(!t&&("("===i&&s++,")"===i&&s--,"="===i&&">"===o&&s>=0))return!0}else t=!0,n=i}return!1}parseArrowFunction(e){const t=this.findArrowIndex(e);let n=e.substring(t+2).trim();return n.startsWith("{")&&n.endsWith("}")&&(n=n.slice(1,-1).trim()),{type:"arrow",body:n,isAsync:e.includes("async")||this.containsAwait(n)}}findArrowIndex(e){let t=!1,n="";for(let s=0;s<e.length-1;s++){const r=e[s],i=e[s+1];if(t||'"'!==r&&"'"!==r&&"`"!==r){if(t&&r===n&&"\\"!==e[s-1])t=!1;else if(!t&&"="===r&&">"===i)return s}else t=!0,n=r}return-1}async executeArrowHandler(e,t,n){const s=this.parseStatements(e.body);let r=!1;for(const e of s)await this.executeSingleStatement(e,t,n)&&(r=!0);r||await this.executeDynamic(e.body,t,n)}async executeComplexHandler(e,t,n){await this.executeDynamic(e.body,t,n)}parseStatements(e){const t=[];let n="",s=0,r=!1,i="";for(let o=0;o<e.length;o++){const a=e[o];r||'"'!==a&&"'"!==a&&"`"!==a?r&&a===i&&"\\"!==e[o-1]&&(r=!1,i=""):(r=!0,i=a),r||("("!==a&&"{"!==a&&"["!==a||s++,")"!==a&&"}"!==a&&"]"!==a||s--,";"!==a||0!==s)?n+=a:n.trim()&&(t.push(n.trim()),n="")}return n.trim()&&t.push(n.trim()),t}async executeInlineModule(e,t,n,s,r){if(t&&t.trim())if(this.isJsonLike(t)){const n=this.parseJson(t);null!==n&&"object"==typeof n?await this.callInlineModule(e,{...n}):await this.callInlineModule(e,n)}else try{const s=this.detectElementHierarchy(n),r=this._createScopedPropsContext(s),i=this.makeScopedEvaluator(t,s)(r);await this.callInlineModule(e,i)}catch{await this.callInlineModule(e,{element:n,event:s})}else await this.handleParsedCallback(n,r,s)}async executeSingleStatement(e,t,n){const s=e.trim();if(!s)return!1;const r=s.match(/^\(\s*\)\s*=>\s*(.+)$/);if(r)return this.executeSingleStatement(r[1],t,n);if(/^\s*(if|for|while|switch|try|return|throw|var|let|const|function|class)\b/.test(s))return await this.executeDynamic(s,t,n),!0;const i=s.match(/^(\w+)\s*\(\s*(.*?)\s*\)$/s);if(i){const[,e,r]=i,o=this.detectElementHierarchy(t),a=this.resolveFunctionName(e,o);let c=[];if(""!==r.trim())try{c=JSON5.parse(`[${r}]`)}catch{try{const e=this._createScopedPropsContext(o),t=this.getOrCreateProxy(e),s=/\bevent\b/.test(r)?r.replace(/\bevent\b/g,"_evt"):r;c=new Function("_evt","proxy","props",`with (proxy) { return [ ${s} ]; }`)(n,t,e)}catch(e){c=[]}}if(a){const e=this.getScopedFunction(a,o);if(e)return c.length>0?await e(...c):await this.executeInlineModule(a,r,t,n,s),!0}if(a){const e=globalThis[a];if("function"==typeof e)return e.apply(globalThis,c),!0}return await this.handleParsedCallback(t,s,n),!0}const o=s.match(/^(\w+)$/);if(o){const e=o[1],s=this.detectElementHierarchy(t),r=this.resolveFunctionName(e,s);if(r){if(this.getScopedFunction(r,s))return await this.handleParsedCallback(t,`${r}()`,n),!0}if(r){const e=globalThis[r];if("function"==typeof e)return e.call(globalThis,n),!0}return await this.handleParsedCallback(t,`${e}()`,n),!0}return await this.executeDynamic(s,t,n),!0}async executeCallHandler(e,t,n,s){const{name:r,args:i}=e,o=this.detectElementHierarchy(t),a=this.resolveFunctionName(r,o);if(a){if(this.getScopedFunction(a,o))return void await this.executeInlineModule(a,i||"",t,n,s);const e=globalThis[a];if("function"==typeof e)return void await this.executeGlobalFunction(e,i||"",t,n)}await this.handleParsedCallback(t,s,n)}resolveFunctionName(e,t){if(e.startsWith("set")){const t=e.charAt(3).toLowerCase()+e.slice(4);if(PPHP._shared.has(t))return e}if(t)for(let n=t.length;n>=0;n--){const s=t.slice(0,n).join("."),r=this._inlineModuleFns.get(s);if(r&&r.has(e))return e}return"function"==typeof globalThis[e]?e:null}async executeSimpleHandler(e,t,n){const{name:s}=e,r=this.detectElementHierarchy(t),i=this.resolveFunctionName(s,r);if(i){if(this.getScopedFunction(i,r))return void await this.handleParsedCallback(t,`${i}()`,n);const e=globalThis[i];if("function"==typeof e)return void e.call(globalThis,n)}await this.handleParsedCallback(t,`${s}()`,n)}async executeHandler(e,t,n,s){switch(e.type){case"arrow":await this.executeArrowHandler(e,t,n);break;case"call":await this.executeCallHandler(e,t,n,s);break;case"simple":await this.executeSimpleHandler(e,t,n);break;case"complex":await this.executeComplexHandler(e,t,n);break;default:await this.handleParsedCallback(t,s,n)}}async executeGlobalFunction(e,t,n,s){if(t.trim())if(this.isJsonLike(t)){const n=this.parseJson(t)??{};e.call(globalThis,{...n})}else{const r=this.detectElementHierarchy(n),i=this._createScopedPropsContext(r),o=this.getOrCreateProxy(i);new Function("event","proxy","props","fn",`with (proxy) { return fn(${t}); }`).call(n,s,o,i,e)}else e.call(globalThis,s)}async executeDynamic(e,t,n){const s=this.detectElementHierarchy(t),r=this._createScopedPropsContext(s),i=this.getOrCreateProxy(r),o=new PPHP.AsyncFunction("event","proxy","props",`\n with (proxy) {\n ${e}\n }`);try{await o.call(t,n,i,r)}finally{this.scheduleFlush()}}static AsyncFunction=Object.getPrototypeOf((async()=>{})).constructor;getOrCreateEvaluator(e){let t=this._evaluatorCache.get(e);return t||(t=this.makeSafeEvaluator(e),this._evaluatorCache.set(e,t)),t}getOrCreateProxy(e){let t=this._handlerProxyCache.get(e);return t||(t=this.createHandlerProxy(e),this._handlerProxyCache.set(e,t)),t}createHandlerProxy(e){const t=this._currentProcessingHierarchy||["app"],n={alert:window.alert.bind(window),confirm:window.confirm.bind(window),prompt:window.prompt.bind(window),console:window.console,setTimeout:window.setTimeout.bind(window),setInterval:window.setInterval.bind(window),clearTimeout:window.clearTimeout.bind(window),clearInterval:window.clearInterval.bind(window),fetch:window.fetch.bind(window)};return new Proxy(e,{get:(e,s,r)=>{if("string"==typeof s){if(n.hasOwnProperty(s))return n[s];const i=this.getScopedFunction(s,t);if(i)return i;if(s in e){const t=Reflect.get(e,s,r),n=globalThis[s];if(!(null==t||"object"==typeof t&&0===Object.keys(t).length||PPHP._isBuiltIn(s)&&typeof t!=typeof n))return t}if(s in globalThis&&!n.hasOwnProperty(s)){const e=globalThis[s];return"function"==typeof e&&/^[a-z]/.test(s)?e.bind(globalThis):e}}return Reflect.get(e,s,r)},set:(e,t,n,s)=>Reflect.set(e,t,n,s),has:(e,t)=>{if("string"==typeof t){const s=this._currentProcessingHierarchy||["app"];return n.hasOwnProperty(t)||!!this.getScopedFunction(t,s)||t in e||t in globalThis}return t in e||t in globalThis}})}isAsyncFunction(e){const t=this._inlineModuleFns.get(e)||globalThis[e];return t&&("AsyncFunction"===t.constructor.name||t.toString().includes("async "))}containsAwait(e){return/\bawait\s+/.test(e)}handleInvokeError(e,t,n){const s=e instanceof Error?e.message:String(e),r=n.tagName+(n.id?`#${n.id}`:"");console.error(`Handler execution failed on ${r}:\nHandler: "${t}"\nError: ${s}`,e),n.dispatchEvent(new CustomEvent("pphp:handler-error",{detail:{handler:t,error:e,element:n},bubbles:!0}))}async handleParsedCallback(e,t,n){const{funcName:s,data:r}=this.parseCallback(e,t);if(!s)return;const i=Array.isArray(s)?s:[s],o=this.detectElementHierarchy(e);let a;for(const e of i){const t=this.getScopedFunction(e,o);if(t){a=t;break}if("function"==typeof this[e]){a=this[e];break}if("function"==typeof window[e]){a=window[e];break}}if(a){const t=e.hasAttribute("pp-after-request"),s="@close"===e.getAttribute("pp-after-request");let i={args:Array.isArray(r.args)?r.args:[],element:e,data:r,event:n};if(t&&!s){const e=this._responseData?this.parseJson(this._responseData):{response:this._responseData};i={...i,...e}}await a.call(this,i)}else this._responseData=null,this._responseData=await this.handleUndefinedFunction(e,Array.isArray(s)?s[0]:s,r)}async handleUndefinedFunction(e,t,n){const s={callback:await this.encryptCallbackName(t),...n},r=this.createFetchOptions(s),i=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});try{this.saveElementOriginalState(e),this.handleSuspenseElement(e);const s=new URL(window.location.href);let o="",a="",c={success:!1};const l=e.querySelector("input[type='file']");if(l){if(o=await this.fetchFileWithData(s.href,t,l,n),a=this.extractJson(o)||"",a)try{c=this.parseJson(a)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}else{const e=await this.fetch(s.href,r);if(o=await e.text(),this.getRedirectUrl(o))return void await this.redirect(this.getRedirectUrl(o)||"");if(a=this.extractJson(o)||"",a)try{c=this.parseJson(a)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}const h=e.getAttribute("pp-before-request")||"",d=e.getAttribute("pp-after-request")||"";if((h||d&&c.success)&&this.restoreSuspenseElement(e),h||d){let e="";if(c.success){e=o.replace(a,"")}else e=o;if(this.appendAfterbegin(e),!d&&!c.success)return}if(d&&c.success){this.handleAfterRequest(d,a);const e=o.replace(a,"");return this.appendAfterbegin(e),a}if("@close"===d)return c.success?a:void 0;const p=await this.fetch(s.href,i),u=await p.text();if(this.getRedirectUrl(u))return void await this.redirect(this.getRedirectUrl(u)||"");await this.handleResponseRedirectOrUpdate(o,u,a,c)}catch(e){console.error(`Error handling undefined function "${t}". Please ensure the function is defined and accessible.`,e)}}handleAfterRequest(e,t){if(!this.isJsonLike(e))return;const n=this.parseJson(e),s=t?this.parseJson(t):null,r=n.targets;Array.isArray(r)&&r.forEach((e=>{const{id:t,...n}=e,r=document.querySelector(t);let i={};if(s){for(const t in n)if(n.hasOwnProperty(t))switch(t){case"innerHTML":case"outerHTML":case"textContent":case"innerText":"response"===n[t]&&(i[t]=e.responseKey?s[e.responseKey]:s.response);break;default:i[t]=n[t]}}else i=n;r&&this.updateElementAttributes(r,i)}))}sanitizePassiveHandlers(e){return e.replace(/\s+onwheel\s*=\s*(['"])([\s\S]*?)\1/gi,((e,t,n)=>` data-onwheel-code="${this.decodeEntities(n).replace(/"/g,""")}"`)).replace(/\s+onmousewheel\s*=\s*(['"])[\s\S]*?\1/gi,"")}handlePassiveWheelStashes(e){(e instanceof Document?e.body:e).querySelectorAll("[data-onwheel-code]").forEach((e=>{const t=this.decodeEntities(e.dataset.onwheelCode||"").trim();delete e.dataset.onwheelCode,e.onwheel=null,t&&(e.removeAllEventListeners("wheel"),this.handleDebounce(e,"wheel",t))}))}async handleResponseRedirectOrUpdate(e,t,n,s){const r=this.sanitizePassiveHandlers(t),i=this.getUpdatedHTMLContent(e,n,s),o=(new DOMParser).parseFromString(r,"text/html");i&&o.body.insertAdjacentElement("afterbegin",i),this.updateBodyContent(o.body.outerHTML)}getUpdatedHTMLContent(e,t,n){const s=document.createElement("div");if(s.id="afterbegin-8D95D",n&&t?.success){const t=e.replace(n,"");s.innerHTML=t}else s.innerHTML=e;return s.innerHTML?s:null}async updateBodyContent(e){try{const t=this.saveScrollPositions();this.saveElementState();const n=(new DOMParser).parseFromString(e,"text/html");this.scrubTemplateValueAttributes(n),await this.appendCallbackResponse(n),await this.populateDocumentBody(n),await this.removeAllEventListenersOnNavigation(),await this.initReactiveOn(),this.restoreScrollPositions(t),this.attachWireFunctionEvents(),this.handlerAutofocusAttribute(),document.body.removeAttribute("hidden")}catch(e){console.error("updateBodyContent failed:",e)}}restoreElementState(){if(this._elementState.focusId){const e=document.getElementById(this._elementState.focusId)||document.querySelector(`[name="${this._elementState.focusId}"]`);if(e instanceof HTMLInputElement){const t=e.value.length||0;void 0!==this._elementState.focusSelectionStart&&null!==this._elementState.focusSelectionEnd&&e.setSelectionRange(t,t),this._elementState.focusValue&&("checkbox"===e.type||"radio"===e.type?e.checked=!!this._elementState.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=this._elementState.focusValue)),e.focus()}else if(e instanceof HTMLTextAreaElement){const t=e.value.length||0;void 0!==this._elementState.focusSelectionStart&&null!==this._elementState.focusSelectionEnd&&e.setSelectionRange(t,t),this._elementState.focusValue&&""!==e.value&&(e.value=this._elementState.focusValue),e.focus()}else e instanceof HTMLSelectElement&&(this._elementState.focusValue&&""!==e.value&&(e.value=this._elementState.focusValue),e.focus())}this._elementState.checkedElements.forEach((e=>{const t=document.getElementById(e);t&&(t.checked=!0)}))}async 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)}}saveElementState(){const e=document.activeElement;this._elementState.focusId=e?.id||e?.name,this._elementState.focusValue=e?.value,this._elementState.focusChecked=e?.checked,this._elementState.focusType=e?.type,this._elementState.focusSelectionStart=e?.selectionStart,this._elementState.focusSelectionEnd=e?.selectionEnd,this._elementState.isSuspense=e.hasAttribute("pp-suspense"),this._elementState.checkedElements.clear(),document.querySelectorAll('input[type="checkbox"]:checked').forEach((e=>{this._elementState.checkedElements.add(e.id||e.name)})),document.querySelectorAll('input[type="radio"]:checked').forEach((e=>{this._elementState.checkedElements.add(e.id||e.name)}))}updateElementAttributes(e,t){for(const n in t)if(t.hasOwnProperty(n))switch(n){case"innerHTML":case"outerHTML":case"textContent":case"innerText":e[n]=this.decodeHTML(t[n]);break;case"insertAdjacentHTML":e.insertAdjacentHTML(t.position||"beforeend",this.decodeHTML(t[n].html));break;case"insertAdjacentText":e.insertAdjacentText(t.position||"beforeend",this.decodeHTML(t[n].text));break;case"setAttribute":e.setAttribute(t.attrName,this.decodeHTML(t[n]));break;case"removeAttribute":e.removeAttribute(t[n]);break;case"className":e.className=this.decodeHTML(t[n]);break;case"classList.add":e.classList.add(...this.decodeHTML(t[n]).split(","));break;case"classList.remove":e.classList.remove(...this.decodeHTML(t[n]).split(","));break;case"classList.toggle":e.classList.toggle(this.decodeHTML(t[n]));break;case"classList.replace":const[s,r]=this.decodeHTML(t[n]).split(",");e.classList.replace(s,r);break;case"dataset":e.dataset[t.attrName]=this.decodeHTML(t[n]);break;case"style":Object.assign(e.style,t[n]);break;case"value":e.value=this.decodeHTML(t[n]);break;case"checked":e.checked=t[n];break;default:e.setAttribute(n,this.decodeHTML(t[n]))}}decodeHTML(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}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))}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)},s=(e,t)=>{for(const s in t)if(t.hasOwnProperty(s))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(this.isJsonLike(e)){const s=this.parseJson(e);n(t,s)}else r(t,e);t.removeAttribute("pp-original-state")}}},r=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},i=(e,t)=>{e instanceof HTMLFormElement?s(e,t):n(e,t)};try{const r=this.parseJson(t);if(r)if(e instanceof HTMLFormElement){const t=e.id;if(t){const e=document.querySelector(`[form="${t}"]`);if(e){const t=e.getAttribute("pp-original-state");if(t&&this.isJsonLike(t)){const s=this.parseJson(t);n(e,s)}}}const r=new FormData(e),i={};if(r.forEach(((e,t)=>{i[t]=e})),s(e,i),e.hasAttribute("pp-suspense")){const t=e.getAttribute("pp-suspense")||"";if(this.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(r.targets){r.targets.forEach((e=>{const{id:t,...n}=e,s=document.querySelector(t);s&&i(s,n)}));const{targets:t,...s}=r;n(e,s)}else{const{empty:t,...s}=r;n(e,s)}}catch(e){console.error(`Error parsing JSON: ${e instanceof Error?e.message:"Unknown error"}. Please ensure the JSON string is valid.`,e)}}e.querySelectorAll("[pp-suspense]").forEach((e=>this.restoreSuspenseElement(e))),e.removeAttribute("pp-original-state")}extractJson(e){const t=e?.match(/\{[\s\S]*\}/);return t?t[0]:null}getRedirectUrl(e){const t=e.match(this._redirectRegex);return t?t[1]:null}async fetchFileWithData(e,t,n,s={}){const r=new FormData,i=n.files;if(i)for(let e=0;e<i.length;e++)r.append("file[]",i[e]);r.append("callback",t);for(const e in s)s.hasOwnProperty(e)&&r.append(e,s[e]);const o=await this.fetch(e,{method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:r});return await o.text()}async 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(this.isJsonLike(e)){const n=this.parseJson(e);"disabled"!==n.onsubmit&&this.updateElementAttributes(t,n),n.targets&&n.targets.forEach((e=>{const{id:t,...n}=e,s=document.querySelector(t);s&&r(s,n)}))}else s(t,e)}},s=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},r=(e,t)=>{e instanceof HTMLFormElement?n(e,t):this.updateElementAttributes(e,t)};try{if(t&&this.isJsonLike(t)){const s=this.parseJson(t);if(s)if(e instanceof HTMLFormElement){const t=new FormData(e),r={};t.forEach(((e,t)=>{r[t]=e})),s.disabled&&this.toggleFormElements(e,!0);const{disabled:i,...o}=s;this.updateElementAttributes(e,o),n(e,r)}else if(s.targets){s.targets.forEach((e=>{const{id:t,...n}=e,s=document.querySelector(t);s&&r(s,n)}));const{targets:t,...n}=s;this.updateElementAttributes(e,n)}else{if("disabled"===s.empty&&""===e.value)return;const{empty:t,...n}=s;this.updateElementAttributes(e,n)}}else if(t)s(e,t);else if(e instanceof HTMLFormElement){const t=new FormData(e),s={};t.forEach(((e,t)=>{s[t]=e})),n(e,s)}}catch(e){console.error(`Error parsing JSON: ${e instanceof Error?e.message:"Unknown error"}. Please ensure the JSON string is valid.`,e)}}toggleFormElements(e,t){Array.from(e.elements).forEach((e=>{(e instanceof HTMLInputElement||e instanceof HTMLButtonElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(e.disabled=t)}))}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 s=e.attributes[n];t[s.name]=s.value}e.setAttribute("pp-original-state",JSON.stringify(t))}if(e instanceof HTMLFormElement){let t=null;const n=e.id;n&&(t=document.querySelector(`[form="${n}"]`)),n&&t||(t=Array.from(e.elements).find((e=>e instanceof HTMLButtonElement||e instanceof HTMLInputElement))),t?t.hasAttribute("pp-original-state")||this.saveElementOriginalState(t):console.warn("Warning: No invoker detected for the form. Ensure the form has an associated invoker or an ID for proper handling.")}e.querySelectorAll("[pp-suspense]").forEach((e=>this.saveElementOriginalState(e)))}getUrlParams(){const e={};return new URLSearchParams(window.location.search).forEach(((t,n)=>{e[n]=t})),e}createFetchOptions(e){return{method:"POST",headers:{"Content-Type":"application/json",HTTP_PPHP_WIRE_REQUEST:"true"},body:JSON.stringify(e)}}parseCallback(e,t){let n={};const s=e.closest("form");if(s){new FormData(s).forEach(((e,t)=>{const s=this.clean(e);n[t]?n[t]=Array.isArray(n[t])?[...n[t],s]:[n[t],s]:n[t]=s}))}else e instanceof HTMLInputElement?n=this.handleInputElement(e):(e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(n[e.name]=e.value);const r=t.match(/^([^(]+)\(([\s\S]*)\)$/);if(r){const e=r[1].trim(),t=r[2].trim(),s=/,(?=(?:[^'"]*['"][^'"]*['"])*[^'"]*$)/;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))if(this.isJsonLike(t))try{const e=this.parseJson(t);Array.isArray(e)?n.args=e:e&&"object"==typeof e&&(n={...n,...e})}catch(e){console.error("Error parsing JSON args:",e),n.rawArgs=t}else try{const e=this.evaluateJavaScriptObject(t);Array.isArray(e)?n.args=e:e&&"object"==typeof e?n={...n,...e}:n.rawArgs=t}catch(e){console.error("Error evaluating JS object args:",e),n.rawArgs=t}else if(/^[\s\d"'[\{]/.test(t))try{const e=new Function(`return [${t}];`)();n.args=Array.isArray(e)?e:[e]}catch{s.test(t)?n.args=t.split(s).map((e=>e.trim().replace(/^['"]|['"]$/g,""))):n.args=[t.replace(/^['"]|['"]$/g,"")]}else try{const e=this.getOrCreateEvaluator(t)(this.props);n.args=[e]}catch{n.args=t.split(s).map((e=>e.trim().replace(/^['"]|['"]$/g,"")))}return{funcName:e,data:n}}return{funcName:t,data:n}}clean(e){if("string"!=typeof e)return e;let t=e.replace(/"/g,'"').trim();/^"(?:[^"\\]|\\.)*"$/.test(t)&&(t=t.slice(1,-1));try{return JSON.parse(t)}catch{}if(/^-?\d+(\.\d+)?$/.test(t)&&!/^0\d/.test(t)){const e=Number(t);if(!Number.isNaN(e))return e}return t}evaluateJavaScriptObject(e){try{const t=this.getOrCreateProxy(this.props);return new Function("proxy","Date","Math","JSON",`\n with (proxy) {\n return ${e};\n }\n `).call(null,t,Date,Math,JSON)}catch(e){throw console.error("Failed to evaluate JavaScript object:",e),e}}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}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)}}handleInputAppendParams(e,t){const n=e.getAttribute("pp-append-params"),s=e.getAttribute("pp-append-params-sync");if("true"===n){if("true"===s){const t=e.name||e.id;if(t){const n=new URL(window.location.href),s=new URLSearchParams(n.search);s.has(t)&&(e.value=s.get(t)||"")}}e.addEventListener(t,(e=>{const t=e.currentTarget,n=t.value,s=new URL(window.location.href),r=new URLSearchParams(s.search),i=t.name||t.id;if(i){n?r.set(i,n):r.delete(i);const e=r.toString()?`${s.pathname}?${r.toString()}`:s.pathname;history.replaceState(null,"",e)}}))}}handleHiddenAttribute(){const e=document.querySelectorAll("[pp-visibility]"),t=document.querySelectorAll("[pp-display]"),n=this.handleElementVisibility.bind(this),s=this.handleElementDisplay.bind(this);e.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-visibility",n))),t.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-display",s)))}handleVisibilityElementAttribute(e,t,n){const s=e.getAttribute(t);if(s)if(this.isJsonLike(s)){n(e,this.parseJson(s))}else{const n=this.parseTime(s);if(n>0){const s="pp-visibility"===t?"visibility":"display",r="visibility"===s?"hidden":"none";this.scheduleChange(e,n,s,r)}}}handleElementVisibility(e,t){this.handleElementChange(e,t,"visibility","hidden","visible")}handleElementDisplay(e,t){this.handleElementChange(e,t,"display","none","block")}handleElementChange(e,t,n,s,r){const i=t.start?this.parseTime(t.start):0,o=t.end?this.parseTime(t.end):0;i>0?(e.style[n]=s,this.scheduleChange(e,i,n,r),o>0&&this.scheduleChange(e,i+o,n,s)):o>0&&this.scheduleChange(e,o,n,s)}handleAnchorTag(){document.querySelectorAll("a").forEach((e=>{e.addEventListener("click",(async e=>{const t=e.currentTarget,n=t.getAttribute("href"),s=t.getAttribute("target");if(n&&"_blank"!==s&&!e.metaKey&&!e.ctrlKey&&(e.preventDefault(),!this._isNavigating)){this._isNavigating=!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 s="";const[r,i]=n.split("#");i&&(s=`#${i}`);new URLSearchParams(r.split("?")[1]).forEach(((e,n)=>{t.set(n,e)}));const o=`${e.pathname}?${t.toString()}${s}`;history.pushState(null,"",o)}else{const[e,t]=n.split("#"),s=`${e}${t?`#${t}`:""}`;history.pushState(null,"",s)}const s=n.indexOf("#");if(-1!==s){const e=n.slice(s+1),t=document.getElementById(e);if(t)t.scrollIntoView({behavior:"smooth"});else{await this.handleNavigation();const t=document.getElementById(e);t&&t.scrollIntoView({behavior:"smooth"})}}else await this.handleNavigation()}}catch(e){console.error("Anchor click error:",e)}finally{this._isNavigating=!1}}}))}))}handlePopState(){window.addEventListener("popstate",(async()=>{await this.handleNavigation()}))}async handleNavigation(){try{const e=document.getElementById("loading-file-1B87E");if(e){const t=this.findLoadingElement(e,window.location.pathname);t&&await this.updateContentWithTransition(t)}const t=await this.fetch(window.location.href),n=await t.text();if(!t.ok)return await this.updateDocumentContent(n),void console.error(`Navigation error: ${t.status} ${t.statusText}`);const s=n.match(this._redirectRegex);if(s&&s[1])return void await this.redirect(s[1]);await this.updateDocumentContent(n)}catch(e){console.error("Navigation error:",e)}}findLoadingElement(e,t){let n=t;for(;;){const t=e.querySelector(`div[pp-loading-url='${n}']`);if(t)return t;if("/"===n)break;const s=n.lastIndexOf("/");n=s<=0?"/":n.substring(0,s)}return e.querySelector("div[pp-loading-url='/' ]")}async updateContentWithTransition(e){const t=document.querySelector("[pp-loading-content='true']")||document.body;if(!t)return;const{fadeIn:n,fadeOut:s}=this.parseTransition(e);await this.fadeOut(t,s),t.innerHTML=e.innerHTML,this.fadeIn(t,n)}parseTransition(e){let t=250,n=250;const s=e.querySelector("[pp-loading-transition]"),r=s?.getAttribute("pp-loading-transition");if(r){const e=this.parseJson(r);e&&"object"==typeof e?(t=this.parseTime(e.fadeIn??t),n=this.parseTime(e.fadeOut??n)):console.warn("pp-loading-transition is not valid JSON → default values (250 ms) will be used. String:",r)}return{fadeIn:t,fadeOut:n}}fadeOut(e,t){return new Promise((n=>{e.style.transition=`opacity ${t}ms ease-out`,e.style.opacity="0",setTimeout((()=>{e.style.transition="",n()}),t)}))}fadeIn(e,t){e.style.transition=`opacity ${t}ms ease-in`,e.style.opacity="1",setTimeout((()=>{e.style.transition=""}),t)}getElementKey(e){return e.id||e.className||e.tagName}async redirect(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 this.handleNavigation())}catch(e){console.error("Redirect error:",e)}}abortActiveRequest(){this._activeAbortController&&this._activeAbortController.abort()}async fetch(e,t,n=!1){let s;return n?(this._activeAbortController&&this._activeAbortController.abort(),this._activeAbortController=new AbortController,s=this._activeAbortController):s=new AbortController,fetch(e,{...t,signal:s.signal,headers:{...t?.headers,"X-PPHP-Navigation":"partial","X-Requested-With":"XMLHttpRequest"}})}isJsonLike(e){if("string"!=typeof e)return!1;const t=e.trim();return!(!/^\{[\s\S]*\}$/.test(t)&&!/^\[[\s\S]*\]$/.test(t))&&!(t.includes("(")||t.includes(")")||t.includes("=>"))}parseJson(e){try{return JSON5.parse(e)}catch(e){return console.error(`Error parsing JSON: ${e.message}. Please ensure the JSON string is valid.`,e),{}}}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":default:return e;case"s":return 1e3*e;case"m":return 60*e*1e3}}return 0}scheduleChange(e,t,n,s){setTimeout((()=>{requestAnimationFrame((()=>{e.style[n]=s}))}),t)}async fetchFunction(e,t={},n=!1){try{const s={callback:await this.encryptCallbackName(e),...t},r=window.location.href;let i;if(Object.keys(s).some((e=>{const t=s[e];return t instanceof File||t instanceof FileList&&t.length>0}))){const e=new FormData;Object.keys(s).forEach((t=>{const n=s[t];n instanceof File?e.append(t,n):n instanceof FileList?Array.from(n).forEach((n=>e.append(t,n))):e.append(t,n)})),i={method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:e}}else i=this.createFetchOptions(s);const o=await this.fetch(r,i,n);if(!o.ok)throw new Error(`Fetch failed with status: ${o.status} ${o.statusText}`);const a=await o.text();try{return JSON.parse(a)}catch{return a}}catch(e){throw console.error("Error in fetchFunction:",e),new Error("Failed to fetch data.")}}async sync(...e){try{const t=this.saveScrollPositions();this.saveElementState();const n=e.length?e:["true"],s=e=>`[pp-sync="${e}"]`,r=await this.fetch(window.location.href,this.createFetchOptions({pphpSync71163:!0,selectors:n,secondRequestC69CD:!0,...this.getUrlParams()}));let i;if(r.headers.get("content-type")?.includes("application/json")){i=(await r.json()).fragments}else i={[n[0]]:await r.text()};const o=`<body>${Object.values(i).join("")}</body>`,a=(new DOMParser).parseFromString(o,"text/html");await this.initReactiveOn(a),n.forEach((e=>{const t=s(e),n=document.querySelectorAll(t),r=a.body.querySelector(t);r&&n.forEach((e=>e.innerHTML=r.innerHTML))})),this.restoreElementState(),this.restoreScrollPositions(t),this.attachWireFunctionEvents()}catch(e){console.error("pphp.sync failed:",e)}}async fetchAndUpdateBodyContent(){const e=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});this.abortActiveRequest();const t=await this.fetch(window.location.href,e,!0),n=await t.text();await this.updateBodyContent(n)}copyCode(e,t,n,s,r="img",i=2e3){if(!(e instanceof HTMLElement))return;const o=e.closest(`.${t}`)?.querySelector("pre code"),a=o?.textContent?.trim()||"";a?navigator.clipboard.writeText(a).then((()=>{const t=e.querySelector(r);if(t)for(const[e,n]of Object.entries(s))e in t?t[e]=n:t.setAttribute(e,n);setTimeout((()=>{if(t)for(const[e,s]of Object.entries(n))e in t?t[e]=s:t.setAttribute(e,s)}),i)}),(()=>{alert("Failed to copy command to clipboard")})):alert("Failed to find the code block to copy")}getCookie(e){return document.cookie.split("; ").find((t=>t.startsWith(e+"=")))?.split("=")[1]||null}}class PPHPLocalStore{state;static instance=null;listeners;pphp;STORAGE_KEY;lastSyncedState=null;constructor(e={}){this.state=e,this.listeners=[],this.pphp=PPHP.instance,this.STORAGE_KEY=this.pphp.getCookie("pphp_local_store_key")||"pphp_local_store_59e13",this.lastSyncedState=localStorage.getItem(this.STORAGE_KEY),this.loadState()}static getInstance(e={}){return PPHPLocalStore.instance||(PPHPLocalStore.instance=new PPHPLocalStore(e)),PPHPLocalStore.instance}setState(e,t=!1){const n={...this.state,...e};if(JSON.stringify(n)!==JSON.stringify(this.state)&&(this.state=n,this.listeners.forEach((e=>e(this.state))),this.saveState(),t)){const e=localStorage.getItem(this.STORAGE_KEY);e&&e!==this.lastSyncedState&&(this.pphp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]:e}),this.lastSyncedState=e)}}saveState(){localStorage.setItem(this.STORAGE_KEY,JSON.stringify(this.state))}loadState(){const e=localStorage.getItem(this.STORAGE_KEY);e&&(this.state=this.pphp.parseJson(e),this.listeners.forEach((e=>e(this.state))))}resetState(e,t=!1){if(e?(delete this.state[e],this.saveState()):(this.state={},localStorage.removeItem(this.STORAGE_KEY)),this.listeners.forEach((e=>e(this.state))),t){const t=e?localStorage.getItem(this.STORAGE_KEY):null;this.pphp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]:t}),this.lastSyncedState=t}}}class SearchParamsManager{static instance=null;listeners=[];constructor(){}static getInstance(){return SearchParamsManager.instance||(SearchParamsManager.instance=new SearchParamsManager),SearchParamsManager.instance}get params(){return new URLSearchParams(window.location.search)}get(e){return this.params.get(e)}set(e,t){const n=this.params;n.set(e,t),this.updateURL(n)}delete(e){const t=this.params;t.delete(e),this.updateURL(t)}replace(e){const t=new URLSearchParams;for(const n in e){const s=e[n];null!==s&&t.set(n,s)}this.updateURL(t,!0)}updateURL(e,t=!1){const n=`${window.location.pathname}?${e.toString()}`;t?history.replaceState(null,"",n):history.pushState(null,"",n),this.notifyListeners(e)}listen(e){this.listeners.push(e)}notifyListeners(e){for(const t of this.listeners)t(e)}enablePopStateListener(){window.addEventListener("popstate",(()=>{this.notifyListeners(this.params)}))}}var pphp=PPHP.instance,store=PPHPLocalStore.getInstance(),searchParams=SearchParamsManager.getInstance();
|
|
1
|
+
(()=>{const e=EventTarget.prototype.addEventListener,t=EventTarget.prototype.removeEventListener,n=new Map,s=new Set(["wheel","mousewheel","touchstart","touchmove","touchend","touchcancel","scroll"]);EventTarget.prototype.addEventListener=function(t,r,i){let a=i;s.has(t)&&(void 0===a?a={passive:!0}:"boolean"==typeof a?a={capture:a,passive:!0}:a&&void 0===a.passive&&(a={...a,passive:!0})),n.has(this)||n.set(this,new Map);const o=n.get(this),c=o.get(t)||new Set;c.add(r),o.set(t,c),e.call(this,t,r,a)},EventTarget.prototype.removeEventListener=function(e,s,r){if(n.has(this)&&n.get(this).has(e)){const t=n.get(this).get(e);t.delete(s),0===t.size&&n.get(this).delete(e)}t.call(this,e,s,r)},EventTarget.prototype.removeAllEventListeners=function(e){if(n.has(this)){if(e){const s=n.get(this).get(e);if(!s)return;return s.forEach((n=>t.call(this,e,n))),void n.get(this).delete(e)}n.get(this).forEach(((e,n)=>{e.forEach((e=>t.call(this,n,e)))})),n.delete(this)}}})(),function(){const e=console.log;console.log=(...t)=>{const n=t.map((e=>"function"==typeof e&&e.__isReactiveProxy?e():e));e.apply(console,n)}}();class PPHP{props={};_isNavigating=!1;_responseData=null;_elementState={checkedElements:new Set};_activeAbortController=null;_reservedWords;_declaredStateRoots=new Set;_arrayMethodCache=new WeakMap;_updateScheduled=!1;_pendingBindings=new Set;_effects=new Set;_pendingEffects=new Set;_processedPhpScripts=new WeakSet;_bindings=[];_templateStore=new WeakMap;_inlineDepth=0;_proxyCache=new WeakMap;_rawProps={};_refs=new Map;_wheelHandlersStashed=!1;_evaluatorCache=new Map;_depsCache=new Map;_dirtyDeps=new Set;_handlerCache=new Map;_handlerProxyCache=new WeakMap;_sharedStateMap=new Set;_processedLoops=new WeakSet;_hydrated=!1;_currentProcessingHierarchy=null;_stateHierarchy=new Map;_currentTemplateHierarchy=null;_inlineModuleFns=new Map;_currentExecutionScope=null;_transitionStyleInjected=!1;_eventHandlers;_redirectRegex=/redirect_7F834\s*=\s*(\/[^\s]*)/;_assignmentRe=/^\s*[\w.]+\s*=(?!=)/;_mustacheRe=/\{\{\s*([\s\S]+?)\s*\}\}/gu;_mutators;_boolAttrs=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected","truespeed"]);static _instance;static _effectCleanups;static _debounceTimers=new Map;static _shared=new Map;static _cryptoKey=null;static _cancelableEvents=new Set(["click","submit","change"]);static _mustacheTest=/\{\{\s*[\s\S]+?\s*\}\}/;static _mustachePattern=/\{\{\s*([\s\S]+?)\s*\}\}/g;static _passiveEvents=new Set(["wheel","mousewheel","touchstart","touchmove","touchend","touchcancel","scroll"]);constructor(){const e=Object.getOwnPropertyNames(HTMLElement.prototype).filter((e=>e.startsWith("on"))),t=Object.getOwnPropertyNames(Document.prototype).filter((e=>e.startsWith("on"))),n=Object.getOwnPropertyNames(Window.prototype).filter((e=>e.startsWith("on")));this._eventHandlers=new Set([...e,...t,...n].map((e=>e.toLowerCase()))),this._reservedWords=new Set(["null","undefined","true","false","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","finally","for","function","if","import","in","instanceof","let","new","return","super","switch","this","throw","try","typeof","var","void","while","with","yield","async","await","implements","interface","event","NaN","Infinity","Number","String","Boolean","Object","Array","Function","Date","RegExp","Error","JSON","Math","Map","Set"]),this._mutators=new Set(["push","pop","shift","unshift","splice","sort","reverse","copyWithin","fill"]),this.handlePopState(),this._proxyCache=new WeakMap,this._evaluatorCache.clear(),this._depsCache.clear(),this.props=this.makeReactive(this._rawProps),this.scheduleInitialHydration()}static get instance(){return PPHP._instance||(PPHP._instance=new PPHP),PPHP._instance}debugProps(){console.group("%cPPHP Debug Snapshot","font-weight:bold; color:teal"),console.groupCollapsed("📦 Raw props"),console.log(JSON.stringify(this.props,null,2)),console.groupEnd(),console.groupCollapsed("🌐 Shared state (pphp.share)"),0===PPHP._shared.size?console.log("(none)"):console.table(Array.from(PPHP._shared.entries()).map((([e,{getter:t}])=>({key:e,value:this.formatValue(t()),type:typeof t()})))),console.groupEnd(),console.groupCollapsed("🔗 Shared keys declared this run"),0===this._sharedStateMap.size?console.log("(none)"):console.log([...this._sharedStateMap]),console.groupEnd(),console.groupCollapsed("🔖 State hierarchy"),console.table(Array.from(this._stateHierarchy.entries()).map((([e,t])=>({scopedKey:e,originalKey:t.originalKey,level:t.level,value:this.formatValue(this.getNested(this.props,e)),path:t.hierarchy.join(" → ")})))),console.groupEnd(),console.groupCollapsed("⚙️ Reactive internals"),console.log("Bindings total:",this._bindings.length),console.log("Pending bindings:",this._pendingBindings.size),console.log("Effects:",this._effects.size),console.log("Pending effects:",this._pendingEffects.size),console.log("Dirty deps:",Array.from(this._dirtyDeps).join(", ")||"(none)"),console.groupEnd(),console.groupCollapsed("🔗 Refs"),console.table(Array.from(this._refs.entries()).map((([e,t])=>({key:e,count:t.length,selectors:t.map((e=>e.tagName.toLowerCase())).join(", ")})))),console.groupEnd(),console.groupCollapsed("📦 Inline modules"),this._inlineModuleFns.forEach(((e,t)=>{console.log(`${t}:`,[...e.keys()])})),console.groupEnd(),console.log("Hydrated:",this._hydrated),console.groupCollapsed("🔀 Conditionals (pp-if chains)");Array.from(document.querySelectorAll("[pp-if], [pp-elseif], [pp-else]")).forEach(((e,t)=>{const n=e.hasAttribute("pp-if")?"if":e.hasAttribute("pp-elseif")?"elseif":"else",s=e.getAttribute(`pp-${n}`)??null;let r=null;if(s){const t=s.replace(/^{\s*|\s*}$/g,""),n=this.detectElementHierarchy(e);try{r=!!this.makeScopedEvaluator(t,n)(this._createScopedPropsContext(n))}catch{r=null}}console.log(`#${t}`,{element:e.tagName+(e.id?`#${e.id}`:""),type:n,expr:s,visible:!e.hasAttribute("hidden"),result:r})})),console.groupEnd(),console.groupCollapsed("🔁 Loops (pp-for)");const e=Array.from(document.querySelectorAll("template[pp-for]"));if(0===e.length)console.log("(none)");else{const t=e.map(((e,t)=>{const{itemName:n,idxName:s,arrExpr:r}=this.parseForExpression(e);let i=0;const a=e.previousSibling;if(a?.nodeType===Node.COMMENT_NODE&&"pp-for"===a.data){let e=a.nextSibling;for(;e&&!(e instanceof HTMLTemplateElement&&e.hasAttribute("pp-for"));)i+=1,e=e.nextSibling}return{"#":t,"(expr)":r,item:n||"(default)",idx:s||"(—)",rendered:i}}));console.table(t)}console.groupEnd(),console.groupEnd()}scheduleInitialHydration(){const e=()=>new Promise((e=>setTimeout(e,0))),t=async()=>{try{await Promise.all([this.initRefs(),this.bootstrapDeclarativeState(),this.processInlineModuleScripts(),this._hydrated=!0]),await e(),await this.initializeAllReferencedProps(),await e(),await this.manageAttributeBindings(),await e(),await this.processIfChains(),await e(),await this.initLoopBindings(),await e(),await this.attachWireFunctionEvents();const t=250;for(let n=0;n<this._bindings.length;n+=t)this._bindings.slice(n,n+t).forEach((e=>{try{e.update()}catch(e){console.error("Initial binding update error:",e)}})),await e();document.body.removeAttribute("hidden")}catch(e){console.error("Hydration failed:",e),document.body.removeAttribute("hidden")}};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t,{once:!0}):t()}async initCryptoKey(){const e=document.cookie.split("; ").find((e=>e.startsWith("pphp_function_call_jwt=")))?.split("=",2)[1];if(!e)throw new Error("Missing function-call token");const[,t]=e.split("."),n=atob(t.replace(/-/g,"+").replace(/_/g,"/")),{k:s,exp:r}=JSON.parse(n);if(Date.now()/1e3>r)throw new Error("Function-call token expired");const i=Uint8Array.from(atob(s),(e=>e.charCodeAt(0)));PPHP._cryptoKey=await crypto.subtle.importKey("raw",i,{name:"AES-CBC"},!1,["encrypt","decrypt"])}async encryptCallbackName(e){await this.initCryptoKey();const t=crypto.getRandomValues(new Uint8Array(16)),n=(new TextEncoder).encode(e),s=await crypto.subtle.encrypt({name:"AES-CBC",iv:t},PPHP._cryptoKey,n);return`${btoa(String.fromCharCode(...t))}:${btoa(String.fromCharCode(...new Uint8Array(s)))}`}async decryptCallbackName(e){await this.initCryptoKey();const[t,n]=e.split(":",2),s=Uint8Array.from(atob(t),(e=>e.charCodeAt(0))),r=Uint8Array.from(atob(n),(e=>e.charCodeAt(0))).buffer,i=await crypto.subtle.decrypt({name:"AES-CBC",iv:s},PPHP._cryptoKey,r);return(new TextDecoder).decode(i)}qsa(e,t){try{if(e)return e.querySelectorAll(t)}catch(e){console.error("qsa() failed:",e)}return document.createDocumentFragment().querySelectorAll(t)}async bootstrapDeclarativeState(e=document.body){this.qsa(e,"[pp-init-state]").forEach((e=>{let t,n=e.getAttribute("pp-init-state").trim();if(!n)return void e.removeAttribute("pp-init-state");try{t=JSON5.parse(n)}catch(e){return void console.error("Bad pp-init-state JSON:",n)}const s=this.detectElementHierarchy(e),r=this._currentProcessingHierarchy;this._currentProcessingHierarchy=s,Object.entries(t).forEach((([e,t])=>{this.state(e,t)})),this._currentProcessingHierarchy=r,e.removeAttribute("pp-init-state")}))}detectComponentHierarchy(e){const t=[];let n=e;for(;n&&n!==document.documentElement;){const e=n.getAttribute("pp-component");e&&t.unshift(e),n=n.parentElement}return 0===t.length?(console.warn('PPHP: No component hierarchy found - ensure <body data-component="app"> exists'),["app"]):t}detectElementHierarchy(e){const t=[];let n=e;for(;n&&n!==document.documentElement;){const e=n.getAttribute("pp-component");e&&t.unshift(e),n=n.parentElement}return t.length>0?t:["app"]}generateScopedKey(e,t){return e.join(".")+"."+t}ref(e,t){const n=this._refs.get(e)??[];if(null!=t){const s=n[t];if(!s)throw new Error(`pphp.ref('${e}', ${t}) — no element at that index`);return s}if(0===n.length)throw new Error(`pphp.ref('${e}') failed — no element was found`);return 1===n.length?n[0]:n}effect(e,t){const n=Array.isArray(t),s=n?t:[],r=n&&0===s.length,i=this._currentProcessingHierarchy||["app"],a=s.map((e=>{if("function"==typeof e){const t=e.__pphp_key;if(t)return t;try{const t=e.toString().match(/([a-zA-Z_$][a-zA-Z0-9_$]*(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*)*)/);if(t){const e=t[1];return this.resolveDependencyPath(e,i)}}catch(e){}return null}return"string"==typeof e?this.resolveDependencyPath(e,i):null})).filter((e=>Boolean(e))),o=s.filter((e=>"function"==typeof e&&!e.__pphp_key)),c=new Set(a),l=new Map;for(const e of a)try{l.set(e,this.getResolvedValue(e))}catch(t){l.set(e,void 0)}const h=new Map;for(const e of o)try{const t=e();h.set(e,t)}catch(t){h.set(e,Symbol("error"))}let d=0,p=0;PPHP._effectCleanups||(PPHP._effectCleanups=new WeakMap);const u=PPHP._effectCleanups,f=()=>{const t=u.get(f);if(t){try{t()}catch(e){console.error("cleanup error:",e)}u.delete(f)}const s=performance.now();if(s-p<16)requestAnimationFrame((()=>{performance.now()-p>=16&&f()}));else{if(p=s,++d>100)throw console.error("PPHP: effect exceeded 100 runs - possible infinite loop"),console.error("Effect function:",e.toString()),console.error("Dependencies:",Array.from(c)),new Error("PPHP: effect ran >100 times — possible loop");if(!r){let e=!1;const t=[];if(a.length>0)for(const n of a)try{const s=this.getResolvedValue(n),r=l.get(n);this.hasValueChanged(s,r)&&(e=!0,t.push(n),l.set(n,s))}catch(s){e=!0,t.push(n),l.set(n,void 0)}for(const n of o)try{const s=n(),r=h.get(n);this.hasValueChanged(s,r)&&(e=!0,t.push("(function)"),h.set(n,s))}catch(s){h.get(n)!==Symbol("error")&&(e=!0,t.push("(function-error)"),h.set(n,Symbol("error")))}if(n&&(a.length>0||o.length>0)&&!e)return}try{const t=e();"function"==typeof t&&u.set(f,t),d=0}catch(t){console.error("effect error:",t),console.error("Effect function:",e.toString())}}};Object.assign(f,{__deps:c,__static:r,__functionDeps:o,__hierarchy:i,__isEffect:!0});try{const t=e();"function"==typeof t&&u.set(f,t),d=0}catch(e){console.error("effect error (initial):",e)}const m=n&&this._inlineDepth>0?this._pendingEffects:this._effects;return r?this._effects.add(f):m.add(f),()=>{const e=u.get(f);if(e){try{e()}catch(e){console.error("cleanup error:",e)}u.delete(f)}this._effects.delete(f),this._pendingEffects.delete(f)}}resolveDependencyPath(e,t){const n=e.startsWith("app.")?e.substring(4):e,s=n.split(".")[0];if(PPHP._shared.has(s))return n;const r=t.join(".")+"."+e;if(this.hasNested(this.props,r))return r;if(this.hasNested(this.props,e))return e;for(let n=t.length-1;n>=0;n--){const s=t.slice(0,n).join("."),r=s?s+"."+e:e;if(this.hasNested(this.props,r))return r}return e}getResolvedValue(e){e.split(".")[0];const t=(e.startsWith("app.")?e.substring(4):e).split("."),n=t[0],s=PPHP._shared.get(n);if(s){if(1===t.length)return s.getter();{const e=s.getter(),n=t.slice(1).join(".");return this.getNested(e,n)}}return this.getNested(this.props,e)}hasValueChanged(e,t){if(e===t)return!1;if(null==e||null==t)return e!==t;if("object"!=typeof e||"object"!=typeof t)return e!==t;try{return JSON.stringify(e)!==JSON.stringify(t)}catch(e){return!0}}resetProps(){this._isNavigating=!1,this._activeAbortController&&this._activeAbortController.abort(),this._activeAbortController=null,this._responseData=null,Object.keys(this._rawProps).forEach((e=>{if(window.hasOwnProperty(e)){const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable&&delete window[e]}})),this._rawProps={},this.clearShare(),this._proxyCache=new WeakMap,this._templateStore=new WeakMap,this._arrayMethodCache=new WeakMap,this._handlerProxyCache=new WeakMap,this._processedLoops=new WeakSet,this._depsCache.clear(),this._dirtyDeps.clear(),this._evaluatorCache.clear(),this._handlerCache.clear(),this._sharedStateMap.clear(),this._processedPhpScripts=new WeakSet,this._declaredStateRoots.clear(),this._inlineModuleFns.clear(),this._inlineDepth=0,this._currentProcessingHierarchy=null,this._currentTemplateHierarchy=null,this._currentExecutionScope=null,this._stateHierarchy.clear(),this._bindings=[],this._pendingBindings.clear(),this._effects.clear(),this._pendingEffects.clear(),PPHP._effectCleanups=new WeakMap,this._refs.clear(),PPHP._debounceTimers.forEach((e=>clearTimeout(e))),PPHP._debounceTimers.clear(),this._updateScheduled=!1,this._wheelHandlersStashed=!1;try{const e=window;Object.getOwnPropertyNames(e).forEach((t=>{if(t.startsWith("__pphp_")||t.startsWith("_temp_"))try{delete e[t]}catch(e){}}))}catch(e){}this.props=this.makeReactive(this._rawProps),this._hydrated=!1;const e=document.createNodeIterator(document.body,NodeFilter.SHOW_COMMENT,{acceptNode:e=>"pp-for"===e.data?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT});let t;for(;t=e.nextNode();){let e=t.nextSibling;for(;e&&!(e instanceof HTMLTemplateElement&&e.hasAttribute("pp-for"));){const t=e.nextSibling;e.parentNode?.removeChild(e),e=t}t.parentNode?.removeChild(t)}}async initReactiveOn(e=document.body){const t=()=>new Promise((e=>setTimeout(e,0)));await Promise.all([this.initRefs(e),this.bootstrapDeclarativeState(e),this.processInlineModuleScripts(e),this._hydrated=!0]),await t(),await this.initializeAllReferencedProps(e),await t(),await this.manageAttributeBindings(e),await t(),await this.processIfChains(e),await t(),await this.initLoopBindings(e),await t();for(let e=0;e<this._bindings.length;e+=250)this._bindings.slice(e,e+250).forEach((e=>e.update())),await t()}async removeAllEventListenersOnNavigation(){document.removeAllEventListeners(),this._refs.forEach((e=>e.forEach((e=>e.removeAllEventListeners?.())))),document.querySelectorAll("*").forEach((e=>e.removeAllEventListeners?.()))}async initLoopBindings(e=document.body){this.qsa(e,"template[pp-for]").forEach((e=>{this._processedLoops.has(e)||(this._processedLoops.add(e),this.registerLoop(e))}))}registerLoop(e){const t=this.parseForExpression(e),{marker:n,parent:s,templateHierarchy:r}=this.setupLoopMarker(e),i=this.initializeLoopState(),a=this.createLoopUpdater(e,t,n,s,r,i),o={dependencies:this.extractComprehensiveLoopDependencies(e,t,r),update:a,__isLoop:!0};this._bindings.push(o)}processIfChainsInFragment(e,t,n,s,r,i){const a=new WeakSet;e.querySelectorAll("[pp-if]").forEach((e=>{if(a.has(e))return;const o=[];let c=e;for(;c;){if(c.hasAttribute("pp-if"))o.push({el:c,expr:c.getAttribute("pp-if")});else if(c.hasAttribute("pp-elseif"))o.push({el:c,expr:c.getAttribute("pp-elseif")});else{if(!c.hasAttribute("pp-else"))break;o.push({el:c,expr:null})}a.add(c),c=c.nextElementSibling}o.forEach((e=>{if(null!==e.expr){const i=e.expr.replace(/^{\s*|\s*}$/g,"");e.deps=this.extractScopedDependencies(i,n);const a=this.makeScopedEvaluator(i,n);e.evaluate=()=>{const e={...this._createScopedPropsContext(n),[t.itemName]:s};return t.idxName&&(e[t.idxName]=r),!!a(e)}}}));let l=!1;for(const{el:e,expr:t,evaluate:n}of o)!l&&null!==t&&n()?(e.removeAttribute("hidden"),l=!0):l||null!==t?e.setAttribute("hidden",""):(e.removeAttribute("hidden"),l=!0);const h=new Set;o.forEach((e=>e.deps?.forEach((e=>h.add(e)))));const d=n.join("."),p=d?`${d}.${t.arrExpr}`:t.arrExpr;h.add(p);i.push({dependencies:h,update:()=>{const e=this.makeScopedEvaluator(t.arrExpr,n)(this._createScopedPropsContext(n));if(Array.isArray(e)){const i=this.getItemKey(s,r),a=this.findItemByKey(e,i,s),c=e.findIndex((t=>this.getItemKey(t,e.indexOf(t))===i));if(a&&-1!==c){let e=!1;for(const{el:s,expr:r,evaluate:i}of o)if(null!==r){const i=this.makeScopedEvaluator(r.replace(/^{\s*|\s*}$/g,""),n),o={...this._createScopedPropsContext(n),[t.itemName]:a};t.idxName&&(o[t.idxName]=c);const l=!!i(o);!e&&l?(s.removeAttribute("hidden"),e=!0):s.setAttribute("hidden","")}else e?s.setAttribute("hidden",""):(s.removeAttribute("hidden"),e=!0)}}},__isLoop:!0})}))}extractComprehensiveLoopDependencies(e,t,n){const s=new Set;let r=null;for(let e=n.length;e>=0;e--){const s=n.slice(0,e),i=s.length>0?`${s.join(".")}.${t.arrExpr}`:t.arrExpr;try{const e=this.getNested(this.props,i);if(Array.isArray(e)){r=i;break}}catch{}}if(!r)try{const e=this.getNested(this.props,t.arrExpr);Array.isArray(e)&&(r=t.arrExpr)}catch{r=n.length>0?`${n.join(".")}.${t.arrExpr}`:t.arrExpr}const i=r;null!==i&&s.add(i);const a=this.extractItemPropertiesFromTemplate(e,t);for(const e of a)if(s.add(`${i}.*`),s.add(`${i}.*.${e}`),"string"==typeof i){const t=this.getNested(this.props,i);if(Array.isArray(t))for(let n=0;n<t.length;n++)s.add(`${i}.${n}.${e}`)}return Array.from(s).some((e=>e.includes("*")))||s.add(`${i}.*`),s}extractItemPropertiesFromTemplate(e,t){const n=new Set,s=new RegExp(`\\b${t.itemName}\\.(\\w+(?:\\.\\w+)*)`,"g"),r=document.createTreeWalker(e.content,NodeFilter.SHOW_ALL,null);for(;r.nextNode();){const e=r.currentNode;let t="";if(e.nodeType===Node.TEXT_NODE)t=e.nodeValue||"";else if(e.nodeType===Node.ELEMENT_NODE){const n=e;for(const e of Array.from(n.attributes))t+=" "+e.value}const i=t.matchAll(s);for(const e of i)n.add(e[1])}return n}parseForExpression(e){const t=e.getAttribute("pp-for").trim(),[n,s]=t.split(/\s+in\s+/),[r,i]=n.replace(/^\(|\)$/g,"").split(",").map((e=>e.trim()));return{forExpr:t,vars:n,arrExpr:s,itemName:r,idxName:i}}setupLoopMarker(e){const t=e.parentNode,n=document.createComment("pp-for"),s=this.detectElementHierarchy(e);return t.insertBefore(n,e),t.removeChild(e),{marker:n,parent:t,templateHierarchy:s}}initializeLoopState(){return{previousList:[],renderedItems:new Map}}createItemNodes(e,t,n,s,r){this._currentTemplateHierarchy=r;const i={...this._createScopedPropsContext(r),[s.itemName]:t};s.idxName&&(i[s.idxName]=n);const a=e.content.cloneNode(!0),o=[],c=this.getItemKey(t,n);return this.processTextNodesInFragment(a,s,r,c,t,n,o),this.processElementBindingsInFragment(a,s,r,c,t,n,o),this.processEventHandlersInFragment(a,s,r,t,n),this.processIfChainsInFragment(a,s,r,t,n,o),o.forEach((e=>{e.__isLoop=!0,this._bindings.push(e)})),this._currentTemplateHierarchy=null,{nodes:Array.from(a.childNodes),bindings:o}}processTextNodesInFragment(e,t,n,s,r,i,a){const o=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);for(;o.nextNode();){const e=o.currentNode,c=e.nodeValue||"";if(PPHP._mustacheTest.test(c)){const o=new Set,l=n.join("."),h=l?`${l}.${t.arrExpr}`:t.arrExpr;o.add(h);for(const e of c.matchAll(PPHP._mustachePattern))this.extractScopedDependencies(e[1],n).forEach((e=>o.add(e)));const d=this.createTextNodeUpdaterWithItemKey(e,c,t,n,s,r);a.push({dependencies:o,update:d}),this.renderTextNode(e,c,t,n,r,i)}}}createTextNodeUpdaterWithItemKey(e,t,n,s,r,i){const a=this.makeScopedEvaluator(n.arrExpr,s);return()=>{const o=a(this._createScopedPropsContext(s));if(Array.isArray(o)){const a=this.findItemByKey(o,r,i),c=o.findIndex((e=>this.getItemKey(e,o.indexOf(e))===r));if(a&&-1!==c){const r={...this._createScopedPropsContext(s),[n.itemName]:a};n.idxName&&(r[n.idxName]=c);const i=this.renderMustacheText(t,s,r);e.nodeValue!==i&&(e.nodeValue=i)}}}}findItemByKey(e,t,n){for(let n=0;n<e.length;n++){const s=e[n];if(this.getItemKey(s,n)===t)return s}return n&&"object"==typeof n&&n.id?e.find((e=>e&&e.id===n.id)):null}processElementBindingsInFragment(e,t,n,s,r,i,a){e.querySelectorAll("*").forEach((e=>{this.processElementBindings(e,t,n,s,r,i,a)}))}processElementBindings(e,t,n,s,r,i,a){const o=new Set,c=new Set;for(const{name:t,value:n}of Array.from(e.attributes))if(PPHP._mustacheTest.test(n)&&!t.startsWith("pp-bind"))o.add(t);else if(t.startsWith("pp-bind-")){const e=t.replace(/^pp-bind-/,"");c.add(e)}for(const{name:c,value:l}of Array.from(e.attributes))if("pp-bind"===c)this.createElementBindingWithItemKey(e,l,"text",t,n,s,r,i,a);else if("pp-bind-expr"===c){const o=this.decodeEntities(l);this.createElementBindingWithItemKey(e,o,"text",t,n,s,r,i,a)}else if(c.startsWith("pp-bind-")){const h=c.replace(/^pp-bind-/,"");if(o.has(h)){if(!this._boolAttrs.has(h))continue;e.removeAttribute(h)}this.createElementBindingWithItemKey(e,l,h,t,n,s,r,i,a)}else PPHP._mustacheTest.test(l)&&this.createElementAttributeTemplateBindingWithItemKey(e,c,l,t,n,s,r,i,a)}createElementAttributeTemplateBindingWithItemKey(e,t,n,s,r,i,a,o,c){const l=new Set,h=r.join("."),d=h?`${h}.${s.arrExpr}`:s.arrExpr;l.add(d);for(const e of n.matchAll(PPHP._mustachePattern))this.extractScopedDependencies(e[1],r).forEach((e=>l.add(e)));const p=this.createAttributeTemplateUpdaterWithItemKey(e,t,n,s,r,i,a);c.push({dependencies:l,update:p}),this.renderAttributeTemplate(e,t,n,s,r,a,o)}createAttributeTemplateUpdaterWithItemKey(e,t,n,s,r,i,a){const o=this.makeScopedEvaluator(s.arrExpr,r);return()=>{const c=o(this._createScopedPropsContext(r));if(Array.isArray(c)){const o=this.findItemByKey(c,i,a),l=c.findIndex((e=>this.getItemKey(e,c.indexOf(e))===i));o&&-1!==l&&this.renderAttributeTemplate(e,t,n,s,r,o,l)}}}renderAttributeTemplate(e,t,n,s,r,i,a){const o={...this._createScopedPropsContext(r),[s.itemName]:i};s.idxName&&(o[s.idxName]=a);const c=n.replace(PPHP._mustachePattern,((e,t)=>{try{const e=this.makeScopedEvaluator(t,r);return this.formatValue(e(o))}catch(e){return console.error("PPHP: mustache token error:",t,e),""}}));e.getAttribute(t)!==c&&e.setAttribute(t,c)}createElementBindingWithItemKey(e,t,n,s,r,i,a,o,c){const l=new Set,h=r.join("."),d=h?`${h}.${s.arrExpr}`:s.arrExpr;l.add(d),this.extractScopedDependencies(t,r).forEach((e=>l.add(e)));const p=this.createElementBindingUpdaterWithItemKey(e,t,n,s,r,i,a);c.push({dependencies:l,update:p}),this.renderElementBinding(e,t,n,s,r,a,o)}createElementBindingUpdaterWithItemKey(e,t,n,s,r,i,a){const o=this.makeScopedEvaluator(s.arrExpr,r);return()=>{const c=o(this._createScopedPropsContext(r));if(Array.isArray(c)){const o=this.findItemByKey(c,i,a),l=c.findIndex((e=>this.getItemKey(e,c.indexOf(e))===i));if(o&&-1!==l){const i={...this._createScopedPropsContext(r),[s.itemName]:o};s.idxName&&(i[s.idxName]=l),this.updateElementBinding(e,t,n,r,i)}}}}getItemKey(e,t){if(e&&"object"==typeof e){if("id"in e&&null!=e.id)return`id_${e.id}`;if("key"in e&&null!=e.key)return`key_${e.key}`;if("_id"in e&&null!=e._id)return`_id_${e._id}`;const t=Object.keys(e).filter((t=>(t.toLowerCase().includes("id")||t.toLowerCase().includes("uuid"))&&null!=e[t]&&("string"==typeof e[t]||"number"==typeof e[t])));if(t.length>0){const n=t[0];return`${n}_${e[n]}`}}return`idx_${t}`}renderTextNode(e,t,n,s,r,i){const a={...this._createScopedPropsContext(s),[n.itemName]:r};n.idxName&&(a[n.idxName]=i),e.nodeValue=this.renderMustacheText(t,s,a)}renderMustacheText(e,t,n){return e.replace(PPHP._mustachePattern,((e,s)=>{try{const e=this.makeScopedEvaluator(s,t);return this.formatValue(e(n))}catch{return""}}))}updateElementBinding(e,t,n,s,r){const i=this.makeScopedEvaluator(t,s)(r);if("text"===n){const t=this.formatValue(i);e.textContent!==t&&(e.textContent=t)}else this.applyAttributeBinding(e,n,i)}renderElementBinding(e,t,n,s,r,i,a){const o={...this._createScopedPropsContext(r),[s.itemName]:i};s.idxName&&(o[s.idxName]=a),this.updateElementBinding(e,t,n,r,o)}applyAttributeBinding(e,t,n){if(this._boolAttrs.has(t)){const s=!!n;s!==e.hasAttribute(t)&&(s?e.setAttribute(t,""):e.removeAttribute(t)),t in e&&e[t]!==s&&(e[t]=s)}else{const s=String(n);t in e&&e[t]!==s&&(e[t]=s),e.getAttribute(t)!==s&&e.setAttribute(t,s)}}processEventHandlersInFragment(e,t,n,s,r){e.querySelectorAll("*").forEach((e=>{for(const{name:r,value:i}of Array.from(e.attributes)){const a=r.toLowerCase();if(!this._eventHandlers.has(a))continue;let o=i;const c=t=>{try{if(t&&"object"==typeof t&&!Array.isArray(t)){const n=`__pphp_data_${Date.now()}_${Math.random().toString(36).slice(2,7)}`;return e[n]=t,`(event.currentTarget.${n} || event.target.${n})`}return JSON.stringify(t)}catch(e){return console.error("Failed to serialize item:",e),"null"}};if(o=o.replace(new RegExp(`\\b${t.itemName}\\b`,"g"),c(s)),t.idxName){const e=`(globalThis.pphp._idxOf(${c(s)}, '${t.arrExpr}', ${JSON.stringify(n)}))`;o=o.replace(new RegExp(`\\b${t.idxName}\\b`,"g"),e)}e.setAttribute(r,o)}}))}_idxOf(e,t,n){try{const s=this.makeScopedEvaluator(t,n)(this._createScopedPropsContext(n));if(!Array.isArray(s))return-1;let r=s.findIndex((t=>t===e));if(-1!==r)return r;const i=this.getItemKey(e,-1);return r=s.findIndex(((e,t)=>this.getItemKey(e,t)===i)),r}catch{return-1}}updateItemNodes(e,t,n,s,r,i){if(t===n)return;if("object"==typeof t&&"object"==typeof n&&JSON.stringify(t)===JSON.stringify(n))return;this._currentTemplateHierarchy=i;const a={...this._createScopedPropsContext(i),[r.itemName]:n};r.idxName&&(a[r.idxName]=s),this.updateNodesContent(e,i,a),this.updateConditionalNodes(e,i,a),this._currentTemplateHierarchy=null}updateConditionalNodes(e,t,n){e.forEach((e=>{if(e.nodeType===Node.ELEMENT_NODE){e.querySelectorAll("[pp-if], [pp-elseif], [pp-else]").forEach((e=>{const s=e.getAttribute("pp-if")||e.getAttribute("pp-elseif");if(s){const r=s.replace(/^{\s*|\s*}$/g,"");try{const s=this.makeScopedEvaluator(r,t);!!s(n)?e.removeAttribute("hidden"):e.setAttribute("hidden","")}catch(e){console.error("Error evaluating pp-if condition:",r,e)}}else if(e.hasAttribute("pp-else")){const t=e.previousElementSibling;t&&t.hasAttribute("hidden")?e.removeAttribute("hidden"):e.setAttribute("hidden","")}}))}}))}updateNodesContent(e,t,n){e.forEach((e=>{e.nodeType===Node.ELEMENT_NODE&&this.updateElementContent(e,t,n)}))}updateElementContent(e,t,n){const s=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>{const t=e.nodeValue||"";return t.includes("{{")&&t.includes("}}")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT}});for(;s.nextNode();){const e=s.nextNode(),r=e.nodeValue||"",i=this.renderMustacheText(r,t,n);e.nodeValue!==i&&(e.nodeValue=i)}e.querySelectorAll("*").forEach((e=>{this.updateElementBindingsContent(e,t,n),this.updateElementTemplateAttributes(e,t,n)}))}updateElementTemplateAttributes(e,t,n){for(const{name:s,value:r}of Array.from(e.attributes))if(!s.startsWith("pp-bind")&&PPHP._mustacheTest.test(r)){const i=r.replace(PPHP._mustachePattern,((e,s)=>{try{const e=this.makeScopedEvaluator(s,t);return this.formatValue(e(n))}catch(e){return console.error("PPHP: mustache token error:",s,e),""}}));e.getAttribute(s)!==i&&e.setAttribute(s,i)}}updateElementBindingsContent(e,t,n){for(const{name:s,value:r}of Array.from(e.attributes))if("pp-bind"===s)this.updateElementBinding(e,r,"text",t,n);else if(s.startsWith("pp-bind-")){const i=s.replace(/^pp-bind-/,"");this.updateElementBinding(e,r,i,t,n)}}createLoopUpdater(e,t,n,s,r,i){let a;for(let e=r.length;e>=0;e--){const n=r.slice(0,e);try{const e=this.makeScopedEvaluator(t.arrExpr,n),s=e(this._createScopedPropsContext(n));if(Array.isArray(s)){a=e;break}}catch{}}return a=this.makeScopedEvaluator(t.arrExpr,r),()=>{this.performLoopUpdate(e,t,n,s,r,i,a)}}captureFocusState(e){const t=document.activeElement,n=t&&e.contains(t),s=n?t.closest("[key]")?.getAttribute("key"):null;return{active:t,hadFocus:n,focusKey:s,caretPos:n&&t instanceof HTMLInputElement?t.selectionStart:null}}restoreFocusState(e,t){if(e.focusKey){const n=t.querySelector(`[key="${e.focusKey}"]`),s=n?.querySelector("input,textarea");if(s&&(s.focus({preventScroll:!0}),null!==e.caretPos&&s instanceof HTMLInputElement)){const t=Math.min(e.caretPos,s.value.length);s.setSelectionRange(t,t)}}}calculateLoopDiff(e,t){const n=new Map,s=new Map;e.forEach(((e,t)=>{const s=this.getItemKey(e,t);n.set(s,{item:e,index:t})})),t.forEach(((e,t)=>{const n=this.getItemKey(e,t);s.set(n,{item:e,index:t})}));const r=new Set,i=new Map,a=new Map;for(const[e]of n)s.has(e)||r.add(e);for(const[e,{item:t,index:r}]of s)if(n.has(e)){const s=n.get(e);s.item===t&&s.index===r||a.set(e,{oldItem:s.item,newItem:t,newIndex:r,oldIndex:s.index})}else i.set(e,{item:t,index:r});return{toDelete:r,toInsert:i,toUpdate:a}}applyLoopChanges(e,t,n,s,r,i,a){this.applyLoopDeletions(e.toDelete,t),this.applyLoopUpdates(e.toUpdate,t,n,i),this.applyLoopInsertions(e.toInsert,t,n,s,r,i,a)}applyLoopUpdates(e,t,n,s){for(const[r,{oldItem:i,newItem:a,newIndex:o,oldIndex:c}]of e){const e=t.renderedItems.get(r);e&&(this.updateItemNodes(e.nodes,i,a,o,n,s),e.item=a,e.index=o,e.bindings.forEach((e=>{e.update()})))}}applyLoopInsertions(e,t,n,s,r,i,a){if(0===e.size)return;const o=Array.from(e.entries()).sort((([,e],[,t])=>e.index-t.index));for(const[e,{item:c,index:l}]of o){if(t.renderedItems.has(e)){console.warn(`Item with key ${e} already exists, skipping insertion`);continue}const{nodes:o,bindings:h}=this.createItemNodes(a,c,l,n,i);let d=s;const p=Array.from(t.renderedItems.entries()).map((([e,t])=>({key:e,...t}))).sort(((e,t)=>e.index-t.index));for(let e=p.length-1;e>=0;e--)if(p[e].index<l){d=p[e].nodes[p[e].nodes.length-1];break}o.forEach((e=>{r.insertBefore(e,d.nextSibling),d=e})),t.renderedItems.set(e,{nodes:o,item:c,index:l,bindings:h})}}performLoopUpdate(e,t,n,s,r,i,a){const o=this.captureFocusState(s);let c,l=[];for(let e=r.length;e>=0;e--){const t=r.slice(0,e);try{c=this._createScopedPropsContext(t);const e=a(c);if(Array.isArray(e)&&e.length>=0){l=e;break}}catch(e){console.log("🔥 Debug: Failed to evaluate at hierarchy:",t,e)}}if(!c){c=this._createScopedPropsContext(r);const e=a(c);l=Array.isArray(e)?e:[]}if(!Array.isArray(l))return void console.warn("Loop expression did not return an array:",l);const h=this.calculateLoopDiff(i.previousList,l);this.applyLoopChanges(h,i,t,n,s,r,e),i.previousList=[...l],this.restoreFocusState(o,s),this.attachWireFunctionEvents()}applyLoopDeletions(e,t){for(const n of e){const e=t.renderedItems.get(n);e&&(e.bindings.forEach((e=>{const t=this._bindings.indexOf(e);t>-1&&this._bindings.splice(t,1)})),e.nodes.forEach((e=>{e.parentNode&&e.parentNode.removeChild(e)})),t.renderedItems.delete(n))}}async initRefs(e=document.body){this.qsa(e,"[pp-ref]").forEach((e=>{const t=e.getAttribute("pp-ref"),n=this._refs.get(t)??[];n.push(e),this._refs.set(t,n),e.removeAttribute("pp-ref")}))}scheduleBindingUpdate(e){this._pendingBindings.add(e),this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this.flushBindings()})))}makeReactive(e,t=[]){if(this.shouldUnwrapValue(e))return e;const n=this._proxyCache.get(e);if(n)return n;if(e instanceof Map||e instanceof Set||"object"!=typeof e||null===e)return e;if(e.__isReactiveProxy)return e;const s=this,r=new Proxy(e,{get(e,n,r){if("__isReactiveProxy"===n)return!0;const i=Reflect.get(e,n,r);if(Array.isArray(e)&&"string"==typeof n&&s._mutators.has(n)){let a=s._arrayMethodCache.get(e);if(a||(a=new Map,s._arrayMethodCache.set(e,a)),!a.has(n)){const e=i.bind(r),o=t.join("."),c=function(...t){const n=e(...t);return queueMicrotask((()=>{s._bindings.forEach((e=>{const t=s.getBindingType(e);for(const n of e.dependencies)if(s.dependencyMatches(o,n,t)){s.scheduleBindingUpdate(e);break}}))})),n};a.set(n,c)}return a.get(n)}if(null!==i&&"object"==typeof i&&!i.__isReactiveProxy)return s.makeReactive(i,[...t,n]);if(Array.isArray(e)&&"function"==typeof i){let t=s._arrayMethodCache.get(e);return t||(t=new Map,s._arrayMethodCache.set(e,t)),t.has(n)||t.set(n,i.bind(e)),t.get(n)}return i},set(e,n,r,i){if("__isReactiveProxy"===n)return!0;let a=r;null===r||"object"!=typeof r||r.__isReactiveProxy||(a=s.makeReactive(r,[...t,n]));const o=e[n],c=Reflect.set(e,n,a,i);if(o===a)return c;const l=[...t,n].join(".");if(s._dirtyDeps.add(l),l.startsWith("app.")){const e=l.substring(4),t=e.split(".")[0];PPHP._shared.has(t)&&s._dirtyDeps.add(e)}if(Array.isArray(e)&&/^\d+$/.test(String(n))){const e=t.join(".");if(s._dirtyDeps.add(`${e}.*`),e.startsWith("app.")){const t=e.substring(4),n=t.split(".")[0];PPHP._shared.has(n)&&s._dirtyDeps.add(`${t}.*`)}a&&"object"==typeof a&&Object.keys(a).forEach((t=>{if(s._dirtyDeps.add(`${e}.*.${t}`),e.startsWith("app.")){const n=e.substring(4),r=n.split(".")[0];PPHP._shared.has(r)&&s._dirtyDeps.add(`${n}.*.${t}`)}}))}if(t.length>=2&&/^\d+$/.test(t[t.length-1])){const e=t.slice(0,-1).join(".");if(s._dirtyDeps.add(`${e}.*.${String(n)}`),e.startsWith("app.")){const t=e.substring(4),r=t.split(".")[0];PPHP._shared.has(r)&&s._dirtyDeps.add(`${t}.*.${String(n)}`)}}return s._bindings.forEach((e=>{const t=s.getBindingType(e);for(const n of e.dependencies){if(s.dependencyMatches(l,n,t)){s.scheduleBindingUpdate(e);break}if(l.startsWith("app.")){const r=l.substring(4),i=r.split(".")[0];if(PPHP._shared.has(i)&&s.dependencyMatches(r,n,t)){s.scheduleBindingUpdate(e);break}}}})),s._hydrated&&s.scheduleFlush(),c}});return this._proxyCache.set(e,r),r}shouldUnwrapValue(e){return e instanceof Date||e instanceof RegExp||e instanceof Error||e instanceof URLSearchParams||e instanceof URL||e instanceof Promise||e instanceof ArrayBuffer||e instanceof DataView||"object"==typeof e&&null!==e&&e.constructor!==Object&&e.constructor!==Array}getBindingType(e){if(e.__isEffect)return"effect";if(e.__isLoop)return"loop";for(const t of e.dependencies)if(t.includes("*")||t.match(/\.\d+\./)||t.endsWith(".*"))return"loop";for(const t of e.dependencies)try{const e=this.getNested(this.props,t);if(Array.isArray(e))return"loop"}catch{}return"binding"}makeAttrTemplateUpdater(e,t,n,s){let r=this._templateStore.get(e);r||(r=new Map,this._templateStore.set(e,r)),r.has(t)||r.set(t,e.getAttribute(t)||"");const i=s??r.get(t),a=this.detectElementHierarchy(e);return(i.match(this._mustacheRe)||[]).forEach((e=>{const t=e.replace(/^\{\{\s*|\s*\}\}$/g,"");this.extractScopedDependencies(t,a).forEach((e=>n.add(e)))})),()=>{try{const n=i.replace(this._mustacheRe,((e,t)=>{try{const e=this.makeScopedEvaluator(t,a),n=this._createScopedPropsContext(a);return this.formatValue(e(n))}catch(e){return console.error("PPHP: mustache token error:",t,e),""}}));e.getAttribute(t)!==n&&e.setAttribute(t,n)}catch(e){console.error(`PPHP: failed to render attribute "${t}" with template "${i}"`,e)}}}formatValue(e){if(e instanceof Date)return e.toISOString();if("function"==typeof e){if(e.__isReactiveProxy)try{return this.formatValue(e())}catch{}return""}if(e&&"object"==typeof e){if(e.__isReactiveProxy&&"value"in e)try{return this.formatValue(e.value)}catch{return String(e)}if(e.__isReactiveProxy)try{const t={};for(const n in e)if("__isReactiveProxy"!==n&&"__pphp_key"!==n)try{t[n]=e[n]}catch{}return Object.keys(t).length?JSON.stringify(t,null,2):""}catch{return String(e)}try{return JSON.stringify(e,((e,t)=>{if("__isReactiveProxy"!==e&&"__pphp_key"!==e)return t&&"object"==typeof t&&t.__isReactiveProxy?"function"==typeof t&&"value"in t?t.value:"[Reactive Object]":t}),2)}catch{return String(e)}}return null!==e&&"object"==typeof e&&1===Object.keys(e).length&&Object.prototype.hasOwnProperty.call(e,"value")?this.formatValue(e.value):"boolean"==typeof e?e?"true":"false":Array.isArray(e)?e.map((e=>"object"==typeof e&&null!==e?(()=>{try{return JSON.stringify(e)}catch{return String(e)}})():String(e))).join(", "):e?.toString()??""}registerBinding(e,t,n="text",s){if(this._assignmentRe.test(t))return;const r=this.detectElementHierarchy(e),i=this.extractScopedDependencies(t,r),a=this.makeScopedEvaluator(t,r);if("value"===s||"checked"===s){const t=()=>{try{const t=this._createScopedPropsContext(r),n=a(t),i=this.formatValue(n);let o=!1;if("value"===s){const t=e;"value"in e&&t.value!==i?(t.value=i,o=!0):"value"in e||(e.setAttribute("value",i),o=!0)}else{const t=e,n="true"===i;"checked"in e&&t.checked!==n?(t.checked=n,o=!0):"checked"in e||(e.setAttribute("checked",i),o=!0)}if(!o||!this._hydrated||e instanceof HTMLInputElement&&("hidden"===e.type||e.disabled||e.readOnly))return;const c={};this._eventHandlers.forEach((e=>{if(e.startsWith("on")){const t=e.slice(2);c[t]=t}})),c.value="input",c.checked="change";const l=c[s]||s,h="click"===l?new MouseEvent(l,{bubbles:!0,cancelable:!0}):new Event(l,{bubbles:!0});e.dispatchEvent(h)}catch(e){console.error(`Error evaluating attribute "${s}":`,e)}};return void this._bindings.push({dependencies:i,update:t})}if(s){const n=s.toLowerCase();if(this._boolAttrs.has(n)){e.removeAttribute(n);const o=()=>{try{const t=this._createScopedPropsContext(r),i=!!a(t);e[s]!==i&&(e[s]=i),i?e.setAttribute(n,""):e.removeAttribute(n)}catch(e){console.error(`PPHP: error evaluating boolean attribute ${s}="${t}"`,e)}};return void this._bindings.push({dependencies:i,update:o})}const o=e.getAttribute(s)??"";if(this._mustacheRe.test(t)||this._mustacheRe.test(o)){const t=this.makeAttrTemplateUpdater(e,s,i,o);return void this._bindings.push({dependencies:i,update:t})}const c=()=>{try{const t=this._createScopedPropsContext(r),n=a(t),i=this.formatValue(n);s in e&&(e[s]=i),e.setAttribute(s,i)}catch(e){console.error(`Error evaluating attribute ${s}="${t}"`,e)}};return void this._bindings.push({dependencies:i,update:c})}const o={text(e,t){e.textContent!==t&&(e.textContent=t)},value(e,t){e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement?e.value!==t&&(e.value=t):e.setAttribute("value",t)},checked(e,t){e instanceof HTMLInputElement?e.checked="true"===t:e.setAttribute("checked",t)},attr(e,t){e.setAttribute("attr",t)}};this._bindings.push({dependencies:i,update:()=>{try{const t=this._createScopedPropsContext(r),s=a(t),i=this.formatValue(s);o[n](e,i)}catch(e){console.error(`Error evaluating expression "${t}"`,e)}}})}makeSafeEvaluator(e){const t=e.trim(),n=`\n try {\n with (ctx) {\n ${/^\s*[\w.]+\s*=(?!=)/.test(t)?`${t}; return "";`:`return (${t});`}\n }\n } catch {\n return "";\n }\n `;let s;try{s=new Function("ctx",n)}catch(t){const n=JSON.stringify(e);s=new Function("ctx",`try { return ${n}; } catch { return ""; }`)}return e=>{try{const t=s(e);return null==t?"":t}catch{return""}}}makeScopedEvaluator(e,t){const n=e.trim(),s=`\n try {\n with (ctx) {\n ${/^\s*[\w.]+\s*=(?!=)/.test(n)?`${n}; return "";`:`return (${n});`}\n }\n } catch {\n return "";\n }\n `;let r;try{r=new Function("ctx",s)}catch(t){const n=JSON.stringify(e);r=new Function("ctx",`try { return ${n}; } catch { return ""; }`)}return n=>{try{for(let s=t.length;s>=0;s--){const i=t.slice(0,s);try{const t=this._createScopedPropsContext(i,n),s=r(t);if(Array.isArray(s)&&"voucherItems"===e)return s;if(null!=s&&""!==s&&"voucherItems"!==e)return s}catch{}}const s=this._createScopedPropsContext(t,n),i=r(s);return null==i?"":i}catch{return""}}}_createScopedPropsContext(e,t={}){const n=e.join("."),s=this.getNested(this.props,n)||{},r=this;return new Proxy(t,{get(t,n,i){if("string"==typeof n){const e=Reflect.get(t,n,i);if("function"==typeof e&&e.__isReactiveProxy)try{return e()}catch{}}if(n in t)return Reflect.get(t,n,i);const a=r.getScopedFunction(n,e);if(a)return a;if(s&&n in s)return s[n];for(let t=e.length-1;t>=0;t--){const s=e.slice(0,t).join("."),i=r.getScopedFunction(n,e.slice(0,t));if(i)return i;const a=s?r.getNested(r.props,s):r.props;if(a&&n in a)return a[n]}return n in globalThis?globalThis[n]:void 0},set(t,s,i,a){if("string"!=typeof s)return Reflect.set(t,s,i,a);if(s in t)return Reflect.set(t,s,i,a);for(let t=e.length;t>=0;t--){const n=e.slice(0,t).join("."),a=n?`${n}.${s}`:s;if(r.hasNested(r.props,a))return r.setNested(r.props,a,i),r._dirtyDeps.add(a),r.scheduleFlush(),!0}const o=n?`${n}.${s}`:s;return r.setNested(r.props,o,i),r._dirtyDeps.add(o),r.scheduleFlush(),!0},has:(t,n)=>"string"==typeof n&&(n in t||!!r.getScopedFunction(n,e)||s&&n in s||n in globalThis||e.some(((t,s)=>{const i=e.slice(0,s).join("."),a=i?r.getNested(r.props,i):r.props;return a&&n in a})))})}extractScopedDependencies(e,t){const n=this.extractDependencies(e),s=new Set,r=t.join(".");for(const e of n){if(this._reservedWords.has(e.split(".")[0]))continue;const n=r+"."+e;if(this._stateHierarchy.has(n)){s.add(n);continue}if(this.hasNested(this.props,n)){s.add(n);continue}let i=!1;for(let n=t.length-1;n>=0&&!i;n--){const r=t.slice(0,n).join("."),a=r?r+"."+e:e;this._stateHierarchy.has(a)?(s.add(a),i=!0):this.hasNested(this.props,a)&&(s.add(a),i=!0)}if(!i){const t=r+"."+e;s.add(t)}}return s}async processIfChains(e=document.body){const t=new WeakSet;this.qsa(e,"[pp-if]").forEach((e=>{if(t.has(e))return;const n=this.detectElementHierarchy(e),s=[];let r=e;for(;r;){if(r.hasAttribute("pp-if"))s.push({el:r,expr:r.getAttribute("pp-if")});else if(r.hasAttribute("pp-elseif"))s.push({el:r,expr:r.getAttribute("pp-elseif")});else{if(!r.hasAttribute("pp-else"))break;s.push({el:r,expr:null})}t.add(r),r=r.nextElementSibling}s.forEach((e=>{if(null!==e.expr){const t=e.expr.replace(/^{\s*|\s*}$/g,"");e.deps=this.extractScopedDependencies(t,n);const s=this.makeScopedEvaluator(t,n);e.evaluate=()=>{const e=this._createScopedPropsContext(n);return!!s(e)}}}));const i=new Set;s.forEach((e=>e.deps?.forEach((e=>i.add(e)))));this._bindings.push({dependencies:i,update:()=>{let e=!1;for(const{el:t,expr:n,evaluate:r}of s)!e&&null!==n&&r()?(t.removeAttribute("hidden"),e=!0):e||null!==n?t.setAttribute("hidden",""):(t.removeAttribute("hidden"),e=!0)}})}))}async manageAttributeBindings(e=document.body){this.qsa(e,"*").forEach((e=>{const t=new Map;Array.from(e.attributes).forEach((e=>{if(e.name.startsWith("pp-bind"))return;const n=this.decodeEntities(e.value);PPHP._mustacheTest.test(n)&&t.set(e.name.toLowerCase(),n)})),["pp-bind","pp-bind-expr"].forEach((t=>{const n=e.getAttribute(t);n&&this.registerBinding(e,n,"text")})),Array.from(e.attributes).forEach((t=>{const n=t.name.toLowerCase(),s=t.value.trim();this._boolAttrs.has(n)&&!t.name.startsWith("pp-bind-")&&/^[A-Za-z_$][\w$]*$/.test(s)&&(e.removeAttribute(t.name),this.registerBinding(e,s,"text",n))})),Array.from(e.attributes).forEach((n=>{if(!n.name.startsWith("pp-bind-"))return;if(["pp-bind","pp-bind-expr","pp-bind-spread"].includes(n.name))return;const s=n.name.replace(/^pp-bind-/,"").toLowerCase(),r=this.decodeEntities(n.value).replace(/^{{\s*|\s*}}$/g,""),i="value"===s?"value":"checked"===s?"checked":"text";if(t.has(s)){const a=t.get(s).replace(PPHP._mustachePattern,"").trim(),o=a.length>0?`\`${a} \${${r}}\``:r;e.setAttribute(n.name,o);try{const t=this._createScopedPropsContext(this.detectElementHierarchy(e)),n=this.formatValue(this.makeScopedEvaluator(o,this.detectElementHierarchy(e))(t));e.setAttribute(s,n)}catch{}return this.registerBinding(e,o,i,s),void t.delete(s)}this.registerBinding(e,r,i,s)})),Array.from(e.attributes).forEach((t=>{if("pp-bind-spread"!==t.name)return;const n=this.detectElementHierarchy(e),s=this.decodeEntities(t.value).split(",").map((e=>e.trim())).filter(Boolean),r=new Set;s.forEach((e=>this.extractScopedDependencies(e,n).forEach((e=>r.add(e)))));const i=new Set;this._bindings.push({dependencies:r,update:()=>{try{const t={},r=this._createScopedPropsContext(n);s.forEach((e=>Object.assign(t,this.makeScopedEvaluator(e,n)(r)??{}))),i.forEach((n=>{n in t||e.hasAttribute(n)||(e.removeAttribute(n),i.delete(n))})),Object.entries(t).forEach((([t,n])=>{if(!i.has(t)&&e.hasAttribute(t))return;if(null==n||!1===n)return void(i.has(t)&&(e.removeAttribute(t),i.delete(t)));const s="object"==typeof n?JSON.stringify(n):String(n);e.getAttribute(t)!==s&&e.setAttribute(t,s),i.add(t)}))}catch(e){console.error("pp-bind-spread error:",e)}}})})),t.forEach(((t,n)=>{this.registerBinding(e,t,"text",n)}))}))}callInlineModule(e,...t){const n=this._currentProcessingHierarchy||["app"],s=this.getScopedFunction(e,n);if(!s)throw new Error(`PPHP: no inline module named "${e}" in scope ${n.join(".")}`);return s(...t)}getScopedFunction(e,t){if("string"!=typeof e)return null;for(let n=t.length;n>=0;n--){const s=t.slice(0,n).join("."),r=this._inlineModuleFns.get(s);if(r&&r.has(e))return r.get(e)}if(e.startsWith("set")){const n=e.charAt(3).toLowerCase()+e.slice(4);if(PPHP._shared.has(n)){const e=PPHP._shared.get(n);return e?.setter||null}for(let e=t.length;e>=0;e--){const s=t.slice(0,e).join("."),r=s?`${s}.${n}`:n;if(this.hasNested(this.props,r))return e=>{this.setNested(this.props,r,e),this._dirtyDeps.add(r),this.scheduleFlush()}}}return null}async processInlineModuleScripts(e=document.body){this._inlineDepth++;try{const t=Array.from(this.qsa(e,'script[type="text/php"]:not([src])')).filter((e=>!this._processedPhpScripts.has(e)));if(0===t.length)return;const n=t.map(((e,t)=>{const n=this.detectComponentHierarchy(e);(e.textContent||"").trim().substring(0,100);return{script:e,hierarchy:n,depth:n.length}})).sort(((e,t)=>e.depth-t.depth));for(const{script:e,hierarchy:t}of n){this._currentProcessingHierarchy=t;const n=t.join(".");let s=(e.textContent||"").trim();s=this.decodeEntities(s),s=this.stripComments(s),s=this.transformStateDeclarations(s),s=this.injectScopedVariables(s,t);const r=this.extractSetters(s);if(r.length){s+="\n\n";for(const e of r)s+=`pphp._registerScopedFunction('${n}', '${e}', ${e});\n`}s=s=this.stateDeclarations(s);const i=[];for(const[,e]of[...s.matchAll(/export\s+function\s+([A-Za-z_$]\w*)/g),...s.matchAll(/export\s+const\s+([A-Za-z_$]\w*)/g)])i.push(`pphp._registerScopedFunction('${n}', '${e}', ${e});`);i.length&&(s+="\n\n"+i.join("\n"));const a=new Blob([s],{type:"application/javascript"}),o=URL.createObjectURL(a);try{const e=await import(o);this._inlineModuleFns.has(n)||this._inlineModuleFns.set(n,new Map);const t=this._inlineModuleFns.get(n);for(const[n,s]of Object.entries(e))"function"!=typeof s||t.has(n)||t.set(n,s)}catch(e){console.error("❌ Inline module import failed:",e),console.error("📄 Generated source:",s)}finally{URL.revokeObjectURL(o),this._processedPhpScripts.add(e),this._currentProcessingHierarchy=null}}}finally{this._inlineDepth--,0===this._inlineDepth&&requestAnimationFrame((()=>{this._pendingEffects.forEach((e=>this._effects.add(e))),this._pendingEffects.clear()}))}}stateDeclarations(e){const t="pphp.",n=["state","share"];let s=e;for(const e of n){let n=0;for(;-1!==(n=s.indexOf(`${t}${e}(`,n));){const t=n+5+e.length+1,r=s.slice(t).match(/^(['"])([^'" ]+)\1\s*,/);if(r){const[e,s,i]=r;n=t+e.length}else{const e=s.slice(t),r=e.indexOf(",");if(-1===r)break;{const i=`'${e.slice(0,r).trim()}', `;s=s.slice(0,t)+i+s.slice(t),n=t+i.length+r}}}}return s}injectScopedVariables(e,t){const n=this.extractVariableReferences(e),s=this.extractDeclaredVariables(e),r=this.extractStateVariables(e),i=new Set([...s,...r]),a=[],o=new Set;for(const e of n)if(!o.has(e)&&!i.has(e)&&this.hasInScopedContext(e,t)){const n=this.findScopedKeyForVariable(e,t);a.push(`\nconst ${e} = (() => {\n const fn = () => {\n const ctx = globalThis.pphp._createScopedPropsContext(${JSON.stringify(t)});\n return ctx.${e};\n };\n \n fn.__isReactiveProxy = true;\n fn.__pphp_key = '${n}';\n \n Object.defineProperty(fn, 'value', {\n get() {\n const ctx = globalThis.pphp._createScopedPropsContext(${JSON.stringify(t)});\n return ctx.${e};\n },\n configurable: true\n });\n \n fn.valueOf = function() { return this.value; };\n fn.toString = function() { return String(this.value); };\n \n return fn;\n})();`),o.add(e);const s=`set${e.charAt(0).toUpperCase()}${e.slice(1)}`;this.hasInScopedContext(s,t)&&!i.has(s)&&(a.push(`\nconst ${s} = (...args) => {\n const ctx = globalThis.pphp._createScopedPropsContext(${JSON.stringify(t)});\n return ctx.${s}(...args);\n};`),o.add(s))}return a.length>0?a.join("\n")+"\n\n"+e:e}extractStateVariables(e){const t=new Set,n=/\b(?:const|let|var)\s+\[\s*([^,\]]+)(?:\s*,\s*([^,\]]+))?\s*\]\s*=\s*pphp\.state/g;let s;for(;null!==(s=n.exec(e));){const e=s[1]?.trim(),n=s[2]?.trim();e&&t.add(e),n&&t.add(n)}const r=/pphp\.state\s*\(\s*['"]([^'"]+)['"]/g;for(;null!==(s=r.exec(e));){const e=s[1];if(e){t.add(e);const n=`set${e.charAt(0).toUpperCase()}${e.slice(1)}`;t.add(n)}}return t}extractDeclaredVariables(e){const t=new Set;let n=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"").replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g,"");const s=[/\b(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,/\b(?:const|let|var)\s+\[\s*([^\]]+?)\s*\]/g,/\b(?:const|let|var)\s+\{\s*([^}]+?)\s*\}/g,/\bfunction\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,/\b(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*(?:\([^)]*\))?\s*=>/g,/\bexport\s+(?:function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)|(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*))/g];for(const e of s){let s;for(;null!==(s=e.exec(n));){const n=s[1]||s[2];if(e.source.includes("\\[")&&!e.source.includes("\\{")){const e=n.split(",").map((e=>e.trim())).filter(Boolean).map((e=>e.startsWith("...")?e.substring(3).trim():e));for(const n of e)/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(n)&&t.add(n)}else if(e.source.includes("\\{")&&!e.source.includes("\\[")){const e=n.split(",").map((e=>e.trim())).filter(Boolean).map((e=>{const t=e.indexOf(":");return-1!==t?e.substring(t+1).trim():e.startsWith("...")?e.substring(3).trim():e}));for(const n of e)/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(n)&&t.add(n)}else n&&t.add(n)}}return t}findScopedKeyForVariable(e,t){const n=t.join("."),s=this.getNested(this.props,n)||{};if(s&&e in s)return`${n}.${e}`;for(let n=t.length-1;n>=0;n--){const s=t.slice(0,n).join("."),r=s?this.getNested(this.props,s):this.props;if(r&&"object"==typeof r&&e in r)return s?`${s}.${e}`:e}return`${n}.${e}`}extractVariableReferences(e){const t=new Set;let n=e.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/.*$/gm," ").replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g," ");const s=/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g;let r;for(;null!==(r=s.exec(n));){const e=r[1],s=r.index;if(this._reservedWords.has(e))continue;const i=n.substring(Math.max(0,s-50),s),a=n.substring(s+e.length,s+e.length+10);/\b(?:const|let|var|function|class|export)\s+$/.test(i)||(s>0&&"."===n[s-1]||/^\s*:/.test(a)||this.isActualFunctionParameter(n,s,e)||this.isInDestructuringDeclaration(n,s,e)||t.add(e))}return t}isActualFunctionParameter(e,t,n){let s=-1,r=-1,i=0;for(let n=t-1;n>=0;n--){const t=e[n];if(")"===t)i++;else if("("===t){if(0===i){s=n;break}i--}}if(-1===s)return!1;i=0;for(let s=t+n.length;s<e.length;s++){const t=e[s];if("("===t)i++;else if(")"===t){if(0===i){r=s;break}i--}}if(-1===r)return!1;const a=e.substring(Math.max(0,s-20),s).trim(),o=e.substring(r+1,Math.min(e.length,r+10)).trim(),c=/\bfunction(?:\s+[a-zA-Z_$]\w*)?\s*$/.test(a),l=o.startsWith("=>");if(c||l){e.substring(s+1,r);const i=e.substring(t+n.length,r);return!i.includes("=>")&&!i.includes("{")}return!1}isInDestructuringDeclaration(e,t,n){const s=e.substring(Math.max(0,t-100),t);if(s.match(/\b(?:const|let|var)\s+\[\s*[^\]]*$/)){const s=e.substring(t+n.length,Math.min(e.length,t+n.length+100));if(/[^\]]*\]\s*=/.test(s))return!0}if(s.match(/\b(?:const|let|var)\s+\{\s*[^}]*$/)){const s=e.substring(t+n.length,Math.min(e.length,t+n.length+100));if(/[^}]*\}\s*=/.test(s))return!0}return!1}hasInScopedContext(e,t){if(this.getScopedFunction(e,t))return!0;const n=t.join("."),s=this.getNested(this.props,n)||{};if(s&&e in s)return!0;for(let n=t.length-1;n>=0;n--){const s=t.slice(0,n),r=s.join(".");if(this.getScopedFunction(e,s))return!0;const i=r?this.getNested(this.props,r):this.props;if(i&&"object"==typeof i&&e in i)return!0;const a=r?`${r}.${e}`:e;if(this._stateHierarchy.has(a))return!0}return!1}_registerScopedFunction(e,t,n){this._inlineModuleFns.has(e)||this._inlineModuleFns.set(e,new Map);this._inlineModuleFns.get(e).set(t,((...s)=>{const r=this._currentExecutionScope;this._currentExecutionScope=e;try{return t.startsWith("set")&&s.length>0?n(s[0]):n(...s)}finally{this._currentExecutionScope=r}}))}extractSetters(e){const t=[],n=/\[\s*([A-Za-z_$]\w*)\s*,\s*([A-Za-z_$]\w*)\s*\]\s*=\s*pphp\.(state|share)\(/g;let s;for(;s=n.exec(e);){const[,e,n,r]=s;"share"===r&&this.markShared(e),this._sharedStateMap.has(e)||t.push(n)}return t}markShared(e){this._sharedStateMap.add(e)}transformStateDeclarations(e){return e=(e=(e=e.replace(/(\b(?:const|let|var)\s+\[\s*)([A-Za-z_$]\w*)\s*,\s*([A-Za-z_$]\w*)\s*(\]\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,n,s,r)=>`${t}${n}, ${s}${r}'${n}', `))).replace(/(\b(?:const|let|var)\s+\[\s*)([A-Za-z_$]\w*)(\s*\]\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,n,s)=>`${t}${n}${s}'${n}', `))).replace(/(\b(?:const|let|var)\s+)([A-Za-z_$]\w*)(\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,n,s)=>`${t}[${n}] = pphp.state('${n}', `))}stripComments(e){let t="",n=0,s=!1,r="",i=!1;for(;n<e.length;){const a=e[n],o=e[n+1];if(i||"'"!==a&&'"'!==a&&"`"!==a||"\\"===e[n-1])if(s)t+=a,n++;else if(i||"/"!==a||"*"!==o)if(i)"*"===a&&"/"===o?(i=!1,n+=2):n++;else if("/"!==a||"/"!==o)t+=a,n++;else for(;n<e.length&&"\n"!==e[n];)n++;else i=!0,n+=2;else s=!s,r=s?a:"",t+=a,n++}return t}flushBindings(){const e=new Set(this._dirtyDeps);this._bindings.forEach((t=>{let n=!1;const s=this.getBindingType(t);for(const r of t.dependencies){for(const t of e)if(this.dependencyMatches(t,r,s)){n=!0;break}if(n)break}if(n)try{t.update()}catch(e){console.error("Binding update error:",e)}})),this._pendingBindings.forEach((e=>{try{e.update()}catch(e){console.error("Pending binding update error:",e)}})),this._pendingBindings.clear(),this._dirtyDeps.clear(),this._updateScheduled=!1,this._effects.forEach((t=>{if(t.__static)return;const n=t.__deps||new Set,s=t.__functionDeps||[];if(0===n.size&&0===s.length){try{t()}catch(e){console.error("effect error:",e)}return}const r=[...n].some((t=>[...e].some((e=>this.dependencyMatches(e,t,"effect"))))),i=s.length>0;if(r||i)try{t()}catch(e){console.error("effect error:",e)}}))}static ARRAY_INTRINSICS=(()=>{const e=new Set(["push","pop","shift","unshift","splice","sort","reverse","copyWithin","fill"]);return new Set(Object.getOwnPropertyNames(Array.prototype).filter((t=>!e.has(t))))})();static headMatch(e,t){return e===t||e.startsWith(t+".")}dependencyMatches(e,t,n="binding"){const s=e=>{if(e.startsWith("app.")){const t=e.slice(4),n=t.split(".")[0];if(PPHP._shared.has(n))return t}return e},r=s(e),i=s(t);if(r===i||e===t)return!0;const a=i.split(".");if(a.length>1&&PPHP.ARRAY_INTRINSICS.has(a.at(-1))&&PPHP.headMatch(r,a.slice(0,-1).join(".")))return!0;switch(n){case"effect":return this.matchEffectDependency(r,i);case"loop":return!(!PPHP.headMatch(r,i)&&!PPHP.headMatch(i,r))||!(!i.includes("*")&&!this.matchesArrayIndexPattern(r,i))&&this.matchLoopDependency(r,i);default:return!!PPHP.headMatch(r,i)||!(!i.includes("*")&&!this.matchesArrayIndexPattern(r,i))&&this.matchBindingDependency(r,i)}}matchEffectDependency(e,t){if(e.startsWith(t+".")){return!e.substring(t.length+1).includes(".")}return!!t.includes("*")&&this.matchesWildcardPattern(e,t)}matchLoopDependency(e,t){return!(!e.startsWith(t+".")&&!t.startsWith(e+"."))||(!(!this.isArrayPath(t)||!this.isArrayItemPath(e,t))||(t.includes("*")?this.matchesWildcardPattern(e,t):this.matchesArrayIndexPattern(e,t)))}isArrayPath(e){try{const t=this.getNested(this.props,e);return Array.isArray(t)}catch{return!1}}isArrayItemPath(e,t){return new RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\.\\d+($|\\.)`).test(e)}matchBindingDependency(e,t){if(e.startsWith(t+".")){return e.substring(t.length+1).split(".").length<=2}return t.includes("*")?this.matchesWildcardPattern(e,t):this.matchesArrayIndexPattern(e,t)}matchesWildcardPattern(e,t){const n=e.split("."),s=t.split(".");if(n.length!==s.length)return!1;for(let e=0;e<s.length;e++){const t=s[e],r=n[e];if("*"!==t&&t!==r)return!1}return!0}matchesArrayIndexPattern(e,t){const n=e.split("."),s=t.split(".");if(n.length!==s.length)return!1;for(let e=0;e<s.length;e++){const t=n[e],r=s[e];if(t!==r&&(!/^\d+$/.test(t)||!/^\d+$/.test(r)))return!1}return!0}scheduleFlush(){this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this._updateScheduled=!1,this.flushBindings()})))}getNested(e,t){return t.split(".").reduce(((e,t)=>e?e[t]:void 0),e)}setNested(e,t,n){const s=t.split("."),r=s.pop(),i=s.reduce(((e,t)=>e[t]??={}),e);null===n||"object"!=typeof n||Array.isArray(n)||n.__isReactiveProxy?i[r]=n:i[r]=this.makeReactive(n,s.concat(r))}hasNested(e,t){const n=t.split(".");let s=e;for(let e=0;e<n.length;e++){const t=n[e];if(null==s||"object"!=typeof s)return!1;if(!(t in s))return!1;s=s[t]}return!0}share(e,t){if("string"!=typeof e||""===e.trim())throw new Error("PPHP.share: key must be a non‑empty string.");if(this._reservedWords.has(e))throw new Error(`'${e}' is reserved – choose another share key.`);const n=PPHP._shared.get(e);if(n)return[n.getter,n.setter];const s=this._currentProcessingHierarchy;this._currentProcessingHierarchy=["app"];const[r,i]=this.state(e,t);return this._currentProcessingHierarchy=s,PPHP._shared.set(e,{getter:r,setter:i}),[r,i]}clearShare=e=>{e?PPHP._shared.delete(e):PPHP._shared.clear()};state(e,t){if("string"!=typeof e||""===e.trim())throw new Error("PPHP.state: missing or invalid key—make sure the build-time injector rewrote your declaration to pphp.state('foo', 0).");if(arguments.length<2&&(t=void 0),this._reservedWords.has(e))throw new Error(`'${e}' is reserved – choose another state key.`);if(PPHP._shared.has(e)){const{getter:t,setter:n}=PPHP._shared.get(e);return[t,n]}const n=this._currentProcessingHierarchy||["app"],s=this.generateScopedKey(n,e);this._stateHierarchy.set(s,{originalKey:e,hierarchy:[...n],level:n.length}),this.hasNested(this.props,s)||this.setNested(this.props,s,t);const r=()=>this.getNested(this.props,s),i=e=>{const t=r(),n="function"==typeof e?e(t):e;this.setNested(this.props,s,n),this._dirtyDeps.add(s),n&&"object"==typeof n&&this.markNestedPropertiesDirty(s,n),this.scheduleFlush()},a=()=>r();Object.defineProperty(a,"value",{get:()=>r(),set:e=>i(e)}),Object.defineProperties(a,{valueOf:{value:()=>r()},toString:{value:()=>String(r())},__isReactiveProxy:{value:!0,writable:!1}}),a.__pphp_key=s;const o=r();if(null===o||"object"!=typeof o)return[a,i];const c=this;return[new Proxy(a,{apply:(e,t,n)=>Reflect.apply(e,t,n),get(e,t,n){if("value"===t)return r();if("__pphp_key"===t)return s;if("__isReactiveProxy"===t)return!0;if("valueOf"===t||"toString"===t)return Reflect.get(e,t,n);if("string"==typeof t){const n=r();if(n&&"object"==typeof n){const r=Object.prototype.hasOwnProperty.call(n,t),i=t in e&&void 0!==e[t];if(r||!i){let e=n[t];return e&&"object"==typeof e&&!e.__isReactiveProxy&&(e=c.makeReactive(e,[...s.split("."),t])),e}}}if(t in e)return Reflect.get(e,t,n);const i=r();return i&&"object"==typeof i?i[t]:void 0},set(e,t,n){if("value"===t)return i(n),!0;if("__isReactiveProxy"===t)return!0;const a=r();return a&&"object"==typeof a&&(a[t]=n,c._dirtyDeps.add(`${s}.${String(t)}`),c.scheduleFlush()),!0},has(e,t){if("value"===t||"__isReactiveProxy"===t||t in a)return!0;const n=r();return n&&"object"==typeof n&&t in n}}),i]}markNestedPropertiesDirty(e,t,n=new WeakSet){t&&"object"==typeof t&&!n.has(t)&&(n.add(t),Object.keys(t).forEach((s=>{const r=`${e}.${s}`;this._dirtyDeps.add(r);const i=t[s];i&&"object"==typeof i&&!n.has(i)&&this.markNestedPropertiesDirty(r,i,n)})))}static _isBuiltIn=(()=>{const e=new Map,t=[Object.prototype,Function.prototype,Array.prototype,String.prototype,Number.prototype,Boolean.prototype,Date.prototype,RegExp.prototype,Map.prototype,Set.prototype,WeakMap.prototype,WeakSet.prototype,Error.prototype,Promise.prototype];return n=>{const s=e.get(n);if(void 0!==s)return s;const r=n in globalThis||t.some((e=>n in e));return e.set(n,r),r}})();extractDependencies(e){const t=e.trim();if(this.isPlainText(t))return new Set;let n=e.replace(/\?\./g,".");const s=new Set,r=/(?:^|[^\w$])(?:\(\s*([^)]*?)\s*\)|([A-Za-z_$][\w$]*))\s*=>/g;for(let e;e=r.exec(n);)(e[1]??e[2]??"").split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>s.add(e)));const i=/function\s*(?:[A-Za-z_$][\w$]*\s*)?\(\s*([^)]*?)\s*\)/g;for(let e;e=i.exec(n);)e[1].split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>s.add(e)));const a=e=>{let t="",n=0;for(;n<e.length;)if("`"===e[n])for(n++;n<e.length;)if("\\"===e[n])n+=2;else if("$"===e[n]&&"{"===e[n+1]){n+=2;let s=1,r=n;for(;n<e.length&&s;)"{"===e[n]?s++:"}"===e[n]&&s--,n++;t+=a(e.slice(r,n-1))+" "}else{if("`"===e[n]){n++;break}n++}else t+=e[n++];return t};n=a(n),n=n.replace(/(['"])(?:\\.|[^\\])*?\1/g,""),n=n.replace(/\/(?:\\.|[^\/\\])+\/[gimsuy]*/g,"");const o=new Set,c=/\b[A-Za-z_$]\w*(?:\.[A-Za-z_$]\w*)*\b/g;for(const t of n.match(c)??[]){const[n,...r]=t.split(".");s.has(n)||(0===r.length&&PPHP._isBuiltIn(n)&&new RegExp(`\\.${n}\\b`).test(e)||0===r.length&&new RegExp(`\\b${t}\\s*\\(`).test(e)&&n in globalThis&&"function"==typeof globalThis[n]||o.add(t))}return o}isPlainText(e){const t=e.trim();if(/^['"`]/.test(t))return!1;return![/[+\-*/%=<>!&|?:]/,/\.\w+/,/\[\s*\w+\s*\]/,/\(\s*[^)]*\s*\)/,/=>/,/\b(true|false|null|undefined|typeof|new|delete|void|in|of|instanceof)\b/,/\?\./,/\?\?/,/\.\.\./,/\{[^}]*\}/,/\[[^\]]*\]/].some((e=>e.test(t)))&&(!!t.includes(" ")&&(!/\w+\.\w+/.test(t)&&!/\w+\[\w+\]/.test(t)))}async initializeAllReferencedProps(e=document.body){const t=PPHP._mustachePattern,n=PPHP._mustacheTest,s=this.props,r=new Set;this.qsa(e,"*").forEach((e=>{const s=this.detectElementHierarchy(e);for(const{name:i,value:a}of Array.from(e.attributes))if(a){if(n.test(a))for(const e of a.matchAll(t))this.extractScopedDependencies(e[1],s).forEach((e=>r.add(e)));("pp-if"===i||"pp-elseif"===i||i.startsWith("pp-bind"))&&this.extractScopedDependencies(a,s).forEach((e=>r.add(e)))}}));const i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>n.test(e.nodeValue??"")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT});for(;;){const e=i.nextNode();if(!e)break;const n=e.parentElement;if(!n)continue;const s=this.detectElementHierarchy(n);for(const n of e.nodeValue.matchAll(t))this.extractScopedDependencies(n[1],s).forEach((e=>r.add(e)))}const a=Array.from(r).sort(((e,t)=>t.split(".").length-e.split(".").length));for(const e of a){const t=e.split(".");let n=s;for(let e=0;e<t.length;e++){const s=t[e],r=e===t.length-1,i=t.slice(0,e+1).join(".");if(!(s in n)||!r&&(null==n[s]||"object"!=typeof n[s])){const e=this._stateHierarchy.has(i);r&&e||(n[s]=r?void 0:{})}n=n[s]}}}async updateDocumentContent(e){const t=(new DOMParser).parseFromString(this.sanitizePassiveHandlers(e),"text/html");this.scrubTemplateValueAttributes(t),this.reconcileHead(t),this.resetProps(),await this.removeAllEventListenersOnNavigation(),this.ensurePageTransitionStyles();const n=async()=>{morphdom(document.body,t.body,{childrenOnly:!0}),await this.initReactiveOn(),this.attachWireFunctionEvents()};"startViewTransition"in document?await document.startViewTransition(n).finished:(await this.fadeOutBody(),await n(),await this.fadeInBody()),document.body.removeAttribute("hidden")}ensurePageTransitionStyles(){if(this._transitionStyleInjected)return;const e=document.createElement("style");e.id="pphp-page-transition-style",e.textContent="\n body.pphp-fade-out { opacity: 0; }\n body.pphp-fade-in { opacity: 1; }\n body.pphp-fade-in,\n body.pphp-fade-out { transition: opacity 0.25s ease; }\n ",document.head.appendChild(e),this._transitionStyleInjected=!0}async fadeOutBody(e=document.body){e.classList.add("pphp-fade-out");const t=e.getAnimations()[0];return t&&t.finished?t.finished.then((()=>{})):new Promise((e=>setTimeout(e,250)))}async fadeInBody(e=document.body){e.classList.remove("pphp-fade-out"),e.classList.add("pphp-fade-in");const t=e.getAnimations()[0];t&&t.finished?await t.finished:await new Promise((e=>setTimeout(e,250))),e.classList.remove("pphp-fade-in")}reconcileHead(e){const t="pp-dynamic-script",n="pp-dynamic-link";document.head.querySelectorAll("[pp-dynamic-meta]").forEach((e=>e.remove())),document.head.querySelectorAll(`[${n}]`).forEach((e=>e.remove())),document.head.querySelectorAll(`[${t}]`).forEach((e=>e.remove())),Array.from(e.head.children).forEach((e=>{switch(e.tagName){case"SCRIPT":if(e.hasAttribute(t)){const t=document.createElement("script");Array.from(e.attributes).forEach((e=>t.setAttribute(e.name,e.value))),t.textContent=e.textContent,document.head.appendChild(t)}break;case"META":{const t=e;if(t.getAttribute("charset")||"viewport"===t.name)break;const n=t.name?`meta[name="${t.name}"]`:`meta[property="${t.getAttribute("property")}"]`,s=t.cloneNode(!0),r=document.head.querySelector(n);r?document.head.replaceChild(s,r):document.head.insertBefore(s,document.head.querySelector("title")?.nextSibling||null);break}case"TITLE":{const t=e.cloneNode(!0),n=document.head.querySelector("title");n?document.head.replaceChild(t,n):document.head.appendChild(t);break}case"LINK":{const t=e;if("icon"===t.rel){const e=t.cloneNode(!0),n=document.head.querySelector('link[rel="icon"]');n?document.head.replaceChild(e,n):document.head.appendChild(e)}else t.hasAttribute(n)&&document.head.appendChild(t.cloneNode(!0));break}}}))}scrubTemplateValueAttributes(e){e.querySelectorAll('input[value*="{{"], textarea[value*="{{"], select[value*="{{"],[checked*="{{"], [selected*="{{"]').forEach((e=>{e.hasAttribute("value")&&e.removeAttribute("value"),e.hasAttribute("checked")&&e.removeAttribute("checked"),e.hasAttribute("selected")&&e.removeAttribute("selected")}))}PRESERVE_HANDLERS={DETAILS:(e,t)=>(t.open=e.open,!0),INPUT(e,t){const n=e,s=t;return n.value!==s.value&&(s.value=n.value),s.checked=n.checked,document.activeElement!==n||(null!=n.selectionStart&&(s.selectionStart=n.selectionStart,s.selectionEnd=n.selectionEnd),!1)},TEXTAREA(e,t){const n=e,s=t;return n.value!==s.value&&(s.value=n.value),document.activeElement!==n||(s.selectionStart=n.selectionStart,s.selectionEnd=n.selectionEnd,!1)},SELECT(e,t){const n=e;return t.selectedIndex=n.selectedIndex,document.activeElement!==n},VIDEO(e,t){const n=e,s=t;return s.currentTime=n.currentTime,n.paused?s.pause():s.play(),!0},AUDIO:(e,t)=>this.PRESERVE_HANDLERS.VIDEO(e,t),CANVAS:()=>!1};async populateDocumentBody(e){try{const t=document.body,n=e instanceof Document?e.body:e;this._wheelHandlersStashed||(document.querySelectorAll("[onwheel]").forEach((e=>{const t=e.getAttribute("onwheel").trim();if(e.removeAttribute("onwheel"),t){const n=new Function("event",t);e.addEventListener("wheel",n,{passive:!0})}})),this._wheelHandlersStashed=!0);const s=this.PRESERVE_HANDLERS;morphdom(t,n,{getNodeKey(e){if(e.nodeType!==Node.ELEMENT_NODE)return;const t=e;return t.hasAttribute("pp-sync-script")?`pp-sync-script:${t.getAttribute("pp-sync-script")}`:t.getAttribute("key")||void 0},onBeforeElUpdated(e,t){const n=e.tagName;if("SCRIPT"===n||e.hasAttribute("data-nomorph"))return!1;const r=s[n];return!r||r(e,t)},onBeforeNodeDiscarded:e=>(e instanceof HTMLElement&&e.dataset.timerId&&clearTimeout(Number(e.dataset.timerId)),!0)})}catch(e){console.error("Error populating document body:",e)}}async attachWireFunctionEvents(){this.handleHiddenAttribute(),this.handleAnchorTag();const e=Array.from(this._eventHandlers).map((e=>`[${e}]`)).join(","),t=this.qsa(document.body,e);for(const e of t)for(const t of this._eventHandlers){const n=e.getAttribute(t);if(!n)continue;const s=this.decodeEntities(n).trim();if(!s){e.removeAttribute(t);continue}const r=`(event) => { ${this.unwrapArrowBody(this.buildHandlerFromRawBody(s))} }`;e.removeAttribute(t);const i=t.slice(2);e instanceof HTMLInputElement&&this.handleInputAppendParams(e,i),this.handleDebounce(e,i,r)}return this.handlePassiveWheelStashes(document),Promise.resolve()}decodeEntities=e=>{const t=document.createElement("textarea");t.innerHTML=e;let n=t.value;for(;n.includes("&");){t.innerHTML=n;const e=t.value;if(e===n)break;n=e}return n};unwrapArrowBody=e=>{if(!e.trim())return"";const t=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>\s*\{([\s\S]*)\}\s*$/);if(t){let e=t[1].trim();return e&&!e.endsWith(";")&&(e+=";"),e}const n=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>\s*/);if(n){let t=e.substring(n[0].length).trim();return t&&!t.endsWith(";")&&(t+=";"),t}let s=e.trim();return s&&!s.endsWith(";")&&(s+=";"),s};buildHandlerFromRawBody(e){let t=e.trim();t=t.replace(/([A-Za-z_$][\w$]*)->([A-Za-z_$][\w$]*)\s*\(\s*([^)]*?)\s*\)/g,((e,t,n,s)=>{const r=`${t}->${n}(${s.trim()})`;return`await pphp.handleParsedCallback(this, ${JSON.stringify(r)}, event);`})),t=t.replace(/([A-Za-z_$][\w$]*)::([A-Za-z_$][\w$]*)\s*\(\s*([^)]*?)\s*\)/g,((e,t,n,s)=>{const r=`${t}::${n}(${s.trim()})`;return`await pphp.handleParsedCallback(this, ${JSON.stringify(r)}, event);`}));const{normalized:n,originalParam:s}=this.normalizeToArrow(t),r=this.renameEventParam(n,s);return this.replaceThisReferences(r)}replaceThisReferences(e){return e.replace(/\bthis\./g,"event.target.")}normalizeToArrow(e){const t=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>/);if(!t)return{normalized:`() => { ${e} }`,originalParam:null};const n=t[0].replace(/\s*=>\s*$/,"").trim().replace(/^\(|\)$/g,"").trim();return{normalized:e,originalParam:/^[A-Za-z_$]\w*$/.test(n)?n:null}}renameEventParam(e,t){if(!t||"event"===t)return e;const n=new RegExp(`\\b${this.escapeRegex(t)}\\b`,"g");return e.replace(n,((e,t,n)=>{const s=n[t-1],r=n[t+e.length];return s&&/[\w$]/.test(s)||r&&/[\w$]/.test(r)?e:"event"}))}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async handleDebounce(e,t,n){const s=e.getAttribute("pp-debounce"),r=s?this.parseTime(s):0,i=e.getAttribute("pp-before-request")??"",a=e.getAttribute("pp-after-request")??"",o=PPHP._cancelableEvents,c=async s=>{o.has(t)&&s.cancelable&&s.preventDefault();try{i&&await this.invokeHandler(e,i,s),await this.invokeHandler(e,n,s),a&&!a.startsWith("@close")&&await this.invokeHandler(e,a,s)}catch(e){console.error("Error in debounced handler:",e)}},l={passive:PPHP._passiveEvents.has(t)&&!o.has(t)},h=`${t}::${e.__pphpId||e.tagName}`,d=e=>{if(r>0){const t=PPHP._debounceTimers.get(h);t&&clearTimeout(t);const n=setTimeout((()=>{PPHP._debounceTimers.delete(h),c(e)}),r);PPHP._debounceTimers.set(h,n)}else c(e)};e instanceof HTMLFormElement&&"submit"===t?e.addEventListener("submit",(e=>{e.cancelable&&e.preventDefault(),d(e)}),l):e.addEventListener(t,d,l)}debounce(e,t=300,n=!1){let s;return function(...r){const i=this;s&&clearTimeout(s),s=setTimeout((()=>{s=null,n||e.apply(i,r)}),t),n&&!s&&e.apply(i,r)}}async invokeHandler(e,t,n){try{const s=t.trim();let r=this._handlerCache.get(s);r||(r=this.parseHandler(s),this._handlerCache.set(s,r)),await this.executeHandler(r,e,n,s)}catch(n){this.handleInvokeError(n,t,e)}finally{this.scheduleFlush()}}parseHandler(e){const t=e.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").trim();if(this.isArrowFunction(t))return this.parseArrowFunction(t);const n=t.match(/^(\w+(?:\.\w+)*)\s*\(\s*(.*?)\s*\)$/s);if(n)return{type:"call",name:n[1],args:n[2],isAsync:this.isAsyncFunction(n[1])};const s=t.match(/^(\w+)$/);return s?{type:"simple",name:s[1],isAsync:this.isAsyncFunction(s[1])}:{type:"complex",body:t,isAsync:!1}}isArrowFunction(e){let t=!1,n="",s=0;for(let r=0;r<e.length-1;r++){const i=e[r],a=e[r+1];if(t||'"'!==i&&"'"!==i&&"`"!==i){if(t&&i===n&&"\\"!==e[r-1])t=!1,n="";else if(!t&&("("===i&&s++,")"===i&&s--,"="===i&&">"===a&&s>=0))return!0}else t=!0,n=i}return!1}parseArrowFunction(e){const t=this.findArrowIndex(e);let n=e.substring(t+2).trim();return n.startsWith("{")&&n.endsWith("}")&&(n=n.slice(1,-1).trim()),{type:"arrow",body:n,isAsync:e.includes("async")||this.containsAwait(n)}}findArrowIndex(e){let t=!1,n="";for(let s=0;s<e.length-1;s++){const r=e[s],i=e[s+1];if(t||'"'!==r&&"'"!==r&&"`"!==r){if(t&&r===n&&"\\"!==e[s-1])t=!1;else if(!t&&"="===r&&">"===i)return s}else t=!0,n=r}return-1}async executeArrowHandler(e,t,n){const s=this.parseStatements(e.body);let r=!1;for(const e of s)await this.executeSingleStatement(e,t,n)&&(r=!0);r||await this.executeDynamic(e.body,t,n)}async executeComplexHandler(e,t,n){await this.executeDynamic(e.body,t,n)}parseStatements(e){const t=[];let n="",s=0,r=!1,i="";for(let a=0;a<e.length;a++){const o=e[a];r||'"'!==o&&"'"!==o&&"`"!==o?r&&o===i&&"\\"!==e[a-1]&&(r=!1,i=""):(r=!0,i=o),r||("("!==o&&"{"!==o&&"["!==o||s++,")"!==o&&"}"!==o&&"]"!==o||s--,";"!==o||0!==s)?n+=o:n.trim()&&(t.push(n.trim()),n="")}return n.trim()&&t.push(n.trim()),t}async executeInlineModule(e,t,n,s,r){if(t&&t.trim())if(this.isJsonLike(t)){const n=this.parseJson(t);null!==n&&"object"==typeof n?await this.callInlineModule(e,{...n}):await this.callInlineModule(e,n)}else try{const s=this.detectElementHierarchy(n),r=this._createScopedPropsContext(s),i=this.makeScopedEvaluator(t,s)(r);await this.callInlineModule(e,i)}catch{await this.callInlineModule(e,{element:n,event:s})}else await this.handleParsedCallback(n,r,s)}async executeSingleStatement(e,t,n){const s=e.trim();if(!s)return!1;const r=s.match(/^\(\s*\)\s*=>\s*(.+)$/);if(r)return this.executeSingleStatement(r[1],t,n);if(/^\s*(if|for|while|switch|try|return|throw|var|let|const|function|class)\b/.test(s))return await this.executeDynamic(s,t,n),!0;const i=s.match(/^(\w+)\s*\(\s*(.*?)\s*\)$/s);if(i){const[,e,r]=i,a=this.detectElementHierarchy(t),o=this.resolveFunctionName(e,a);let c=[];if(""!==r.trim())try{c=JSON5.parse(`[${r}]`)}catch{try{const e=this._createScopedPropsContext(a),t=this.getOrCreateProxy(e),s=/\bevent\b/.test(r)?r.replace(/\bevent\b/g,"_evt"):r;c=new Function("_evt","proxy","props",`with (proxy) { return [ ${s} ]; }`)(n,t,e)}catch(e){c=[]}}if(o){const e=this.getScopedFunction(o,a);if(e)return c.length>0?await e(...c):await this.executeInlineModule(o,r,t,n,s),!0}if(o){const e=globalThis[o];if("function"==typeof e)return e.apply(globalThis,c),!0}return await this.handleParsedCallback(t,s,n),!0}const a=s.match(/^(\w+)$/);if(a){const e=a[1],s=this.detectElementHierarchy(t),r=this.resolveFunctionName(e,s);if(r){if(this.getScopedFunction(r,s))return await this.handleParsedCallback(t,`${r}()`,n),!0}if(r){const e=globalThis[r];if("function"==typeof e)return e.call(globalThis,n),!0}return await this.handleParsedCallback(t,`${e}()`,n),!0}return await this.executeDynamic(s,t,n),!0}async executeCallHandler(e,t,n,s){const{name:r,args:i}=e,a=this.detectElementHierarchy(t),o=this.resolveFunctionName(r,a);if(o){if(this.getScopedFunction(o,a))return void await this.executeInlineModule(o,i||"",t,n,s);const e=globalThis[o];if("function"==typeof e)return void await this.executeGlobalFunction(e,i||"",t,n)}await this.handleParsedCallback(t,s,n)}resolveFunctionName(e,t){if(e.startsWith("set")){const t=e.charAt(3).toLowerCase()+e.slice(4);if(PPHP._shared.has(t))return e}if(t)for(let n=t.length;n>=0;n--){const s=t.slice(0,n).join("."),r=this._inlineModuleFns.get(s);if(r&&r.has(e))return e}return"function"==typeof globalThis[e]?e:null}async executeSimpleHandler(e,t,n){const{name:s}=e,r=this.detectElementHierarchy(t),i=this.resolveFunctionName(s,r);if(i){if(this.getScopedFunction(i,r))return void await this.handleParsedCallback(t,`${i}()`,n);const e=globalThis[i];if("function"==typeof e)return void e.call(globalThis,n)}await this.handleParsedCallback(t,`${s}()`,n)}async executeHandler(e,t,n,s){switch(e.type){case"arrow":await this.executeArrowHandler(e,t,n);break;case"call":await this.executeCallHandler(e,t,n,s);break;case"simple":await this.executeSimpleHandler(e,t,n);break;case"complex":await this.executeComplexHandler(e,t,n);break;default:await this.handleParsedCallback(t,s,n)}}async executeGlobalFunction(e,t,n,s){if(t.trim())if(this.isJsonLike(t)){const n=this.parseJson(t)??{};e.call(globalThis,{...n})}else{const r=this.detectElementHierarchy(n),i=this._createScopedPropsContext(r),a=this.getOrCreateProxy(i);new Function("event","proxy","props","fn",`with (proxy) { return fn(${t}); }`).call(n,s,a,i,e)}else e.call(globalThis,s)}async executeDynamic(e,t,n){const s=this.detectElementHierarchy(t),r=this._createScopedPropsContext(s),i=this.getOrCreateProxy(r),a=new PPHP.AsyncFunction("event","proxy","props",`\n with (proxy) {\n ${e}\n }`);try{await a.call(t,n,i,r)}finally{this.scheduleFlush()}}static AsyncFunction=Object.getPrototypeOf((async()=>{})).constructor;getOrCreateEvaluator(e){let t=this._evaluatorCache.get(e);return t||(t=this.makeSafeEvaluator(e),this._evaluatorCache.set(e,t)),t}getOrCreateProxy(e){let t=this._handlerProxyCache.get(e);return t||(t=this.createHandlerProxy(e),this._handlerProxyCache.set(e,t)),t}createHandlerProxy(e){const t=this._currentProcessingHierarchy||["app"],n={alert:window.alert.bind(window),confirm:window.confirm.bind(window),prompt:window.prompt.bind(window),console:window.console,setTimeout:window.setTimeout.bind(window),setInterval:window.setInterval.bind(window),clearTimeout:window.clearTimeout.bind(window),clearInterval:window.clearInterval.bind(window),fetch:window.fetch.bind(window)};return new Proxy(e,{get:(e,s,r)=>{if("string"==typeof s){if(n.hasOwnProperty(s))return n[s];const i=this.getScopedFunction(s,t);if(i)return i;if(s in e){const t=Reflect.get(e,s,r),n=globalThis[s];if(!(null==t||"object"==typeof t&&0===Object.keys(t).length||PPHP._isBuiltIn(s)&&typeof t!=typeof n))return t}if(s in globalThis&&!n.hasOwnProperty(s)){const e=globalThis[s];return"function"==typeof e&&/^[a-z]/.test(s)?e.bind(globalThis):e}}return Reflect.get(e,s,r)},set:(e,t,n,s)=>Reflect.set(e,t,n,s),has:(e,t)=>{if("string"==typeof t){const s=this._currentProcessingHierarchy||["app"];return n.hasOwnProperty(t)||!!this.getScopedFunction(t,s)||t in e||t in globalThis}return t in e||t in globalThis}})}isAsyncFunction(e){const t=this._inlineModuleFns.get(e)||globalThis[e];return t&&("AsyncFunction"===t.constructor.name||t.toString().includes("async "))}containsAwait(e){return/\bawait\s+/.test(e)}handleInvokeError(e,t,n){const s=e instanceof Error?e.message:String(e),r=n.tagName+(n.id?`#${n.id}`:"");console.error(`Handler execution failed on ${r}:\nHandler: "${t}"\nError: ${s}`,e),n.dispatchEvent(new CustomEvent("pphp:handler-error",{detail:{handler:t,error:e,element:n},bubbles:!0}))}async handleParsedCallback(e,t,n){const{funcName:s,data:r}=this.parseCallback(e,t);if(!s)return;const i=Array.isArray(s)?s:[s],a=this.detectElementHierarchy(e);let o;for(const e of i){const t=this.getScopedFunction(e,a);if(t){o=t;break}if("function"==typeof this[e]){o=this[e];break}if("function"==typeof window[e]){o=window[e];break}}if(o){const t=e.hasAttribute("pp-after-request"),s="@close"===e.getAttribute("pp-after-request");let i={args:Array.isArray(r.args)?r.args:[],element:e,data:r,event:n};if(t&&!s){const e=this._responseData?this.parseJson(this._responseData):{response:this._responseData};i={...i,...e}}await o.call(this,i)}else this._responseData=null,this._responseData=await this.handleUndefinedFunction(e,Array.isArray(s)?s[0]:s,r)}async handleUndefinedFunction(e,t,n){const s={callback:await this.encryptCallbackName(t),...n},r=this.createFetchOptions(s),i=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});try{this.saveElementOriginalState(e),this.handleSuspenseElement(e);const s=new URL(window.location.href);let a="",o="",c={success:!1};const l=e.querySelector("input[type='file']");if(l){if(a=await this.fetchFileWithData(s.href,t,l,n),o=this.extractJson(a)||"",o)try{c=this.parseJson(o)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}else{const e=await this.fetch(s.href,r);if(a=await e.text(),this.getRedirectUrl(a))return void await this.redirect(this.getRedirectUrl(a)||"");if(o=this.extractJson(a)||"",o)try{c=this.parseJson(o)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}const h=e.getAttribute("pp-before-request")||"",d=e.getAttribute("pp-after-request")||"";if((h||d&&c.success)&&this.restoreSuspenseElement(e),h||d){let e="";if(c.success){e=a.replace(o,"")}else e=a;if(this.appendAfterbegin(e),!d&&!c.success)return}if(d&&c.success){this.handleAfterRequest(d,o);const e=a.replace(o,"");return this.appendAfterbegin(e),o}if("@close"===d)return c.success?o:void 0;const p=await this.fetch(s.href,i),u=await p.text();if(this.getRedirectUrl(u))return void await this.redirect(this.getRedirectUrl(u)||"");await this.handleResponseRedirectOrUpdate(a,u,o,c)}catch(e){console.error(`Error handling undefined function "${t}". Please ensure the function is defined and accessible.`,e)}}handleAfterRequest(e,t){if(!this.isJsonLike(e))return;const n=this.parseJson(e),s=t?this.parseJson(t):null,r=n.targets;Array.isArray(r)&&r.forEach((e=>{const{id:t,...n}=e,r=document.querySelector(t);let i={};if(s){for(const t in n)if(n.hasOwnProperty(t))switch(t){case"innerHTML":case"outerHTML":case"textContent":case"innerText":"response"===n[t]&&(i[t]=e.responseKey?s[e.responseKey]:s.response);break;default:i[t]=n[t]}}else i=n;r&&this.updateElementAttributes(r,i)}))}sanitizePassiveHandlers(e){return e.replace(/\s+onwheel\s*=\s*(['"])([\s\S]*?)\1/gi,((e,t,n)=>` data-onwheel-code="${this.decodeEntities(n).replace(/"/g,""")}"`)).replace(/\s+onmousewheel\s*=\s*(['"])[\s\S]*?\1/gi,"")}handlePassiveWheelStashes(e){(e instanceof Document?e.body:e).querySelectorAll("[data-onwheel-code]").forEach((e=>{const t=this.decodeEntities(e.dataset.onwheelCode||"").trim();delete e.dataset.onwheelCode,e.onwheel=null,t&&(e.removeAllEventListeners("wheel"),this.handleDebounce(e,"wheel",t))}))}async handleResponseRedirectOrUpdate(e,t,n,s){const r=this.sanitizePassiveHandlers(t),i=this.getUpdatedHTMLContent(e,n,s),a=(new DOMParser).parseFromString(r,"text/html");i&&a.body.insertAdjacentElement("afterbegin",i),this.updateBodyContent(a.body.outerHTML)}getUpdatedHTMLContent(e,t,n){const s=document.createElement("div");if(s.id="afterbegin-8D95D",n&&t?.success){const t=e.replace(n,"");s.innerHTML=t}else s.innerHTML=e;return s.innerHTML?s:null}async updateBodyContent(e){try{this.saveElementState();const t=(new DOMParser).parseFromString(e,"text/html");this.scrubTemplateValueAttributes(t),await this.appendCallbackResponse(t),await this.populateDocumentBody(t),await this.removeAllEventListenersOnNavigation(),await this.initReactiveOn(),this.attachWireFunctionEvents(),document.body.removeAttribute("hidden")}catch(e){console.error("updateBodyContent failed:",e)}}restoreElementState(){if(this._elementState.focusId){const e=document.getElementById(this._elementState.focusId)||document.querySelector(`[name="${this._elementState.focusId}"]`);if(e instanceof HTMLInputElement){const t=e.value.length||0;void 0!==this._elementState.focusSelectionStart&&null!==this._elementState.focusSelectionEnd&&e.setSelectionRange(t,t),this._elementState.focusValue&&("checkbox"===e.type||"radio"===e.type?e.checked=!!this._elementState.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=this._elementState.focusValue)),e.focus()}else if(e instanceof HTMLTextAreaElement){const t=e.value.length||0;void 0!==this._elementState.focusSelectionStart&&null!==this._elementState.focusSelectionEnd&&e.setSelectionRange(t,t),this._elementState.focusValue&&""!==e.value&&(e.value=this._elementState.focusValue),e.focus()}else e instanceof HTMLSelectElement&&(this._elementState.focusValue&&""!==e.value&&(e.value=this._elementState.focusValue),e.focus())}this._elementState.checkedElements.forEach((e=>{const t=document.getElementById(e);t&&(t.checked=!0)}))}async 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)}}saveElementState(){const e=document.activeElement;this._elementState.focusId=e?.id||e?.name,this._elementState.focusValue=e?.value,this._elementState.focusChecked=e?.checked,this._elementState.focusType=e?.type,this._elementState.focusSelectionStart=e?.selectionStart,this._elementState.focusSelectionEnd=e?.selectionEnd,this._elementState.isSuspense=e.hasAttribute("pp-suspense"),this._elementState.checkedElements.clear(),document.querySelectorAll('input[type="checkbox"]:checked').forEach((e=>{this._elementState.checkedElements.add(e.id||e.name)})),document.querySelectorAll('input[type="radio"]:checked').forEach((e=>{this._elementState.checkedElements.add(e.id||e.name)}))}updateElementAttributes(e,t){for(const n in t)if(t.hasOwnProperty(n))switch(n){case"innerHTML":case"outerHTML":case"textContent":case"innerText":e[n]=this.decodeHTML(t[n]);break;case"insertAdjacentHTML":e.insertAdjacentHTML(t.position||"beforeend",this.decodeHTML(t[n].html));break;case"insertAdjacentText":e.insertAdjacentText(t.position||"beforeend",this.decodeHTML(t[n].text));break;case"setAttribute":e.setAttribute(t.attrName,this.decodeHTML(t[n]));break;case"removeAttribute":e.removeAttribute(t[n]);break;case"className":e.className=this.decodeHTML(t[n]);break;case"classList.add":e.classList.add(...this.decodeHTML(t[n]).split(","));break;case"classList.remove":e.classList.remove(...this.decodeHTML(t[n]).split(","));break;case"classList.toggle":e.classList.toggle(this.decodeHTML(t[n]));break;case"classList.replace":const[s,r]=this.decodeHTML(t[n]).split(",");e.classList.replace(s,r);break;case"dataset":e.dataset[t.attrName]=this.decodeHTML(t[n]);break;case"style":Object.assign(e.style,t[n]);break;case"value":e.value=this.decodeHTML(t[n]);break;case"checked":e.checked=t[n];break;default:e.setAttribute(n,this.decodeHTML(t[n]))}}decodeHTML(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}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))}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)},s=(e,t)=>{for(const s in t)if(t.hasOwnProperty(s))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(this.isJsonLike(e)){const s=this.parseJson(e);n(t,s)}else r(t,e);t.removeAttribute("pp-original-state")}}},r=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},i=(e,t)=>{e instanceof HTMLFormElement?s(e,t):n(e,t)};try{const r=this.parseJson(t);if(r)if(e instanceof HTMLFormElement){const t=e.id;if(t){const e=document.querySelector(`[form="${t}"]`);if(e){const t=e.getAttribute("pp-original-state");if(t&&this.isJsonLike(t)){const s=this.parseJson(t);n(e,s)}}}const r=new FormData(e),i={};if(r.forEach(((e,t)=>{i[t]=e})),s(e,i),e.hasAttribute("pp-suspense")){const t=e.getAttribute("pp-suspense")||"";if(this.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(r.targets){r.targets.forEach((e=>{const{id:t,...n}=e,s=document.querySelector(t);s&&i(s,n)}));const{targets:t,...s}=r;n(e,s)}else{const{empty:t,...s}=r;n(e,s)}}catch(e){console.error(`Error parsing JSON: ${e instanceof Error?e.message:"Unknown error"}. Please ensure the JSON string is valid.`,e)}}e.querySelectorAll("[pp-suspense]").forEach((e=>this.restoreSuspenseElement(e))),e.removeAttribute("pp-original-state")}extractJson(e){const t=e?.match(/\{[\s\S]*\}/);return t?t[0]:null}getRedirectUrl(e){const t=e.match(this._redirectRegex);return t?t[1]:null}async fetchFileWithData(e,t,n,s={}){const r=new FormData,i=n.files;if(i)for(let e=0;e<i.length;e++)r.append("file[]",i[e]);r.append("callback",t);for(const e in s)s.hasOwnProperty(e)&&r.append(e,s[e]);const a=await this.fetch(e,{method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:r});return await a.text()}async 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(this.isJsonLike(e)){const n=this.parseJson(e);"disabled"!==n.onsubmit&&this.updateElementAttributes(t,n),n.targets&&n.targets.forEach((e=>{const{id:t,...n}=e,s=document.querySelector(t);s&&r(s,n)}))}else s(t,e)}},s=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},r=(e,t)=>{e instanceof HTMLFormElement?n(e,t):this.updateElementAttributes(e,t)};try{if(t&&this.isJsonLike(t)){const s=this.parseJson(t);if(s)if(e instanceof HTMLFormElement){const t=new FormData(e),r={};t.forEach(((e,t)=>{r[t]=e})),s.disabled&&this.toggleFormElements(e,!0);const{disabled:i,...a}=s;this.updateElementAttributes(e,a),n(e,r)}else if(s.targets){s.targets.forEach((e=>{const{id:t,...n}=e,s=document.querySelector(t);s&&r(s,n)}));const{targets:t,...n}=s;this.updateElementAttributes(e,n)}else{if("disabled"===s.empty&&""===e.value)return;const{empty:t,...n}=s;this.updateElementAttributes(e,n)}}else if(t)s(e,t);else if(e instanceof HTMLFormElement){const t=new FormData(e),s={};t.forEach(((e,t)=>{s[t]=e})),n(e,s)}}catch(e){console.error(`Error parsing JSON: ${e instanceof Error?e.message:"Unknown error"}. Please ensure the JSON string is valid.`,e)}}toggleFormElements(e,t){Array.from(e.elements).forEach((e=>{(e instanceof HTMLInputElement||e instanceof HTMLButtonElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(e.disabled=t)}))}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 s=e.attributes[n];t[s.name]=s.value}e.setAttribute("pp-original-state",JSON.stringify(t))}if(e instanceof HTMLFormElement){let t=null;const n=e.id;n&&(t=document.querySelector(`[form="${n}"]`)),n&&t||(t=Array.from(e.elements).find((e=>e instanceof HTMLButtonElement||e instanceof HTMLInputElement))),t?t.hasAttribute("pp-original-state")||this.saveElementOriginalState(t):console.warn("Warning: No invoker detected for the form. Ensure the form has an associated invoker or an ID for proper handling.")}e.querySelectorAll("[pp-suspense]").forEach((e=>this.saveElementOriginalState(e)))}getUrlParams(){const e={};return new URLSearchParams(window.location.search).forEach(((t,n)=>{e[n]=t})),e}createFetchOptions(e){return{method:"POST",headers:{"Content-Type":"application/json",HTTP_PPHP_WIRE_REQUEST:"true"},body:JSON.stringify(e)}}parseCallback(e,t){let n={};const s=e.closest("form");if(s){new FormData(s).forEach(((e,t)=>{const s=this.clean(e);n[t]?n[t]=Array.isArray(n[t])?[...n[t],s]:[n[t],s]:n[t]=s}))}else e instanceof HTMLInputElement?n=this.handleInputElement(e):(e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(n[e.name]=e.value);const r=t.match(/^([^(]+)\(([\s\S]*)\)$/);if(r){const e=r[1].trim(),t=r[2].trim(),s=/,(?=(?:[^'"]*['"][^'"]*['"])*[^'"]*$)/;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))if(this.isJsonLike(t))try{const e=this.parseJson(t);Array.isArray(e)?n.args=e:e&&"object"==typeof e&&(n={...n,...e})}catch(e){console.error("Error parsing JSON args:",e),n.rawArgs=t}else try{const e=this.evaluateJavaScriptObject(t);Array.isArray(e)?n.args=e:e&&"object"==typeof e?n={...n,...e}:n.rawArgs=t}catch(e){console.error("Error evaluating JS object args:",e),n.rawArgs=t}else if(/^[\s\d"'[\{]/.test(t))try{const e=new Function(`return [${t}];`)();n.args=Array.isArray(e)?e:[e]}catch{s.test(t)?n.args=t.split(s).map((e=>e.trim().replace(/^['"]|['"]$/g,""))):n.args=[t.replace(/^['"]|['"]$/g,"")]}else try{const e=this.getOrCreateEvaluator(t)(this.props);n.args=[e]}catch{n.args=t.split(s).map((e=>e.trim().replace(/^['"]|['"]$/g,"")))}return{funcName:e,data:n}}return{funcName:t,data:n}}clean(e){if("string"!=typeof e)return e;let t=e.replace(/"/g,'"').trim();/^"(?:[^"\\]|\\.)*"$/.test(t)&&(t=t.slice(1,-1));try{return JSON.parse(t)}catch{}if(/^-?\d+(\.\d+)?$/.test(t)&&!/^0\d/.test(t)){const e=Number(t);if(!Number.isNaN(e))return e}return t}evaluateJavaScriptObject(e){try{const t=this.getOrCreateProxy(this.props);return new Function("proxy","Date","Math","JSON",`\n with (proxy) {\n return ${e};\n }\n `).call(null,t,Date,Math,JSON)}catch(e){throw console.error("Failed to evaluate JavaScript object:",e),e}}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}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)}}handleInputAppendParams(e,t){const n=e.getAttribute("pp-append-params"),s=e.getAttribute("pp-append-params-sync");if("true"===n){if("true"===s){const t=e.name||e.id;if(t){const n=new URL(window.location.href),s=new URLSearchParams(n.search);s.has(t)&&(e.value=s.get(t)||"")}}e.addEventListener(t,(e=>{const t=e.currentTarget,n=t.value,s=new URL(window.location.href),r=new URLSearchParams(s.search),i=t.name||t.id;if(i){n?r.set(i,n):r.delete(i);const e=r.toString()?`${s.pathname}?${r.toString()}`:s.pathname;history.replaceState(null,"",e)}}))}}handleHiddenAttribute(){const e=document.querySelectorAll("[pp-visibility]"),t=document.querySelectorAll("[pp-display]"),n=this.handleElementVisibility.bind(this),s=this.handleElementDisplay.bind(this);e.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-visibility",n))),t.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-display",s)))}handleVisibilityElementAttribute(e,t,n){const s=e.getAttribute(t);if(s)if(this.isJsonLike(s)){n(e,this.parseJson(s))}else{const n=this.parseTime(s);if(n>0){const s="pp-visibility"===t?"visibility":"display",r="visibility"===s?"hidden":"none";this.scheduleChange(e,n,s,r)}}}handleElementVisibility(e,t){this.handleElementChange(e,t,"visibility","hidden","visible")}handleElementDisplay(e,t){this.handleElementChange(e,t,"display","none","block")}handleElementChange(e,t,n,s,r){const i=t.start?this.parseTime(t.start):0,a=t.end?this.parseTime(t.end):0;i>0?(e.style[n]=s,this.scheduleChange(e,i,n,r),a>0&&this.scheduleChange(e,i+a,n,s)):a>0&&this.scheduleChange(e,a,n,s)}handleAnchorTag(){document.querySelectorAll("a").forEach((e=>{e.addEventListener("click",(async e=>{const t=e.currentTarget,n=t.getAttribute("href"),s=t.getAttribute("target");if(n&&"_blank"!==s&&!e.metaKey&&!e.ctrlKey&&(e.preventDefault(),!this._isNavigating)){this._isNavigating=!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 s="";const[r,i]=n.split("#");i&&(s=`#${i}`);new URLSearchParams(r.split("?")[1]).forEach(((e,n)=>{t.set(n,e)}));const a=`${e.pathname}?${t.toString()}${s}`;history.pushState(null,"",a)}else{const[e,t]=n.split("#"),s=`${e}${t?`#${t}`:""}`;history.pushState(null,"",s)}const s=n.indexOf("#");if(-1!==s){const e=n.slice(s+1),t=document.getElementById(e);if(t)t.scrollIntoView({behavior:"smooth"});else{await this.handleNavigation();const t=document.getElementById(e);t&&t.scrollIntoView({behavior:"smooth"})}}else await this.handleNavigation()}}catch(e){console.error("Anchor click error:",e)}finally{this._isNavigating=!1}}}))}))}handlePopState(){window.addEventListener("popstate",(async()=>{await this.handleNavigation()}))}async handleNavigation(){try{const e=document.getElementById("loading-file-1B87E");if(e){const t=this.findLoadingElement(e,window.location.pathname);t&&await this.updateContentWithTransition(t)}const t=await this.fetch(window.location.href),n=await t.text();if(!t.ok)return await this.updateDocumentContent(n),void console.error(`Navigation error: ${t.status} ${t.statusText}`);const s=n.match(this._redirectRegex);if(s&&s[1])return void await this.redirect(s[1]);await this.updateDocumentContent(n)}catch(e){console.error("Navigation error:",e)}}findLoadingElement(e,t){let n=t;for(;;){const t=e.querySelector(`div[pp-loading-url='${n}']`);if(t)return t;if("/"===n)break;const s=n.lastIndexOf("/");n=s<=0?"/":n.substring(0,s)}return e.querySelector("div[pp-loading-url='/' ]")}async updateContentWithTransition(e){const t=document.querySelector("[pp-loading-content='true']")||document.body;if(!t)return;const{fadeIn:n,fadeOut:s}=this.parseTransition(e);await this.fadeOut(t,s),t.innerHTML=e.innerHTML,this.fadeIn(t,n)}parseTransition(e){let t=250,n=250;const s=e.querySelector("[pp-loading-transition]"),r=s?.getAttribute("pp-loading-transition");if(r){const e=this.parseJson(r);e&&"object"==typeof e?(t=this.parseTime(e.fadeIn??t),n=this.parseTime(e.fadeOut??n)):console.warn("pp-loading-transition is not valid JSON → default values (250 ms) will be used. String:",r)}return{fadeIn:t,fadeOut:n}}fadeOut(e,t){return new Promise((n=>{e.style.transition=`opacity ${t}ms ease-out`,e.style.opacity="0",setTimeout((()=>{e.style.transition="",n()}),t)}))}fadeIn(e,t){e.style.transition=`opacity ${t}ms ease-in`,e.style.opacity="1",setTimeout((()=>{e.style.transition=""}),t)}getElementKey(e){return e.id||e.className||e.tagName}async redirect(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 this.handleNavigation())}catch(e){console.error("Redirect error:",e)}}abortActiveRequest(){this._activeAbortController&&this._activeAbortController.abort()}async fetch(e,t,n=!1){let s;return n?(this._activeAbortController&&this._activeAbortController.abort(),this._activeAbortController=new AbortController,s=this._activeAbortController):s=new AbortController,fetch(e,{...t,signal:s.signal,headers:{...t?.headers,"X-PPHP-Navigation":"partial","X-Requested-With":"XMLHttpRequest"}})}isJsonLike(e){if("string"!=typeof e)return!1;const t=e.trim();return!(!/^\{[\s\S]*\}$/.test(t)&&!/^\[[\s\S]*\]$/.test(t))&&!(t.includes("(")||t.includes(")")||t.includes("=>"))}parseJson(e){try{return JSON5.parse(e)}catch(e){return console.error(`Error parsing JSON: ${e.message}. Please ensure the JSON string is valid.`,e),{}}}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":default:return e;case"s":return 1e3*e;case"m":return 60*e*1e3}}return 0}scheduleChange(e,t,n,s){setTimeout((()=>{requestAnimationFrame((()=>{e.style[n]=s}))}),t)}async fetchFunction(e,t={},n=!1){try{const s={callback:await this.encryptCallbackName(e),...t},r=window.location.href;let i;if(Object.keys(s).some((e=>{const t=s[e];return t instanceof File||t instanceof FileList&&t.length>0}))){const e=new FormData;Object.keys(s).forEach((t=>{const n=s[t];n instanceof File?e.append(t,n):n instanceof FileList?Array.from(n).forEach((n=>e.append(t,n))):e.append(t,n)})),i={method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:e}}else i=this.createFetchOptions(s);const a=await this.fetch(r,i,n);if(!a.ok)throw new Error(`Fetch failed with status: ${a.status} ${a.statusText}`);const o=await a.text();try{return JSON.parse(o)}catch{return o}}catch(e){throw console.error("Error in fetchFunction:",e),new Error("Failed to fetch data.")}}async sync(...e){try{this.saveElementState();const t=e.length?e:["true"],n=e=>`[pp-sync="${e}"]`,s=await this.fetch(window.location.href,this.createFetchOptions({pphpSync71163:!0,selectors:t,secondRequestC69CD:!0,...this.getUrlParams()}));let r;if(s.headers.get("content-type")?.includes("application/json")){r=(await s.json()).fragments}else r={[t[0]]:await s.text()};const i=`<body>${Object.values(r).join("")}</body>`,a=(new DOMParser).parseFromString(i,"text/html");await this.initReactiveOn(a),t.forEach((e=>{const t=n(e),s=document.querySelectorAll(t),r=a.body.querySelector(t);r&&s.forEach((e=>e.innerHTML=r.innerHTML))})),this.restoreElementState(),this.attachWireFunctionEvents()}catch(e){console.error("pphp.sync failed:",e)}}async fetchAndUpdateBodyContent(){const e=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});this.abortActiveRequest();const t=await this.fetch(window.location.href,e,!0),n=await t.text();await this.updateBodyContent(n)}copyCode(e,t,n,s,r="img",i=2e3){if(!(e instanceof HTMLElement))return;const a=e.closest(`.${t}`)?.querySelector("pre code"),o=a?.textContent?.trim()||"";o?navigator.clipboard.writeText(o).then((()=>{const t=e.querySelector(r);if(t)for(const[e,n]of Object.entries(s))e in t?t[e]=n:t.setAttribute(e,n);setTimeout((()=>{if(t)for(const[e,s]of Object.entries(n))e in t?t[e]=s:t.setAttribute(e,s)}),i)}),(()=>{alert("Failed to copy command to clipboard")})):alert("Failed to find the code block to copy")}getCookie(e){return document.cookie.split("; ").find((t=>t.startsWith(e+"=")))?.split("=")[1]||null}}class PPHPLocalStore{state;static instance=null;listeners;pphp;STORAGE_KEY;lastSyncedState=null;constructor(e={}){this.state=e,this.listeners=[],this.pphp=PPHP.instance,this.STORAGE_KEY=this.pphp.getCookie("pphp_local_store_key")||"pphp_local_store_59e13",this.lastSyncedState=localStorage.getItem(this.STORAGE_KEY),this.loadState()}static getInstance(e={}){return PPHPLocalStore.instance||(PPHPLocalStore.instance=new PPHPLocalStore(e)),PPHPLocalStore.instance}setState(e,t=!1){const n={...this.state,...e};if(JSON.stringify(n)!==JSON.stringify(this.state)&&(this.state=n,this.listeners.forEach((e=>e(this.state))),this.saveState(),t)){const e=localStorage.getItem(this.STORAGE_KEY);e&&e!==this.lastSyncedState&&(this.pphp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]:e}),this.lastSyncedState=e)}}saveState(){localStorage.setItem(this.STORAGE_KEY,JSON.stringify(this.state))}loadState(){const e=localStorage.getItem(this.STORAGE_KEY);e&&(this.state=this.pphp.parseJson(e),this.listeners.forEach((e=>e(this.state))))}resetState(e,t=!1){if(e?(delete this.state[e],this.saveState()):(this.state={},localStorage.removeItem(this.STORAGE_KEY)),this.listeners.forEach((e=>e(this.state))),t){const t=e?localStorage.getItem(this.STORAGE_KEY):null;this.pphp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]:t}),this.lastSyncedState=t}}}class SearchParamsManager{static instance=null;listeners=[];constructor(){}static getInstance(){return SearchParamsManager.instance||(SearchParamsManager.instance=new SearchParamsManager),SearchParamsManager.instance}get params(){return new URLSearchParams(window.location.search)}get(e){return this.params.get(e)}set(e,t){const n=this.params;n.set(e,t),this.updateURL(n)}delete(e){const t=this.params;t.delete(e),this.updateURL(t)}replace(e){const t=new URLSearchParams;for(const n in e){const s=e[n];null!==s&&t.set(n,s)}this.updateURL(t,!0)}updateURL(e,t=!1){const n=`${window.location.pathname}?${e.toString()}`;t?history.replaceState(null,"",n):history.pushState(null,"",n),this.notifyListeners(e)}listen(e){this.listeners.push(e)}notifyListeners(e){for(const t of this.listeners)t(e)}enablePopStateListener(){window.addEventListener("popstate",(()=>{this.notifyListeners(this.params)}))}}var pphp=PPHP.instance,store=PPHPLocalStore.getInstance(),searchParams=SearchParamsManager.getInstance();
|