create-prisma-php-app 4.0.0-alpha.94 → 4.0.0-alpha.96
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 +1 -1
- package/dist/public/js/reactive-v1.js +3 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
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"],STARTER_KITS={basic:{id:"basic",name:"Basic PHP Application",description:"Simple PHP backend with minimal dependencies",features:{backendOnly:!0,tailwindcss:!1,websocket:!1,prisma:!1,docker:!1,swaggerDocs:!1,mcp:!1},requiredFiles:["bootstrap.php",".htaccess","src/app/layout.php","src/app/index.php"]},fullstack:{id:"fullstack",name:"Full-Stack Application",description:"Complete web application with frontend and backend",features:{backendOnly:!1,tailwindcss:!0,websocket:!1,prisma:!0,docker:!1,swaggerDocs:!0,mcp:!1},requiredFiles:["bootstrap.php",".htaccess","postcss.config.js","src/app/layout.php","src/app/index.php","public/js/main.js","src/app/globals.css"]},api:{id:"api",name:"REST API",description:"Backend API with database and documentation",features:{backendOnly:!0,tailwindcss:!1,websocket:!1,prisma:!0,docker:!0,swaggerDocs:!0,mcp:!1},requiredFiles:["bootstrap.php",".htaccess","docker-compose.yml","Dockerfile"]},realtime:{id:"realtime",name:"Real-time Application",description:"Application with WebSocket support and MCP",features:{backendOnly:!1,tailwindcss:!0,websocket:!0,prisma:!0,docker:!1,swaggerDocs:!0,mcp:!0},requiredFiles:["bootstrap.php",".htaccess","postcss.config.js","src/lib/websocket","src/lib/mcp"]},ecommerce:{id:"ecommerce",name:"E-commerce Starter",description:"Full e-commerce application with cart, payments, and admin",features:{backendOnly:!1,tailwindcss:!0,websocket:!1,prisma:!0,docker:!0,swaggerDocs:!0,mcp:!1},requiredFiles:[],source:{type:"git",url:"https://github.com/your-org/prisma-php-ecommerce-starter",branch:"main"}},blog:{id:"blog",name:"Blog CMS",description:"Blog content management system",features:{backendOnly:!1,tailwindcss:!0,websocket:!1,prisma:!0,docker:!1,swaggerDocs:!1,mcp:!1},requiredFiles:[],source:{type:"git",url:"https://github.com/your-org/prisma-php-blog-starter"}}};function bsConfigUrls(e){const s=e.indexOf("\\htdocs\\");if(-1===s)return console.error("Invalid PROJECT_ROOT_PATH. The path does not contain \\htdocs\\"),{bsTarget:"",bsPathRewrite:{}};const t=e.substring(0,s+8).replace(/\\/g,"\\\\"),c=e.replace(new RegExp(`^${t}`),"").replace(/\\/g,"/");let o=`http://localhost/${c}`;o=o.endsWith("/")?o.slice(0,-1):o;const n=o.replace(/(?<!:)(\/\/+)/g,"/"),r=c.replace(/\/\/+/g,"/");return{bsTarget:`${n}/`,bsPathRewrite:{"^/":`/${r.startsWith("/")?r.substring(1):r}/`}}}async function updatePackageJson(e,s){const t=path.join(e,"package.json");if(checkExcludeFiles(t))return;const c=JSON.parse(fs.readFileSync(t,"utf8"));c.scripts={...c.scripts,projectName:"tsx settings/project-name.ts"};let o=[];if(s.tailwindcss&&(c.scripts={...c.scripts,tailwind:"postcss src/app/globals.css -o public/css/styles.css --watch","tailwind:build":"postcss src/app/globals.css -o public/css/styles.css"},o.push("tailwind")),s.websocket&&(c.scripts={...c.scripts,websocket:"tsx settings/restart-websocket.ts"},o.push("websocket")),s.mcp&&(c.scripts={...c.scripts,mcp:"tsx settings/restart-mcp.ts"},o.push("mcp")),s.docker&&(c.scripts={...c.scripts,docker:"docker-compose up"},o.push("docker")),s.swaggerDocs){const e=s.prisma?"tsx settings/auto-swagger-docs.ts":"tsx settings/swagger-config.ts";c.scripts={...c.scripts,"create-swagger-docs":e}}let n={...c.scripts};n.browserSync="tsx settings/bs-config.ts",n["browserSync:build"]="tsx settings/build.ts",n.dev=`npm-run-all projectName -p browserSync ${o.join(" ")}`,n.build=`npm-run-all${s.tailwindcss?" tailwind:build":""} browserSync:build`,c.scripts=n,c.type="module",fs.writeFileSync(t,JSON.stringify(c,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,"public","js","main.js");if(checkExcludeFiles(t))return;let c=fs.readFileSync(t,"utf8");c+='\nwindow.ws = new WebSocket("ws://localhost:8080");\n',fs.writeFileSync(t,c,"utf8")}function generateAuthSecret(){return randomBytes(33).toString("base64")}function generateHexEncodedKey(e=16){return randomBytes(e).toString("hex")}function copyRecursiveSync(e,s,t){const c=fs.existsSync(e),o=c&&fs.statSync(e);if(c&&o&&o.isDirectory()){const c=s.toLowerCase();if(!t.websocket&&c.includes("src\\lib\\websocket"))return;if(!t.mcp&&c.includes("src\\lib\\mcp"))return;if(t.backendOnly&&c.includes("public\\js")||t.backendOnly&&c.includes("public\\css")||t.backendOnly&&c.includes("public\\assets"))return;if(!t.swaggerDocs&&c.includes("src\\app\\swagger-docs"))return;const o=s.replace(/\\/g,"/");if(updateAnswer?.excludeFilePath?.includes(o))return;fs.existsSync(s)||fs.mkdirSync(s,{recursive:!0}),fs.readdirSync(e).forEach((c=>{copyRecursiveSync(path.join(e,c),path.join(s,c),t)}))}else{if(checkExcludeFiles(s))return;if(!t.tailwindcss&&(s.includes("globals.css")||s.includes("styles.css")))return;if(!t.websocket&&s.includes("restart-websocket.ts"))return;if(!t.mcp&&s.includes("restart-mcp.ts"))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:c})=>{copyRecursiveSync(path.join(__dirname,s),path.join(e,c),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"),c="";s.backendOnly||(s.tailwindcss||(c='\n <link href="/css/index.css" rel="stylesheet" />'),c+='\n <script type="module" src="/js/main.js"><\/script>');let o="";s.backendOnly||(o=s.tailwindcss?` <link href="/css/styles.css" rel="stylesheet" /> ${c}`:c),e=e.replace("</head>",`${o}\n</head>`),fs.writeFileSync(t,e,{flag:"w"})}catch(e){console.error(chalk.red("Error modifying layout.php:"),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 c=[{src:"/settings",dest:"/settings"},{src:"/src",dest:"/src"},{src:"/public",dest:"/public"}];s.docker&&c.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 c=path.join(__dirname,s),o=path.join(e,t);if(checkExcludeFiles(o))return;const n=fs.readFileSync(c,"utf8");fs.writeFileSync(o,n,{flag:"w"})})),await executeCopy(e,c,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 o=generateAuthSecret(),n=generateHexEncodedKey(),r=`# Authentication secret key for JWT or session encryption.\nAUTH_SECRET="${o}"\n# Name of the authentication cookie.\nAUTH_COOKIE_NAME="${generateHexEncodedKey(8)}"\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="${n}"\n\n# Secret key for encrypting function calls.\nFUNCTION_CALL_SECRET="${generateHexEncodedKey(32)}"\n\n# Single or multiple origins (CSV or JSON array)\nCORS_ALLOWED_ORIGINS=[]\n\n# If you need cookies/Authorization across origins, keep this true\nCORS_ALLOW_CREDENTIALS="true"\n\n# Optional tuning\nCORS_ALLOWED_METHODS="GET,POST,PUT,PATCH,DELETE,OPTIONS"\nCORS_ALLOWED_HEADERS="Content-Type,Authorization,X-Requested-With"\nCORS_EXPOSE_HEADERS=""\nCORS_MAX_AGE="86400"`;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${r}`;await createOrUpdateEnvFile(e,s)}else await createOrUpdateEnvFile(e,r)}async function getAnswer(e={}){if(e.starterKit){const s=e.starterKit;let t=null;if(STARTER_KITS[s]&&(t=STARTER_KITS[s]),t){const c={projectName:e.projectName??"my-app",starterKit:s,starterKitSource:e.starterKitSource,backendOnly:t.features.backendOnly??!1,tailwindcss:t.features.tailwindcss??!1,websocket:t.features.websocket??!1,prisma:t.features.prisma??!1,docker:t.features.docker??!1,swaggerDocs:t.features.swaggerDocs??!1,mcp:t.features.mcp??!1},o=process.argv.slice(2);return o.includes("--backend-only")&&(c.backendOnly=!0),o.includes("--swagger-docs")&&(c.swaggerDocs=!0),o.includes("--tailwindcss")&&(c.tailwindcss=!0),o.includes("--websocket")&&(c.websocket=!0),o.includes("--mcp")&&(c.mcp=!0),o.includes("--prisma")&&(c.prisma=!0),o.includes("--docker")&&(c.docker=!0),c}if(e.starterKitSource){const t={projectName:e.projectName??"my-app",starterKit:s,starterKitSource:e.starterKitSource,backendOnly:!1,tailwindcss:!0,websocket:!1,prisma:!0,docker:!1,swaggerDocs:!0,mcp:!1},c=process.argv.slice(2);return c.includes("--backend-only")&&(t.backendOnly=!0),c.includes("--swagger-docs")&&(t.swaggerDocs=!0),c.includes("--tailwindcss")&&(t.tailwindcss=!0),c.includes("--websocket")&&(t.websocket=!0),c.includes("--mcp")&&(t.mcp=!0),c.includes("--prisma")&&(t.prisma=!0),c.includes("--docker")&&(t.docker=!0),t}}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=()=>{console.warn(chalk.red("Operation cancelled by the user.")),process.exit(0)},c=await prompts(s,{onCancel:t}),o=[];c.backendOnly??e.backendOnly??!1?(e.swaggerDocs||o.push({type:"toggle",name:"swaggerDocs",message:`Would you like to use ${chalk.blue("Swagger Docs")}?`,initial:!1,active:"Yes",inactive:"No"}),e.websocket||o.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!1,active:"Yes",inactive:"No"}),e.mcp||o.push({type:"toggle",name:"mcp",message:`Would you like to use ${chalk.blue("MCP (Model Context Protocol)")}?`,initial:!1,active:"Yes",inactive:"No"}),e.prisma||o.push({type:"toggle",name:"prisma",message:`Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,initial:!1,active:"Yes",inactive:"No"}),e.docker||o.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"})):(e.swaggerDocs||o.push({type:"toggle",name:"swaggerDocs",message:`Would you like to use ${chalk.blue("Swagger Docs")}?`,initial:!1,active:"Yes",inactive:"No"}),e.tailwindcss||o.push({type:"toggle",name:"tailwindcss",message:`Would you like to use ${chalk.blue("Tailwind CSS")}?`,initial:!1,active:"Yes",inactive:"No"}),e.websocket||o.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!1,active:"Yes",inactive:"No"}),e.mcp||o.push({type:"toggle",name:"mcp",message:`Would you like to use ${chalk.blue("MCP (Model Context Protocol)")}?`,initial:!1,active:"Yes",inactive:"No"}),e.prisma||o.push({type:"toggle",name:"prisma",message:`Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,initial:!1,active:"Yes",inactive:"No"}),e.docker||o.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"}));const n=await prompts(o,{onCancel:t});return{projectName:c.projectName?String(c.projectName).trim().replace(/ /g,"-"):e.projectName??"my-app",backendOnly:c.backendOnly??e.backendOnly??!1,swaggerDocs:n.swaggerDocs??e.swaggerDocs??!1,tailwindcss:n.tailwindcss??e.tailwindcss??!1,websocket:n.websocket??e.websocket??!1,mcp:n.mcp??e.mcp??!1,prisma:n.prisma??e.prisma??!1,docker:n.docker??e.docker??!1}}async function uninstallNpmDependencies(e,s,t=!1){console.log("Uninstalling Node dependencies:"),s.forEach((e=>console.log(`- ${chalk.blue(e)}`)));const c=`npm uninstall ${t?"--save-dev":"--save"} ${s.join(" ")}`;execSync(c,{stdio:"inherit",cwd:e})}async function uninstallComposerDependencies(e,s){console.log("Uninstalling Composer dependencies:"),s.forEach((e=>console.log(`- ${chalk.blue(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 c="";e.on("data",(e=>c+=e)),e.on("end",(()=>{try{const e=JSON.parse(c);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),c=s.split(".").map(Number);for(let e=0;e<t.length;e++){if(t[e]>c[e])return 1;if(t[e]<c[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]:(console.error(`Package ${e} is not installed`),null)}catch(e){return console.error(e instanceof Error?e.message:String(e)),null}}async function installNpmDependencies(e,s,t=!1){fs.existsSync(path.join(e,"package.json"))?console.log("Updating existing Node.js project..."):console.log("Initializing new Node.js project..."),fs.existsSync(path.join(e,"package.json"))||execSync("npm init -y",{stdio:"inherit",cwd:e}),console.log((t?"Installing development dependencies":"Installing dependencies")+":"),s.forEach((e=>console.log(`- ${chalk.blue(e)}`)));const c=`npm install ${t?"--save-dev":""} ${s.join(" ")}`;execSync(c,{stdio:"inherit",cwd:e})}function getComposerCmd(){try{return execSync("composer --version",{stdio:"ignore"}),console.log("✓ Using global composer command"),{cmd:"composer",baseArgs:[]}}catch{const e="C:\\xampp\\php\\php.exe",s="C:\\ProgramData\\ComposerSetup\\bin\\composer.phar";if(!fs.existsSync(e))throw console.error(`✗ PHP not found at ${e}`),new Error(`PHP executable not found at ${e}`);if(!fs.existsSync(s))throw console.error(`✗ Composer not found at ${s}`),new Error(`Composer phar not found at ${s}`);return console.log("✓ Using XAMPP PHP with Composer phar"),{cmd:e,baseArgs:[s]}}}export async function installComposerDependencies(e,s){const{cmd:t,baseArgs:c}=getComposerCmd(),o=path.join(e,"composer.json"),n=fs.existsSync(o);if(console.log(chalk.green("Composer project initialization: "+(n?"Updating existing project…":"Setting up new project…"))),fs.existsSync(e)||(console.log(`Creating base directory: ${e}`),fs.mkdirSync(e,{recursive:!0})),!n){const s=[...c,"init","--no-interaction","--name","tsnc/prisma-php-app","--require","php:^8.2","--type","project","--version","1.0.0"];console.log("Attempting composer init...");const n=spawnSync(t,s,{cwd:e,stdio:["ignore","pipe","pipe"],encoding:"utf8"}),r=fs.existsSync(o);if(0===n.status&&r)console.log("✓ Composer init successful and composer.json created");else{0!==n.status?(console.log(`Composer init failed with status ${n.status}`),n.stderr&&console.log(`Stderr: ${n.stderr}`)):console.log("Composer init reported success but didn't create composer.json"),console.log("Creating composer.json manually...");const s={name:"tsnc/prisma-php-app",type:"project",version:"1.0.0",require:{php:"^8.2"},autoload:{"psr-4":{"":"src/"}}};try{const t=path.resolve(e,"composer.json");if(console.log(`Writing composer.json to: ${t}`),fs.writeFileSync(t,JSON.stringify(s,null,2),{encoding:"utf8"}),!fs.existsSync(t))throw new Error("File creation appeared to succeed but file doesn't exist");console.log("✓ Successfully created composer.json")}catch(s){if(console.error("✗ Failed to create composer.json:",s),console.error(`Base directory: ${e}`),console.error(`Absolute base directory: ${path.resolve(e)}`),console.error(`Target file path: ${o}`),console.error(`Absolute target file path: ${path.resolve(o)}`),console.error(`Current working directory: ${process.cwd()}`),console.error(`Base directory exists: ${fs.existsSync(e)}`),fs.existsSync(e))try{const s=fs.statSync(e);console.error(`Base directory is writable: ${s.isDirectory()}`)}catch(e){console.error(`Cannot stat base directory: ${e}`)}throw new Error(`Cannot create composer.json: ${s}`)}}}const r=path.resolve(e,"composer.json");if(!fs.existsSync(r))throw console.error(`✗ composer.json still not found at ${r}`),console.error("Directory contents:",fs.readdirSync(e)),new Error("Failed to create composer.json - file does not exist after all attempts");let i;try{const e=fs.readFileSync(r,"utf8");console.log("✓ Successfully read composer.json"),i=JSON.parse(e)}catch(e){throw console.error("✗ Failed to read/parse composer.json:",e),new Error(`Cannot read composer.json: ${e}`)}i.autoload??={},i.autoload["psr-4"]??={},i.autoload["psr-4"][""]??="src/";try{fs.writeFileSync(r,JSON.stringify(i,null,2)),console.log("✓ Updated composer.json with PSR-4 autoload")}catch(e){throw console.error("✗ Failed to update composer.json:",e),e}if(s.length){console.log("Installing Composer dependencies:"),s.forEach((e=>console.log(`- ${chalk.blue(e)}`)));try{const o=`${t} ${[...c,"require","--no-interaction",...s].join(" ")}`;execSync(o,{stdio:"inherit",cwd:e,env:{...process.env}}),console.log("✓ Composer dependencies installed")}catch(e){throw console.error("✗ Failed to install composer dependencies:",e),e}}if(n)try{execSync(`${t} ${[...c,"update","--lock","--no-install","--no-interaction"].join(" ")}`,{stdio:"inherit",cwd:e}),console.log("✓ Composer lock updated")}catch(e){throw console.error("✗ Failed to update composer lock:",e),e}try{execSync(`${t} ${[...c,"dump-autoload","--quiet"].join(" ")}`,{stdio:"inherit",cwd:e}),console.log("✓ Composer autoloader regenerated")}catch(e){throw console.error("✗ Failed to regenerate autoloader:",e),e}}const npmPinnedVersions={"@tailwindcss/postcss":"^4.1.13","@types/browser-sync":"^2.29.0","@types/node":"^24.5.2","@types/prompts":"^2.4.9","browser-sync":"^3.0.4",chalk:"^5.6.2","chokidar-cli":"^3.0.0",cssnano:"^7.1.1","http-proxy-middleware":"^3.0.5","npm-run-all":"^4.1.5","php-parser":"^3.2.5",postcss:"^8.5.6","postcss-cli":"^11.0.1",prompts:"^2.4.2",tailwindcss:"^4.1.13",tsx:"^4.20.5",typescript:"^5.9.2"};function npmPkg(e){return npmPinnedVersions[e]?`${e}@${npmPinnedVersions[e]}`:e}const composerPinnedVersions={"vlucas/phpdotenv":"^5.6.2","firebase/php-jwt":"^6.11.1","phpmailer/phpmailer":"^6.10.0","guzzlehttp/guzzle":"^7.10.0","symfony/uid":"^7.2.0","brick/math":"^0.14.0","cboden/ratchet":"^0.4.4","tsnc/prisma-php":"^1.0.0","php-mcp/server":"3.3.0"};function composerPkg(e){return composerPinnedVersions[e]?`${e}:${composerPinnedVersions[e]}`:e}async function setupStarterKit(e,s){if(!s.starterKit)return;let t=null;if(STARTER_KITS[s.starterKit]?t=STARTER_KITS[s.starterKit]:s.starterKitSource&&(t={id:s.starterKit,name:`Custom Starter Kit (${s.starterKit})`,description:"Custom starter kit from external source",features:{},requiredFiles:[],source:{type:"git",url:s.starterKitSource}}),t){if(console.log(chalk.green(`Setting up ${t.name}...`)),t.source)try{const c=t.source.branch?`git clone -b ${t.source.branch} --depth 1 ${t.source.url} ${e}`:`git clone --depth 1 ${t.source.url} ${e}`;execSync(c,{stdio:"inherit"});const o=path.join(e,".git");fs.existsSync(o)&&fs.rmSync(o,{recursive:!0,force:!0}),console.log(chalk.blue("Starter kit cloned successfully!"));const n=path.join(e,"prisma-php.json");if(fs.existsSync(n))try{const t=JSON.parse(fs.readFileSync(n,"utf8")),c=e.replace(/\\/g,"\\"),o=bsConfigUrls(c);t.projectName=s.projectName,t.projectRootPath=c,t.bsTarget=o.bsTarget,t.bsPathRewrite=o.bsPathRewrite;const r=await fetchPackageVersion("create-prisma-php-app");t.version=r,fs.writeFileSync(n,JSON.stringify(t,null,2)),console.log(chalk.green("Updated prisma-php.json with new project details"))}catch(e){console.warn(chalk.yellow("Failed to update prisma-php.json, will create new one"))}}catch(e){throw console.error(chalk.red(`Failed to setup starter kit: ${e}`)),e}t.customSetup&&await t.customSetup(e,s),console.log(chalk.green(`✓ ${t.name} setup complete!`))}else console.warn(chalk.yellow(`Starter kit '${s.starterKit}' not found. Skipping...`))}function showStarterKits(){console.log(chalk.blue("\n🚀 Available Starter Kits:\n")),Object.values(STARTER_KITS).forEach((e=>{const s=e.source?" (Custom)":" (Built-in)";console.log(chalk.green(` ${e.id}${chalk.gray(s)}`)),console.log(` ${e.name}`),console.log(chalk.gray(` ${e.description}`)),e.source&&console.log(chalk.cyan(` Source: ${e.source.url}`));const t=Object.entries(e.features).filter((([,e])=>!0===e)).map((([e])=>e)).join(", ");t&&console.log(chalk.magenta(` Features: ${t}`)),console.log()})),console.log(chalk.yellow("Usage:")),console.log(" npx create-prisma-php-app my-project --starter-kit=basic"),console.log(" npx create-prisma-php-app my-project --starter-kit=custom --starter-kit-source=https://github.com/user/repo"),console.log()}async function main(){try{const e=process.argv.slice(2);let s=e[0];const t=e.find((e=>e.startsWith("--starter-kit="))),c=t?.split("=")[1],o=e.find((e=>e.startsWith("--starter-kit-source="))),n=o?.split("=")[1];if(e.includes("--list-starter-kits"))return void showStarterKits();let r=null,i=!1;if(s){const t=process.cwd(),o=path.join(t,"prisma-php.json");if(c&&n){i=!0;const t={projectName:s,starterKit:c,starterKitSource:n,backendOnly:e.includes("--backend-only"),swaggerDocs:e.includes("--swagger-docs"),tailwindcss:e.includes("--tailwindcss"),websocket:e.includes("--websocket"),mcp:e.includes("--mcp"),prisma:e.includes("--prisma"),docker:e.includes("--docker")};r=await getAnswer(t)}else if(fs.existsSync(o)){const c=readJsonFile(o);let n=[];c.excludeFiles?.map((e=>{const s=path.join(t,e);fs.existsSync(s)&&n.push(s.replace(/\\/g,"/"))})),updateAnswer={projectName:s,backendOnly:c.backendOnly,swaggerDocs:c.swaggerDocs,tailwindcss:c.tailwindcss,websocket:c.websocket,mcp:c.mcp,prisma:c.prisma,docker:c.docker,isUpdate:!0,componentScanDirs:c.componentScanDirs??[],excludeFiles:c.excludeFiles??[],excludeFilePath:n??[],filePath:t};const i={projectName:s,backendOnly:e.includes("--backend-only")||c.backendOnly,swaggerDocs:e.includes("--swagger-docs")||c.swaggerDocs,tailwindcss:e.includes("--tailwindcss")||c.tailwindcss,websocket:e.includes("--websocket")||c.websocket,prisma:e.includes("--prisma")||c.prisma,docker:e.includes("--docker")||c.docker,mcp:e.includes("--mcp")||c.mcp};r=await getAnswer(i),null!==r&&(updateAnswer={projectName:s,backendOnly:r.backendOnly,swaggerDocs:r.swaggerDocs,tailwindcss:r.tailwindcss,websocket:r.websocket,mcp:r.mcp,prisma:r.prisma,docker:r.docker,isUpdate:!0,componentScanDirs:c.componentScanDirs??[],excludeFiles:c.excludeFiles??[],excludeFilePath:n??[],filePath:t})}else{const t={projectName:s,starterKit:c,starterKitSource:n,backendOnly:e.includes("--backend-only"),swaggerDocs:e.includes("--swagger-docs"),tailwindcss:e.includes("--tailwindcss"),websocket:e.includes("--websocket"),mcp:e.includes("--mcp"),prisma:e.includes("--prisma"),docker:e.includes("--docker")};r=await getAnswer(t)}if(null===r)return void console.log(chalk.red("Installation cancelled."))}else r=await getAnswer();if(null===r)return void console.warn(chalk.red("Installation cancelled."));const a=await fetchPackageVersion("create-prisma-php-app"),p=getInstalledPackageVersion("create-prisma-php-app");p?-1===compareVersions(p,a)&&(execSync("npm uninstall -g create-prisma-php-app",{stdio:"inherit"}),execSync("npm install -g create-prisma-php-app",{stdio:"inherit"})):execSync("npm install -g create-prisma-php-app",{stdio:"inherit"});const l=process.cwd();let d;if(s)if(i){const t=path.join(l,s);fs.existsSync(t)||fs.mkdirSync(t,{recursive:!0}),d=t,await setupStarterKit(d,r),process.chdir(d);const c=path.join(d,"prisma-php.json");if(fs.existsSync(c)){const s=JSON.parse(fs.readFileSync(c,"utf8"));e.includes("--backend-only")&&(s.backendOnly=!0),e.includes("--swagger-docs")&&(s.swaggerDocs=!0),e.includes("--tailwindcss")&&(s.tailwindcss=!0),e.includes("--websocket")&&(s.websocket=!0),e.includes("--mcp")&&(s.mcp=!0),e.includes("--prisma")&&(s.prisma=!0),e.includes("--docker")&&(s.docker=!0),r={...r,backendOnly:s.backendOnly,swaggerDocs:s.swaggerDocs,tailwindcss:s.tailwindcss,websocket:s.websocket,mcp:s.mcp,prisma:s.prisma,docker:s.docker};let t=[];s.excludeFiles?.map((e=>{const s=path.join(d,e);fs.existsSync(s)&&t.push(s.replace(/\\/g,"/"))})),updateAnswer={...r,isUpdate:!0,componentScanDirs:s.componentScanDirs??[],excludeFiles:s.excludeFiles??[],excludeFilePath:t??[],filePath:d}}}else{const e=path.join(l,"prisma-php.json"),t=path.join(l,s),c=path.join(t,"prisma-php.json");fs.existsSync(e)?d=l:fs.existsSync(t)&&fs.existsSync(c)?(d=t,process.chdir(t)):(fs.existsSync(t)||fs.mkdirSync(t,{recursive:!0}),d=t,process.chdir(t))}else fs.mkdirSync(r.projectName,{recursive:!0}),d=path.join(l,r.projectName),process.chdir(r.projectName);let u=[npmPkg("typescript"),npmPkg("@types/node"),npmPkg("tsx"),npmPkg("http-proxy-middleware"),npmPkg("chalk"),npmPkg("npm-run-all"),npmPkg("browser-sync"),npmPkg("@types/browser-sync"),npmPkg("php-parser")],m=[composerPkg("vlucas/phpdotenv"),composerPkg("firebase/php-jwt"),composerPkg("phpmailer/phpmailer"),composerPkg("guzzlehttp/guzzle"),composerPkg("ezyang/htmlpurifier"),composerPkg("symfony/uid"),composerPkg("brick/math"),composerPkg("tsnc/prisma-php")];if(r.swaggerDocs&&u.push(npmPkg("swagger-jsdoc"),npmPkg("@types/swagger-jsdoc")),r.swaggerDocs&&r.prisma&&u.push(npmPkg("prompts"),npmPkg("@types/prompts")),r.tailwindcss&&u.push(npmPkg("tailwindcss"),npmPkg("postcss"),npmPkg("postcss-cli"),npmPkg("@tailwindcss/postcss"),npmPkg("cssnano")),r.websocket&&m.push("cboden/ratchet"),r.mcp&&m.push("php-mcp/server"),r.prisma&&execSync("npm install -g prisma-client-php",{stdio:"inherit"}),r.starterKit&&!i&&await setupStarterKit(d,r),await installNpmDependencies(d,u,!0),await installComposerDependencies(d,m),s||execSync("npx tsc --init",{stdio:"inherit"}),await createDirectoryStructure(d,r),r.prisma&&execSync("npx ppo init --prisma-php",{stdio:"inherit"}),r.swaggerDocs){const e=path.join(d,"src","app","swagger-docs");fs.existsSync(e)&&fs.readdirSync(e).length>0&&(console.log("Removing existing swagger-docs directory..."),fs.rmSync(e,{recursive:!0,force:!0})),execSync(`git clone https://github.com/TheSteelNinjaCode/prisma-php-swagger-docs.git ${e}`,{stdio:"inherit"}),fs.rmSync(path.join(e,".git"),{recursive:!0,force:!0})}if(updateAnswer?.isUpdate){const e=[],s=[],t=e=>{try{const s=path.join(d,"composer.json");if(fs.existsSync(s)){const t=JSON.parse(fs.readFileSync(s,"utf8"));return!(!t.require||!t.require[e])}return!1}catch{return!1}},c=e=>{try{const s=path.join(d,"package.json");if(fs.existsSync(s)){const t=JSON.parse(fs.readFileSync(s,"utf8"));return!!(t.dependencies&&t.dependencies[e]||t.devDependencies&&t.devDependencies[e])}return!1}catch{return!1}};if(updateAnswer.backendOnly){nonBackendFiles.forEach((e=>{const s=path.join(d,"src","app",e);fs.existsSync(s)&&(fs.unlinkSync(s),console.log(`${e} was deleted successfully.`))}));["js","css"].forEach((e=>{const s=path.join(d,"src","app",e);fs.existsSync(s)&&(fs.rmSync(s,{recursive:!0,force:!0}),console.log(`${e} was deleted successfully.`))}))}if(!updateAnswer.swaggerDocs){const s=path.join(d,"src","app","swagger-docs");fs.existsSync(s)&&(fs.rmSync(s,{recursive:!0,force:!0}),console.log("swagger-docs was deleted successfully."));["swagger-config.ts"].forEach((e=>{const s=path.join(d,"settings",e);fs.existsSync(s)&&(fs.unlinkSync(s),console.log(`${e} was deleted successfully.`))})),c("swagger-jsdoc")&&e.push("swagger-jsdoc"),c("@types/swagger-jsdoc")&&e.push("@types/swagger-jsdoc"),c("prompts")&&e.push("prompts"),c("@types/prompts")&&e.push("@types/prompts")}if(!updateAnswer.tailwindcss){["postcss.config.js"].forEach((e=>{const s=path.join(d,e);fs.existsSync(s)&&(fs.unlinkSync(s),console.log(`${e} was deleted successfully.`))}));["tailwindcss","postcss","postcss-cli","@tailwindcss/postcss","cssnano"].forEach((s=>{c(s)&&e.push(s)}))}if(!updateAnswer.websocket){["restart-websocket.ts"].forEach((e=>{const s=path.join(d,"settings",e);fs.existsSync(s)&&(fs.unlinkSync(s),console.log(`${e} was deleted successfully.`))}));const e=path.join(d,"src","Lib","Websocket");fs.existsSync(e)&&(fs.rmSync(e,{recursive:!0,force:!0}),console.log("Websocket folder was deleted successfully.")),t("cboden/ratchet")&&s.push("cboden/ratchet")}if(!updateAnswer.mcp){["restart-mcp.ts"].forEach((e=>{const s=path.join(d,"settings",e);fs.existsSync(s)&&(fs.unlinkSync(s),console.log(`${e} was deleted successfully.`))}));const e=path.join(d,"src","Lib","MCP");fs.existsSync(e)&&(fs.rmSync(e,{recursive:!0,force:!0}),console.log("MCP folder was deleted successfully.")),t("php-mcp/server")&&s.push("php-mcp/server")}if(!updateAnswer.prisma){["prisma","@prisma/client","@prisma/internals"].forEach((s=>{c(s)&&e.push(s)}))}if(!updateAnswer.docker){[".dockerignore","docker-compose.yml","Dockerfile","apache.conf"].forEach((e=>{const s=path.join(d,e);fs.existsSync(s)&&(fs.unlinkSync(s),console.log(`${e} was deleted successfully.`))}))}const o=e=>Array.from(new Set(e)),n=o(e),r=o(s);n.length>0&&(console.log(`Uninstalling npm packages: ${n.join(", ")}`),await uninstallNpmDependencies(d,n,!0)),r.length>0&&(console.log(`Uninstalling composer packages: ${r.join(", ")}`),await uninstallComposerDependencies(d,r))}if(!i||!fs.existsSync(path.join(d,"prisma-php.json"))){const e=d.replace(/\\/g,"\\"),s=bsConfigUrls(e),t={projectName:r.projectName,projectRootPath:e,phpEnvironment:"XAMPP",phpRootPathExe:"C:\\xampp\\php\\php.exe",bsTarget:s.bsTarget,bsPathRewrite:s.bsPathRewrite,backendOnly:r.backendOnly,swaggerDocs:r.swaggerDocs,tailwindcss:r.tailwindcss,websocket:r.websocket,mcp:r.mcp,prisma:r.prisma,docker:r.docker,version:a,componentScanDirs:updateAnswer?.componentScanDirs??["src","vendor/tsnc/prisma-php/src"],excludeFiles:updateAnswer?.excludeFiles??[]};fs.writeFileSync(path.join(d,"prisma-php.json"),JSON.stringify(t,null,2),{flag:"w"})}execSync(updateAnswer?.isUpdate?"C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar update":"C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar install",{stdio:"inherit"}),console.log("\n=========================\n"),console.log(`${chalk.green("Success!")} Prisma PHP project successfully created in ${chalk.green(d.replace(/\\/g,"/"))}!`),console.log("\n=========================")}catch(e){console.error("Error while creating the project:",e),process.exit(1)}}main();
|
|
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"],STARTER_KITS={basic:{id:"basic",name:"Basic PHP Application",description:"Simple PHP backend with minimal dependencies",features:{backendOnly:!0,tailwindcss:!1,websocket:!1,prisma:!1,docker:!1,swaggerDocs:!1,mcp:!1},requiredFiles:["bootstrap.php",".htaccess","src/app/layout.php","src/app/index.php"]},fullstack:{id:"fullstack",name:"Full-Stack Application",description:"Complete web application with frontend and backend",features:{backendOnly:!1,tailwindcss:!0,websocket:!1,prisma:!0,docker:!1,swaggerDocs:!0,mcp:!1},requiredFiles:["bootstrap.php",".htaccess","postcss.config.js","src/app/layout.php","src/app/index.php","public/js/main.js","src/app/globals.css"]},api:{id:"api",name:"REST API",description:"Backend API with database and documentation",features:{backendOnly:!0,tailwindcss:!1,websocket:!1,prisma:!0,docker:!0,swaggerDocs:!0,mcp:!1},requiredFiles:["bootstrap.php",".htaccess","docker-compose.yml","Dockerfile"]},realtime:{id:"realtime",name:"Real-time Application",description:"Application with WebSocket support and MCP",features:{backendOnly:!1,tailwindcss:!0,websocket:!0,prisma:!0,docker:!1,swaggerDocs:!0,mcp:!0},requiredFiles:["bootstrap.php",".htaccess","postcss.config.js","src/lib/websocket","src/lib/mcp"]},ecommerce:{id:"ecommerce",name:"E-commerce Starter",description:"Full e-commerce application with cart, payments, and admin",features:{backendOnly:!1,tailwindcss:!0,websocket:!1,prisma:!0,docker:!0,swaggerDocs:!0,mcp:!1},requiredFiles:[],source:{type:"git",url:"https://github.com/your-org/prisma-php-ecommerce-starter",branch:"main"}},blog:{id:"blog",name:"Blog CMS",description:"Blog content management system",features:{backendOnly:!1,tailwindcss:!0,websocket:!1,prisma:!0,docker:!1,swaggerDocs:!1,mcp:!1},requiredFiles:[],source:{type:"git",url:"https://github.com/your-org/prisma-php-blog-starter"}}};function bsConfigUrls(e){const s=e.indexOf("\\htdocs\\");if(-1===s)return console.error("Invalid PROJECT_ROOT_PATH. The path does not contain \\htdocs\\"),{bsTarget:"",bsPathRewrite:{}};const t=e.substring(0,s+8).replace(/\\/g,"\\\\"),c=e.replace(new RegExp(`^${t}`),"").replace(/\\/g,"/");let o=`http://localhost/${c}`;o=o.endsWith("/")?o.slice(0,-1):o;const n=o.replace(/(?<!:)(\/\/+)/g,"/"),r=c.replace(/\/\/+/g,"/");return{bsTarget:`${n}/`,bsPathRewrite:{"^/":`/${r.startsWith("/")?r.substring(1):r}/`}}}async function updatePackageJson(e,s){const t=path.join(e,"package.json");if(checkExcludeFiles(t))return;const c=JSON.parse(fs.readFileSync(t,"utf8"));c.scripts={...c.scripts,projectName:"tsx settings/project-name.ts"};let o=[];if(s.tailwindcss&&(c.scripts={...c.scripts,tailwind:"postcss src/app/globals.css -o public/css/styles.css --watch","tailwind:build":"postcss src/app/globals.css -o public/css/styles.css"},o.push("tailwind")),s.websocket&&(c.scripts={...c.scripts,websocket:"tsx settings/restart-websocket.ts"},o.push("websocket")),s.mcp&&(c.scripts={...c.scripts,mcp:"tsx settings/restart-mcp.ts"},o.push("mcp")),s.docker&&(c.scripts={...c.scripts,docker:"docker-compose up"},o.push("docker")),s.swaggerDocs){const e=s.prisma?"tsx settings/auto-swagger-docs.ts":"tsx settings/swagger-config.ts";c.scripts={...c.scripts,"create-swagger-docs":e}}let n={...c.scripts};n.browserSync="tsx settings/bs-config.ts",n["browserSync:build"]="tsx settings/build.ts",n.dev=`npm-run-all projectName -p browserSync ${o.join(" ")}`,n.build=`npm-run-all${s.tailwindcss?" tailwind:build":""} browserSync:build`,c.scripts=n,c.type="module",fs.writeFileSync(t,JSON.stringify(c,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,"public","js","main.js");if(checkExcludeFiles(t))return;let c=fs.readFileSync(t,"utf8");c+='\nwindow.ws = new WebSocket("ws://localhost:8080");\n',fs.writeFileSync(t,c,"utf8")}function generateAuthSecret(){return randomBytes(33).toString("base64")}function generateHexEncodedKey(e=16){return randomBytes(e).toString("hex")}function copyRecursiveSync(e,s,t){const c=fs.existsSync(e),o=c&&fs.statSync(e);if(c&&o&&o.isDirectory()){const c=s.toLowerCase();if(!t.websocket&&c.includes("src\\lib\\websocket"))return;if(!t.mcp&&c.includes("src\\lib\\mcp"))return;if(t.backendOnly&&c.includes("public\\js")||t.backendOnly&&c.includes("public\\css")||t.backendOnly&&c.includes("public\\assets"))return;if(!t.swaggerDocs&&c.includes("src\\app\\swagger-docs"))return;const o=s.replace(/\\/g,"/");if(updateAnswer?.excludeFilePath?.includes(o))return;fs.existsSync(s)||fs.mkdirSync(s,{recursive:!0}),fs.readdirSync(e).forEach((c=>{copyRecursiveSync(path.join(e,c),path.join(s,c),t)}))}else{if(checkExcludeFiles(s))return;if(!t.tailwindcss&&(s.includes("globals.css")||s.includes("styles.css")))return;if(!t.websocket&&s.includes("restart-websocket.ts"))return;if(!t.mcp&&s.includes("restart-mcp.ts"))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:c})=>{copyRecursiveSync(path.join(__dirname,s),path.join(e,c),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"),c="";s.backendOnly||(s.tailwindcss||(c='\n <link href="/css/index.css" rel="stylesheet" />'),c+='\n <script type="module" src="/js/main.js"><\/script>');let o="";s.backendOnly||(o=s.tailwindcss?` <link href="/css/styles.css" rel="stylesheet" /> ${c}`:c),e=e.replace("</head>",`${o}\n</head>`),fs.writeFileSync(t,e,{flag:"w"})}catch(e){console.error(chalk.red("Error modifying layout.php:"),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 c=[{src:"/settings",dest:"/settings"},{src:"/src",dest:"/src"},{src:"/public",dest:"/public"}];s.docker&&c.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 c=path.join(__dirname,s),o=path.join(e,t);if(checkExcludeFiles(o))return;const n=fs.readFileSync(c,"utf8");fs.writeFileSync(o,n,{flag:"w"})})),await executeCopy(e,c,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 o=generateAuthSecret(),n=generateHexEncodedKey(),r=`# Authentication secret key for JWT or session encryption.\nAUTH_SECRET="${o}"\n# Name of the authentication cookie.\nAUTH_COOKIE_NAME="${generateHexEncodedKey(8)}"\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="${n}"\n\n# Secret key for encrypting function calls.\nFUNCTION_CALL_SECRET="${generateHexEncodedKey(32)}"\n\n# Single or multiple origins (CSV or JSON array)\nCORS_ALLOWED_ORIGINS=[]\n\n# If you need cookies/Authorization across origins, keep this true\nCORS_ALLOW_CREDENTIALS="true"\n\n# Optional tuning\nCORS_ALLOWED_METHODS="GET,POST,PUT,PATCH,DELETE,OPTIONS"\nCORS_ALLOWED_HEADERS="Content-Type,Authorization,X-Requested-With"\nCORS_EXPOSE_HEADERS=""\nCORS_MAX_AGE="86400"`;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${r}`;await createOrUpdateEnvFile(e,s)}else await createOrUpdateEnvFile(e,r)}async function getAnswer(e={}){if(e.starterKit){const s=e.starterKit;let t=null;if(STARTER_KITS[s]&&(t=STARTER_KITS[s]),t){const c={projectName:e.projectName??"my-app",starterKit:s,starterKitSource:e.starterKitSource,backendOnly:t.features.backendOnly??!1,tailwindcss:t.features.tailwindcss??!1,websocket:t.features.websocket??!1,prisma:t.features.prisma??!1,docker:t.features.docker??!1,swaggerDocs:t.features.swaggerDocs??!1,mcp:t.features.mcp??!1},o=process.argv.slice(2);return o.includes("--backend-only")&&(c.backendOnly=!0),o.includes("--swagger-docs")&&(c.swaggerDocs=!0),o.includes("--tailwindcss")&&(c.tailwindcss=!0),o.includes("--websocket")&&(c.websocket=!0),o.includes("--mcp")&&(c.mcp=!0),o.includes("--prisma")&&(c.prisma=!0),o.includes("--docker")&&(c.docker=!0),c}if(e.starterKitSource){const t={projectName:e.projectName??"my-app",starterKit:s,starterKitSource:e.starterKitSource,backendOnly:!1,tailwindcss:!0,websocket:!1,prisma:!0,docker:!1,swaggerDocs:!0,mcp:!1},c=process.argv.slice(2);return c.includes("--backend-only")&&(t.backendOnly=!0),c.includes("--swagger-docs")&&(t.swaggerDocs=!0),c.includes("--tailwindcss")&&(t.tailwindcss=!0),c.includes("--websocket")&&(t.websocket=!0),c.includes("--mcp")&&(t.mcp=!0),c.includes("--prisma")&&(t.prisma=!0),c.includes("--docker")&&(t.docker=!0),t}}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=()=>{console.warn(chalk.red("Operation cancelled by the user.")),process.exit(0)},c=await prompts(s,{onCancel:t}),o=[];c.backendOnly??e.backendOnly??!1?(e.swaggerDocs||o.push({type:"toggle",name:"swaggerDocs",message:`Would you like to use ${chalk.blue("Swagger Docs")}?`,initial:!1,active:"Yes",inactive:"No"}),e.websocket||o.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!1,active:"Yes",inactive:"No"}),e.mcp||o.push({type:"toggle",name:"mcp",message:`Would you like to use ${chalk.blue("MCP (Model Context Protocol)")}?`,initial:!1,active:"Yes",inactive:"No"}),e.prisma||o.push({type:"toggle",name:"prisma",message:`Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,initial:!1,active:"Yes",inactive:"No"}),e.docker||o.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"})):(e.swaggerDocs||o.push({type:"toggle",name:"swaggerDocs",message:`Would you like to use ${chalk.blue("Swagger Docs")}?`,initial:!1,active:"Yes",inactive:"No"}),e.tailwindcss||o.push({type:"toggle",name:"tailwindcss",message:`Would you like to use ${chalk.blue("Tailwind CSS")}?`,initial:!1,active:"Yes",inactive:"No"}),e.websocket||o.push({type:"toggle",name:"websocket",message:`Would you like to use ${chalk.blue("Websocket")}?`,initial:!1,active:"Yes",inactive:"No"}),e.mcp||o.push({type:"toggle",name:"mcp",message:`Would you like to use ${chalk.blue("MCP (Model Context Protocol)")}?`,initial:!1,active:"Yes",inactive:"No"}),e.prisma||o.push({type:"toggle",name:"prisma",message:`Would you like to use ${chalk.blue("Prisma PHP ORM")}?`,initial:!1,active:"Yes",inactive:"No"}),e.docker||o.push({type:"toggle",name:"docker",message:`Would you like to use ${chalk.blue("Docker")}?`,initial:!1,active:"Yes",inactive:"No"}));const n=await prompts(o,{onCancel:t});return{projectName:c.projectName?String(c.projectName).trim().replace(/ /g,"-"):e.projectName??"my-app",backendOnly:c.backendOnly??e.backendOnly??!1,swaggerDocs:n.swaggerDocs??e.swaggerDocs??!1,tailwindcss:n.tailwindcss??e.tailwindcss??!1,websocket:n.websocket??e.websocket??!1,mcp:n.mcp??e.mcp??!1,prisma:n.prisma??e.prisma??!1,docker:n.docker??e.docker??!1}}async function uninstallNpmDependencies(e,s,t=!1){console.log("Uninstalling Node dependencies:"),s.forEach((e=>console.log(`- ${chalk.blue(e)}`)));const c=`npm uninstall ${t?"--save-dev":"--save"} ${s.join(" ")}`;execSync(c,{stdio:"inherit",cwd:e})}async function uninstallComposerDependencies(e,s){console.log("Uninstalling Composer dependencies:"),s.forEach((e=>console.log(`- ${chalk.blue(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 c="";e.on("data",(e=>c+=e)),e.on("end",(()=>{try{const e=JSON.parse(c);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),c=s.split(".").map(Number);for(let e=0;e<t.length;e++){if(t[e]>c[e])return 1;if(t[e]<c[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]:(console.error(`Package ${e} is not installed`),null)}catch(e){return console.error(e instanceof Error?e.message:String(e)),null}}async function installNpmDependencies(e,s,t=!1){fs.existsSync(path.join(e,"package.json"))?console.log("Updating existing Node.js project..."):console.log("Initializing new Node.js project..."),fs.existsSync(path.join(e,"package.json"))||execSync("npm init -y",{stdio:"inherit",cwd:e}),console.log((t?"Installing development dependencies":"Installing dependencies")+":"),s.forEach((e=>console.log(`- ${chalk.blue(e)}`)));const c=`npm install ${t?"--save-dev":""} ${s.join(" ")}`;execSync(c,{stdio:"inherit",cwd:e})}function getComposerCmd(){try{return execSync("composer --version",{stdio:"ignore"}),console.log("✓ Using global composer command"),{cmd:"composer",baseArgs:[]}}catch{const e="C:\\xampp\\php\\php.exe",s="C:\\ProgramData\\ComposerSetup\\bin\\composer.phar";if(!fs.existsSync(e))throw console.error(`✗ PHP not found at ${e}`),new Error(`PHP executable not found at ${e}`);if(!fs.existsSync(s))throw console.error(`✗ Composer not found at ${s}`),new Error(`Composer phar not found at ${s}`);return console.log("✓ Using XAMPP PHP with Composer phar"),{cmd:e,baseArgs:[s]}}}export async function installComposerDependencies(e,s){const{cmd:t,baseArgs:c}=getComposerCmd(),o=path.join(e,"composer.json"),n=fs.existsSync(o);if(console.log(chalk.green("Composer project initialization: "+(n?"Updating existing project…":"Setting up new project…"))),fs.existsSync(e)||(console.log(`Creating base directory: ${e}`),fs.mkdirSync(e,{recursive:!0})),!n){const s=[...c,"init","--no-interaction","--name","tsnc/prisma-php-app","--require","php:^8.2","--type","project","--version","1.0.0"];console.log("Attempting composer init...");const n=spawnSync(t,s,{cwd:e,stdio:["ignore","pipe","pipe"],encoding:"utf8"}),r=fs.existsSync(o);if(0===n.status&&r)console.log("✓ Composer init successful and composer.json created");else{0!==n.status?(console.log(`Composer init failed with status ${n.status}`),n.stderr&&console.log(`Stderr: ${n.stderr}`)):console.log("Composer init reported success but didn't create composer.json"),console.log("Creating composer.json manually...");const s={name:"tsnc/prisma-php-app",type:"project",version:"1.0.0",require:{php:"^8.2"},autoload:{"psr-4":{"":"src/"}}};try{const t=path.resolve(e,"composer.json");if(console.log(`Writing composer.json to: ${t}`),fs.writeFileSync(t,JSON.stringify(s,null,2),{encoding:"utf8"}),!fs.existsSync(t))throw new Error("File creation appeared to succeed but file doesn't exist");console.log("✓ Successfully created composer.json")}catch(s){if(console.error("✗ Failed to create composer.json:",s),console.error(`Base directory: ${e}`),console.error(`Absolute base directory: ${path.resolve(e)}`),console.error(`Target file path: ${o}`),console.error(`Absolute target file path: ${path.resolve(o)}`),console.error(`Current working directory: ${process.cwd()}`),console.error(`Base directory exists: ${fs.existsSync(e)}`),fs.existsSync(e))try{const s=fs.statSync(e);console.error(`Base directory is writable: ${s.isDirectory()}`)}catch(e){console.error(`Cannot stat base directory: ${e}`)}throw new Error(`Cannot create composer.json: ${s}`)}}}const r=path.resolve(e,"composer.json");if(!fs.existsSync(r))throw console.error(`✗ composer.json still not found at ${r}`),console.error("Directory contents:",fs.readdirSync(e)),new Error("Failed to create composer.json - file does not exist after all attempts");let i;try{const e=fs.readFileSync(r,"utf8");console.log("✓ Successfully read composer.json"),i=JSON.parse(e)}catch(e){throw console.error("✗ Failed to read/parse composer.json:",e),new Error(`Cannot read composer.json: ${e}`)}i.autoload??={},i.autoload["psr-4"]??={},i.autoload["psr-4"][""]??="src/";try{fs.writeFileSync(r,JSON.stringify(i,null,2)),console.log("✓ Updated composer.json with PSR-4 autoload")}catch(e){throw console.error("✗ Failed to update composer.json:",e),e}if(s.length){console.log("Installing Composer dependencies:"),s.forEach((e=>console.log(`- ${chalk.blue(e)}`)));try{const o=`${t} ${[...c,"require","--no-interaction",...s].join(" ")}`;execSync(o,{stdio:"inherit",cwd:e,env:{...process.env}}),console.log("✓ Composer dependencies installed")}catch(e){throw console.error("✗ Failed to install composer dependencies:",e),e}}if(n)try{execSync(`${t} ${[...c,"update","--lock","--no-install","--no-interaction"].join(" ")}`,{stdio:"inherit",cwd:e}),console.log("✓ Composer lock updated")}catch(e){throw console.error("✗ Failed to update composer lock:",e),e}try{execSync(`${t} ${[...c,"dump-autoload","--quiet"].join(" ")}`,{stdio:"inherit",cwd:e}),console.log("✓ Composer autoloader regenerated")}catch(e){throw console.error("✗ Failed to regenerate autoloader:",e),e}}const npmPinnedVersions={"@tailwindcss/postcss":"^4.1.13","@types/browser-sync":"^2.29.0","@types/node":"^24.5.2","@types/prompts":"^2.4.9","browser-sync":"^3.0.4",chalk:"^5.6.2","chokidar-cli":"^3.0.0",cssnano:"^7.1.1","http-proxy-middleware":"^3.0.5","npm-run-all":"^4.1.5","php-parser":"^3.2.5",postcss:"^8.5.6","postcss-cli":"^11.0.1",prompts:"^2.4.2",tailwindcss:"^4.1.13",tsx:"^4.20.5",typescript:"^5.9.2"};function npmPkg(e){return npmPinnedVersions[e]?`${e}@${npmPinnedVersions[e]}`:e}const composerPinnedVersions={"vlucas/phpdotenv":"^5.6.2","firebase/php-jwt":"^6.11.1","phpmailer/phpmailer":"^6.10.0","guzzlehttp/guzzle":"^7.10.0","symfony/uid":"^7.2.0","brick/math":"^0.14.0","cboden/ratchet":"^0.4.4","tsnc/prisma-php":"^1.0.0","php-mcp/server":"3.3.0"};function composerPkg(e){return composerPinnedVersions[e]?`${e}:${composerPinnedVersions[e]}`:e}async function setupStarterKit(e,s){if(!s.starterKit)return;let t=null;if(STARTER_KITS[s.starterKit]?t=STARTER_KITS[s.starterKit]:s.starterKitSource&&(t={id:s.starterKit,name:`Custom Starter Kit (${s.starterKit})`,description:"Custom starter kit from external source",features:{},requiredFiles:[],source:{type:"git",url:s.starterKitSource}}),t){if(console.log(chalk.green(`Setting up ${t.name}...`)),t.source)try{const c=t.source.branch?`git clone -b ${t.source.branch} --depth 1 ${t.source.url} ${e}`:`git clone --depth 1 ${t.source.url} ${e}`;execSync(c,{stdio:"inherit"});const o=path.join(e,".git");fs.existsSync(o)&&fs.rmSync(o,{recursive:!0,force:!0}),console.log(chalk.blue("Starter kit cloned successfully!"));const n=path.join(e,"prisma-php.json");if(fs.existsSync(n))try{const t=JSON.parse(fs.readFileSync(n,"utf8")),c=e.replace(/\\/g,"\\"),o=bsConfigUrls(c);t.projectName=s.projectName,t.projectRootPath=c,t.bsTarget=o.bsTarget,t.bsPathRewrite=o.bsPathRewrite;const r=await fetchPackageVersion("create-prisma-php-app");t.version=r,fs.writeFileSync(n,JSON.stringify(t,null,2)),console.log(chalk.green("Updated prisma-php.json with new project details"))}catch(e){console.warn(chalk.yellow("Failed to update prisma-php.json, will create new one"))}}catch(e){throw console.error(chalk.red(`Failed to setup starter kit: ${e}`)),e}t.customSetup&&await t.customSetup(e,s),console.log(chalk.green(`✓ ${t.name} setup complete!`))}else console.warn(chalk.yellow(`Starter kit '${s.starterKit}' not found. Skipping...`))}function showStarterKits(){console.log(chalk.blue("\n🚀 Available Starter Kits:\n")),Object.values(STARTER_KITS).forEach((e=>{const s=e.source?" (Custom)":" (Built-in)";console.log(chalk.green(` ${e.id}${chalk.gray(s)}`)),console.log(` ${e.name}`),console.log(chalk.gray(` ${e.description}`)),e.source&&console.log(chalk.cyan(` Source: ${e.source.url}`));const t=Object.entries(e.features).filter((([,e])=>!0===e)).map((([e])=>e)).join(", ");t&&console.log(chalk.magenta(` Features: ${t}`)),console.log()})),console.log(chalk.yellow("Usage:")),console.log(" npx create-prisma-php-app my-project --starter-kit=basic"),console.log(" npx create-prisma-php-app my-project --starter-kit=custom --starter-kit-source=https://github.com/user/repo"),console.log()}async function main(){try{const e=process.argv.slice(2);let s=e[0];const t=e.find((e=>e.startsWith("--starter-kit="))),c=t?.split("=")[1],o=e.find((e=>e.startsWith("--starter-kit-source="))),n=o?.split("=")[1];if(e.includes("--list-starter-kits"))return void showStarterKits();let r=null,i=!1;if(s){const t=process.cwd(),o=path.join(t,"prisma-php.json");if(c&&n){i=!0;const t={projectName:s,starterKit:c,starterKitSource:n,backendOnly:e.includes("--backend-only"),swaggerDocs:e.includes("--swagger-docs"),tailwindcss:e.includes("--tailwindcss"),websocket:e.includes("--websocket"),mcp:e.includes("--mcp"),prisma:e.includes("--prisma"),docker:e.includes("--docker")};r=await getAnswer(t)}else if(fs.existsSync(o)){const c=readJsonFile(o);let n=[];c.excludeFiles?.map((e=>{const s=path.join(t,e);fs.existsSync(s)&&n.push(s.replace(/\\/g,"/"))})),updateAnswer={projectName:s,backendOnly:c.backendOnly,swaggerDocs:c.swaggerDocs,tailwindcss:c.tailwindcss,websocket:c.websocket,mcp:c.mcp,prisma:c.prisma,docker:c.docker,isUpdate:!0,componentScanDirs:c.componentScanDirs??[],excludeFiles:c.excludeFiles??[],excludeFilePath:n??[],filePath:t};const i={projectName:s,backendOnly:e.includes("--backend-only")||c.backendOnly,swaggerDocs:e.includes("--swagger-docs")||c.swaggerDocs,tailwindcss:e.includes("--tailwindcss")||c.tailwindcss,websocket:e.includes("--websocket")||c.websocket,prisma:e.includes("--prisma")||c.prisma,docker:e.includes("--docker")||c.docker,mcp:e.includes("--mcp")||c.mcp};r=await getAnswer(i),null!==r&&(updateAnswer={projectName:s,backendOnly:r.backendOnly,swaggerDocs:r.swaggerDocs,tailwindcss:r.tailwindcss,websocket:r.websocket,mcp:r.mcp,prisma:r.prisma,docker:r.docker,isUpdate:!0,componentScanDirs:c.componentScanDirs??[],excludeFiles:c.excludeFiles??[],excludeFilePath:n??[],filePath:t})}else{const t={projectName:s,starterKit:c,starterKitSource:n,backendOnly:e.includes("--backend-only"),swaggerDocs:e.includes("--swagger-docs"),tailwindcss:e.includes("--tailwindcss"),websocket:e.includes("--websocket"),mcp:e.includes("--mcp"),prisma:e.includes("--prisma"),docker:e.includes("--docker")};r=await getAnswer(t)}if(null===r)return void console.log(chalk.red("Installation cancelled."))}else r=await getAnswer();if(null===r)return void console.warn(chalk.red("Installation cancelled."));const a=await fetchPackageVersion("create-prisma-php-app"),p=getInstalledPackageVersion("create-prisma-php-app");p?-1===compareVersions(p,a)&&(execSync("npm uninstall -g create-prisma-php-app",{stdio:"inherit"}),execSync("npm install -g create-prisma-php-app",{stdio:"inherit"})):execSync("npm install -g create-prisma-php-app",{stdio:"inherit"});const l=process.cwd();let d;if(s)if(i){const t=path.join(l,s);fs.existsSync(t)||fs.mkdirSync(t,{recursive:!0}),d=t,await setupStarterKit(d,r),process.chdir(d);const c=path.join(d,"prisma-php.json");if(fs.existsSync(c)){const s=JSON.parse(fs.readFileSync(c,"utf8"));e.includes("--backend-only")&&(s.backendOnly=!0),e.includes("--swagger-docs")&&(s.swaggerDocs=!0),e.includes("--tailwindcss")&&(s.tailwindcss=!0),e.includes("--websocket")&&(s.websocket=!0),e.includes("--mcp")&&(s.mcp=!0),e.includes("--prisma")&&(s.prisma=!0),e.includes("--docker")&&(s.docker=!0),r={...r,backendOnly:s.backendOnly,swaggerDocs:s.swaggerDocs,tailwindcss:s.tailwindcss,websocket:s.websocket,mcp:s.mcp,prisma:s.prisma,docker:s.docker};let t=[];s.excludeFiles?.map((e=>{const s=path.join(d,e);fs.existsSync(s)&&t.push(s.replace(/\\/g,"/"))})),updateAnswer={...r,isUpdate:!0,componentScanDirs:s.componentScanDirs??[],excludeFiles:s.excludeFiles??[],excludeFilePath:t??[],filePath:d}}}else{const e=path.join(l,"prisma-php.json"),t=path.join(l,s),c=path.join(t,"prisma-php.json");fs.existsSync(e)?d=l:fs.existsSync(t)&&fs.existsSync(c)?(d=t,process.chdir(t)):(fs.existsSync(t)||fs.mkdirSync(t,{recursive:!0}),d=t,process.chdir(t))}else fs.mkdirSync(r.projectName,{recursive:!0}),d=path.join(l,r.projectName),process.chdir(r.projectName);let u=[npmPkg("typescript"),npmPkg("@types/node"),npmPkg("tsx"),npmPkg("http-proxy-middleware"),npmPkg("chalk"),npmPkg("npm-run-all"),npmPkg("browser-sync"),npmPkg("@types/browser-sync"),npmPkg("php-parser")],m=[composerPkg("vlucas/phpdotenv"),composerPkg("firebase/php-jwt"),composerPkg("phpmailer/phpmailer"),composerPkg("guzzlehttp/guzzle"),composerPkg("symfony/uid"),composerPkg("brick/math"),composerPkg("tsnc/prisma-php")];if(r.swaggerDocs&&u.push(npmPkg("swagger-jsdoc"),npmPkg("@types/swagger-jsdoc")),r.swaggerDocs&&r.prisma&&u.push(npmPkg("prompts"),npmPkg("@types/prompts")),r.tailwindcss&&u.push(npmPkg("tailwindcss"),npmPkg("postcss"),npmPkg("postcss-cli"),npmPkg("@tailwindcss/postcss"),npmPkg("cssnano")),r.websocket&&m.push("cboden/ratchet"),r.mcp&&m.push("php-mcp/server"),r.prisma&&execSync("npm install -g prisma-client-php",{stdio:"inherit"}),r.starterKit&&!i&&await setupStarterKit(d,r),await installNpmDependencies(d,u,!0),await installComposerDependencies(d,m),s||execSync("npx tsc --init",{stdio:"inherit"}),await createDirectoryStructure(d,r),r.prisma&&execSync("npx ppo init --prisma-php",{stdio:"inherit"}),r.swaggerDocs){const e=path.join(d,"src","app","swagger-docs");fs.existsSync(e)&&fs.readdirSync(e).length>0&&(console.log("Removing existing swagger-docs directory..."),fs.rmSync(e,{recursive:!0,force:!0})),execSync(`git clone https://github.com/TheSteelNinjaCode/prisma-php-swagger-docs.git ${e}`,{stdio:"inherit"}),fs.rmSync(path.join(e,".git"),{recursive:!0,force:!0})}if(updateAnswer?.isUpdate){const e=[],s=[],t=e=>{try{const s=path.join(d,"composer.json");if(fs.existsSync(s)){const t=JSON.parse(fs.readFileSync(s,"utf8"));return!(!t.require||!t.require[e])}return!1}catch{return!1}},c=e=>{try{const s=path.join(d,"package.json");if(fs.existsSync(s)){const t=JSON.parse(fs.readFileSync(s,"utf8"));return!!(t.dependencies&&t.dependencies[e]||t.devDependencies&&t.devDependencies[e])}return!1}catch{return!1}};if(updateAnswer.backendOnly){nonBackendFiles.forEach((e=>{const s=path.join(d,"src","app",e);fs.existsSync(s)&&(fs.unlinkSync(s),console.log(`${e} was deleted successfully.`))}));["js","css"].forEach((e=>{const s=path.join(d,"src","app",e);fs.existsSync(s)&&(fs.rmSync(s,{recursive:!0,force:!0}),console.log(`${e} was deleted successfully.`))}))}if(!updateAnswer.swaggerDocs){const s=path.join(d,"src","app","swagger-docs");fs.existsSync(s)&&(fs.rmSync(s,{recursive:!0,force:!0}),console.log("swagger-docs was deleted successfully."));["swagger-config.ts"].forEach((e=>{const s=path.join(d,"settings",e);fs.existsSync(s)&&(fs.unlinkSync(s),console.log(`${e} was deleted successfully.`))})),c("swagger-jsdoc")&&e.push("swagger-jsdoc"),c("@types/swagger-jsdoc")&&e.push("@types/swagger-jsdoc"),c("prompts")&&e.push("prompts"),c("@types/prompts")&&e.push("@types/prompts")}if(!updateAnswer.tailwindcss){["postcss.config.js"].forEach((e=>{const s=path.join(d,e);fs.existsSync(s)&&(fs.unlinkSync(s),console.log(`${e} was deleted successfully.`))}));["tailwindcss","postcss","postcss-cli","@tailwindcss/postcss","cssnano"].forEach((s=>{c(s)&&e.push(s)}))}if(!updateAnswer.websocket){["restart-websocket.ts"].forEach((e=>{const s=path.join(d,"settings",e);fs.existsSync(s)&&(fs.unlinkSync(s),console.log(`${e} was deleted successfully.`))}));const e=path.join(d,"src","Lib","Websocket");fs.existsSync(e)&&(fs.rmSync(e,{recursive:!0,force:!0}),console.log("Websocket folder was deleted successfully.")),t("cboden/ratchet")&&s.push("cboden/ratchet")}if(!updateAnswer.mcp){["restart-mcp.ts"].forEach((e=>{const s=path.join(d,"settings",e);fs.existsSync(s)&&(fs.unlinkSync(s),console.log(`${e} was deleted successfully.`))}));const e=path.join(d,"src","Lib","MCP");fs.existsSync(e)&&(fs.rmSync(e,{recursive:!0,force:!0}),console.log("MCP folder was deleted successfully.")),t("php-mcp/server")&&s.push("php-mcp/server")}if(!updateAnswer.prisma){["prisma","@prisma/client","@prisma/internals"].forEach((s=>{c(s)&&e.push(s)}))}if(!updateAnswer.docker){[".dockerignore","docker-compose.yml","Dockerfile","apache.conf"].forEach((e=>{const s=path.join(d,e);fs.existsSync(s)&&(fs.unlinkSync(s),console.log(`${e} was deleted successfully.`))}))}const o=e=>Array.from(new Set(e)),n=o(e),r=o(s);n.length>0&&(console.log(`Uninstalling npm packages: ${n.join(", ")}`),await uninstallNpmDependencies(d,n,!0)),r.length>0&&(console.log(`Uninstalling composer packages: ${r.join(", ")}`),await uninstallComposerDependencies(d,r))}if(!i||!fs.existsSync(path.join(d,"prisma-php.json"))){const e=d.replace(/\\/g,"\\"),s=bsConfigUrls(e),t={projectName:r.projectName,projectRootPath:e,phpEnvironment:"XAMPP",phpRootPathExe:"C:\\xampp\\php\\php.exe",bsTarget:s.bsTarget,bsPathRewrite:s.bsPathRewrite,backendOnly:r.backendOnly,swaggerDocs:r.swaggerDocs,tailwindcss:r.tailwindcss,websocket:r.websocket,mcp:r.mcp,prisma:r.prisma,docker:r.docker,version:a,componentScanDirs:updateAnswer?.componentScanDirs??["src","vendor/tsnc/prisma-php/src"],excludeFiles:updateAnswer?.excludeFiles??[]};fs.writeFileSync(path.join(d,"prisma-php.json"),JSON.stringify(t,null,2),{flag:"w"})}execSync(updateAnswer?.isUpdate?"C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar update":"C:\\xampp\\php\\php.exe C:\\ProgramData\\ComposerSetup\\bin\\composer.phar install",{stdio:"inherit"}),console.log("\n=========================\n"),console.log(`${chalk.green("Success!")} Prisma PHP project successfully created in ${chalk.green(d.replace(/\\/g,"/"))}!`),console.log("\n=========================")}catch(e){console.error("Error while creating the project:",e),process.exit(1)}}main();
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
var Dt=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,80,3,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,343,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,726,6,110,6,6,9,4759,9,787719,239],tt=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,2,60,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,42,9,8936,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,496,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4153,7,221,3,5761,15,7472,16,621,2467,541,1507,4938,6,4191],Bt="·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛-࢟࣊-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄ఼ా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ೳഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-໎໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜕ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠏-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿ-ᫎᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯・꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_・",st="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࡰ-ࢇࢉ-ࢎࢠ-ࣉऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౝౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೝೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜑᜟ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭌᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-Ა-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-Ꟑꟑꟓꟕ-ꟲ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",Me={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"},Re="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this",$t={5:Re,"5module":Re+" export import",6:Re+" const class extends export import super"},jt=/^in(stanceof)?$/,Wt=new RegExp("["+st+"]"),Ut=new RegExp("["+st+Bt+"]");function Le(t,e){for(var s=65536,i=0;i<e.length;i+=2){if(s+=e[i],s>t)return!1;if(s+=e[i+1],s>=t)return!0}return!1}function q(t,e){return t<65?t===36:t<91?!0:t<97?t===95:t<123?!0:t<=65535?t>=170&&Wt.test(String.fromCharCode(t)):e===!1?!1:Le(t,tt)}function J(t,e){return t<48?t===36:t<58?!0:t<65?!1:t<91?!0:t<97?t===95:t<123?!0:t<=65535?t>=170&&Ut.test(String.fromCharCode(t)):e===!1?!1:Le(t,tt)||Le(t,Dt)}var w=function(e,s){s===void 0&&(s={}),this.label=e,this.keyword=s.keyword,this.beforeExpr=!!s.beforeExpr,this.startsExpr=!!s.startsExpr,this.isLoop=!!s.isLoop,this.isAssign=!!s.isAssign,this.prefix=!!s.prefix,this.postfix=!!s.postfix,this.binop=s.binop||null,this.updateContext=null};function F(t,e){return new w(t,{beforeExpr:!0,binop:e})}var D={beforeExpr:!0},O={startsExpr:!0},$e={};function T(t,e){return e===void 0&&(e={}),e.keyword=t,$e[t]=new w(t,e)}var u={num:new w("num",O),regexp:new w("regexp",O),string:new w("string",O),name:new w("name",O),privateId:new w("privateId",O),eof:new w("eof"),bracketL:new w("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new w("]"),braceL:new w("{",{beforeExpr:!0,startsExpr:!0}),braceR:new w("}"),parenL:new w("(",{beforeExpr:!0,startsExpr:!0}),parenR:new w(")"),comma:new w(",",D),semi:new w(";",D),colon:new w(":",D),dot:new w("."),question:new w("?",D),questionDot:new w("?."),arrow:new w("=>",D),template:new w("template"),invalidTemplate:new w("invalidTemplate"),ellipsis:new w("...",D),backQuote:new w("`",O),dollarBraceL:new w("${",{beforeExpr:!0,startsExpr:!0}),eq:new w("=",{beforeExpr:!0,isAssign:!0}),assign:new w("_=",{beforeExpr:!0,isAssign:!0}),incDec:new w("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new w("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:F("||",1),logicalAND:F("&&",2),bitwiseOR:F("|",3),bitwiseXOR:F("^",4),bitwiseAND:F("&",5),equality:F("==/!=/===/!==",6),relational:F("</>/<=/>=",7),bitShift:F("<</>>/>>>",8),plusMin:new w("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:F("%",10),star:F("*",10),slash:F("/",10),starstar:new w("**",{beforeExpr:!0}),coalesce:F("??",1),_break:T("break"),_case:T("case",D),_catch:T("catch"),_continue:T("continue"),_debugger:T("debugger"),_default:T("default",D),_do:T("do",{isLoop:!0,beforeExpr:!0}),_else:T("else",D),_finally:T("finally"),_for:T("for",{isLoop:!0}),_function:T("function",O),_if:T("if"),_return:T("return",D),_switch:T("switch"),_throw:T("throw",D),_try:T("try"),_var:T("var"),_const:T("const"),_while:T("while",{isLoop:!0}),_with:T("with"),_new:T("new",{beforeExpr:!0,startsExpr:!0}),_this:T("this",O),_super:T("super",O),_class:T("class",O),_extends:T("extends",D),_export:T("export"),_import:T("import",O),_null:T("null",O),_true:T("true",O),_false:T("false",O),_in:T("in",{beforeExpr:!0,binop:7}),_instanceof:T("instanceof",{beforeExpr:!0,binop:7}),_typeof:T("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:T("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:T("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},V=/\r\n?|\n|\u2028|\u2029/,Ht=new RegExp(V.source,"g");function ue(t){return t===10||t===13||t===8232||t===8233}function it(t,e,s){s===void 0&&(s=t.length);for(var i=e;i<s;i++){var n=t.charCodeAt(i);if(ue(n))return i<s-1&&n===13&&t.charCodeAt(i+1)===10?i+2:i+1}return-1}var nt=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/,N=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,rt=Object.prototype,zt=rt.hasOwnProperty,qt=rt.toString,le=Object.hasOwn||(function(t,e){return zt.call(t,e)}),Ge=Array.isArray||(function(t){return qt.call(t)==="[object Array]"}),Qe=Object.create(null);function Z(t){return Qe[t]||(Qe[t]=new RegExp("^(?:"+t.replace(/ /g,"|")+")$"))}function G(t){return t<=65535?String.fromCharCode(t):(t-=65536,String.fromCharCode((t>>10)+55296,(t&1023)+56320))}var Xt=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,me=function(e,s){this.line=e,this.column=s};me.prototype.offset=function(e){return new me(this.line,this.column+e)};var Te=function(e,s,i){this.start=s,this.end=i,e.sourceFile!==null&&(this.source=e.sourceFile)};function at(t,e){for(var s=1,i=0;;){var n=it(t,i,e);if(n<0)return new me(s,e-i);++s,i=n}}var Ve={ecmaVersion:null,sourceType:"script",onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},Ye=!1;function Kt(t){var e={};for(var s in Ve)e[s]=t&&le(t,s)?t[s]:Ve[s];if(e.ecmaVersion==="latest"?e.ecmaVersion=1e8:e.ecmaVersion==null?(!Ye&&typeof console=="object"&&console.warn&&(Ye=!0,console.warn(`Since Acorn 8.0.0, options.ecmaVersion is required.
|
|
2
2
|
Defaulting to 2020, but this will stop working in the future.`)),e.ecmaVersion=11):e.ecmaVersion>=2015&&(e.ecmaVersion-=2009),e.allowReserved==null&&(e.allowReserved=e.ecmaVersion<5),(!t||t.allowHashBang==null)&&(e.allowHashBang=e.ecmaVersion>=14),Ge(e.onToken)){var i=e.onToken;e.onToken=function(n){return i.push(n)}}return Ge(e.onComment)&&(e.onComment=Gt(e,e.onComment)),e}function Gt(t,e){return function(s,i,n,r,a,o){var c={type:s?"Block":"Line",value:i,start:n,end:r};t.locations&&(c.loc=new Te(this,a,o)),t.ranges&&(c.range=[n,r]),e.push(c)}}var ge=1,he=2,je=4,ot=8,We=16,ct=32,we=64,ut=128,ne=256,xe=512,Pe=ge|he|ne;function Ue(t,e){return he|(t?je:0)|(e?ot:0)}var Ce=0,He=1,Y=2,lt=3,ht=4,pt=5,I=function(e,s,i){this.options=e=Kt(e),this.sourceFile=e.sourceFile,this.keywords=Z($t[e.ecmaVersion>=6?6:e.sourceType==="module"?"5module":5]);var n="";e.allowReserved!==!0&&(n=Me[e.ecmaVersion>=6?6:e.ecmaVersion===5?5:3],e.sourceType==="module"&&(n+=" await")),this.reservedWords=Z(n);var r=(n?n+" ":"")+Me.strict;this.reservedWordsStrict=Z(r),this.reservedWordsStrictBind=Z(r+" "+Me.strictBind),this.input=String(s),this.containsEsc=!1,i?(this.pos=i,this.lineStart=this.input.lastIndexOf(`
|
|
3
|
-
`,i-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(V).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=u.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule=e.sourceType==="module",this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),this.pos===0&&e.allowHashBang&&this.input.slice(0,2)==="#!"&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(ge),this.regexpState=null,this.privateNameStack=[]},X={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};I.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)};X.inFunction.get=function(){return(this.currentVarScope().flags&he)>0};X.inGenerator.get=function(){return(this.currentVarScope().flags&ot)>0};X.inAsync.get=function(){return(this.currentVarScope().flags&je)>0};X.canAwait.get=function(){for(var t=this.scopeStack.length-1;t>=0;t--){var e=this.scopeStack[t],s=e.flags;if(s&(ne|xe))return!1;if(s&he)return(s&je)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction};X.allowSuper.get=function(){var t=this.currentThisScope(),e=t.flags;return(e&we)>0||this.options.allowSuperOutsideMethod};X.allowDirectSuper.get=function(){return(this.currentThisScope().flags&ut)>0};X.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};X.allowNewDotTarget.get=function(){for(var t=this.scopeStack.length-1;t>=0;t--){var e=this.scopeStack[t],s=e.flags;if(s&(ne|xe)||s&he&&!(s&We))return!0}return!1};X.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&ne)>0};I.extend=function(){for(var e=[],s=arguments.length;s--;)e[s]=arguments[s];for(var i=this,n=0;n<e.length;n++)i=e[n](i);return i};I.parse=function(e,s){return new this(s,e).parse()};I.parseExpressionAt=function(e,s,i){var n=new this(i,e,s);return n.nextToken(),n.parseExpression()};I.tokenizer=function(e,s){return new this(s,e)};Object.defineProperties(I.prototype,X);var R=I.prototype,Qt=/^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/;R.strictDirective=function(t){if(this.options.ecmaVersion<5)return!1;for(;;){N.lastIndex=t,t+=N.exec(this.input)[0].length;var e=Qt.exec(this.input.slice(t));if(!e)return!1;if((e[1]||e[2])==="use strict"){N.lastIndex=t+e[0].length;var s=N.exec(this.input),i=s.index+s[0].length,n=this.input.charAt(i);return n===";"||n==="}"||V.test(s[0])&&!(/[(`.[+\-/*%<>=,?^&]/.test(n)||n==="!"&&this.input.charAt(i+1)==="=")}t+=e[0].length,N.lastIndex=t,t+=N.exec(this.input)[0].length,this.input[t]===";"&&t++}};R.eat=function(t){return this.type===t?(this.next(),!0):!1};R.isContextual=function(t){return this.type===u.name&&this.value===t&&!this.containsEsc};R.eatContextual=function(t){return this.isContextual(t)?(this.next(),!0):!1};R.expectContextual=function(t){this.eatContextual(t)||this.unexpected()};R.canInsertSemicolon=function(){return this.type===u.eof||this.type===u.braceR||V.test(this.input.slice(this.lastTokEnd,this.start))};R.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0};R.semicolon=function(){!this.eat(u.semi)&&!this.insertSemicolon()&&this.unexpected()};R.afterTrailingComma=function(t,e){if(this.type===t)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),e||this.next(),!0};R.expect=function(t){this.eat(t)||this.unexpected()};R.unexpected=function(t){this.raise(t??this.start,"Unexpected token")};var _e=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};R.checkPatternErrors=function(t,e){if(t){t.trailingComma>-1&&this.raiseRecoverable(t.trailingComma,"Comma is not permitted after the rest element");var s=e?t.parenthesizedAssign:t.parenthesizedBind;s>-1&&this.raiseRecoverable(s,e?"Assigning to rvalue":"Parenthesized pattern")}};R.checkExpressionErrors=function(t,e){if(!t)return!1;var s=t.shorthandAssign,i=t.doubleProto;if(!e)return s>=0||i>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),i>=0&&this.raiseRecoverable(i,"Redefinition of __proto__ property")};R.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos<this.awaitPos)&&this.raise(this.yieldPos,"Yield expression cannot be a default value"),this.awaitPos&&this.raise(this.awaitPos,"Await expression cannot be a default value")};R.isSimpleAssignTarget=function(t){return t.type==="ParenthesizedExpression"?this.isSimpleAssignTarget(t.expression):t.type==="Identifier"||t.type==="MemberExpression"};var b=I.prototype;b.parseTopLevel=function(t){var e=Object.create(null);for(t.body||(t.body=[]);this.type!==u.eof;){var s=this.parseStatement(null,!0,e);t.body.push(s)}if(this.inModule)for(var i=0,n=Object.keys(this.undefinedExports);i<n.length;i+=1){var r=n[i];this.raiseRecoverable(this.undefinedExports[r].start,"Export '"+r+"' is not defined")}return this.adaptDirectivePrologue(t.body),this.next(),t.sourceType=this.options.sourceType,this.finishNode(t,"Program")};var ze={kind:"loop"},Yt={kind:"switch"};b.isLet=function(t){if(this.options.ecmaVersion<6||!this.isContextual("let"))return!1;N.lastIndex=this.pos;var e=N.exec(this.input),s=this.pos+e[0].length,i=this.input.charCodeAt(s);if(i===91||i===92)return!0;if(t)return!1;if(i===123||i>55295&&i<56320)return!0;if(q(i,!0)){for(var n=s+1;J(i=this.input.charCodeAt(n),!0);)++n;if(i===92||i>55295&&i<56320)return!0;var r=this.input.slice(s,n);if(!jt.test(r))return!0}return!1};b.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;N.lastIndex=this.pos;var t=N.exec(this.input),e=this.pos+t[0].length,s;return!V.test(this.input.slice(this.pos,e))&&this.input.slice(e,e+8)==="function"&&(e+8===this.input.length||!(J(s=this.input.charCodeAt(e+8))||s>55295&&s<56320))};b.isUsingKeyword=function(t,e){if(this.options.ecmaVersion<17||!this.isContextual(t?"await":"using"))return!1;N.lastIndex=this.pos;var s=N.exec(this.input),i=this.pos+s[0].length;if(V.test(this.input.slice(this.pos,i)))return!1;if(t){var n=i+5,r;if(this.input.slice(i,n)!=="using"||n===this.input.length||J(r=this.input.charCodeAt(n))||r>55295&&r<56320)return!1;N.lastIndex=n;var a=N.exec(this.input);if(a&&V.test(this.input.slice(n,n+a[0].length)))return!1}if(e){var o=i+2,c;if(this.input.slice(i,o)==="of"&&(o===this.input.length||!J(c=this.input.charCodeAt(o))&&!(c>55295&&c<56320)))return!1}var l=this.input.charCodeAt(i);return q(l,!0)||l===92};b.isAwaitUsing=function(t){return this.isUsingKeyword(!0,t)};b.isUsing=function(t){return this.isUsingKeyword(!1,t)};b.parseStatement=function(t,e,s){var i=this.type,n=this.startNode(),r;switch(this.isLet(t)&&(i=u._var,r="let"),i){case u._break:case u._continue:return this.parseBreakContinueStatement(n,i.keyword);case u._debugger:return this.parseDebuggerStatement(n);case u._do:return this.parseDoStatement(n);case u._for:return this.parseForStatement(n);case u._function:return t&&(this.strict||t!=="if"&&t!=="label")&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(n,!1,!t);case u._class:return t&&this.unexpected(),this.parseClass(n,!0);case u._if:return this.parseIfStatement(n);case u._return:return this.parseReturnStatement(n);case u._switch:return this.parseSwitchStatement(n);case u._throw:return this.parseThrowStatement(n);case u._try:return this.parseTryStatement(n);case u._const:case u._var:return r=r||this.value,t&&r!=="var"&&this.unexpected(),this.parseVarStatement(n,r);case u._while:return this.parseWhileStatement(n);case u._with:return this.parseWithStatement(n);case u.braceL:return this.parseBlock(!0,n);case u.semi:return this.parseEmptyStatement(n);case u._export:case u._import:if(this.options.ecmaVersion>10&&i===u._import){N.lastIndex=this.pos;var a=N.exec(this.input),o=this.pos+a[0].length,c=this.input.charCodeAt(o);if(c===40||c===46)return this.parseExpressionStatement(n,this.parseExpression())}return this.options.allowImportExportEverywhere||(e||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),i===u._import?this.parseImport(n):this.parseExport(n,s);default:if(this.isAsyncFunction())return t&&this.unexpected(),this.next(),this.parseFunctionStatement(n,!0,!t);var l=this.isAwaitUsing(!1)?"await using":this.isUsing(!1)?"using":null;if(l)return e&&this.options.sourceType==="script"&&this.raise(this.start,"Using declaration cannot appear in the top level when source type is `script`"),l==="await using"&&(this.canAwait||this.raise(this.start,"Await using cannot appear outside of async function"),this.next()),this.next(),this.parseVar(n,!1,l),this.semicolon(),this.finishNode(n,"VariableDeclaration");var h=this.value,p=this.parseExpression();return i===u.name&&p.type==="Identifier"&&this.eat(u.colon)?this.parseLabeledStatement(n,h,p,t):this.parseExpressionStatement(n,p)}};b.parseBreakContinueStatement=function(t,e){var s=e==="break";this.next(),this.eat(u.semi)||this.insertSemicolon()?t.label=null:this.type!==u.name?this.unexpected():(t.label=this.parseIdent(),this.semicolon());for(var i=0;i<this.labels.length;++i){var n=this.labels[i];if((t.label==null||n.name===t.label.name)&&(n.kind!=null&&(s||n.kind==="loop")||t.label&&s))break}return i===this.labels.length&&this.raise(t.start,"Unsyntactic "+e),this.finishNode(t,s?"BreakStatement":"ContinueStatement")};b.parseDebuggerStatement=function(t){return this.next(),this.semicolon(),this.finishNode(t,"DebuggerStatement")};b.parseDoStatement=function(t){return this.next(),this.labels.push(ze),t.body=this.parseStatement("do"),this.labels.pop(),this.expect(u._while),t.test=this.parseParenExpression(),this.options.ecmaVersion>=6?this.eat(u.semi):this.semicolon(),this.finishNode(t,"DoWhileStatement")};b.parseForStatement=function(t){this.next();var e=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(ze),this.enterScope(0),this.expect(u.parenL),this.type===u.semi)return e>-1&&this.unexpected(e),this.parseFor(t,null);var s=this.isLet();if(this.type===u._var||this.type===u._const||s){var i=this.startNode(),n=s?"let":this.value;return this.next(),this.parseVar(i,!0,n),this.finishNode(i,"VariableDeclaration"),this.parseForAfterInit(t,i,e)}var r=this.isContextual("let"),a=!1,o=this.isUsing(!0)?"using":this.isAwaitUsing(!0)?"await using":null;if(o){var c=this.startNode();return this.next(),o==="await using"&&this.next(),this.parseVar(c,!0,o),this.finishNode(c,"VariableDeclaration"),this.parseForAfterInit(t,c,e)}var l=this.containsEsc,h=new _e,p=this.start,f=e>-1?this.parseExprSubscripts(h,"await"):this.parseExpression(!0,h);return this.type===u._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(e>-1?(this.type===u._in&&this.unexpected(e),t.await=!0):a&&this.options.ecmaVersion>=8&&(f.start===p&&!l&&f.type==="Identifier"&&f.name==="async"?this.unexpected():this.options.ecmaVersion>=9&&(t.await=!1)),r&&a&&this.raise(f.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(f,!1,h),this.checkLValPattern(f),this.parseForIn(t,f)):(this.checkExpressionErrors(h,!0),e>-1&&this.unexpected(e),this.parseFor(t,f))};b.parseForAfterInit=function(t,e,s){return(this.type===u._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&e.declarations.length===1?(this.options.ecmaVersion>=9&&(this.type===u._in?s>-1&&this.unexpected(s):t.await=s>-1),this.parseForIn(t,e)):(s>-1&&this.unexpected(s),this.parseFor(t,e))};b.parseFunctionStatement=function(t,e,s){return this.next(),this.parseFunction(t,de|(s?0:Fe),!1,e)};b.parseIfStatement=function(t){return this.next(),t.test=this.parseParenExpression(),t.consequent=this.parseStatement("if"),t.alternate=this.eat(u._else)?this.parseStatement("if"):null,this.finishNode(t,"IfStatement")};b.parseReturnStatement=function(t){return!this.inFunction&&!this.options.allowReturnOutsideFunction&&this.raise(this.start,"'return' outside of function"),this.next(),this.eat(u.semi)||this.insertSemicolon()?t.argument=null:(t.argument=this.parseExpression(),this.semicolon()),this.finishNode(t,"ReturnStatement")};b.parseSwitchStatement=function(t){this.next(),t.discriminant=this.parseParenExpression(),t.cases=[],this.expect(u.braceL),this.labels.push(Yt),this.enterScope(0);for(var e,s=!1;this.type!==u.braceR;)if(this.type===u._case||this.type===u._default){var i=this.type===u._case;e&&this.finishNode(e,"SwitchCase"),t.cases.push(e=this.startNode()),e.consequent=[],this.next(),i?e.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,e.test=null),this.expect(u.colon)}else e||this.unexpected(),e.consequent.push(this.parseStatement(null));return this.exitScope(),e&&this.finishNode(e,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(t,"SwitchStatement")};b.parseThrowStatement=function(t){return this.next(),V.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),t.argument=this.parseExpression(),this.semicolon(),this.finishNode(t,"ThrowStatement")};var Zt=[];b.parseCatchClauseParam=function(){var t=this.parseBindingAtom(),e=t.type==="Identifier";return this.enterScope(e?ct:0),this.checkLValPattern(t,e?ht:Y),this.expect(u.parenR),t};b.parseTryStatement=function(t){if(this.next(),t.block=this.parseBlock(),t.handler=null,this.type===u._catch){var e=this.startNode();this.next(),this.eat(u.parenL)?e.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),e.param=null,this.enterScope(0)),e.body=this.parseBlock(!1),this.exitScope(),t.handler=this.finishNode(e,"CatchClause")}return t.finalizer=this.eat(u._finally)?this.parseBlock():null,!t.handler&&!t.finalizer&&this.raise(t.start,"Missing catch or finally clause"),this.finishNode(t,"TryStatement")};b.parseVarStatement=function(t,e,s){return this.next(),this.parseVar(t,!1,e,s),this.semicolon(),this.finishNode(t,"VariableDeclaration")};b.parseWhileStatement=function(t){return this.next(),t.test=this.parseParenExpression(),this.labels.push(ze),t.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(t,"WhileStatement")};b.parseWithStatement=function(t){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),t.object=this.parseParenExpression(),t.body=this.parseStatement("with"),this.finishNode(t,"WithStatement")};b.parseEmptyStatement=function(t){return this.next(),this.finishNode(t,"EmptyStatement")};b.parseLabeledStatement=function(t,e,s,i){for(var n=0,r=this.labels;n<r.length;n+=1){var a=r[n];a.name===e&&this.raise(s.start,"Label '"+e+"' is already declared")}for(var o=this.type.isLoop?"loop":this.type===u._switch?"switch":null,c=this.labels.length-1;c>=0;c--){var l=this.labels[c];if(l.statementStart===t.start)l.statementStart=this.start,l.kind=o;else break}return this.labels.push({name:e,kind:o,statementStart:this.start}),t.body=this.parseStatement(i?i.indexOf("label")===-1?i+"label":i:"label"),this.labels.pop(),t.label=s,this.finishNode(t,"LabeledStatement")};b.parseExpressionStatement=function(t,e){return t.expression=e,this.semicolon(),this.finishNode(t,"ExpressionStatement")};b.parseBlock=function(t,e,s){for(t===void 0&&(t=!0),e===void 0&&(e=this.startNode()),e.body=[],this.expect(u.braceL),t&&this.enterScope(0);this.type!==u.braceR;){var i=this.parseStatement(null);e.body.push(i)}return s&&(this.strict=!1),this.next(),t&&this.exitScope(),this.finishNode(e,"BlockStatement")};b.parseFor=function(t,e){return t.init=e,this.expect(u.semi),t.test=this.type===u.semi?null:this.parseExpression(),this.expect(u.semi),t.update=this.type===u.parenR?null:this.parseExpression(),this.expect(u.parenR),t.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(t,"ForStatement")};b.parseForIn=function(t,e){var s=this.type===u._in;return this.next(),e.type==="VariableDeclaration"&&e.declarations[0].init!=null&&(!s||this.options.ecmaVersion<8||this.strict||e.kind!=="var"||e.declarations[0].id.type!=="Identifier")&&this.raise(e.start,(s?"for-in":"for-of")+" loop variable declaration may not have an initializer"),t.left=e,t.right=s?this.parseExpression():this.parseMaybeAssign(),this.expect(u.parenR),t.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(t,s?"ForInStatement":"ForOfStatement")};b.parseVar=function(t,e,s,i){for(t.declarations=[],t.kind=s;;){var n=this.startNode();if(this.parseVarId(n,s),this.eat(u.eq)?n.init=this.parseMaybeAssign(e):!i&&s==="const"&&!(this.type===u._in||this.options.ecmaVersion>=6&&this.isContextual("of"))?this.unexpected():!i&&(s==="using"||s==="await using")&&this.options.ecmaVersion>=17&&this.type!==u._in&&!this.isContextual("of")?this.raise(this.lastTokEnd,"Missing initializer in "+s+" declaration"):!i&&n.id.type!=="Identifier"&&!(e&&(this.type===u._in||this.isContextual("of")))?this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):n.init=null,t.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(u.comma))break}return t};b.parseVarId=function(t,e){t.id=e==="using"||e==="await using"?this.parseIdent():this.parseBindingAtom(),this.checkLValPattern(t.id,e==="var"?He:Y,!1)};var de=1,Fe=2,ft=4;b.parseFunction=function(t,e,s,i,n){this.initFunction(t),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!i)&&(this.type===u.star&&e&Fe&&this.unexpected(),t.generator=this.eat(u.star)),this.options.ecmaVersion>=8&&(t.async=!!i),e&de&&(t.id=e&ft&&this.type!==u.name?null:this.parseIdent(),t.id&&!(e&Fe)&&this.checkLValSimple(t.id,this.strict||t.generator||t.async?this.treatFunctionsAsVar?He:Y:lt));var r=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(Ue(t.async,t.generator)),e&de||(t.id=this.type===u.name?this.parseIdent():null),this.parseFunctionParams(t),this.parseFunctionBody(t,s,!1,n),this.yieldPos=r,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(t,e&de?"FunctionDeclaration":"FunctionExpression")};b.parseFunctionParams=function(t){this.expect(u.parenL),t.params=this.parseBindingList(u.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()};b.parseClass=function(t,e){this.next();var s=this.strict;this.strict=!0,this.parseClassId(t,e),this.parseClassSuper(t);var i=this.enterClassBody(),n=this.startNode(),r=!1;for(n.body=[],this.expect(u.braceL);this.type!==u.braceR;){var a=this.parseClassElement(t.superClass!==null);a&&(n.body.push(a),a.type==="MethodDefinition"&&a.kind==="constructor"?(r&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),r=!0):a.key&&a.key.type==="PrivateIdentifier"&&Jt(i,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=s,this.next(),t.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(t,e?"ClassDeclaration":"ClassExpression")};b.parseClassElement=function(t){if(this.eat(u.semi))return null;var e=this.options.ecmaVersion,s=this.startNode(),i="",n=!1,r=!1,a="method",o=!1;if(this.eatContextual("static")){if(e>=13&&this.eat(u.braceL))return this.parseClassStaticBlock(s),s;this.isClassElementNameStart()||this.type===u.star?o=!0:i="static"}if(s.static=o,!i&&e>=8&&this.eatContextual("async")&&((this.isClassElementNameStart()||this.type===u.star)&&!this.canInsertSemicolon()?r=!0:i="async"),!i&&(e>=9||!r)&&this.eat(u.star)&&(n=!0),!i&&!r&&!n){var c=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=c:i=c)}if(i?(s.computed=!1,s.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),s.key.name=i,this.finishNode(s.key,"Identifier")):this.parseClassElementName(s),e<13||this.type===u.parenL||a!=="method"||n||r){var l=!s.static&&ye(s,"constructor"),h=l&&t;l&&a!=="method"&&this.raise(s.key.start,"Constructor can't have get/set modifier"),s.kind=l?"constructor":a,this.parseClassMethod(s,n,r,h)}else this.parseClassField(s);return s};b.isClassElementNameStart=function(){return this.type===u.name||this.type===u.privateId||this.type===u.num||this.type===u.string||this.type===u.bracketL||this.type.keyword};b.parseClassElementName=function(t){this.type===u.privateId?(this.value==="constructor"&&this.raise(this.start,"Classes can't have an element named '#constructor'"),t.computed=!1,t.key=this.parsePrivateIdent()):this.parsePropertyName(t)};b.parseClassMethod=function(t,e,s,i){var n=t.key;t.kind==="constructor"?(e&&this.raise(n.start,"Constructor can't be a generator"),s&&this.raise(n.start,"Constructor can't be an async method")):t.static&&ye(t,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var r=t.value=this.parseMethod(e,s,i);return t.kind==="get"&&r.params.length!==0&&this.raiseRecoverable(r.start,"getter should have no params"),t.kind==="set"&&r.params.length!==1&&this.raiseRecoverable(r.start,"setter should have exactly one param"),t.kind==="set"&&r.params[0].type==="RestElement"&&this.raiseRecoverable(r.params[0].start,"Setter cannot use rest params"),this.finishNode(t,"MethodDefinition")};b.parseClassField=function(t){return ye(t,"constructor")?this.raise(t.key.start,"Classes can't have a field named 'constructor'"):t.static&&ye(t,"prototype")&&this.raise(t.key.start,"Classes can't have a static field named 'prototype'"),this.eat(u.eq)?(this.enterScope(xe|we),t.value=this.parseMaybeAssign(),this.exitScope()):t.value=null,this.semicolon(),this.finishNode(t,"PropertyDefinition")};b.parseClassStaticBlock=function(t){t.body=[];var e=this.labels;for(this.labels=[],this.enterScope(ne|we);this.type!==u.braceR;){var s=this.parseStatement(null);t.body.push(s)}return this.next(),this.exitScope(),this.labels=e,this.finishNode(t,"StaticBlock")};b.parseClassId=function(t,e){this.type===u.name?(t.id=this.parseIdent(),e&&this.checkLValSimple(t.id,Y,!1)):(e===!0&&this.unexpected(),t.id=null)};b.parseClassSuper=function(t){t.superClass=this.eat(u._extends)?this.parseExprSubscripts(null,!1):null};b.enterClassBody=function(){var t={declared:Object.create(null),used:[]};return this.privateNameStack.push(t),t.declared};b.exitClassBody=function(){var t=this.privateNameStack.pop(),e=t.declared,s=t.used;if(this.options.checkPrivateFields)for(var i=this.privateNameStack.length,n=i===0?null:this.privateNameStack[i-1],r=0;r<s.length;++r){var a=s[r];le(e,a.name)||(n?n.used.push(a):this.raiseRecoverable(a.start,"Private field '#"+a.name+"' must be declared in an enclosing class"))}};function Jt(t,e){var s=e.key.name,i=t[s],n="true";return e.type==="MethodDefinition"&&(e.kind==="get"||e.kind==="set")&&(n=(e.static?"s":"i")+e.kind),i==="iget"&&n==="iset"||i==="iset"&&n==="iget"||i==="sget"&&n==="sset"||i==="sset"&&n==="sget"?(t[s]="true",!1):i?!0:(t[s]=n,!1)}function ye(t,e){var s=t.computed,i=t.key;return!s&&(i.type==="Identifier"&&i.name===e||i.type==="Literal"&&i.value===e)}b.parseExportAllDeclaration=function(t,e){return this.options.ecmaVersion>=11&&(this.eatContextual("as")?(t.exported=this.parseModuleExportName(),this.checkExport(e,t.exported,this.lastTokStart)):t.exported=null),this.expectContextual("from"),this.type!==u.string&&this.unexpected(),t.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(t.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(t,"ExportAllDeclaration")};b.parseExport=function(t,e){if(this.next(),this.eat(u.star))return this.parseExportAllDeclaration(t,e);if(this.eat(u._default))return this.checkExport(e,"default",this.lastTokStart),t.declaration=this.parseExportDefaultDeclaration(),this.finishNode(t,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())t.declaration=this.parseExportDeclaration(t),t.declaration.type==="VariableDeclaration"?this.checkVariableExport(e,t.declaration.declarations):this.checkExport(e,t.declaration.id,t.declaration.id.start),t.specifiers=[],t.source=null,this.options.ecmaVersion>=16&&(t.attributes=[]);else{if(t.declaration=null,t.specifiers=this.parseExportSpecifiers(e),this.eatContextual("from"))this.type!==u.string&&this.unexpected(),t.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(t.attributes=this.parseWithClause());else{for(var s=0,i=t.specifiers;s<i.length;s+=1){var n=i[s];this.checkUnreserved(n.local),this.checkLocalExport(n.local),n.local.type==="Literal"&&this.raise(n.local.start,"A string literal cannot be used as an exported binding without `from`.")}t.source=null,this.options.ecmaVersion>=16&&(t.attributes=[])}this.semicolon()}return this.finishNode(t,"ExportNamedDeclaration")};b.parseExportDeclaration=function(t){return this.parseStatement(null)};b.parseExportDefaultDeclaration=function(){var t;if(this.type===u._function||(t=this.isAsyncFunction())){var e=this.startNode();return this.next(),t&&this.next(),this.parseFunction(e,de|ft,!1,t)}else if(this.type===u._class){var s=this.startNode();return this.parseClass(s,"nullableID")}else{var i=this.parseMaybeAssign();return this.semicolon(),i}};b.checkExport=function(t,e,s){t&&(typeof e!="string"&&(e=e.type==="Identifier"?e.name:e.value),le(t,e)&&this.raiseRecoverable(s,"Duplicate export '"+e+"'"),t[e]=!0)};b.checkPatternExport=function(t,e){var s=e.type;if(s==="Identifier")this.checkExport(t,e,e.start);else if(s==="ObjectPattern")for(var i=0,n=e.properties;i<n.length;i+=1){var r=n[i];this.checkPatternExport(t,r)}else if(s==="ArrayPattern")for(var a=0,o=e.elements;a<o.length;a+=1){var c=o[a];c&&this.checkPatternExport(t,c)}else s==="Property"?this.checkPatternExport(t,e.value):s==="AssignmentPattern"?this.checkPatternExport(t,e.left):s==="RestElement"&&this.checkPatternExport(t,e.argument)};b.checkVariableExport=function(t,e){if(t)for(var s=0,i=e;s<i.length;s+=1){var n=i[s];this.checkPatternExport(t,n.id)}};b.shouldParseExportStatement=function(){return this.type.keyword==="var"||this.type.keyword==="const"||this.type.keyword==="class"||this.type.keyword==="function"||this.isLet()||this.isAsyncFunction()};b.parseExportSpecifier=function(t){var e=this.startNode();return e.local=this.parseModuleExportName(),e.exported=this.eatContextual("as")?this.parseModuleExportName():e.local,this.checkExport(t,e.exported,e.exported.start),this.finishNode(e,"ExportSpecifier")};b.parseExportSpecifiers=function(t){var e=[],s=!0;for(this.expect(u.braceL);!this.eat(u.braceR);){if(s)s=!1;else if(this.expect(u.comma),this.afterTrailingComma(u.braceR))break;e.push(this.parseExportSpecifier(t))}return e};b.parseImport=function(t){return this.next(),this.type===u.string?(t.specifiers=Zt,t.source=this.parseExprAtom()):(t.specifiers=this.parseImportSpecifiers(),this.expectContextual("from"),t.source=this.type===u.string?this.parseExprAtom():this.unexpected()),this.options.ecmaVersion>=16&&(t.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(t,"ImportDeclaration")};b.parseImportSpecifier=function(){var t=this.startNode();return t.imported=this.parseModuleExportName(),this.eatContextual("as")?t.local=this.parseIdent():(this.checkUnreserved(t.imported),t.local=t.imported),this.checkLValSimple(t.local,Y),this.finishNode(t,"ImportSpecifier")};b.parseImportDefaultSpecifier=function(){var t=this.startNode();return t.local=this.parseIdent(),this.checkLValSimple(t.local,Y),this.finishNode(t,"ImportDefaultSpecifier")};b.parseImportNamespaceSpecifier=function(){var t=this.startNode();return this.next(),this.expectContextual("as"),t.local=this.parseIdent(),this.checkLValSimple(t.local,Y),this.finishNode(t,"ImportNamespaceSpecifier")};b.parseImportSpecifiers=function(){var t=[],e=!0;if(this.type===u.name&&(t.push(this.parseImportDefaultSpecifier()),!this.eat(u.comma)))return t;if(this.type===u.star)return t.push(this.parseImportNamespaceSpecifier()),t;for(this.expect(u.braceL);!this.eat(u.braceR);){if(e)e=!1;else if(this.expect(u.comma),this.afterTrailingComma(u.braceR))break;t.push(this.parseImportSpecifier())}return t};b.parseWithClause=function(){var t=[];if(!this.eat(u._with))return t;this.expect(u.braceL);for(var e={},s=!0;!this.eat(u.braceR);){if(s)s=!1;else if(this.expect(u.comma),this.afterTrailingComma(u.braceR))break;var i=this.parseImportAttribute(),n=i.key.type==="Identifier"?i.key.name:i.key.value;le(e,n)&&this.raiseRecoverable(i.key.start,"Duplicate attribute key '"+n+"'"),e[n]=!0,t.push(i)}return t};b.parseImportAttribute=function(){var t=this.startNode();return t.key=this.type===u.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never"),this.expect(u.colon),this.type!==u.string&&this.unexpected(),t.value=this.parseExprAtom(),this.finishNode(t,"ImportAttribute")};b.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===u.string){var t=this.parseLiteral(this.value);return Xt.test(t.value)&&this.raise(t.start,"An export name cannot include a lone surrogate."),t}return this.parseIdent(!0)};b.adaptDirectivePrologue=function(t){for(var e=0;e<t.length&&this.isDirectiveCandidate(t[e]);++e)t[e].directive=t[e].expression.raw.slice(1,-1)};b.isDirectiveCandidate=function(t){return this.options.ecmaVersion>=5&&t.type==="ExpressionStatement"&&t.expression.type==="Literal"&&typeof t.expression.value=="string"&&(this.input[t.start]==='"'||this.input[t.start]==="'")};var j=I.prototype;j.toAssignable=function(t,e,s){if(this.options.ecmaVersion>=6&&t)switch(t.type){case"Identifier":this.inAsync&&t.name==="await"&&this.raise(t.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":t.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var i=0,n=t.properties;i<n.length;i+=1){var r=n[i];this.toAssignable(r,e),r.type==="RestElement"&&(r.argument.type==="ArrayPattern"||r.argument.type==="ObjectPattern")&&this.raise(r.argument.start,"Unexpected token")}break;case"Property":t.kind!=="init"&&this.raise(t.key.start,"Object pattern can't contain getter or setter"),this.toAssignable(t.value,e);break;case"ArrayExpression":t.type="ArrayPattern",s&&this.checkPatternErrors(s,!0),this.toAssignableList(t.elements,e);break;case"SpreadElement":t.type="RestElement",this.toAssignable(t.argument,e),t.argument.type==="AssignmentPattern"&&this.raise(t.argument.start,"Rest elements cannot have a default value");break;case"AssignmentExpression":t.operator!=="="&&this.raise(t.left.end,"Only '=' operator can be used for specifying default value."),t.type="AssignmentPattern",delete t.operator,this.toAssignable(t.left,e);break;case"ParenthesizedExpression":this.toAssignable(t.expression,e,s);break;case"ChainExpression":this.raiseRecoverable(t.start,"Optional chaining cannot appear in left-hand side");break;case"MemberExpression":if(!e)break;default:this.raise(t.start,"Assigning to rvalue")}else s&&this.checkPatternErrors(s,!0);return t};j.toAssignableList=function(t,e){for(var s=t.length,i=0;i<s;i++){var n=t[i];n&&this.toAssignable(n,e)}if(s){var r=t[s-1];this.options.ecmaVersion===6&&e&&r&&r.type==="RestElement"&&r.argument.type!=="Identifier"&&this.unexpected(r.argument.start)}return t};j.parseSpread=function(t){var e=this.startNode();return this.next(),e.argument=this.parseMaybeAssign(!1,t),this.finishNode(e,"SpreadElement")};j.parseRestBinding=function(){var t=this.startNode();return this.next(),this.options.ecmaVersion===6&&this.type!==u.name&&this.unexpected(),t.argument=this.parseBindingAtom(),this.finishNode(t,"RestElement")};j.parseBindingAtom=function(){if(this.options.ecmaVersion>=6)switch(this.type){case u.bracketL:var t=this.startNode();return this.next(),t.elements=this.parseBindingList(u.bracketR,!0,!0),this.finishNode(t,"ArrayPattern");case u.braceL:return this.parseObj(!0)}return this.parseIdent()};j.parseBindingList=function(t,e,s,i){for(var n=[],r=!0;!this.eat(t);)if(r?r=!1:this.expect(u.comma),e&&this.type===u.comma)n.push(null);else{if(s&&this.afterTrailingComma(t))break;if(this.type===u.ellipsis){var a=this.parseRestBinding();this.parseBindingListItem(a),n.push(a),this.type===u.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.expect(t);break}else n.push(this.parseAssignableListItem(i))}return n};j.parseAssignableListItem=function(t){var e=this.parseMaybeDefault(this.start,this.startLoc);return this.parseBindingListItem(e),e};j.parseBindingListItem=function(t){return t};j.parseMaybeDefault=function(t,e,s){if(s=s||this.parseBindingAtom(),this.options.ecmaVersion<6||!this.eat(u.eq))return s;var i=this.startNodeAt(t,e);return i.left=s,i.right=this.parseMaybeAssign(),this.finishNode(i,"AssignmentPattern")};j.checkLValSimple=function(t,e,s){e===void 0&&(e=Ce);var i=e!==Ce;switch(t.type){case"Identifier":this.strict&&this.reservedWordsStrictBind.test(t.name)&&this.raiseRecoverable(t.start,(i?"Binding ":"Assigning to ")+t.name+" in strict mode"),i&&(e===Y&&t.name==="let"&&this.raiseRecoverable(t.start,"let is disallowed as a lexically bound name"),s&&(le(s,t.name)&&this.raiseRecoverable(t.start,"Argument name clash"),s[t.name]=!0),e!==pt&&this.declareName(t.name,e,t.start));break;case"ChainExpression":this.raiseRecoverable(t.start,"Optional chaining cannot appear in left-hand side");break;case"MemberExpression":i&&this.raiseRecoverable(t.start,"Binding member expression");break;case"ParenthesizedExpression":return i&&this.raiseRecoverable(t.start,"Binding parenthesized expression"),this.checkLValSimple(t.expression,e,s);default:this.raise(t.start,(i?"Binding":"Assigning to")+" rvalue")}};j.checkLValPattern=function(t,e,s){switch(e===void 0&&(e=Ce),t.type){case"ObjectPattern":for(var i=0,n=t.properties;i<n.length;i+=1){var r=n[i];this.checkLValInnerPattern(r,e,s)}break;case"ArrayPattern":for(var a=0,o=t.elements;a<o.length;a+=1){var c=o[a];c&&this.checkLValInnerPattern(c,e,s)}break;default:this.checkLValSimple(t,e,s)}};j.checkLValInnerPattern=function(t,e,s){switch(e===void 0&&(e=Ce),t.type){case"Property":this.checkLValInnerPattern(t.value,e,s);break;case"AssignmentPattern":this.checkLValPattern(t.left,e,s);break;case"RestElement":this.checkLValPattern(t.argument,e,s);break;default:this.checkLValPattern(t,e,s)}};var W=function(e,s,i,n,r){this.token=e,this.isExpr=!!s,this.preserveSpace=!!i,this.override=n,this.generator=!!r},k={b_stat:new W("{",!1),b_expr:new W("{",!0),b_tmpl:new W("${",!1),p_stat:new W("(",!1),p_expr:new W("(",!0),q_tmpl:new W("`",!0,!0,function(t){return t.tryReadTemplateToken()}),f_stat:new W("function",!1),f_expr:new W("function",!0),f_expr_gen:new W("function",!0,!1,null,!0),f_gen:new W("function",!1,!1,null,!0)},pe=I.prototype;pe.initialContext=function(){return[k.b_stat]};pe.curContext=function(){return this.context[this.context.length-1]};pe.braceIsBlock=function(t){var e=this.curContext();return e===k.f_expr||e===k.f_stat?!0:t===u.colon&&(e===k.b_stat||e===k.b_expr)?!e.isExpr:t===u._return||t===u.name&&this.exprAllowed?V.test(this.input.slice(this.lastTokEnd,this.start)):t===u._else||t===u.semi||t===u.eof||t===u.parenR||t===u.arrow?!0:t===u.braceL?e===k.b_stat:t===u._var||t===u._const||t===u.name?!1:!this.exprAllowed};pe.inGeneratorContext=function(){for(var t=this.context.length-1;t>=1;t--){var e=this.context[t];if(e.token==="function")return e.generator}return!1};pe.updateContext=function(t){var e,s=this.type;s.keyword&&t===u.dot?this.exprAllowed=!1:(e=s.updateContext)?e.call(this,t):this.exprAllowed=s.beforeExpr};pe.overrideContext=function(t){this.curContext()!==t&&(this.context[this.context.length-1]=t)};u.parenR.updateContext=u.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=!0;return}var t=this.context.pop();t===k.b_stat&&this.curContext().token==="function"&&(t=this.context.pop()),this.exprAllowed=!t.isExpr};u.braceL.updateContext=function(t){this.context.push(this.braceIsBlock(t)?k.b_stat:k.b_expr),this.exprAllowed=!0};u.dollarBraceL.updateContext=function(){this.context.push(k.b_tmpl),this.exprAllowed=!0};u.parenL.updateContext=function(t){var e=t===u._if||t===u._for||t===u._with||t===u._while;this.context.push(e?k.p_stat:k.p_expr),this.exprAllowed=!0};u.incDec.updateContext=function(){};u._function.updateContext=u._class.updateContext=function(t){t.beforeExpr&&t!==u._else&&!(t===u.semi&&this.curContext()!==k.p_stat)&&!(t===u._return&&V.test(this.input.slice(this.lastTokEnd,this.start)))&&!((t===u.colon||t===u.braceL)&&this.curContext()===k.b_stat)?this.context.push(k.f_expr):this.context.push(k.f_stat),this.exprAllowed=!1};u.colon.updateContext=function(){this.curContext().token==="function"&&this.context.pop(),this.exprAllowed=!0};u.backQuote.updateContext=function(){this.curContext()===k.q_tmpl?this.context.pop():this.context.push(k.q_tmpl),this.exprAllowed=!1};u.star.updateContext=function(t){if(t===u._function){var e=this.context.length-1;this.context[e]===k.f_expr?this.context[e]=k.f_expr_gen:this.context[e]=k.f_gen}this.exprAllowed=!0};u.name.updateContext=function(t){var e=!1;this.options.ecmaVersion>=6&&t!==u.dot&&(this.value==="of"&&!this.exprAllowed||this.value==="yield"&&this.inGeneratorContext())&&(e=!0),this.exprAllowed=e};var v=I.prototype;v.checkPropClash=function(t,e,s){if(!(this.options.ecmaVersion>=9&&t.type==="SpreadElement")&&!(this.options.ecmaVersion>=6&&(t.computed||t.method||t.shorthand))){var i=t.key,n;switch(i.type){case"Identifier":n=i.name;break;case"Literal":n=String(i.value);break;default:return}var r=t.kind;if(this.options.ecmaVersion>=6){n==="__proto__"&&r==="init"&&(e.proto&&(s?s.doubleProto<0&&(s.doubleProto=i.start):this.raiseRecoverable(i.start,"Redefinition of __proto__ property")),e.proto=!0);return}n="$"+n;var a=e[n];if(a){var o;r==="init"?o=this.strict&&a.init||a.get||a.set:o=a.init||a[r],o&&this.raiseRecoverable(i.start,"Redefinition of property")}else a=e[n]={init:!1,get:!1,set:!1};a[r]=!0}};v.parseExpression=function(t,e){var s=this.start,i=this.startLoc,n=this.parseMaybeAssign(t,e);if(this.type===u.comma){var r=this.startNodeAt(s,i);for(r.expressions=[n];this.eat(u.comma);)r.expressions.push(this.parseMaybeAssign(t,e));return this.finishNode(r,"SequenceExpression")}return n};v.parseMaybeAssign=function(t,e,s){if(this.isContextual("yield")){if(this.inGenerator)return this.parseYield(t);this.exprAllowed=!1}var i=!1,n=-1,r=-1,a=-1;e?(n=e.parenthesizedAssign,r=e.trailingComma,a=e.doubleProto,e.parenthesizedAssign=e.trailingComma=-1):(e=new _e,i=!0);var o=this.start,c=this.startLoc;(this.type===u.parenL||this.type===u.name)&&(this.potentialArrowAt=this.start,this.potentialArrowInForAwait=t==="await");var l=this.parseMaybeConditional(t,e);if(s&&(l=s.call(this,l,o,c)),this.type.isAssign){var h=this.startNodeAt(o,c);return h.operator=this.value,this.type===u.eq&&(l=this.toAssignable(l,!1,e)),i||(e.parenthesizedAssign=e.trailingComma=e.doubleProto=-1),e.shorthandAssign>=l.start&&(e.shorthandAssign=-1),this.type===u.eq?this.checkLValPattern(l):this.checkLValSimple(l),h.left=l,this.next(),h.right=this.parseMaybeAssign(t),a>-1&&(e.doubleProto=a),this.finishNode(h,"AssignmentExpression")}else i&&this.checkExpressionErrors(e,!0);return n>-1&&(e.parenthesizedAssign=n),r>-1&&(e.trailingComma=r),l};v.parseMaybeConditional=function(t,e){var s=this.start,i=this.startLoc,n=this.parseExprOps(t,e);if(this.checkExpressionErrors(e))return n;if(this.eat(u.question)){var r=this.startNodeAt(s,i);return r.test=n,r.consequent=this.parseMaybeAssign(),this.expect(u.colon),r.alternate=this.parseMaybeAssign(t),this.finishNode(r,"ConditionalExpression")}return n};v.parseExprOps=function(t,e){var s=this.start,i=this.startLoc,n=this.parseMaybeUnary(e,!1,!1,t);return this.checkExpressionErrors(e)||n.start===s&&n.type==="ArrowFunctionExpression"?n:this.parseExprOp(n,s,i,-1,t)};v.parseExprOp=function(t,e,s,i,n){var r=this.type.binop;if(r!=null&&(!n||this.type!==u._in)&&r>i){var a=this.type===u.logicalOR||this.type===u.logicalAND,o=this.type===u.coalesce;o&&(r=u.logicalAND.binop);var c=this.value;this.next();var l=this.start,h=this.startLoc,p=this.parseExprOp(this.parseMaybeUnary(null,!1,!1,n),l,h,r,n),f=this.buildBinary(e,s,t,p,c,a||o);return(a&&this.type===u.coalesce||o&&(this.type===u.logicalOR||this.type===u.logicalAND))&&this.raiseRecoverable(this.start,"Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"),this.parseExprOp(f,e,s,i,n)}return t};v.buildBinary=function(t,e,s,i,n,r){i.type==="PrivateIdentifier"&&this.raise(i.start,"Private identifier can only be left side of binary expression");var a=this.startNodeAt(t,e);return a.left=s,a.operator=n,a.right=i,this.finishNode(a,r?"LogicalExpression":"BinaryExpression")};v.parseMaybeUnary=function(t,e,s,i){var n=this.start,r=this.startLoc,a;if(this.isContextual("await")&&this.canAwait)a=this.parseAwait(i),e=!0;else if(this.type.prefix){var o=this.startNode(),c=this.type===u.incDec;o.operator=this.value,o.prefix=!0,this.next(),o.argument=this.parseMaybeUnary(null,!0,c,i),this.checkExpressionErrors(t,!0),c?this.checkLValSimple(o.argument):this.strict&&o.operator==="delete"&&dt(o.argument)?this.raiseRecoverable(o.start,"Deleting local variable in strict mode"):o.operator==="delete"&&De(o.argument)?this.raiseRecoverable(o.start,"Private fields can not be deleted"):e=!0,a=this.finishNode(o,c?"UpdateExpression":"UnaryExpression")}else if(!e&&this.type===u.privateId)(i||this.privateNameStack.length===0)&&this.options.checkPrivateFields&&this.unexpected(),a=this.parsePrivateIdent(),this.type!==u._in&&this.unexpected();else{if(a=this.parseExprSubscripts(t,i),this.checkExpressionErrors(t))return a;for(;this.type.postfix&&!this.canInsertSemicolon();){var l=this.startNodeAt(n,r);l.operator=this.value,l.prefix=!1,l.argument=a,this.checkLValSimple(a),this.next(),a=this.finishNode(l,"UpdateExpression")}}if(!s&&this.eat(u.starstar))if(e)this.unexpected(this.lastTokStart);else return this.buildBinary(n,r,a,this.parseMaybeUnary(null,!1,!1,i),"**",!1);else return a};function dt(t){return t.type==="Identifier"||t.type==="ParenthesizedExpression"&&dt(t.expression)}function De(t){return t.type==="MemberExpression"&&t.property.type==="PrivateIdentifier"||t.type==="ChainExpression"&&De(t.expression)||t.type==="ParenthesizedExpression"&&De(t.expression)}v.parseExprSubscripts=function(t,e){var s=this.start,i=this.startLoc,n=this.parseExprAtom(t,e);if(n.type==="ArrowFunctionExpression"&&this.input.slice(this.lastTokStart,this.lastTokEnd)!==")")return n;var r=this.parseSubscripts(n,s,i,!1,e);return t&&r.type==="MemberExpression"&&(t.parenthesizedAssign>=r.start&&(t.parenthesizedAssign=-1),t.parenthesizedBind>=r.start&&(t.parenthesizedBind=-1),t.trailingComma>=r.start&&(t.trailingComma=-1)),r};v.parseSubscripts=function(t,e,s,i,n){for(var r=this.options.ecmaVersion>=8&&t.type==="Identifier"&&t.name==="async"&&this.lastTokEnd===t.end&&!this.canInsertSemicolon()&&t.end-t.start===5&&this.potentialArrowAt===t.start,a=!1;;){var o=this.parseSubscript(t,e,s,i,r,a,n);if(o.optional&&(a=!0),o===t||o.type==="ArrowFunctionExpression"){if(a){var c=this.startNodeAt(e,s);c.expression=o,o=this.finishNode(c,"ChainExpression")}return o}t=o}};v.shouldParseAsyncArrow=function(){return!this.canInsertSemicolon()&&this.eat(u.arrow)};v.parseSubscriptAsyncArrow=function(t,e,s,i){return this.parseArrowExpression(this.startNodeAt(t,e),s,!0,i)};v.parseSubscript=function(t,e,s,i,n,r,a){var o=this.options.ecmaVersion>=11,c=o&&this.eat(u.questionDot);i&&c&&this.raise(this.lastTokStart,"Optional chaining cannot appear in the callee of new expressions");var l=this.eat(u.bracketL);if(l||c&&this.type!==u.parenL&&this.type!==u.backQuote||this.eat(u.dot)){var h=this.startNodeAt(e,s);h.object=t,l?(h.property=this.parseExpression(),this.expect(u.bracketR)):this.type===u.privateId&&t.type!=="Super"?h.property=this.parsePrivateIdent():h.property=this.parseIdent(this.options.allowReserved!=="never"),h.computed=!!l,o&&(h.optional=c),t=this.finishNode(h,"MemberExpression")}else if(!i&&this.eat(u.parenL)){var p=new _e,f=this.yieldPos,m=this.awaitPos,x=this.awaitIdentPos;this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0;var C=this.parseExprList(u.parenR,this.options.ecmaVersion>=8,!1,p);if(n&&!c&&this.shouldParseAsyncArrow())return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.awaitIdentPos>0&&this.raise(this.awaitIdentPos,"Cannot use 'await' as identifier inside an async function"),this.yieldPos=f,this.awaitPos=m,this.awaitIdentPos=x,this.parseSubscriptAsyncArrow(e,s,C,a);this.checkExpressionErrors(p,!0),this.yieldPos=f||this.yieldPos,this.awaitPos=m||this.awaitPos,this.awaitIdentPos=x||this.awaitIdentPos;var S=this.startNodeAt(e,s);S.callee=t,S.arguments=C,o&&(S.optional=c),t=this.finishNode(S,"CallExpression")}else if(this.type===u.backQuote){(c||r)&&this.raise(this.start,"Optional chaining cannot appear in the tag of tagged template expressions");var P=this.startNodeAt(e,s);P.tag=t,P.quasi=this.parseTemplate({isTagged:!0}),t=this.finishNode(P,"TaggedTemplateExpression")}return t};v.parseExprAtom=function(t,e,s){this.type===u.slash&&this.readRegexp();var i,n=this.potentialArrowAt===this.start;switch(this.type){case u._super:return this.allowSuper||this.raise(this.start,"'super' keyword outside a method"),i=this.startNode(),this.next(),this.type===u.parenL&&!this.allowDirectSuper&&this.raise(i.start,"super() call outside constructor of a subclass"),this.type!==u.dot&&this.type!==u.bracketL&&this.type!==u.parenL&&this.unexpected(),this.finishNode(i,"Super");case u._this:return i=this.startNode(),this.next(),this.finishNode(i,"ThisExpression");case u.name:var r=this.start,a=this.startLoc,o=this.containsEsc,c=this.parseIdent(!1);if(this.options.ecmaVersion>=8&&!o&&c.name==="async"&&!this.canInsertSemicolon()&&this.eat(u._function))return this.overrideContext(k.f_expr),this.parseFunction(this.startNodeAt(r,a),0,!1,!0,e);if(n&&!this.canInsertSemicolon()){if(this.eat(u.arrow))return this.parseArrowExpression(this.startNodeAt(r,a),[c],!1,e);if(this.options.ecmaVersion>=8&&c.name==="async"&&this.type===u.name&&!o&&(!this.potentialArrowInForAwait||this.value!=="of"||this.containsEsc))return c=this.parseIdent(!1),(this.canInsertSemicolon()||!this.eat(u.arrow))&&this.unexpected(),this.parseArrowExpression(this.startNodeAt(r,a),[c],!0,e)}return c;case u.regexp:var l=this.value;return i=this.parseLiteral(l.value),i.regex={pattern:l.pattern,flags:l.flags},i;case u.num:case u.string:return this.parseLiteral(this.value);case u._null:case u._true:case u._false:return i=this.startNode(),i.value=this.type===u._null?null:this.type===u._true,i.raw=this.type.keyword,this.next(),this.finishNode(i,"Literal");case u.parenL:var h=this.start,p=this.parseParenAndDistinguishExpression(n,e);return t&&(t.parenthesizedAssign<0&&!this.isSimpleAssignTarget(p)&&(t.parenthesizedAssign=h),t.parenthesizedBind<0&&(t.parenthesizedBind=h)),p;case u.bracketL:return i=this.startNode(),this.next(),i.elements=this.parseExprList(u.bracketR,!0,!0,t),this.finishNode(i,"ArrayExpression");case u.braceL:return this.overrideContext(k.b_expr),this.parseObj(!1,t);case u._function:return i=this.startNode(),this.next(),this.parseFunction(i,0);case u._class:return this.parseClass(this.startNode(),!1);case u._new:return this.parseNew();case u.backQuote:return this.parseTemplate();case u._import:return this.options.ecmaVersion>=11?this.parseExprImport(s):this.unexpected();default:return this.parseExprAtomDefault()}};v.parseExprAtomDefault=function(){this.unexpected()};v.parseExprImport=function(t){var e=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===u.parenL&&!t)return this.parseDynamicImport(e);if(this.type===u.dot){var s=this.startNodeAt(e.start,e.loc&&e.loc.start);return s.name="import",e.meta=this.finishNode(s,"Identifier"),this.parseImportMeta(e)}else this.unexpected()};v.parseDynamicImport=function(t){if(this.next(),t.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(u.parenR)?t.options=null:(this.expect(u.comma),this.afterTrailingComma(u.parenR)?t.options=null:(t.options=this.parseMaybeAssign(),this.eat(u.parenR)||(this.expect(u.comma),this.afterTrailingComma(u.parenR)||this.unexpected())));else if(!this.eat(u.parenR)){var e=this.start;this.eat(u.comma)&&this.eat(u.parenR)?this.raiseRecoverable(e,"Trailing comma is not allowed in import()"):this.unexpected(e)}return this.finishNode(t,"ImportExpression")};v.parseImportMeta=function(t){this.next();var e=this.containsEsc;return t.property=this.parseIdent(!0),t.property.name!=="meta"&&this.raiseRecoverable(t.property.start,"The only valid meta property for import is 'import.meta'"),e&&this.raiseRecoverable(t.start,"'import.meta' must not contain escaped characters"),this.options.sourceType!=="module"&&!this.options.allowImportExportEverywhere&&this.raiseRecoverable(t.start,"Cannot use 'import.meta' outside a module"),this.finishNode(t,"MetaProperty")};v.parseLiteral=function(t){var e=this.startNode();return e.value=t,e.raw=this.input.slice(this.start,this.end),e.raw.charCodeAt(e.raw.length-1)===110&&(e.bigint=e.value!=null?e.value.toString():e.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(e,"Literal")};v.parseParenExpression=function(){this.expect(u.parenL);var t=this.parseExpression();return this.expect(u.parenR),t};v.shouldParseArrow=function(t){return!this.canInsertSemicolon()};v.parseParenAndDistinguishExpression=function(t,e){var s=this.start,i=this.startLoc,n,r=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a=this.start,o=this.startLoc,c=[],l=!0,h=!1,p=new _e,f=this.yieldPos,m=this.awaitPos,x;for(this.yieldPos=0,this.awaitPos=0;this.type!==u.parenR;)if(l?l=!1:this.expect(u.comma),r&&this.afterTrailingComma(u.parenR,!0)){h=!0;break}else if(this.type===u.ellipsis){x=this.start,c.push(this.parseParenItem(this.parseRestBinding())),this.type===u.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}else c.push(this.parseMaybeAssign(!1,p,this.parseParenItem));var C=this.lastTokEnd,S=this.lastTokEndLoc;if(this.expect(u.parenR),t&&this.shouldParseArrow(c)&&this.eat(u.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=f,this.awaitPos=m,this.parseParenArrowList(s,i,c,e);(!c.length||h)&&this.unexpected(this.lastTokStart),x&&this.unexpected(x),this.checkExpressionErrors(p,!0),this.yieldPos=f||this.yieldPos,this.awaitPos=m||this.awaitPos,c.length>1?(n=this.startNodeAt(a,o),n.expressions=c,this.finishNodeAt(n,"SequenceExpression",C,S)):n=c[0]}else n=this.parseParenExpression();if(this.options.preserveParens){var P=this.startNodeAt(s,i);return P.expression=n,this.finishNode(P,"ParenthesizedExpression")}else return n};v.parseParenItem=function(t){return t};v.parseParenArrowList=function(t,e,s,i){return this.parseArrowExpression(this.startNodeAt(t,e),s,!1,i)};var es=[];v.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var t=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===u.dot){var e=this.startNodeAt(t.start,t.loc&&t.loc.start);e.name="new",t.meta=this.finishNode(e,"Identifier"),this.next();var s=this.containsEsc;return t.property=this.parseIdent(!0),t.property.name!=="target"&&this.raiseRecoverable(t.property.start,"The only valid meta property for new is 'new.target'"),s&&this.raiseRecoverable(t.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(t.start,"'new.target' can only be used in functions and class static block"),this.finishNode(t,"MetaProperty")}var i=this.start,n=this.startLoc;return t.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),i,n,!0,!1),this.eat(u.parenL)?t.arguments=this.parseExprList(u.parenR,this.options.ecmaVersion>=8,!1):t.arguments=es,this.finishNode(t,"NewExpression")};v.parseTemplateElement=function(t){var e=t.isTagged,s=this.startNode();return this.type===u.invalidTemplate?(e||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value.replace(/\r\n?/g,`
|
|
3
|
+
`,i-1)+1,this.curLine=this.input.slice(0,this.lineStart).split(V).length):(this.pos=this.lineStart=0,this.curLine=1),this.type=u.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule=e.sourceType==="module",this.strict=this.inModule||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),this.pos===0&&e.allowHashBang&&this.input.slice(0,2)==="#!"&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(ge),this.regexpState=null,this.privateNameStack=[]},X={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},inClassStaticBlock:{configurable:!0}};I.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)};X.inFunction.get=function(){return(this.currentVarScope().flags&he)>0};X.inGenerator.get=function(){return(this.currentVarScope().flags&ot)>0};X.inAsync.get=function(){return(this.currentVarScope().flags&je)>0};X.canAwait.get=function(){for(var t=this.scopeStack.length-1;t>=0;t--){var e=this.scopeStack[t],s=e.flags;if(s&(ne|xe))return!1;if(s&he)return(s&je)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction};X.allowSuper.get=function(){var t=this.currentThisScope(),e=t.flags;return(e&we)>0||this.options.allowSuperOutsideMethod};X.allowDirectSuper.get=function(){return(this.currentThisScope().flags&ut)>0};X.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};X.allowNewDotTarget.get=function(){for(var t=this.scopeStack.length-1;t>=0;t--){var e=this.scopeStack[t],s=e.flags;if(s&(ne|xe)||s&he&&!(s&We))return!0}return!1};X.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&ne)>0};I.extend=function(){for(var e=[],s=arguments.length;s--;)e[s]=arguments[s];for(var i=this,n=0;n<e.length;n++)i=e[n](i);return i};I.parse=function(e,s){return new this(s,e).parse()};I.parseExpressionAt=function(e,s,i){var n=new this(i,e,s);return n.nextToken(),n.parseExpression()};I.tokenizer=function(e,s){return new this(s,e)};Object.defineProperties(I.prototype,X);var R=I.prototype,Qt=/^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/;R.strictDirective=function(t){if(this.options.ecmaVersion<5)return!1;for(;;){N.lastIndex=t,t+=N.exec(this.input)[0].length;var e=Qt.exec(this.input.slice(t));if(!e)return!1;if((e[1]||e[2])==="use strict"){N.lastIndex=t+e[0].length;var s=N.exec(this.input),i=s.index+s[0].length,n=this.input.charAt(i);return n===";"||n==="}"||V.test(s[0])&&!(/[(`.[+\-/*%<>=,?^&]/.test(n)||n==="!"&&this.input.charAt(i+1)==="=")}t+=e[0].length,N.lastIndex=t,t+=N.exec(this.input)[0].length,this.input[t]===";"&&t++}};R.eat=function(t){return this.type===t?(this.next(),!0):!1};R.isContextual=function(t){return this.type===u.name&&this.value===t&&!this.containsEsc};R.eatContextual=function(t){return this.isContextual(t)?(this.next(),!0):!1};R.expectContextual=function(t){this.eatContextual(t)||this.unexpected()};R.canInsertSemicolon=function(){return this.type===u.eof||this.type===u.braceR||V.test(this.input.slice(this.lastTokEnd,this.start))};R.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0};R.semicolon=function(){!this.eat(u.semi)&&!this.insertSemicolon()&&this.unexpected()};R.afterTrailingComma=function(t,e){if(this.type===t)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),e||this.next(),!0};R.expect=function(t){this.eat(t)||this.unexpected()};R.unexpected=function(t){this.raise(t??this.start,"Unexpected token")};var _e=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};R.checkPatternErrors=function(t,e){if(t){t.trailingComma>-1&&this.raiseRecoverable(t.trailingComma,"Comma is not permitted after the rest element");var s=e?t.parenthesizedAssign:t.parenthesizedBind;s>-1&&this.raiseRecoverable(s,e?"Assigning to rvalue":"Parenthesized pattern")}};R.checkExpressionErrors=function(t,e){if(!t)return!1;var s=t.shorthandAssign,i=t.doubleProto;if(!e)return s>=0||i>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),i>=0&&this.raiseRecoverable(i,"Redefinition of __proto__ property")};R.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos<this.awaitPos)&&this.raise(this.yieldPos,"Yield expression cannot be a default value"),this.awaitPos&&this.raise(this.awaitPos,"Await expression cannot be a default value")};R.isSimpleAssignTarget=function(t){return t.type==="ParenthesizedExpression"?this.isSimpleAssignTarget(t.expression):t.type==="Identifier"||t.type==="MemberExpression"};var b=I.prototype;b.parseTopLevel=function(t){var e=Object.create(null);for(t.body||(t.body=[]);this.type!==u.eof;){var s=this.parseStatement(null,!0,e);t.body.push(s)}if(this.inModule)for(var i=0,n=Object.keys(this.undefinedExports);i<n.length;i+=1){var r=n[i];this.raiseRecoverable(this.undefinedExports[r].start,"Export '"+r+"' is not defined")}return this.adaptDirectivePrologue(t.body),this.next(),t.sourceType=this.options.sourceType,this.finishNode(t,"Program")};var ze={kind:"loop"},Yt={kind:"switch"};b.isLet=function(t){if(this.options.ecmaVersion<6||!this.isContextual("let"))return!1;N.lastIndex=this.pos;var e=N.exec(this.input),s=this.pos+e[0].length,i=this.input.charCodeAt(s);if(i===91||i===92)return!0;if(t)return!1;if(i===123||i>55295&&i<56320)return!0;if(q(i,!0)){for(var n=s+1;J(i=this.input.charCodeAt(n),!0);)++n;if(i===92||i>55295&&i<56320)return!0;var r=this.input.slice(s,n);if(!jt.test(r))return!0}return!1};b.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;N.lastIndex=this.pos;var t=N.exec(this.input),e=this.pos+t[0].length,s;return!V.test(this.input.slice(this.pos,e))&&this.input.slice(e,e+8)==="function"&&(e+8===this.input.length||!(J(s=this.input.charCodeAt(e+8))||s>55295&&s<56320))};b.isUsingKeyword=function(t,e){if(this.options.ecmaVersion<17||!this.isContextual(t?"await":"using"))return!1;N.lastIndex=this.pos;var s=N.exec(this.input),i=this.pos+s[0].length;if(V.test(this.input.slice(this.pos,i)))return!1;if(t){var n=i+5,r;if(this.input.slice(i,n)!=="using"||n===this.input.length||J(r=this.input.charCodeAt(n))||r>55295&&r<56320)return!1;N.lastIndex=n;var a=N.exec(this.input);if(a&&V.test(this.input.slice(n,n+a[0].length)))return!1}if(e){var o=i+2,c;if(this.input.slice(i,o)==="of"&&(o===this.input.length||!J(c=this.input.charCodeAt(o))&&!(c>55295&&c<56320)))return!1}var l=this.input.charCodeAt(i);return q(l,!0)||l===92};b.isAwaitUsing=function(t){return this.isUsingKeyword(!0,t)};b.isUsing=function(t){return this.isUsingKeyword(!1,t)};b.parseStatement=function(t,e,s){var i=this.type,n=this.startNode(),r;switch(this.isLet(t)&&(i=u._var,r="let"),i){case u._break:case u._continue:return this.parseBreakContinueStatement(n,i.keyword);case u._debugger:return this.parseDebuggerStatement(n);case u._do:return this.parseDoStatement(n);case u._for:return this.parseForStatement(n);case u._function:return t&&(this.strict||t!=="if"&&t!=="label")&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(n,!1,!t);case u._class:return t&&this.unexpected(),this.parseClass(n,!0);case u._if:return this.parseIfStatement(n);case u._return:return this.parseReturnStatement(n);case u._switch:return this.parseSwitchStatement(n);case u._throw:return this.parseThrowStatement(n);case u._try:return this.parseTryStatement(n);case u._const:case u._var:return r=r||this.value,t&&r!=="var"&&this.unexpected(),this.parseVarStatement(n,r);case u._while:return this.parseWhileStatement(n);case u._with:return this.parseWithStatement(n);case u.braceL:return this.parseBlock(!0,n);case u.semi:return this.parseEmptyStatement(n);case u._export:case u._import:if(this.options.ecmaVersion>10&&i===u._import){N.lastIndex=this.pos;var a=N.exec(this.input),o=this.pos+a[0].length,c=this.input.charCodeAt(o);if(c===40||c===46)return this.parseExpressionStatement(n,this.parseExpression())}return this.options.allowImportExportEverywhere||(e||this.raise(this.start,"'import' and 'export' may only appear at the top level"),this.inModule||this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")),i===u._import?this.parseImport(n):this.parseExport(n,s);default:if(this.isAsyncFunction())return t&&this.unexpected(),this.next(),this.parseFunctionStatement(n,!0,!t);var l=this.isAwaitUsing(!1)?"await using":this.isUsing(!1)?"using":null;if(l)return e&&this.options.sourceType==="script"&&this.raise(this.start,"Using declaration cannot appear in the top level when source type is `script`"),l==="await using"&&(this.canAwait||this.raise(this.start,"Await using cannot appear outside of async function"),this.next()),this.next(),this.parseVar(n,!1,l),this.semicolon(),this.finishNode(n,"VariableDeclaration");var h=this.value,p=this.parseExpression();return i===u.name&&p.type==="Identifier"&&this.eat(u.colon)?this.parseLabeledStatement(n,h,p,t):this.parseExpressionStatement(n,p)}};b.parseBreakContinueStatement=function(t,e){var s=e==="break";this.next(),this.eat(u.semi)||this.insertSemicolon()?t.label=null:this.type!==u.name?this.unexpected():(t.label=this.parseIdent(),this.semicolon());for(var i=0;i<this.labels.length;++i){var n=this.labels[i];if((t.label==null||n.name===t.label.name)&&(n.kind!=null&&(s||n.kind==="loop")||t.label&&s))break}return i===this.labels.length&&this.raise(t.start,"Unsyntactic "+e),this.finishNode(t,s?"BreakStatement":"ContinueStatement")};b.parseDebuggerStatement=function(t){return this.next(),this.semicolon(),this.finishNode(t,"DebuggerStatement")};b.parseDoStatement=function(t){return this.next(),this.labels.push(ze),t.body=this.parseStatement("do"),this.labels.pop(),this.expect(u._while),t.test=this.parseParenExpression(),this.options.ecmaVersion>=6?this.eat(u.semi):this.semicolon(),this.finishNode(t,"DoWhileStatement")};b.parseForStatement=function(t){this.next();var e=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;if(this.labels.push(ze),this.enterScope(0),this.expect(u.parenL),this.type===u.semi)return e>-1&&this.unexpected(e),this.parseFor(t,null);var s=this.isLet();if(this.type===u._var||this.type===u._const||s){var i=this.startNode(),n=s?"let":this.value;return this.next(),this.parseVar(i,!0,n),this.finishNode(i,"VariableDeclaration"),this.parseForAfterInit(t,i,e)}var r=this.isContextual("let"),a=!1,o=this.isUsing(!0)?"using":this.isAwaitUsing(!0)?"await using":null;if(o){var c=this.startNode();return this.next(),o==="await using"&&this.next(),this.parseVar(c,!0,o),this.finishNode(c,"VariableDeclaration"),this.parseForAfterInit(t,c,e)}var l=this.containsEsc,h=new _e,p=this.start,f=e>-1?this.parseExprSubscripts(h,"await"):this.parseExpression(!0,h);return this.type===u._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(e>-1?(this.type===u._in&&this.unexpected(e),t.await=!0):a&&this.options.ecmaVersion>=8&&(f.start===p&&!l&&f.type==="Identifier"&&f.name==="async"?this.unexpected():this.options.ecmaVersion>=9&&(t.await=!1)),r&&a&&this.raise(f.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(f,!1,h),this.checkLValPattern(f),this.parseForIn(t,f)):(this.checkExpressionErrors(h,!0),e>-1&&this.unexpected(e),this.parseFor(t,f))};b.parseForAfterInit=function(t,e,s){return(this.type===u._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&e.declarations.length===1?(this.options.ecmaVersion>=9&&(this.type===u._in?s>-1&&this.unexpected(s):t.await=s>-1),this.parseForIn(t,e)):(s>-1&&this.unexpected(s),this.parseFor(t,e))};b.parseFunctionStatement=function(t,e,s){return this.next(),this.parseFunction(t,de|(s?0:Fe),!1,e)};b.parseIfStatement=function(t){return this.next(),t.test=this.parseParenExpression(),t.consequent=this.parseStatement("if"),t.alternate=this.eat(u._else)?this.parseStatement("if"):null,this.finishNode(t,"IfStatement")};b.parseReturnStatement=function(t){return!this.inFunction&&!this.options.allowReturnOutsideFunction&&this.raise(this.start,"'return' outside of function"),this.next(),this.eat(u.semi)||this.insertSemicolon()?t.argument=null:(t.argument=this.parseExpression(),this.semicolon()),this.finishNode(t,"ReturnStatement")};b.parseSwitchStatement=function(t){this.next(),t.discriminant=this.parseParenExpression(),t.cases=[],this.expect(u.braceL),this.labels.push(Yt),this.enterScope(0);for(var e,s=!1;this.type!==u.braceR;)if(this.type===u._case||this.type===u._default){var i=this.type===u._case;e&&this.finishNode(e,"SwitchCase"),t.cases.push(e=this.startNode()),e.consequent=[],this.next(),i?e.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,e.test=null),this.expect(u.colon)}else e||this.unexpected(),e.consequent.push(this.parseStatement(null));return this.exitScope(),e&&this.finishNode(e,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(t,"SwitchStatement")};b.parseThrowStatement=function(t){return this.next(),V.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),t.argument=this.parseExpression(),this.semicolon(),this.finishNode(t,"ThrowStatement")};var Zt=[];b.parseCatchClauseParam=function(){var t=this.parseBindingAtom(),e=t.type==="Identifier";return this.enterScope(e?ct:0),this.checkLValPattern(t,e?ht:Y),this.expect(u.parenR),t};b.parseTryStatement=function(t){if(this.next(),t.block=this.parseBlock(),t.handler=null,this.type===u._catch){var e=this.startNode();this.next(),this.eat(u.parenL)?e.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),e.param=null,this.enterScope(0)),e.body=this.parseBlock(!1),this.exitScope(),t.handler=this.finishNode(e,"CatchClause")}return t.finalizer=this.eat(u._finally)?this.parseBlock():null,!t.handler&&!t.finalizer&&this.raise(t.start,"Missing catch or finally clause"),this.finishNode(t,"TryStatement")};b.parseVarStatement=function(t,e,s){return this.next(),this.parseVar(t,!1,e,s),this.semicolon(),this.finishNode(t,"VariableDeclaration")};b.parseWhileStatement=function(t){return this.next(),t.test=this.parseParenExpression(),this.labels.push(ze),t.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(t,"WhileStatement")};b.parseWithStatement=function(t){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),t.object=this.parseParenExpression(),t.body=this.parseStatement("with"),this.finishNode(t,"WithStatement")};b.parseEmptyStatement=function(t){return this.next(),this.finishNode(t,"EmptyStatement")};b.parseLabeledStatement=function(t,e,s,i){for(var n=0,r=this.labels;n<r.length;n+=1){var a=r[n];a.name===e&&this.raise(s.start,"Label '"+e+"' is already declared")}for(var o=this.type.isLoop?"loop":this.type===u._switch?"switch":null,c=this.labels.length-1;c>=0;c--){var l=this.labels[c];if(l.statementStart===t.start)l.statementStart=this.start,l.kind=o;else break}return this.labels.push({name:e,kind:o,statementStart:this.start}),t.body=this.parseStatement(i?i.indexOf("label")===-1?i+"label":i:"label"),this.labels.pop(),t.label=s,this.finishNode(t,"LabeledStatement")};b.parseExpressionStatement=function(t,e){return t.expression=e,this.semicolon(),this.finishNode(t,"ExpressionStatement")};b.parseBlock=function(t,e,s){for(t===void 0&&(t=!0),e===void 0&&(e=this.startNode()),e.body=[],this.expect(u.braceL),t&&this.enterScope(0);this.type!==u.braceR;){var i=this.parseStatement(null);e.body.push(i)}return s&&(this.strict=!1),this.next(),t&&this.exitScope(),this.finishNode(e,"BlockStatement")};b.parseFor=function(t,e){return t.init=e,this.expect(u.semi),t.test=this.type===u.semi?null:this.parseExpression(),this.expect(u.semi),t.update=this.type===u.parenR?null:this.parseExpression(),this.expect(u.parenR),t.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(t,"ForStatement")};b.parseForIn=function(t,e){var s=this.type===u._in;return this.next(),e.type==="VariableDeclaration"&&e.declarations[0].init!=null&&(!s||this.options.ecmaVersion<8||this.strict||e.kind!=="var"||e.declarations[0].id.type!=="Identifier")&&this.raise(e.start,(s?"for-in":"for-of")+" loop variable declaration may not have an initializer"),t.left=e,t.right=s?this.parseExpression():this.parseMaybeAssign(),this.expect(u.parenR),t.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(t,s?"ForInStatement":"ForOfStatement")};b.parseVar=function(t,e,s,i){for(t.declarations=[],t.kind=s;;){var n=this.startNode();if(this.parseVarId(n,s),this.eat(u.eq)?n.init=this.parseMaybeAssign(e):!i&&s==="const"&&!(this.type===u._in||this.options.ecmaVersion>=6&&this.isContextual("of"))?this.unexpected():!i&&(s==="using"||s==="await using")&&this.options.ecmaVersion>=17&&this.type!==u._in&&!this.isContextual("of")?this.raise(this.lastTokEnd,"Missing initializer in "+s+" declaration"):!i&&n.id.type!=="Identifier"&&!(e&&(this.type===u._in||this.isContextual("of")))?this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):n.init=null,t.declarations.push(this.finishNode(n,"VariableDeclarator")),!this.eat(u.comma))break}return t};b.parseVarId=function(t,e){t.id=e==="using"||e==="await using"?this.parseIdent():this.parseBindingAtom(),this.checkLValPattern(t.id,e==="var"?He:Y,!1)};var de=1,Fe=2,ft=4;b.parseFunction=function(t,e,s,i,n){this.initFunction(t),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!i)&&(this.type===u.star&&e&Fe&&this.unexpected(),t.generator=this.eat(u.star)),this.options.ecmaVersion>=8&&(t.async=!!i),e&de&&(t.id=e&ft&&this.type!==u.name?null:this.parseIdent(),t.id&&!(e&Fe)&&this.checkLValSimple(t.id,this.strict||t.generator||t.async?this.treatFunctionsAsVar?He:Y:lt));var r=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(Ue(t.async,t.generator)),e&de||(t.id=this.type===u.name?this.parseIdent():null),this.parseFunctionParams(t),this.parseFunctionBody(t,s,!1,n),this.yieldPos=r,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(t,e&de?"FunctionDeclaration":"FunctionExpression")};b.parseFunctionParams=function(t){this.expect(u.parenL),t.params=this.parseBindingList(u.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()};b.parseClass=function(t,e){this.next();var s=this.strict;this.strict=!0,this.parseClassId(t,e),this.parseClassSuper(t);var i=this.enterClassBody(),n=this.startNode(),r=!1;for(n.body=[],this.expect(u.braceL);this.type!==u.braceR;){var a=this.parseClassElement(t.superClass!==null);a&&(n.body.push(a),a.type==="MethodDefinition"&&a.kind==="constructor"?(r&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),r=!0):a.key&&a.key.type==="PrivateIdentifier"&&Jt(i,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=s,this.next(),t.body=this.finishNode(n,"ClassBody"),this.exitClassBody(),this.finishNode(t,e?"ClassDeclaration":"ClassExpression")};b.parseClassElement=function(t){if(this.eat(u.semi))return null;var e=this.options.ecmaVersion,s=this.startNode(),i="",n=!1,r=!1,a="method",o=!1;if(this.eatContextual("static")){if(e>=13&&this.eat(u.braceL))return this.parseClassStaticBlock(s),s;this.isClassElementNameStart()||this.type===u.star?o=!0:i="static"}if(s.static=o,!i&&e>=8&&this.eatContextual("async")&&((this.isClassElementNameStart()||this.type===u.star)&&!this.canInsertSemicolon()?r=!0:i="async"),!i&&(e>=9||!r)&&this.eat(u.star)&&(n=!0),!i&&!r&&!n){var c=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=c:i=c)}if(i?(s.computed=!1,s.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),s.key.name=i,this.finishNode(s.key,"Identifier")):this.parseClassElementName(s),e<13||this.type===u.parenL||a!=="method"||n||r){var l=!s.static&&ye(s,"constructor"),h=l&&t;l&&a!=="method"&&this.raise(s.key.start,"Constructor can't have get/set modifier"),s.kind=l?"constructor":a,this.parseClassMethod(s,n,r,h)}else this.parseClassField(s);return s};b.isClassElementNameStart=function(){return this.type===u.name||this.type===u.privateId||this.type===u.num||this.type===u.string||this.type===u.bracketL||this.type.keyword};b.parseClassElementName=function(t){this.type===u.privateId?(this.value==="constructor"&&this.raise(this.start,"Classes can't have an element named '#constructor'"),t.computed=!1,t.key=this.parsePrivateIdent()):this.parsePropertyName(t)};b.parseClassMethod=function(t,e,s,i){var n=t.key;t.kind==="constructor"?(e&&this.raise(n.start,"Constructor can't be a generator"),s&&this.raise(n.start,"Constructor can't be an async method")):t.static&&ye(t,"prototype")&&this.raise(n.start,"Classes may not have a static property named prototype");var r=t.value=this.parseMethod(e,s,i);return t.kind==="get"&&r.params.length!==0&&this.raiseRecoverable(r.start,"getter should have no params"),t.kind==="set"&&r.params.length!==1&&this.raiseRecoverable(r.start,"setter should have exactly one param"),t.kind==="set"&&r.params[0].type==="RestElement"&&this.raiseRecoverable(r.params[0].start,"Setter cannot use rest params"),this.finishNode(t,"MethodDefinition")};b.parseClassField=function(t){return ye(t,"constructor")?this.raise(t.key.start,"Classes can't have a field named 'constructor'"):t.static&&ye(t,"prototype")&&this.raise(t.key.start,"Classes can't have a static field named 'prototype'"),this.eat(u.eq)?(this.enterScope(xe|we),t.value=this.parseMaybeAssign(),this.exitScope()):t.value=null,this.semicolon(),this.finishNode(t,"PropertyDefinition")};b.parseClassStaticBlock=function(t){t.body=[];var e=this.labels;for(this.labels=[],this.enterScope(ne|we);this.type!==u.braceR;){var s=this.parseStatement(null);t.body.push(s)}return this.next(),this.exitScope(),this.labels=e,this.finishNode(t,"StaticBlock")};b.parseClassId=function(t,e){this.type===u.name?(t.id=this.parseIdent(),e&&this.checkLValSimple(t.id,Y,!1)):(e===!0&&this.unexpected(),t.id=null)};b.parseClassSuper=function(t){t.superClass=this.eat(u._extends)?this.parseExprSubscripts(null,!1):null};b.enterClassBody=function(){var t={declared:Object.create(null),used:[]};return this.privateNameStack.push(t),t.declared};b.exitClassBody=function(){var t=this.privateNameStack.pop(),e=t.declared,s=t.used;if(this.options.checkPrivateFields)for(var i=this.privateNameStack.length,n=i===0?null:this.privateNameStack[i-1],r=0;r<s.length;++r){var a=s[r];le(e,a.name)||(n?n.used.push(a):this.raiseRecoverable(a.start,"Private field '#"+a.name+"' must be declared in an enclosing class"))}};function Jt(t,e){var s=e.key.name,i=t[s],n="true";return e.type==="MethodDefinition"&&(e.kind==="get"||e.kind==="set")&&(n=(e.static?"s":"i")+e.kind),i==="iget"&&n==="iset"||i==="iset"&&n==="iget"||i==="sget"&&n==="sset"||i==="sset"&&n==="sget"?(t[s]="true",!1):i?!0:(t[s]=n,!1)}function ye(t,e){var s=t.computed,i=t.key;return!s&&(i.type==="Identifier"&&i.name===e||i.type==="Literal"&&i.value===e)}b.parseExportAllDeclaration=function(t,e){return this.options.ecmaVersion>=11&&(this.eatContextual("as")?(t.exported=this.parseModuleExportName(),this.checkExport(e,t.exported,this.lastTokStart)):t.exported=null),this.expectContextual("from"),this.type!==u.string&&this.unexpected(),t.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(t.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(t,"ExportAllDeclaration")};b.parseExport=function(t,e){if(this.next(),this.eat(u.star))return this.parseExportAllDeclaration(t,e);if(this.eat(u._default))return this.checkExport(e,"default",this.lastTokStart),t.declaration=this.parseExportDefaultDeclaration(),this.finishNode(t,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())t.declaration=this.parseExportDeclaration(t),t.declaration.type==="VariableDeclaration"?this.checkVariableExport(e,t.declaration.declarations):this.checkExport(e,t.declaration.id,t.declaration.id.start),t.specifiers=[],t.source=null,this.options.ecmaVersion>=16&&(t.attributes=[]);else{if(t.declaration=null,t.specifiers=this.parseExportSpecifiers(e),this.eatContextual("from"))this.type!==u.string&&this.unexpected(),t.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(t.attributes=this.parseWithClause());else{for(var s=0,i=t.specifiers;s<i.length;s+=1){var n=i[s];this.checkUnreserved(n.local),this.checkLocalExport(n.local),n.local.type==="Literal"&&this.raise(n.local.start,"A string literal cannot be used as an exported binding without `from`.")}t.source=null,this.options.ecmaVersion>=16&&(t.attributes=[])}this.semicolon()}return this.finishNode(t,"ExportNamedDeclaration")};b.parseExportDeclaration=function(t){return this.parseStatement(null)};b.parseExportDefaultDeclaration=function(){var t;if(this.type===u._function||(t=this.isAsyncFunction())){var e=this.startNode();return this.next(),t&&this.next(),this.parseFunction(e,de|ft,!1,t)}else if(this.type===u._class){var s=this.startNode();return this.parseClass(s,"nullableID")}else{var i=this.parseMaybeAssign();return this.semicolon(),i}};b.checkExport=function(t,e,s){t&&(typeof e!="string"&&(e=e.type==="Identifier"?e.name:e.value),le(t,e)&&this.raiseRecoverable(s,"Duplicate export '"+e+"'"),t[e]=!0)};b.checkPatternExport=function(t,e){var s=e.type;if(s==="Identifier")this.checkExport(t,e,e.start);else if(s==="ObjectPattern")for(var i=0,n=e.properties;i<n.length;i+=1){var r=n[i];this.checkPatternExport(t,r)}else if(s==="ArrayPattern")for(var a=0,o=e.elements;a<o.length;a+=1){var c=o[a];c&&this.checkPatternExport(t,c)}else s==="Property"?this.checkPatternExport(t,e.value):s==="AssignmentPattern"?this.checkPatternExport(t,e.left):s==="RestElement"&&this.checkPatternExport(t,e.argument)};b.checkVariableExport=function(t,e){if(t)for(var s=0,i=e;s<i.length;s+=1){var n=i[s];this.checkPatternExport(t,n.id)}};b.shouldParseExportStatement=function(){return this.type.keyword==="var"||this.type.keyword==="const"||this.type.keyword==="class"||this.type.keyword==="function"||this.isLet()||this.isAsyncFunction()};b.parseExportSpecifier=function(t){var e=this.startNode();return e.local=this.parseModuleExportName(),e.exported=this.eatContextual("as")?this.parseModuleExportName():e.local,this.checkExport(t,e.exported,e.exported.start),this.finishNode(e,"ExportSpecifier")};b.parseExportSpecifiers=function(t){var e=[],s=!0;for(this.expect(u.braceL);!this.eat(u.braceR);){if(s)s=!1;else if(this.expect(u.comma),this.afterTrailingComma(u.braceR))break;e.push(this.parseExportSpecifier(t))}return e};b.parseImport=function(t){return this.next(),this.type===u.string?(t.specifiers=Zt,t.source=this.parseExprAtom()):(t.specifiers=this.parseImportSpecifiers(),this.expectContextual("from"),t.source=this.type===u.string?this.parseExprAtom():this.unexpected()),this.options.ecmaVersion>=16&&(t.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(t,"ImportDeclaration")};b.parseImportSpecifier=function(){var t=this.startNode();return t.imported=this.parseModuleExportName(),this.eatContextual("as")?t.local=this.parseIdent():(this.checkUnreserved(t.imported),t.local=t.imported),this.checkLValSimple(t.local,Y),this.finishNode(t,"ImportSpecifier")};b.parseImportDefaultSpecifier=function(){var t=this.startNode();return t.local=this.parseIdent(),this.checkLValSimple(t.local,Y),this.finishNode(t,"ImportDefaultSpecifier")};b.parseImportNamespaceSpecifier=function(){var t=this.startNode();return this.next(),this.expectContextual("as"),t.local=this.parseIdent(),this.checkLValSimple(t.local,Y),this.finishNode(t,"ImportNamespaceSpecifier")};b.parseImportSpecifiers=function(){var t=[],e=!0;if(this.type===u.name&&(t.push(this.parseImportDefaultSpecifier()),!this.eat(u.comma)))return t;if(this.type===u.star)return t.push(this.parseImportNamespaceSpecifier()),t;for(this.expect(u.braceL);!this.eat(u.braceR);){if(e)e=!1;else if(this.expect(u.comma),this.afterTrailingComma(u.braceR))break;t.push(this.parseImportSpecifier())}return t};b.parseWithClause=function(){var t=[];if(!this.eat(u._with))return t;this.expect(u.braceL);for(var e={},s=!0;!this.eat(u.braceR);){if(s)s=!1;else if(this.expect(u.comma),this.afterTrailingComma(u.braceR))break;var i=this.parseImportAttribute(),n=i.key.type==="Identifier"?i.key.name:i.key.value;le(e,n)&&this.raiseRecoverable(i.key.start,"Duplicate attribute key '"+n+"'"),e[n]=!0,t.push(i)}return t};b.parseImportAttribute=function(){var t=this.startNode();return t.key=this.type===u.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never"),this.expect(u.colon),this.type!==u.string&&this.unexpected(),t.value=this.parseExprAtom(),this.finishNode(t,"ImportAttribute")};b.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===u.string){var t=this.parseLiteral(this.value);return Xt.test(t.value)&&this.raise(t.start,"An export name cannot include a lone surrogate."),t}return this.parseIdent(!0)};b.adaptDirectivePrologue=function(t){for(var e=0;e<t.length&&this.isDirectiveCandidate(t[e]);++e)t[e].directive=t[e].expression.raw.slice(1,-1)};b.isDirectiveCandidate=function(t){return this.options.ecmaVersion>=5&&t.type==="ExpressionStatement"&&t.expression.type==="Literal"&&typeof t.expression.value=="string"&&(this.input[t.start]==='"'||this.input[t.start]==="'")};var j=I.prototype;j.toAssignable=function(t,e,s){if(this.options.ecmaVersion>=6&&t)switch(t.type){case"Identifier":this.inAsync&&t.name==="await"&&this.raise(t.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":t.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var i=0,n=t.properties;i<n.length;i+=1){var r=n[i];this.toAssignable(r,e),r.type==="RestElement"&&(r.argument.type==="ArrayPattern"||r.argument.type==="ObjectPattern")&&this.raise(r.argument.start,"Unexpected token")}break;case"Property":t.kind!=="init"&&this.raise(t.key.start,"Object pattern can't contain getter or setter"),this.toAssignable(t.value,e);break;case"ArrayExpression":t.type="ArrayPattern",s&&this.checkPatternErrors(s,!0),this.toAssignableList(t.elements,e);break;case"SpreadElement":t.type="RestElement",this.toAssignable(t.argument,e),t.argument.type==="AssignmentPattern"&&this.raise(t.argument.start,"Rest elements cannot have a default value");break;case"AssignmentExpression":t.operator!=="="&&this.raise(t.left.end,"Only '=' operator can be used for specifying default value."),t.type="AssignmentPattern",delete t.operator,this.toAssignable(t.left,e);break;case"ParenthesizedExpression":this.toAssignable(t.expression,e,s);break;case"ChainExpression":this.raiseRecoverable(t.start,"Optional chaining cannot appear in left-hand side");break;case"MemberExpression":if(!e)break;default:this.raise(t.start,"Assigning to rvalue")}else s&&this.checkPatternErrors(s,!0);return t};j.toAssignableList=function(t,e){for(var s=t.length,i=0;i<s;i++){var n=t[i];n&&this.toAssignable(n,e)}if(s){var r=t[s-1];this.options.ecmaVersion===6&&e&&r&&r.type==="RestElement"&&r.argument.type!=="Identifier"&&this.unexpected(r.argument.start)}return t};j.parseSpread=function(t){var e=this.startNode();return this.next(),e.argument=this.parseMaybeAssign(!1,t),this.finishNode(e,"SpreadElement")};j.parseRestBinding=function(){var t=this.startNode();return this.next(),this.options.ecmaVersion===6&&this.type!==u.name&&this.unexpected(),t.argument=this.parseBindingAtom(),this.finishNode(t,"RestElement")};j.parseBindingAtom=function(){if(this.options.ecmaVersion>=6)switch(this.type){case u.bracketL:var t=this.startNode();return this.next(),t.elements=this.parseBindingList(u.bracketR,!0,!0),this.finishNode(t,"ArrayPattern");case u.braceL:return this.parseObj(!0)}return this.parseIdent()};j.parseBindingList=function(t,e,s,i){for(var n=[],r=!0;!this.eat(t);)if(r?r=!1:this.expect(u.comma),e&&this.type===u.comma)n.push(null);else{if(s&&this.afterTrailingComma(t))break;if(this.type===u.ellipsis){var a=this.parseRestBinding();this.parseBindingListItem(a),n.push(a),this.type===u.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.expect(t);break}else n.push(this.parseAssignableListItem(i))}return n};j.parseAssignableListItem=function(t){var e=this.parseMaybeDefault(this.start,this.startLoc);return this.parseBindingListItem(e),e};j.parseBindingListItem=function(t){return t};j.parseMaybeDefault=function(t,e,s){if(s=s||this.parseBindingAtom(),this.options.ecmaVersion<6||!this.eat(u.eq))return s;var i=this.startNodeAt(t,e);return i.left=s,i.right=this.parseMaybeAssign(),this.finishNode(i,"AssignmentPattern")};j.checkLValSimple=function(t,e,s){e===void 0&&(e=Ce);var i=e!==Ce;switch(t.type){case"Identifier":this.strict&&this.reservedWordsStrictBind.test(t.name)&&this.raiseRecoverable(t.start,(i?"Binding ":"Assigning to ")+t.name+" in strict mode"),i&&(e===Y&&t.name==="let"&&this.raiseRecoverable(t.start,"let is disallowed as a lexically bound name"),s&&(le(s,t.name)&&this.raiseRecoverable(t.start,"Argument name clash"),s[t.name]=!0),e!==pt&&this.declareName(t.name,e,t.start));break;case"ChainExpression":this.raiseRecoverable(t.start,"Optional chaining cannot appear in left-hand side");break;case"MemberExpression":i&&this.raiseRecoverable(t.start,"Binding member expression");break;case"ParenthesizedExpression":return i&&this.raiseRecoverable(t.start,"Binding parenthesized expression"),this.checkLValSimple(t.expression,e,s);default:this.raise(t.start,(i?"Binding":"Assigning to")+" rvalue")}};j.checkLValPattern=function(t,e,s){switch(e===void 0&&(e=Ce),t.type){case"ObjectPattern":for(var i=0,n=t.properties;i<n.length;i+=1){var r=n[i];this.checkLValInnerPattern(r,e,s)}break;case"ArrayPattern":for(var a=0,o=t.elements;a<o.length;a+=1){var c=o[a];c&&this.checkLValInnerPattern(c,e,s)}break;default:this.checkLValSimple(t,e,s)}};j.checkLValInnerPattern=function(t,e,s){switch(e===void 0&&(e=Ce),t.type){case"Property":this.checkLValInnerPattern(t.value,e,s);break;case"AssignmentPattern":this.checkLValPattern(t.left,e,s);break;case"RestElement":this.checkLValPattern(t.argument,e,s);break;default:this.checkLValPattern(t,e,s)}};var H=function(e,s,i,n,r){this.token=e,this.isExpr=!!s,this.preserveSpace=!!i,this.override=n,this.generator=!!r},k={b_stat:new H("{",!1),b_expr:new H("{",!0),b_tmpl:new H("${",!1),p_stat:new H("(",!1),p_expr:new H("(",!0),q_tmpl:new H("`",!0,!0,function(t){return t.tryReadTemplateToken()}),f_stat:new H("function",!1),f_expr:new H("function",!0),f_expr_gen:new H("function",!0,!1,null,!0),f_gen:new H("function",!1,!1,null,!0)},pe=I.prototype;pe.initialContext=function(){return[k.b_stat]};pe.curContext=function(){return this.context[this.context.length-1]};pe.braceIsBlock=function(t){var e=this.curContext();return e===k.f_expr||e===k.f_stat?!0:t===u.colon&&(e===k.b_stat||e===k.b_expr)?!e.isExpr:t===u._return||t===u.name&&this.exprAllowed?V.test(this.input.slice(this.lastTokEnd,this.start)):t===u._else||t===u.semi||t===u.eof||t===u.parenR||t===u.arrow?!0:t===u.braceL?e===k.b_stat:t===u._var||t===u._const||t===u.name?!1:!this.exprAllowed};pe.inGeneratorContext=function(){for(var t=this.context.length-1;t>=1;t--){var e=this.context[t];if(e.token==="function")return e.generator}return!1};pe.updateContext=function(t){var e,s=this.type;s.keyword&&t===u.dot?this.exprAllowed=!1:(e=s.updateContext)?e.call(this,t):this.exprAllowed=s.beforeExpr};pe.overrideContext=function(t){this.curContext()!==t&&(this.context[this.context.length-1]=t)};u.parenR.updateContext=u.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=!0;return}var t=this.context.pop();t===k.b_stat&&this.curContext().token==="function"&&(t=this.context.pop()),this.exprAllowed=!t.isExpr};u.braceL.updateContext=function(t){this.context.push(this.braceIsBlock(t)?k.b_stat:k.b_expr),this.exprAllowed=!0};u.dollarBraceL.updateContext=function(){this.context.push(k.b_tmpl),this.exprAllowed=!0};u.parenL.updateContext=function(t){var e=t===u._if||t===u._for||t===u._with||t===u._while;this.context.push(e?k.p_stat:k.p_expr),this.exprAllowed=!0};u.incDec.updateContext=function(){};u._function.updateContext=u._class.updateContext=function(t){t.beforeExpr&&t!==u._else&&!(t===u.semi&&this.curContext()!==k.p_stat)&&!(t===u._return&&V.test(this.input.slice(this.lastTokEnd,this.start)))&&!((t===u.colon||t===u.braceL)&&this.curContext()===k.b_stat)?this.context.push(k.f_expr):this.context.push(k.f_stat),this.exprAllowed=!1};u.colon.updateContext=function(){this.curContext().token==="function"&&this.context.pop(),this.exprAllowed=!0};u.backQuote.updateContext=function(){this.curContext()===k.q_tmpl?this.context.pop():this.context.push(k.q_tmpl),this.exprAllowed=!1};u.star.updateContext=function(t){if(t===u._function){var e=this.context.length-1;this.context[e]===k.f_expr?this.context[e]=k.f_expr_gen:this.context[e]=k.f_gen}this.exprAllowed=!0};u.name.updateContext=function(t){var e=!1;this.options.ecmaVersion>=6&&t!==u.dot&&(this.value==="of"&&!this.exprAllowed||this.value==="yield"&&this.inGeneratorContext())&&(e=!0),this.exprAllowed=e};var v=I.prototype;v.checkPropClash=function(t,e,s){if(!(this.options.ecmaVersion>=9&&t.type==="SpreadElement")&&!(this.options.ecmaVersion>=6&&(t.computed||t.method||t.shorthand))){var i=t.key,n;switch(i.type){case"Identifier":n=i.name;break;case"Literal":n=String(i.value);break;default:return}var r=t.kind;if(this.options.ecmaVersion>=6){n==="__proto__"&&r==="init"&&(e.proto&&(s?s.doubleProto<0&&(s.doubleProto=i.start):this.raiseRecoverable(i.start,"Redefinition of __proto__ property")),e.proto=!0);return}n="$"+n;var a=e[n];if(a){var o;r==="init"?o=this.strict&&a.init||a.get||a.set:o=a.init||a[r],o&&this.raiseRecoverable(i.start,"Redefinition of property")}else a=e[n]={init:!1,get:!1,set:!1};a[r]=!0}};v.parseExpression=function(t,e){var s=this.start,i=this.startLoc,n=this.parseMaybeAssign(t,e);if(this.type===u.comma){var r=this.startNodeAt(s,i);for(r.expressions=[n];this.eat(u.comma);)r.expressions.push(this.parseMaybeAssign(t,e));return this.finishNode(r,"SequenceExpression")}return n};v.parseMaybeAssign=function(t,e,s){if(this.isContextual("yield")){if(this.inGenerator)return this.parseYield(t);this.exprAllowed=!1}var i=!1,n=-1,r=-1,a=-1;e?(n=e.parenthesizedAssign,r=e.trailingComma,a=e.doubleProto,e.parenthesizedAssign=e.trailingComma=-1):(e=new _e,i=!0);var o=this.start,c=this.startLoc;(this.type===u.parenL||this.type===u.name)&&(this.potentialArrowAt=this.start,this.potentialArrowInForAwait=t==="await");var l=this.parseMaybeConditional(t,e);if(s&&(l=s.call(this,l,o,c)),this.type.isAssign){var h=this.startNodeAt(o,c);return h.operator=this.value,this.type===u.eq&&(l=this.toAssignable(l,!1,e)),i||(e.parenthesizedAssign=e.trailingComma=e.doubleProto=-1),e.shorthandAssign>=l.start&&(e.shorthandAssign=-1),this.type===u.eq?this.checkLValPattern(l):this.checkLValSimple(l),h.left=l,this.next(),h.right=this.parseMaybeAssign(t),a>-1&&(e.doubleProto=a),this.finishNode(h,"AssignmentExpression")}else i&&this.checkExpressionErrors(e,!0);return n>-1&&(e.parenthesizedAssign=n),r>-1&&(e.trailingComma=r),l};v.parseMaybeConditional=function(t,e){var s=this.start,i=this.startLoc,n=this.parseExprOps(t,e);if(this.checkExpressionErrors(e))return n;if(this.eat(u.question)){var r=this.startNodeAt(s,i);return r.test=n,r.consequent=this.parseMaybeAssign(),this.expect(u.colon),r.alternate=this.parseMaybeAssign(t),this.finishNode(r,"ConditionalExpression")}return n};v.parseExprOps=function(t,e){var s=this.start,i=this.startLoc,n=this.parseMaybeUnary(e,!1,!1,t);return this.checkExpressionErrors(e)||n.start===s&&n.type==="ArrowFunctionExpression"?n:this.parseExprOp(n,s,i,-1,t)};v.parseExprOp=function(t,e,s,i,n){var r=this.type.binop;if(r!=null&&(!n||this.type!==u._in)&&r>i){var a=this.type===u.logicalOR||this.type===u.logicalAND,o=this.type===u.coalesce;o&&(r=u.logicalAND.binop);var c=this.value;this.next();var l=this.start,h=this.startLoc,p=this.parseExprOp(this.parseMaybeUnary(null,!1,!1,n),l,h,r,n),f=this.buildBinary(e,s,t,p,c,a||o);return(a&&this.type===u.coalesce||o&&(this.type===u.logicalOR||this.type===u.logicalAND))&&this.raiseRecoverable(this.start,"Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"),this.parseExprOp(f,e,s,i,n)}return t};v.buildBinary=function(t,e,s,i,n,r){i.type==="PrivateIdentifier"&&this.raise(i.start,"Private identifier can only be left side of binary expression");var a=this.startNodeAt(t,e);return a.left=s,a.operator=n,a.right=i,this.finishNode(a,r?"LogicalExpression":"BinaryExpression")};v.parseMaybeUnary=function(t,e,s,i){var n=this.start,r=this.startLoc,a;if(this.isContextual("await")&&this.canAwait)a=this.parseAwait(i),e=!0;else if(this.type.prefix){var o=this.startNode(),c=this.type===u.incDec;o.operator=this.value,o.prefix=!0,this.next(),o.argument=this.parseMaybeUnary(null,!0,c,i),this.checkExpressionErrors(t,!0),c?this.checkLValSimple(o.argument):this.strict&&o.operator==="delete"&&dt(o.argument)?this.raiseRecoverable(o.start,"Deleting local variable in strict mode"):o.operator==="delete"&&De(o.argument)?this.raiseRecoverable(o.start,"Private fields can not be deleted"):e=!0,a=this.finishNode(o,c?"UpdateExpression":"UnaryExpression")}else if(!e&&this.type===u.privateId)(i||this.privateNameStack.length===0)&&this.options.checkPrivateFields&&this.unexpected(),a=this.parsePrivateIdent(),this.type!==u._in&&this.unexpected();else{if(a=this.parseExprSubscripts(t,i),this.checkExpressionErrors(t))return a;for(;this.type.postfix&&!this.canInsertSemicolon();){var l=this.startNodeAt(n,r);l.operator=this.value,l.prefix=!1,l.argument=a,this.checkLValSimple(a),this.next(),a=this.finishNode(l,"UpdateExpression")}}if(!s&&this.eat(u.starstar))if(e)this.unexpected(this.lastTokStart);else return this.buildBinary(n,r,a,this.parseMaybeUnary(null,!1,!1,i),"**",!1);else return a};function dt(t){return t.type==="Identifier"||t.type==="ParenthesizedExpression"&&dt(t.expression)}function De(t){return t.type==="MemberExpression"&&t.property.type==="PrivateIdentifier"||t.type==="ChainExpression"&&De(t.expression)||t.type==="ParenthesizedExpression"&&De(t.expression)}v.parseExprSubscripts=function(t,e){var s=this.start,i=this.startLoc,n=this.parseExprAtom(t,e);if(n.type==="ArrowFunctionExpression"&&this.input.slice(this.lastTokStart,this.lastTokEnd)!==")")return n;var r=this.parseSubscripts(n,s,i,!1,e);return t&&r.type==="MemberExpression"&&(t.parenthesizedAssign>=r.start&&(t.parenthesizedAssign=-1),t.parenthesizedBind>=r.start&&(t.parenthesizedBind=-1),t.trailingComma>=r.start&&(t.trailingComma=-1)),r};v.parseSubscripts=function(t,e,s,i,n){for(var r=this.options.ecmaVersion>=8&&t.type==="Identifier"&&t.name==="async"&&this.lastTokEnd===t.end&&!this.canInsertSemicolon()&&t.end-t.start===5&&this.potentialArrowAt===t.start,a=!1;;){var o=this.parseSubscript(t,e,s,i,r,a,n);if(o.optional&&(a=!0),o===t||o.type==="ArrowFunctionExpression"){if(a){var c=this.startNodeAt(e,s);c.expression=o,o=this.finishNode(c,"ChainExpression")}return o}t=o}};v.shouldParseAsyncArrow=function(){return!this.canInsertSemicolon()&&this.eat(u.arrow)};v.parseSubscriptAsyncArrow=function(t,e,s,i){return this.parseArrowExpression(this.startNodeAt(t,e),s,!0,i)};v.parseSubscript=function(t,e,s,i,n,r,a){var o=this.options.ecmaVersion>=11,c=o&&this.eat(u.questionDot);i&&c&&this.raise(this.lastTokStart,"Optional chaining cannot appear in the callee of new expressions");var l=this.eat(u.bracketL);if(l||c&&this.type!==u.parenL&&this.type!==u.backQuote||this.eat(u.dot)){var h=this.startNodeAt(e,s);h.object=t,l?(h.property=this.parseExpression(),this.expect(u.bracketR)):this.type===u.privateId&&t.type!=="Super"?h.property=this.parsePrivateIdent():h.property=this.parseIdent(this.options.allowReserved!=="never"),h.computed=!!l,o&&(h.optional=c),t=this.finishNode(h,"MemberExpression")}else if(!i&&this.eat(u.parenL)){var p=new _e,f=this.yieldPos,m=this.awaitPos,x=this.awaitIdentPos;this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0;var C=this.parseExprList(u.parenR,this.options.ecmaVersion>=8,!1,p);if(n&&!c&&this.shouldParseAsyncArrow())return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.awaitIdentPos>0&&this.raise(this.awaitIdentPos,"Cannot use 'await' as identifier inside an async function"),this.yieldPos=f,this.awaitPos=m,this.awaitIdentPos=x,this.parseSubscriptAsyncArrow(e,s,C,a);this.checkExpressionErrors(p,!0),this.yieldPos=f||this.yieldPos,this.awaitPos=m||this.awaitPos,this.awaitIdentPos=x||this.awaitIdentPos;var S=this.startNodeAt(e,s);S.callee=t,S.arguments=C,o&&(S.optional=c),t=this.finishNode(S,"CallExpression")}else if(this.type===u.backQuote){(c||r)&&this.raise(this.start,"Optional chaining cannot appear in the tag of tagged template expressions");var P=this.startNodeAt(e,s);P.tag=t,P.quasi=this.parseTemplate({isTagged:!0}),t=this.finishNode(P,"TaggedTemplateExpression")}return t};v.parseExprAtom=function(t,e,s){this.type===u.slash&&this.readRegexp();var i,n=this.potentialArrowAt===this.start;switch(this.type){case u._super:return this.allowSuper||this.raise(this.start,"'super' keyword outside a method"),i=this.startNode(),this.next(),this.type===u.parenL&&!this.allowDirectSuper&&this.raise(i.start,"super() call outside constructor of a subclass"),this.type!==u.dot&&this.type!==u.bracketL&&this.type!==u.parenL&&this.unexpected(),this.finishNode(i,"Super");case u._this:return i=this.startNode(),this.next(),this.finishNode(i,"ThisExpression");case u.name:var r=this.start,a=this.startLoc,o=this.containsEsc,c=this.parseIdent(!1);if(this.options.ecmaVersion>=8&&!o&&c.name==="async"&&!this.canInsertSemicolon()&&this.eat(u._function))return this.overrideContext(k.f_expr),this.parseFunction(this.startNodeAt(r,a),0,!1,!0,e);if(n&&!this.canInsertSemicolon()){if(this.eat(u.arrow))return this.parseArrowExpression(this.startNodeAt(r,a),[c],!1,e);if(this.options.ecmaVersion>=8&&c.name==="async"&&this.type===u.name&&!o&&(!this.potentialArrowInForAwait||this.value!=="of"||this.containsEsc))return c=this.parseIdent(!1),(this.canInsertSemicolon()||!this.eat(u.arrow))&&this.unexpected(),this.parseArrowExpression(this.startNodeAt(r,a),[c],!0,e)}return c;case u.regexp:var l=this.value;return i=this.parseLiteral(l.value),i.regex={pattern:l.pattern,flags:l.flags},i;case u.num:case u.string:return this.parseLiteral(this.value);case u._null:case u._true:case u._false:return i=this.startNode(),i.value=this.type===u._null?null:this.type===u._true,i.raw=this.type.keyword,this.next(),this.finishNode(i,"Literal");case u.parenL:var h=this.start,p=this.parseParenAndDistinguishExpression(n,e);return t&&(t.parenthesizedAssign<0&&!this.isSimpleAssignTarget(p)&&(t.parenthesizedAssign=h),t.parenthesizedBind<0&&(t.parenthesizedBind=h)),p;case u.bracketL:return i=this.startNode(),this.next(),i.elements=this.parseExprList(u.bracketR,!0,!0,t),this.finishNode(i,"ArrayExpression");case u.braceL:return this.overrideContext(k.b_expr),this.parseObj(!1,t);case u._function:return i=this.startNode(),this.next(),this.parseFunction(i,0);case u._class:return this.parseClass(this.startNode(),!1);case u._new:return this.parseNew();case u.backQuote:return this.parseTemplate();case u._import:return this.options.ecmaVersion>=11?this.parseExprImport(s):this.unexpected();default:return this.parseExprAtomDefault()}};v.parseExprAtomDefault=function(){this.unexpected()};v.parseExprImport=function(t){var e=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===u.parenL&&!t)return this.parseDynamicImport(e);if(this.type===u.dot){var s=this.startNodeAt(e.start,e.loc&&e.loc.start);return s.name="import",e.meta=this.finishNode(s,"Identifier"),this.parseImportMeta(e)}else this.unexpected()};v.parseDynamicImport=function(t){if(this.next(),t.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(u.parenR)?t.options=null:(this.expect(u.comma),this.afterTrailingComma(u.parenR)?t.options=null:(t.options=this.parseMaybeAssign(),this.eat(u.parenR)||(this.expect(u.comma),this.afterTrailingComma(u.parenR)||this.unexpected())));else if(!this.eat(u.parenR)){var e=this.start;this.eat(u.comma)&&this.eat(u.parenR)?this.raiseRecoverable(e,"Trailing comma is not allowed in import()"):this.unexpected(e)}return this.finishNode(t,"ImportExpression")};v.parseImportMeta=function(t){this.next();var e=this.containsEsc;return t.property=this.parseIdent(!0),t.property.name!=="meta"&&this.raiseRecoverable(t.property.start,"The only valid meta property for import is 'import.meta'"),e&&this.raiseRecoverable(t.start,"'import.meta' must not contain escaped characters"),this.options.sourceType!=="module"&&!this.options.allowImportExportEverywhere&&this.raiseRecoverable(t.start,"Cannot use 'import.meta' outside a module"),this.finishNode(t,"MetaProperty")};v.parseLiteral=function(t){var e=this.startNode();return e.value=t,e.raw=this.input.slice(this.start,this.end),e.raw.charCodeAt(e.raw.length-1)===110&&(e.bigint=e.value!=null?e.value.toString():e.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(e,"Literal")};v.parseParenExpression=function(){this.expect(u.parenL);var t=this.parseExpression();return this.expect(u.parenR),t};v.shouldParseArrow=function(t){return!this.canInsertSemicolon()};v.parseParenAndDistinguishExpression=function(t,e){var s=this.start,i=this.startLoc,n,r=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a=this.start,o=this.startLoc,c=[],l=!0,h=!1,p=new _e,f=this.yieldPos,m=this.awaitPos,x;for(this.yieldPos=0,this.awaitPos=0;this.type!==u.parenR;)if(l?l=!1:this.expect(u.comma),r&&this.afterTrailingComma(u.parenR,!0)){h=!0;break}else if(this.type===u.ellipsis){x=this.start,c.push(this.parseParenItem(this.parseRestBinding())),this.type===u.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}else c.push(this.parseMaybeAssign(!1,p,this.parseParenItem));var C=this.lastTokEnd,S=this.lastTokEndLoc;if(this.expect(u.parenR),t&&this.shouldParseArrow(c)&&this.eat(u.arrow))return this.checkPatternErrors(p,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=f,this.awaitPos=m,this.parseParenArrowList(s,i,c,e);(!c.length||h)&&this.unexpected(this.lastTokStart),x&&this.unexpected(x),this.checkExpressionErrors(p,!0),this.yieldPos=f||this.yieldPos,this.awaitPos=m||this.awaitPos,c.length>1?(n=this.startNodeAt(a,o),n.expressions=c,this.finishNodeAt(n,"SequenceExpression",C,S)):n=c[0]}else n=this.parseParenExpression();if(this.options.preserveParens){var P=this.startNodeAt(s,i);return P.expression=n,this.finishNode(P,"ParenthesizedExpression")}else return n};v.parseParenItem=function(t){return t};v.parseParenArrowList=function(t,e,s,i){return this.parseArrowExpression(this.startNodeAt(t,e),s,!1,i)};var es=[];v.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var t=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===u.dot){var e=this.startNodeAt(t.start,t.loc&&t.loc.start);e.name="new",t.meta=this.finishNode(e,"Identifier"),this.next();var s=this.containsEsc;return t.property=this.parseIdent(!0),t.property.name!=="target"&&this.raiseRecoverable(t.property.start,"The only valid meta property for new is 'new.target'"),s&&this.raiseRecoverable(t.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(t.start,"'new.target' can only be used in functions and class static block"),this.finishNode(t,"MetaProperty")}var i=this.start,n=this.startLoc;return t.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),i,n,!0,!1),this.eat(u.parenL)?t.arguments=this.parseExprList(u.parenR,this.options.ecmaVersion>=8,!1):t.arguments=es,this.finishNode(t,"NewExpression")};v.parseTemplateElement=function(t){var e=t.isTagged,s=this.startNode();return this.type===u.invalidTemplate?(e||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value.replace(/\r\n?/g,`
|
|
4
4
|
`),cooked:null}):s.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,`
|
|
5
5
|
`),cooked:this.value},this.next(),s.tail=this.type===u.backQuote,this.finishNode(s,"TemplateElement")};v.parseTemplate=function(t){t===void 0&&(t={});var e=t.isTagged;e===void 0&&(e=!1);var s=this.startNode();this.next(),s.expressions=[];var i=this.parseTemplateElement({isTagged:e});for(s.quasis=[i];!i.tail;)this.type===u.eof&&this.raise(this.pos,"Unterminated template literal"),this.expect(u.dollarBraceL),s.expressions.push(this.parseExpression()),this.expect(u.braceR),s.quasis.push(i=this.parseTemplateElement({isTagged:e}));return this.next(),this.finishNode(s,"TemplateLiteral")};v.isAsyncProp=function(t){return!t.computed&&t.key.type==="Identifier"&&t.key.name==="async"&&(this.type===u.name||this.type===u.num||this.type===u.string||this.type===u.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===u.star)&&!V.test(this.input.slice(this.lastTokEnd,this.start))};v.parseObj=function(t,e){var s=this.startNode(),i=!0,n={};for(s.properties=[],this.next();!this.eat(u.braceR);){if(i)i=!1;else if(this.expect(u.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(u.braceR))break;var r=this.parseProperty(t,e);t||this.checkPropClash(r,n,e),s.properties.push(r)}return this.finishNode(s,t?"ObjectPattern":"ObjectExpression")};v.parseProperty=function(t,e){var s=this.startNode(),i,n,r,a;if(this.options.ecmaVersion>=9&&this.eat(u.ellipsis))return t?(s.argument=this.parseIdent(!1),this.type===u.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(s,"RestElement")):(s.argument=this.parseMaybeAssign(!1,e),this.type===u.comma&&e&&e.trailingComma<0&&(e.trailingComma=this.start),this.finishNode(s,"SpreadElement"));this.options.ecmaVersion>=6&&(s.method=!1,s.shorthand=!1,(t||e)&&(r=this.start,a=this.startLoc),t||(i=this.eat(u.star)));var o=this.containsEsc;return this.parsePropertyName(s),!t&&!o&&this.options.ecmaVersion>=8&&!i&&this.isAsyncProp(s)?(n=!0,i=this.options.ecmaVersion>=9&&this.eat(u.star),this.parsePropertyName(s)):n=!1,this.parsePropertyValue(s,t,i,n,r,a,e,o),this.finishNode(s,"Property")};v.parseGetterSetter=function(t){var e=t.key.name;this.parsePropertyName(t),t.value=this.parseMethod(!1),t.kind=e;var s=t.kind==="get"?0:1;if(t.value.params.length!==s){var i=t.value.start;t.kind==="get"?this.raiseRecoverable(i,"getter should have no params"):this.raiseRecoverable(i,"setter should have exactly one param")}else t.kind==="set"&&t.value.params[0].type==="RestElement"&&this.raiseRecoverable(t.value.params[0].start,"Setter cannot use rest params")};v.parsePropertyValue=function(t,e,s,i,n,r,a,o){(s||i)&&this.type===u.colon&&this.unexpected(),this.eat(u.colon)?(t.value=e?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),t.kind="init"):this.options.ecmaVersion>=6&&this.type===u.parenL?(e&&this.unexpected(),t.method=!0,t.value=this.parseMethod(s,i),t.kind="init"):!e&&!o&&this.options.ecmaVersion>=5&&!t.computed&&t.key.type==="Identifier"&&(t.key.name==="get"||t.key.name==="set")&&this.type!==u.comma&&this.type!==u.braceR&&this.type!==u.eq?((s||i)&&this.unexpected(),this.parseGetterSetter(t)):this.options.ecmaVersion>=6&&!t.computed&&t.key.type==="Identifier"?((s||i)&&this.unexpected(),this.checkUnreserved(t.key),t.key.name==="await"&&!this.awaitIdentPos&&(this.awaitIdentPos=n),e?t.value=this.parseMaybeDefault(n,r,this.copyNode(t.key)):this.type===u.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),t.value=this.parseMaybeDefault(n,r,this.copyNode(t.key))):t.value=this.copyNode(t.key),t.kind="init",t.shorthand=!0):this.unexpected()};v.parsePropertyName=function(t){if(this.options.ecmaVersion>=6){if(this.eat(u.bracketL))return t.computed=!0,t.key=this.parseMaybeAssign(),this.expect(u.bracketR),t.key;t.computed=!1}return t.key=this.type===u.num||this.type===u.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};v.initFunction=function(t){t.id=null,this.options.ecmaVersion>=6&&(t.generator=t.expression=!1),this.options.ecmaVersion>=8&&(t.async=!1)};v.parseMethod=function(t,e,s){var i=this.startNode(),n=this.yieldPos,r=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(i),this.options.ecmaVersion>=6&&(i.generator=t),this.options.ecmaVersion>=8&&(i.async=!!e),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(Ue(e,i.generator)|we|(s?ut:0)),this.expect(u.parenL),i.params=this.parseBindingList(u.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(i,!1,!0,!1),this.yieldPos=n,this.awaitPos=r,this.awaitIdentPos=a,this.finishNode(i,"FunctionExpression")};v.parseArrowExpression=function(t,e,s,i){var n=this.yieldPos,r=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(Ue(s,!1)|We),this.initFunction(t),this.options.ecmaVersion>=8&&(t.async=!!s),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,t.params=this.toAssignableList(e,!0),this.parseFunctionBody(t,!0,!1,i),this.yieldPos=n,this.awaitPos=r,this.awaitIdentPos=a,this.finishNode(t,"ArrowFunctionExpression")};v.parseFunctionBody=function(t,e,s,i){var n=e&&this.type!==u.braceL,r=this.strict,a=!1;if(n)t.body=this.parseMaybeAssign(i),t.expression=!0,this.checkParams(t,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(t.params);(!r||o)&&(a=this.strictDirective(this.end),a&&o&&this.raiseRecoverable(t.start,"Illegal 'use strict' directive in function with non-simple parameter list"));var c=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(t,!r&&!a&&!e&&!s&&this.isSimpleParamList(t.params)),this.strict&&t.id&&this.checkLValSimple(t.id,pt),t.body=this.parseBlock(!1,void 0,a&&!r),t.expression=!1,this.adaptDirectivePrologue(t.body.body),this.labels=c}this.exitScope()};v.isSimpleParamList=function(t){for(var e=0,s=t;e<s.length;e+=1){var i=s[e];if(i.type!=="Identifier")return!1}return!0};v.checkParams=function(t,e){for(var s=Object.create(null),i=0,n=t.params;i<n.length;i+=1){var r=n[i];this.checkLValInnerPattern(r,He,e?null:s)}};v.parseExprList=function(t,e,s,i){for(var n=[],r=!0;!this.eat(t);){if(r)r=!1;else if(this.expect(u.comma),e&&this.afterTrailingComma(t))break;var a=void 0;s&&this.type===u.comma?a=null:this.type===u.ellipsis?(a=this.parseSpread(i),i&&this.type===u.comma&&i.trailingComma<0&&(i.trailingComma=this.start)):a=this.parseMaybeAssign(!1,i),n.push(a)}return n};v.checkUnreserved=function(t){var e=t.start,s=t.end,i=t.name;if(this.inGenerator&&i==="yield"&&this.raiseRecoverable(e,"Cannot use 'yield' as identifier inside a generator"),this.inAsync&&i==="await"&&this.raiseRecoverable(e,"Cannot use 'await' as identifier inside an async function"),!(this.currentThisScope().flags&Pe)&&i==="arguments"&&this.raiseRecoverable(e,"Cannot use 'arguments' in class field initializer"),this.inClassStaticBlock&&(i==="arguments"||i==="await")&&this.raise(e,"Cannot use "+i+" in class static initialization block"),this.keywords.test(i)&&this.raise(e,"Unexpected keyword '"+i+"'"),!(this.options.ecmaVersion<6&&this.input.slice(e,s).indexOf("\\")!==-1)){var n=this.strict?this.reservedWordsStrict:this.reservedWords;n.test(i)&&(!this.inAsync&&i==="await"&&this.raiseRecoverable(e,"Cannot use keyword 'await' outside an async function"),this.raiseRecoverable(e,"The keyword '"+i+"' is reserved"))}};v.parseIdent=function(t){var e=this.parseIdentNode();return this.next(!!t),this.finishNode(e,"Identifier"),t||(this.checkUnreserved(e),e.name==="await"&&!this.awaitIdentPos&&(this.awaitIdentPos=e.start)),e};v.parseIdentNode=function(){var t=this.startNode();return this.type===u.name?t.name=this.value:this.type.keyword?(t.name=this.type.keyword,(t.name==="class"||t.name==="function")&&(this.lastTokEnd!==this.lastTokStart+1||this.input.charCodeAt(this.lastTokStart)!==46)&&this.context.pop(),this.type=u.name):this.unexpected(),t};v.parsePrivateIdent=function(){var t=this.startNode();return this.type===u.privateId?t.name=this.value:this.unexpected(),this.next(),this.finishNode(t,"PrivateIdentifier"),this.options.checkPrivateFields&&(this.privateNameStack.length===0?this.raise(t.start,"Private field '#"+t.name+"' must be declared in an enclosing class"):this.privateNameStack[this.privateNameStack.length-1].used.push(t)),t};v.parseYield=function(t){this.yieldPos||(this.yieldPos=this.start);var e=this.startNode();return this.next(),this.type===u.semi||this.canInsertSemicolon()||this.type!==u.star&&!this.type.startsExpr?(e.delegate=!1,e.argument=null):(e.delegate=this.eat(u.star),e.argument=this.parseMaybeAssign(t)),this.finishNode(e,"YieldExpression")};v.parseAwait=function(t){this.awaitPos||(this.awaitPos=this.start);var e=this.startNode();return this.next(),e.argument=this.parseMaybeUnary(null,!0,!1,t),this.finishNode(e,"AwaitExpression")};var ve=I.prototype;ve.raise=function(t,e){var s=at(this.input,t);e+=" ("+s.line+":"+s.column+")",this.sourceFile&&(e+=" in "+this.sourceFile);var i=new SyntaxError(e);throw i.pos=t,i.loc=s,i.raisedAt=this.pos,i};ve.raiseRecoverable=ve.raise;ve.curPosition=function(){if(this.options.locations)return new me(this.curLine,this.pos-this.lineStart)};var ee=I.prototype,ts=function(e){this.flags=e,this.var=[],this.lexical=[],this.functions=[]};ee.enterScope=function(t){this.scopeStack.push(new ts(t))};ee.exitScope=function(){this.scopeStack.pop()};ee.treatFunctionsAsVarInScope=function(t){return t.flags&he||!this.inModule&&t.flags&ge};ee.declareName=function(t,e,s){var i=!1;if(e===Y){var n=this.currentScope();i=n.lexical.indexOf(t)>-1||n.functions.indexOf(t)>-1||n.var.indexOf(t)>-1,n.lexical.push(t),this.inModule&&n.flags&ge&&delete this.undefinedExports[t]}else if(e===ht){var r=this.currentScope();r.lexical.push(t)}else if(e===lt){var a=this.currentScope();this.treatFunctionsAsVar?i=a.lexical.indexOf(t)>-1:i=a.lexical.indexOf(t)>-1||a.var.indexOf(t)>-1,a.functions.push(t)}else for(var o=this.scopeStack.length-1;o>=0;--o){var c=this.scopeStack[o];if(c.lexical.indexOf(t)>-1&&!(c.flags&ct&&c.lexical[0]===t)||!this.treatFunctionsAsVarInScope(c)&&c.functions.indexOf(t)>-1){i=!0;break}if(c.var.push(t),this.inModule&&c.flags&ge&&delete this.undefinedExports[t],c.flags&Pe)break}i&&this.raiseRecoverable(s,"Identifier '"+t+"' has already been declared")};ee.checkLocalExport=function(t){this.scopeStack[0].lexical.indexOf(t.name)===-1&&this.scopeStack[0].var.indexOf(t.name)===-1&&(this.undefinedExports[t.name]=t)};ee.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};ee.currentVarScope=function(){for(var t=this.scopeStack.length-1;;t--){var e=this.scopeStack[t];if(e.flags&(Pe|xe|ne))return e}};ee.currentThisScope=function(){for(var t=this.scopeStack.length-1;;t--){var e=this.scopeStack[t];if(e.flags&(Pe|xe|ne)&&!(e.flags&We))return e}};var ke=function(e,s,i){this.type="",this.start=s,this.end=0,e.options.locations&&(this.loc=new Te(e,i)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[s,0])},Ee=I.prototype;Ee.startNode=function(){return new ke(this,this.start,this.startLoc)};Ee.startNodeAt=function(t,e){return new ke(this,t,e)};function mt(t,e,s,i){return t.type=e,t.end=s,this.options.locations&&(t.loc.end=i),this.options.ranges&&(t.range[1]=s),t}Ee.finishNode=function(t,e){return mt.call(this,t,e,this.lastTokEnd,this.lastTokEndLoc)};Ee.finishNodeAt=function(t,e,s,i){return mt.call(this,t,e,s,i)};Ee.copyNode=function(t){var e=new ke(this,t.start,this.startLoc);for(var s in t)e[s]=t[s];return e};var ss="Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sunu Sunuwar Todhri Todr Tulu_Tigalari Tutg Unknown Zzzz",gt="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS",xt=gt+" Extended_Pictographic",Et=xt,bt=Et+" EBase EComp EMod EPres ExtPict",Ct=bt,is=Ct,ns={9:gt,10:xt,11:Et,12:bt,13:Ct,14:is},rs="Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji",as={9:"",10:"",11:"",12:"",13:"",14:rs},Ze="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu",yt="Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb",vt=yt+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",St=vt+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",At=St+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Tt=At+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",os=Tt+" "+ss,cs={9:yt,10:vt,11:St,12:At,13:Tt,14:os},wt={};function us(t){var e=wt[t]={binary:Z(ns[t]+" "+Ze),binaryOfStrings:Z(as[t]),nonBinary:{General_Category:Z(Ze),Script:Z(cs[t])}};e.nonBinary.Script_Extensions=e.nonBinary.Script,e.nonBinary.gc=e.nonBinary.General_Category,e.nonBinary.sc=e.nonBinary.Script,e.nonBinary.scx=e.nonBinary.Script_Extensions}for(var Oe=0,Je=[9,10,11,12,13,14];Oe<Je.length;Oe+=1){var ls=Je[Oe];us(ls)}var E=I.prototype,Se=function(e,s){this.parent=e,this.base=s||this};Se.prototype.separatedFrom=function(e){for(var s=this;s;s=s.parent)for(var i=e;i;i=i.parent)if(s.base===i.base&&s!==i)return!0;return!1};Se.prototype.sibling=function(){return new Se(this.parent,this.base)};var K=function(e){this.parser=e,this.validFlags="gim"+(e.options.ecmaVersion>=6?"uy":"")+(e.options.ecmaVersion>=9?"s":"")+(e.options.ecmaVersion>=13?"d":"")+(e.options.ecmaVersion>=15?"v":""),this.unicodeProperties=wt[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source="",this.flags="",this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue="",this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};K.prototype.reset=function(e,s,i){var n=i.indexOf("v")!==-1,r=i.indexOf("u")!==-1;this.start=e|0,this.source=s+"",this.flags=i,n&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=r&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=r&&this.parser.options.ecmaVersion>=9)};K.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)};K.prototype.at=function(e,s){s===void 0&&(s=!1);var i=this.source,n=i.length;if(e>=n)return-1;var r=i.charCodeAt(e);if(!(s||this.switchU)||r<=55295||r>=57344||e+1>=n)return r;var a=i.charCodeAt(e+1);return a>=56320&&a<=57343?(r<<10)+a-56613888:r};K.prototype.nextIndex=function(e,s){s===void 0&&(s=!1);var i=this.source,n=i.length;if(e>=n)return n;var r=i.charCodeAt(e),a;return!(s||this.switchU)||r<=55295||r>=57344||e+1>=n||(a=i.charCodeAt(e+1))<56320||a>57343?e+1:e+2};K.prototype.current=function(e){return e===void 0&&(e=!1),this.at(this.pos,e)};K.prototype.lookahead=function(e){return e===void 0&&(e=!1),this.at(this.nextIndex(this.pos,e),e)};K.prototype.advance=function(e){e===void 0&&(e=!1),this.pos=this.nextIndex(this.pos,e)};K.prototype.eat=function(e,s){return s===void 0&&(s=!1),this.current(s)===e?(this.advance(s),!0):!1};K.prototype.eatChars=function(e,s){s===void 0&&(s=!1);for(var i=this.pos,n=0,r=e;n<r.length;n+=1){var a=r[n],o=this.at(i,s);if(o===-1||o!==a)return!1;i=this.nextIndex(i,s)}return this.pos=i,!0};E.validateRegExpFlags=function(t){for(var e=t.validFlags,s=t.flags,i=!1,n=!1,r=0;r<s.length;r++){var a=s.charAt(r);e.indexOf(a)===-1&&this.raise(t.start,"Invalid regular expression flag"),s.indexOf(a,r+1)>-1&&this.raise(t.start,"Duplicate regular expression flag"),a==="u"&&(i=!0),a==="v"&&(n=!0)}this.options.ecmaVersion>=15&&i&&n&&this.raise(t.start,"Invalid regular expression flag")};function hs(t){for(var e in t)return!0;return!1}E.validateRegExpPattern=function(t){this.regexp_pattern(t),!t.switchN&&this.options.ecmaVersion>=9&&hs(t.groupNames)&&(t.switchN=!0,this.regexp_pattern(t))};E.regexp_pattern=function(t){t.pos=0,t.lastIntValue=0,t.lastStringValue="",t.lastAssertionIsQuantifiable=!1,t.numCapturingParens=0,t.maxBackReference=0,t.groupNames=Object.create(null),t.backReferenceNames.length=0,t.branchID=null,this.regexp_disjunction(t),t.pos!==t.source.length&&(t.eat(41)&&t.raise("Unmatched ')'"),(t.eat(93)||t.eat(125))&&t.raise("Lone quantifier brackets")),t.maxBackReference>t.numCapturingParens&&t.raise("Invalid escape");for(var e=0,s=t.backReferenceNames;e<s.length;e+=1){var i=s[e];t.groupNames[i]||t.raise("Invalid named capture referenced")}};E.regexp_disjunction=function(t){var e=this.options.ecmaVersion>=16;for(e&&(t.branchID=new Se(t.branchID,null)),this.regexp_alternative(t);t.eat(124);)e&&(t.branchID=t.branchID.sibling()),this.regexp_alternative(t);e&&(t.branchID=t.branchID.parent),this.regexp_eatQuantifier(t,!0)&&t.raise("Nothing to repeat"),t.eat(123)&&t.raise("Lone quantifier brackets")};E.regexp_alternative=function(t){for(;t.pos<t.source.length&&this.regexp_eatTerm(t););};E.regexp_eatTerm=function(t){return this.regexp_eatAssertion(t)?(t.lastAssertionIsQuantifiable&&this.regexp_eatQuantifier(t)&&t.switchU&&t.raise("Invalid quantifier"),!0):(t.switchU?this.regexp_eatAtom(t):this.regexp_eatExtendedAtom(t))?(this.regexp_eatQuantifier(t),!0):!1};E.regexp_eatAssertion=function(t){var e=t.pos;if(t.lastAssertionIsQuantifiable=!1,t.eat(94)||t.eat(36))return!0;if(t.eat(92)){if(t.eat(66)||t.eat(98))return!0;t.pos=e}if(t.eat(40)&&t.eat(63)){var s=!1;if(this.options.ecmaVersion>=9&&(s=t.eat(60)),t.eat(61)||t.eat(33))return this.regexp_disjunction(t),t.eat(41)||t.raise("Unterminated group"),t.lastAssertionIsQuantifiable=!s,!0}return t.pos=e,!1};E.regexp_eatQuantifier=function(t,e){return e===void 0&&(e=!1),this.regexp_eatQuantifierPrefix(t,e)?(t.eat(63),!0):!1};E.regexp_eatQuantifierPrefix=function(t,e){return t.eat(42)||t.eat(43)||t.eat(63)||this.regexp_eatBracedQuantifier(t,e)};E.regexp_eatBracedQuantifier=function(t,e){var s=t.pos;if(t.eat(123)){var i=0,n=-1;if(this.regexp_eatDecimalDigits(t)&&(i=t.lastIntValue,t.eat(44)&&this.regexp_eatDecimalDigits(t)&&(n=t.lastIntValue),t.eat(125)))return n!==-1&&n<i&&!e&&t.raise("numbers out of order in {} quantifier"),!0;t.switchU&&!e&&t.raise("Incomplete quantifier"),t.pos=s}return!1};E.regexp_eatAtom=function(t){return this.regexp_eatPatternCharacters(t)||t.eat(46)||this.regexp_eatReverseSolidusAtomEscape(t)||this.regexp_eatCharacterClass(t)||this.regexp_eatUncapturingGroup(t)||this.regexp_eatCapturingGroup(t)};E.regexp_eatReverseSolidusAtomEscape=function(t){var e=t.pos;if(t.eat(92)){if(this.regexp_eatAtomEscape(t))return!0;t.pos=e}return!1};E.regexp_eatUncapturingGroup=function(t){var e=t.pos;if(t.eat(40)){if(t.eat(63)){if(this.options.ecmaVersion>=16){var s=this.regexp_eatModifiers(t),i=t.eat(45);if(s||i){for(var n=0;n<s.length;n++){var r=s.charAt(n);s.indexOf(r,n+1)>-1&&t.raise("Duplicate regular expression modifiers")}if(i){var a=this.regexp_eatModifiers(t);!s&&!a&&t.current()===58&&t.raise("Invalid regular expression modifiers");for(var o=0;o<a.length;o++){var c=a.charAt(o);(a.indexOf(c,o+1)>-1||s.indexOf(c)>-1)&&t.raise("Duplicate regular expression modifiers")}}}}if(t.eat(58)){if(this.regexp_disjunction(t),t.eat(41))return!0;t.raise("Unterminated group")}}t.pos=e}return!1};E.regexp_eatCapturingGroup=function(t){if(t.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(t):t.current()===63&&t.raise("Invalid group"),this.regexp_disjunction(t),t.eat(41))return t.numCapturingParens+=1,!0;t.raise("Unterminated group")}return!1};E.regexp_eatModifiers=function(t){for(var e="",s=0;(s=t.current())!==-1&&ps(s);)e+=G(s),t.advance();return e};function ps(t){return t===105||t===109||t===115}E.regexp_eatExtendedAtom=function(t){return t.eat(46)||this.regexp_eatReverseSolidusAtomEscape(t)||this.regexp_eatCharacterClass(t)||this.regexp_eatUncapturingGroup(t)||this.regexp_eatCapturingGroup(t)||this.regexp_eatInvalidBracedQuantifier(t)||this.regexp_eatExtendedPatternCharacter(t)};E.regexp_eatInvalidBracedQuantifier=function(t){return this.regexp_eatBracedQuantifier(t,!0)&&t.raise("Nothing to repeat"),!1};E.regexp_eatSyntaxCharacter=function(t){var e=t.current();return Pt(e)?(t.lastIntValue=e,t.advance(),!0):!1};function Pt(t){return t===36||t>=40&&t<=43||t===46||t===63||t>=91&&t<=94||t>=123&&t<=125}E.regexp_eatPatternCharacters=function(t){for(var e=t.pos,s=0;(s=t.current())!==-1&&!Pt(s);)t.advance();return t.pos!==e};E.regexp_eatExtendedPatternCharacter=function(t){var e=t.current();return e!==-1&&e!==36&&!(e>=40&&e<=43)&&e!==46&&e!==63&&e!==91&&e!==94&&e!==124?(t.advance(),!0):!1};E.regexp_groupSpecifier=function(t){if(t.eat(63)){this.regexp_eatGroupName(t)||t.raise("Invalid group");var e=this.options.ecmaVersion>=16,s=t.groupNames[t.lastStringValue];if(s)if(e)for(var i=0,n=s;i<n.length;i+=1){var r=n[i];r.separatedFrom(t.branchID)||t.raise("Duplicate capture group name")}else t.raise("Duplicate capture group name");e?(s||(t.groupNames[t.lastStringValue]=[])).push(t.branchID):t.groupNames[t.lastStringValue]=!0}};E.regexp_eatGroupName=function(t){if(t.lastStringValue="",t.eat(60)){if(this.regexp_eatRegExpIdentifierName(t)&&t.eat(62))return!0;t.raise("Invalid capture group name")}return!1};E.regexp_eatRegExpIdentifierName=function(t){if(t.lastStringValue="",this.regexp_eatRegExpIdentifierStart(t)){for(t.lastStringValue+=G(t.lastIntValue);this.regexp_eatRegExpIdentifierPart(t);)t.lastStringValue+=G(t.lastIntValue);return!0}return!1};E.regexp_eatRegExpIdentifierStart=function(t){var e=t.pos,s=this.options.ecmaVersion>=11,i=t.current(s);return t.advance(s),i===92&&this.regexp_eatRegExpUnicodeEscapeSequence(t,s)&&(i=t.lastIntValue),fs(i)?(t.lastIntValue=i,!0):(t.pos=e,!1)};function fs(t){return q(t,!0)||t===36||t===95}E.regexp_eatRegExpIdentifierPart=function(t){var e=t.pos,s=this.options.ecmaVersion>=11,i=t.current(s);return t.advance(s),i===92&&this.regexp_eatRegExpUnicodeEscapeSequence(t,s)&&(i=t.lastIntValue),ds(i)?(t.lastIntValue=i,!0):(t.pos=e,!1)};function ds(t){return J(t,!0)||t===36||t===95||t===8204||t===8205}E.regexp_eatAtomEscape=function(t){return this.regexp_eatBackReference(t)||this.regexp_eatCharacterClassEscape(t)||this.regexp_eatCharacterEscape(t)||t.switchN&&this.regexp_eatKGroupName(t)?!0:(t.switchU&&(t.current()===99&&t.raise("Invalid unicode escape"),t.raise("Invalid escape")),!1)};E.regexp_eatBackReference=function(t){var e=t.pos;if(this.regexp_eatDecimalEscape(t)){var s=t.lastIntValue;if(t.switchU)return s>t.maxBackReference&&(t.maxBackReference=s),!0;if(s<=t.numCapturingParens)return!0;t.pos=e}return!1};E.regexp_eatKGroupName=function(t){if(t.eat(107)){if(this.regexp_eatGroupName(t))return t.backReferenceNames.push(t.lastStringValue),!0;t.raise("Invalid named reference")}return!1};E.regexp_eatCharacterEscape=function(t){return this.regexp_eatControlEscape(t)||this.regexp_eatCControlLetter(t)||this.regexp_eatZero(t)||this.regexp_eatHexEscapeSequence(t)||this.regexp_eatRegExpUnicodeEscapeSequence(t,!1)||!t.switchU&&this.regexp_eatLegacyOctalEscapeSequence(t)||this.regexp_eatIdentityEscape(t)};E.regexp_eatCControlLetter=function(t){var e=t.pos;if(t.eat(99)){if(this.regexp_eatControlLetter(t))return!0;t.pos=e}return!1};E.regexp_eatZero=function(t){return t.current()===48&&!Ie(t.lookahead())?(t.lastIntValue=0,t.advance(),!0):!1};E.regexp_eatControlEscape=function(t){var e=t.current();return e===116?(t.lastIntValue=9,t.advance(),!0):e===110?(t.lastIntValue=10,t.advance(),!0):e===118?(t.lastIntValue=11,t.advance(),!0):e===102?(t.lastIntValue=12,t.advance(),!0):e===114?(t.lastIntValue=13,t.advance(),!0):!1};E.regexp_eatControlLetter=function(t){var e=t.current();return _t(e)?(t.lastIntValue=e%32,t.advance(),!0):!1};function _t(t){return t>=65&&t<=90||t>=97&&t<=122}E.regexp_eatRegExpUnicodeEscapeSequence=function(t,e){e===void 0&&(e=!1);var s=t.pos,i=e||t.switchU;if(t.eat(117)){if(this.regexp_eatFixedHexDigits(t,4)){var n=t.lastIntValue;if(i&&n>=55296&&n<=56319){var r=t.pos;if(t.eat(92)&&t.eat(117)&&this.regexp_eatFixedHexDigits(t,4)){var a=t.lastIntValue;if(a>=56320&&a<=57343)return t.lastIntValue=(n-55296)*1024+(a-56320)+65536,!0}t.pos=r,t.lastIntValue=n}return!0}if(i&&t.eat(123)&&this.regexp_eatHexDigits(t)&&t.eat(125)&&ms(t.lastIntValue))return!0;i&&t.raise("Invalid unicode escape"),t.pos=s}return!1};function ms(t){return t>=0&&t<=1114111}E.regexp_eatIdentityEscape=function(t){if(t.switchU)return this.regexp_eatSyntaxCharacter(t)?!0:t.eat(47)?(t.lastIntValue=47,!0):!1;var e=t.current();return e!==99&&(!t.switchN||e!==107)?(t.lastIntValue=e,t.advance(),!0):!1};E.regexp_eatDecimalEscape=function(t){t.lastIntValue=0;var e=t.current();if(e>=49&&e<=57){do t.lastIntValue=10*t.lastIntValue+(e-48),t.advance();while((e=t.current())>=48&&e<=57);return!0}return!1};var kt=0,Q=1,B=2;E.regexp_eatCharacterClassEscape=function(t){var e=t.current();if(gs(e))return t.lastIntValue=-1,t.advance(),Q;var s=!1;if(t.switchU&&this.options.ecmaVersion>=9&&((s=e===80)||e===112)){t.lastIntValue=-1,t.advance();var i;if(t.eat(123)&&(i=this.regexp_eatUnicodePropertyValueExpression(t))&&t.eat(125))return s&&i===B&&t.raise("Invalid property name"),i;t.raise("Invalid property name")}return kt};function gs(t){return t===100||t===68||t===115||t===83||t===119||t===87}E.regexp_eatUnicodePropertyValueExpression=function(t){var e=t.pos;if(this.regexp_eatUnicodePropertyName(t)&&t.eat(61)){var s=t.lastStringValue;if(this.regexp_eatUnicodePropertyValue(t)){var i=t.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(t,s,i),Q}}if(t.pos=e,this.regexp_eatLoneUnicodePropertyNameOrValue(t)){var n=t.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(t,n)}return kt};E.regexp_validateUnicodePropertyNameAndValue=function(t,e,s){le(t.unicodeProperties.nonBinary,e)||t.raise("Invalid property name"),t.unicodeProperties.nonBinary[e].test(s)||t.raise("Invalid property value")};E.regexp_validateUnicodePropertyNameOrValue=function(t,e){if(t.unicodeProperties.binary.test(e))return Q;if(t.switchV&&t.unicodeProperties.binaryOfStrings.test(e))return B;t.raise("Invalid property name")};E.regexp_eatUnicodePropertyName=function(t){var e=0;for(t.lastStringValue="";It(e=t.current());)t.lastStringValue+=G(e),t.advance();return t.lastStringValue!==""};function It(t){return _t(t)||t===95}E.regexp_eatUnicodePropertyValue=function(t){var e=0;for(t.lastStringValue="";xs(e=t.current());)t.lastStringValue+=G(e),t.advance();return t.lastStringValue!==""};function xs(t){return It(t)||Ie(t)}E.regexp_eatLoneUnicodePropertyNameOrValue=function(t){return this.regexp_eatUnicodePropertyValue(t)};E.regexp_eatCharacterClass=function(t){if(t.eat(91)){var e=t.eat(94),s=this.regexp_classContents(t);return t.eat(93)||t.raise("Unterminated character class"),e&&s===B&&t.raise("Negated character class may contain strings"),!0}return!1};E.regexp_classContents=function(t){return t.current()===93?Q:t.switchV?this.regexp_classSetExpression(t):(this.regexp_nonEmptyClassRanges(t),Q)};E.regexp_nonEmptyClassRanges=function(t){for(;this.regexp_eatClassAtom(t);){var e=t.lastIntValue;if(t.eat(45)&&this.regexp_eatClassAtom(t)){var s=t.lastIntValue;t.switchU&&(e===-1||s===-1)&&t.raise("Invalid character class"),e!==-1&&s!==-1&&e>s&&t.raise("Range out of order in character class")}}};E.regexp_eatClassAtom=function(t){var e=t.pos;if(t.eat(92)){if(this.regexp_eatClassEscape(t))return!0;if(t.switchU){var s=t.current();(s===99||Rt(s))&&t.raise("Invalid class escape"),t.raise("Invalid escape")}t.pos=e}var i=t.current();return i!==93?(t.lastIntValue=i,t.advance(),!0):!1};E.regexp_eatClassEscape=function(t){var e=t.pos;if(t.eat(98))return t.lastIntValue=8,!0;if(t.switchU&&t.eat(45))return t.lastIntValue=45,!0;if(!t.switchU&&t.eat(99)){if(this.regexp_eatClassControlLetter(t))return!0;t.pos=e}return this.regexp_eatCharacterClassEscape(t)||this.regexp_eatCharacterEscape(t)};E.regexp_classSetExpression=function(t){var e=Q,s;if(!this.regexp_eatClassSetRange(t))if(s=this.regexp_eatClassSetOperand(t)){s===B&&(e=B);for(var i=t.pos;t.eatChars([38,38]);){if(t.current()!==38&&(s=this.regexp_eatClassSetOperand(t))){s!==B&&(e=Q);continue}t.raise("Invalid character in character class")}if(i!==t.pos)return e;for(;t.eatChars([45,45]);)this.regexp_eatClassSetOperand(t)||t.raise("Invalid character in character class");if(i!==t.pos)return e}else t.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(t)){if(s=this.regexp_eatClassSetOperand(t),!s)return e;s===B&&(e=B)}};E.regexp_eatClassSetRange=function(t){var e=t.pos;if(this.regexp_eatClassSetCharacter(t)){var s=t.lastIntValue;if(t.eat(45)&&this.regexp_eatClassSetCharacter(t)){var i=t.lastIntValue;return s!==-1&&i!==-1&&s>i&&t.raise("Range out of order in character class"),!0}t.pos=e}return!1};E.regexp_eatClassSetOperand=function(t){return this.regexp_eatClassSetCharacter(t)?Q:this.regexp_eatClassStringDisjunction(t)||this.regexp_eatNestedClass(t)};E.regexp_eatNestedClass=function(t){var e=t.pos;if(t.eat(91)){var s=t.eat(94),i=this.regexp_classContents(t);if(t.eat(93))return s&&i===B&&t.raise("Negated character class may contain strings"),i;t.pos=e}if(t.eat(92)){var n=this.regexp_eatCharacterClassEscape(t);if(n)return n;t.pos=e}return null};E.regexp_eatClassStringDisjunction=function(t){var e=t.pos;if(t.eatChars([92,113])){if(t.eat(123)){var s=this.regexp_classStringDisjunctionContents(t);if(t.eat(125))return s}else t.raise("Invalid escape");t.pos=e}return null};E.regexp_classStringDisjunctionContents=function(t){for(var e=this.regexp_classString(t);t.eat(124);)this.regexp_classString(t)===B&&(e=B);return e};E.regexp_classString=function(t){for(var e=0;this.regexp_eatClassSetCharacter(t);)e++;return e===1?Q:B};E.regexp_eatClassSetCharacter=function(t){var e=t.pos;if(t.eat(92))return this.regexp_eatCharacterEscape(t)||this.regexp_eatClassSetReservedPunctuator(t)?!0:t.eat(98)?(t.lastIntValue=8,!0):(t.pos=e,!1);var s=t.current();return s<0||s===t.lookahead()&&Es(s)||bs(s)?!1:(t.advance(),t.lastIntValue=s,!0)};function Es(t){return t===33||t>=35&&t<=38||t>=42&&t<=44||t===46||t>=58&&t<=64||t===94||t===96||t===126}function bs(t){return t===40||t===41||t===45||t===47||t>=91&&t<=93||t>=123&&t<=125}E.regexp_eatClassSetReservedPunctuator=function(t){var e=t.current();return Cs(e)?(t.lastIntValue=e,t.advance(),!0):!1};function Cs(t){return t===33||t===35||t===37||t===38||t===44||t===45||t>=58&&t<=62||t===64||t===96||t===126}E.regexp_eatClassControlLetter=function(t){var e=t.current();return Ie(e)||e===95?(t.lastIntValue=e%32,t.advance(),!0):!1};E.regexp_eatHexEscapeSequence=function(t){var e=t.pos;if(t.eat(120)){if(this.regexp_eatFixedHexDigits(t,2))return!0;t.switchU&&t.raise("Invalid escape"),t.pos=e}return!1};E.regexp_eatDecimalDigits=function(t){var e=t.pos,s=0;for(t.lastIntValue=0;Ie(s=t.current());)t.lastIntValue=10*t.lastIntValue+(s-48),t.advance();return t.pos!==e};function Ie(t){return t>=48&&t<=57}E.regexp_eatHexDigits=function(t){var e=t.pos,s=0;for(t.lastIntValue=0;Nt(s=t.current());)t.lastIntValue=16*t.lastIntValue+Mt(s),t.advance();return t.pos!==e};function Nt(t){return t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102}function Mt(t){return t>=65&&t<=70?10+(t-65):t>=97&&t<=102?10+(t-97):t-48}E.regexp_eatLegacyOctalEscapeSequence=function(t){if(this.regexp_eatOctalDigit(t)){var e=t.lastIntValue;if(this.regexp_eatOctalDigit(t)){var s=t.lastIntValue;e<=3&&this.regexp_eatOctalDigit(t)?t.lastIntValue=e*64+s*8+t.lastIntValue:t.lastIntValue=e*8+s}else t.lastIntValue=e;return!0}return!1};E.regexp_eatOctalDigit=function(t){var e=t.current();return Rt(e)?(t.lastIntValue=e-48,t.advance(),!0):(t.lastIntValue=0,!1)};function Rt(t){return t>=48&&t<=55}E.regexp_eatFixedHexDigits=function(t,e){var s=t.pos;t.lastIntValue=0;for(var i=0;i<e;++i){var n=t.current();if(!Nt(n))return t.pos=s,!1;t.lastIntValue=16*t.lastIntValue+Mt(n),t.advance()}return!0};var qe=function(e){this.type=e.type,this.value=e.value,this.start=e.start,this.end=e.end,e.options.locations&&(this.loc=new Te(e,e.startLoc,e.endLoc)),e.options.ranges&&(this.range=[e.start,e.end])},A=I.prototype;A.next=function(t){!t&&this.type.keyword&&this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword "+this.type.keyword),this.options.onToken&&this.options.onToken(new qe(this)),this.lastTokEnd=this.end,this.lastTokStart=this.start,this.lastTokEndLoc=this.endLoc,this.lastTokStartLoc=this.startLoc,this.nextToken()};A.getToken=function(){return this.next(),new qe(this)};typeof Symbol<"u"&&(A[Symbol.iterator]=function(){var t=this;return{next:function(){var e=t.getToken();return{done:e.type===u.eof,value:e}}}});A.nextToken=function(){var t=this.curContext();if((!t||!t.preserveSpace)&&this.skipSpace(),this.start=this.pos,this.options.locations&&(this.startLoc=this.curPosition()),this.pos>=this.input.length)return this.finishToken(u.eof);if(t.override)return t.override(this);this.readToken(this.fullCharCodeAtPos())};A.readToken=function(t){return q(t,this.options.ecmaVersion>=6)||t===92?this.readWord():this.getTokenFromCode(t)};A.fullCharCodeAtPos=function(){var t=this.input.charCodeAt(this.pos);if(t<=55295||t>=56320)return t;var e=this.input.charCodeAt(this.pos+1);return e<=56319||e>=57344?t:(t<<10)+e-56613888};A.skipBlockComment=function(){var t=this.options.onComment&&this.curPosition(),e=this.pos,s=this.input.indexOf("*/",this.pos+=2);if(s===-1&&this.raise(this.pos-2,"Unterminated comment"),this.pos=s+2,this.options.locations)for(var i=void 0,n=e;(i=it(this.input,n,this.pos))>-1;)++this.curLine,n=this.lineStart=i;this.options.onComment&&this.options.onComment(!0,this.input.slice(e+2,s),e,this.pos,t,this.curPosition())};A.skipLineComment=function(t){for(var e=this.pos,s=this.options.onComment&&this.curPosition(),i=this.input.charCodeAt(this.pos+=t);this.pos<this.input.length&&!ue(i);)i=this.input.charCodeAt(++this.pos);this.options.onComment&&this.options.onComment(!1,this.input.slice(e+t,this.pos),e,this.pos,s,this.curPosition())};A.skipSpace=function(){e:for(;this.pos<this.input.length;){var t=this.input.charCodeAt(this.pos);switch(t){case 32:case 160:++this.pos;break;case 13:this.input.charCodeAt(this.pos+1)===10&&++this.pos;case 10:case 8232:case 8233:++this.pos,this.options.locations&&(++this.curLine,this.lineStart=this.pos);break;case 47:switch(this.input.charCodeAt(this.pos+1)){case 42:this.skipBlockComment();break;case 47:this.skipLineComment(2);break;default:break e}break;default:if(t>8&&t<14||t>=5760&&nt.test(String.fromCharCode(t)))++this.pos;else break e}}};A.finishToken=function(t,e){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var s=this.type;this.type=t,this.value=e,this.updateContext(s)};A.readToken_dot=function(){var t=this.input.charCodeAt(this.pos+1);if(t>=48&&t<=57)return this.readNumber(!0);var e=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&t===46&&e===46?(this.pos+=3,this.finishToken(u.ellipsis)):(++this.pos,this.finishToken(u.dot))};A.readToken_slash=function(){var t=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):t===61?this.finishOp(u.assign,2):this.finishOp(u.slash,1)};A.readToken_mult_modulo_exp=function(t){var e=this.input.charCodeAt(this.pos+1),s=1,i=t===42?u.star:u.modulo;return this.options.ecmaVersion>=7&&t===42&&e===42&&(++s,i=u.starstar,e=this.input.charCodeAt(this.pos+2)),e===61?this.finishOp(u.assign,s+1):this.finishOp(i,s)};A.readToken_pipe_amp=function(t){var e=this.input.charCodeAt(this.pos+1);if(e===t){if(this.options.ecmaVersion>=12){var s=this.input.charCodeAt(this.pos+2);if(s===61)return this.finishOp(u.assign,3)}return this.finishOp(t===124?u.logicalOR:u.logicalAND,2)}return e===61?this.finishOp(u.assign,2):this.finishOp(t===124?u.bitwiseOR:u.bitwiseAND,1)};A.readToken_caret=function(){var t=this.input.charCodeAt(this.pos+1);return t===61?this.finishOp(u.assign,2):this.finishOp(u.bitwiseXOR,1)};A.readToken_plus_min=function(t){var e=this.input.charCodeAt(this.pos+1);return e===t?e===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||V.test(this.input.slice(this.lastTokEnd,this.pos)))?(this.skipLineComment(3),this.skipSpace(),this.nextToken()):this.finishOp(u.incDec,2):e===61?this.finishOp(u.assign,2):this.finishOp(u.plusMin,1)};A.readToken_lt_gt=function(t){var e=this.input.charCodeAt(this.pos+1),s=1;return e===t?(s=t===62&&this.input.charCodeAt(this.pos+2)===62?3:2,this.input.charCodeAt(this.pos+s)===61?this.finishOp(u.assign,s+1):this.finishOp(u.bitShift,s)):e===33&&t===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45?(this.skipLineComment(4),this.skipSpace(),this.nextToken()):(e===61&&(s=2),this.finishOp(u.relational,s))};A.readToken_eq_excl=function(t){var e=this.input.charCodeAt(this.pos+1);return e===61?this.finishOp(u.equality,this.input.charCodeAt(this.pos+2)===61?3:2):t===61&&e===62&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(u.arrow)):this.finishOp(t===61?u.eq:u.prefix,1)};A.readToken_question=function(){var t=this.options.ecmaVersion;if(t>=11){var e=this.input.charCodeAt(this.pos+1);if(e===46){var s=this.input.charCodeAt(this.pos+2);if(s<48||s>57)return this.finishOp(u.questionDot,2)}if(e===63){if(t>=12){var i=this.input.charCodeAt(this.pos+2);if(i===61)return this.finishOp(u.assign,3)}return this.finishOp(u.coalesce,2)}}return this.finishOp(u.question,1)};A.readToken_numberSign=function(){var t=this.options.ecmaVersion,e=35;if(t>=13&&(++this.pos,e=this.fullCharCodeAtPos(),q(e,!0)||e===92))return this.finishToken(u.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+G(e)+"'")};A.getTokenFromCode=function(t){switch(t){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(u.parenL);case 41:return++this.pos,this.finishToken(u.parenR);case 59:return++this.pos,this.finishToken(u.semi);case 44:return++this.pos,this.finishToken(u.comma);case 91:return++this.pos,this.finishToken(u.bracketL);case 93:return++this.pos,this.finishToken(u.bracketR);case 123:return++this.pos,this.finishToken(u.braceL);case 125:return++this.pos,this.finishToken(u.braceR);case 58:return++this.pos,this.finishToken(u.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(u.backQuote);case 48:var e=this.input.charCodeAt(this.pos+1);if(e===120||e===88)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(e===111||e===79)return this.readRadixNumber(8);if(e===98||e===66)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(t);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(t);case 124:case 38:return this.readToken_pipe_amp(t);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(t);case 60:case 62:return this.readToken_lt_gt(t);case 61:case 33:return this.readToken_eq_excl(t);case 63:return this.readToken_question();case 126:return this.finishOp(u.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+G(t)+"'")};A.finishOp=function(t,e){var s=this.input.slice(this.pos,this.pos+e);return this.pos+=e,this.finishToken(t,s)};A.readRegexp=function(){for(var t,e,s=this.pos;;){this.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var i=this.input.charAt(this.pos);if(V.test(i)&&this.raise(s,"Unterminated regular expression"),t)t=!1;else{if(i==="[")e=!0;else if(i==="]"&&e)e=!1;else if(i==="/"&&!e)break;t=i==="\\"}++this.pos}var n=this.input.slice(s,this.pos);++this.pos;var r=this.pos,a=this.readWord1();this.containsEsc&&this.unexpected(r);var o=this.regexpState||(this.regexpState=new K(this));o.reset(s,n,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var c=null;try{c=new RegExp(n,a)}catch{}return this.finishToken(u.regexp,{pattern:n,flags:a,value:c})};A.readInt=function(t,e,s){for(var i=this.options.ecmaVersion>=12&&e===void 0,n=s&&this.input.charCodeAt(this.pos)===48,r=this.pos,a=0,o=0,c=0,l=e??1/0;c<l;++c,++this.pos){var h=this.input.charCodeAt(this.pos),p=void 0;if(i&&h===95){n&&this.raiseRecoverable(this.pos,"Numeric separator is not allowed in legacy octal numeric literals"),o===95&&this.raiseRecoverable(this.pos,"Numeric separator must be exactly one underscore"),c===0&&this.raiseRecoverable(this.pos,"Numeric separator is not allowed at the first of digits"),o=h;continue}if(h>=97?p=h-97+10:h>=65?p=h-65+10:h>=48&&h<=57?p=h-48:p=1/0,p>=t)break;o=h,a=a*t+p}return i&&o===95&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===r||e!=null&&this.pos-r!==e?null:a};function ys(t,e){return e?parseInt(t,8):parseFloat(t.replace(/_/g,""))}function Ot(t){return typeof BigInt!="function"?null:BigInt(t.replace(/_/g,""))}A.readRadixNumber=function(t){var e=this.pos;this.pos+=2;var s=this.readInt(t);return s==null&&this.raise(this.start+2,"Expected number in radix "+t),this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110?(s=Ot(this.input.slice(e,this.pos)),++this.pos):q(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(u.num,s)};A.readNumber=function(t){var e=this.pos;!t&&this.readInt(10,void 0,!0)===null&&this.raise(e,"Invalid number");var s=this.pos-e>=2&&this.input.charCodeAt(e)===48;s&&this.strict&&this.raise(e,"Invalid number");var i=this.input.charCodeAt(this.pos);if(!s&&!t&&this.options.ecmaVersion>=11&&i===110){var n=Ot(this.input.slice(e,this.pos));return++this.pos,q(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(u.num,n)}s&&/[89]/.test(this.input.slice(e,this.pos))&&(s=!1),i===46&&!s&&(++this.pos,this.readInt(10),i=this.input.charCodeAt(this.pos)),(i===69||i===101)&&!s&&(i=this.input.charCodeAt(++this.pos),(i===43||i===45)&&++this.pos,this.readInt(10)===null&&this.raise(e,"Invalid number")),q(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var r=ys(this.input.slice(e,this.pos),s);return this.finishToken(u.num,r)};A.readCodePoint=function(){var t=this.input.charCodeAt(this.pos),e;if(t===123){this.options.ecmaVersion<6&&this.unexpected();var s=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(s,"Code point out of bounds")}else e=this.readHexChar(4);return e};A.readString=function(t){for(var e="",s=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var i=this.input.charCodeAt(this.pos);if(i===t)break;i===92?(e+=this.input.slice(s,this.pos),e+=this.readEscapedChar(!1),s=this.pos):i===8232||i===8233?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(ue(i)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return e+=this.input.slice(s,this.pos++),this.finishToken(u.string,e)};var Lt={};A.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(t){if(t===Lt)this.readInvalidTemplateToken();else throw t}this.inTemplateElement=!1};A.invalidStringToken=function(t,e){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw Lt;this.raise(t,e)};A.readTmplToken=function(){for(var t="",e=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var s=this.input.charCodeAt(this.pos);if(s===96||s===36&&this.input.charCodeAt(this.pos+1)===123)return this.pos===this.start&&(this.type===u.template||this.type===u.invalidTemplate)?s===36?(this.pos+=2,this.finishToken(u.dollarBraceL)):(++this.pos,this.finishToken(u.backQuote)):(t+=this.input.slice(e,this.pos),this.finishToken(u.template,t));if(s===92)t+=this.input.slice(e,this.pos),t+=this.readEscapedChar(!0),e=this.pos;else if(ue(s)){switch(t+=this.input.slice(e,this.pos),++this.pos,s){case 13:this.input.charCodeAt(this.pos)===10&&++this.pos;case 10:t+=`
|
|
6
6
|
`;break;default:t+=String.fromCharCode(s);break}this.options.locations&&(++this.curLine,this.lineStart=this.pos),e=this.pos}else++this.pos}};A.readInvalidTemplateToken=function(){for(;this.pos<this.input.length;this.pos++)switch(this.input[this.pos]){case"\\":++this.pos;break;case"$":if(this.input[this.pos+1]!=="{")break;case"`":return this.finishToken(u.invalidTemplate,this.input.slice(this.start,this.pos));case"\r":this.input[this.pos+1]===`
|
|
7
7
|
`&&++this.pos;case`
|
|
8
8
|
`:case"\u2028":case"\u2029":++this.curLine,this.lineStart=this.pos+1;break}this.raise(this.start,"Unterminated template")};A.readEscapedChar=function(t){var e=this.input.charCodeAt(++this.pos);switch(++this.pos,e){case 110:return`
|
|
9
|
-
`;case 114:return"\r";case 120:return String.fromCharCode(this.readHexChar(2));case 117:return G(this.readCodePoint());case 116:return" ";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 13:this.input.charCodeAt(this.pos)===10&&++this.pos;case 10:return this.options.locations&&(this.lineStart=this.pos,++this.curLine),"";case 56:case 57:if(this.strict&&this.invalidStringToken(this.pos-1,"Invalid escape sequence"),t){var s=this.pos-1;this.invalidStringToken(s,"Invalid escape sequence in template string")}default:if(e>=48&&e<=55){var i=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(i,8);return n>255&&(i=i.slice(0,-1),n=parseInt(i,8)),this.pos+=i.length-1,e=this.input.charCodeAt(this.pos),(i!=="0"||e===56||e===57)&&(this.strict||t)&&this.invalidStringToken(this.pos-1-i.length,t?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return ue(e)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(e)}};A.readHexChar=function(t){var e=this.pos,s=this.readInt(16,t);return s===null&&this.invalidStringToken(e,"Bad character escape sequence"),s};A.readWord1=function(){this.containsEsc=!1;for(var t="",e=!0,s=this.pos,i=this.options.ecmaVersion>=6;this.pos<this.input.length;){var n=this.fullCharCodeAtPos();if(J(n,i))this.pos+=n<=65535?1:2;else if(n===92){this.containsEsc=!0,t+=this.input.slice(s,this.pos);var r=this.pos;this.input.charCodeAt(++this.pos)!==117&&this.invalidStringToken(this.pos,"Expecting Unicode escape sequence \\uXXXX"),++this.pos;var a=this.readCodePoint();(e?q:J)(a,i)||this.invalidStringToken(r,"Invalid Unicode escape"),t+=G(a),s=this.pos}else break;e=!1}return t+this.input.slice(s,this.pos)};A.readWord=function(){var t=this.readWord1(),e=u.name;return this.keywords.test(t)&&(e=$e[t]),this.finishToken(e,t)};var vs="8.15.0";I.acorn={Parser:I,version:vs,defaultOptions:Ve,Position:me,SourceLocation:Te,getLineInfo:at,Node:ke,TokenType:w,tokTypes:u,keywordTypes:$e,TokContext:W,tokContexts:k,isIdentifierChar:J,isIdentifierStart:q,Token:qe,isNewLine:ue,lineBreak:V,lineBreakG:Ht,nonASCIIwhitespace:nt};function U(t,e){return I.parse(t,e)}function H(t,e,s,i,n){s||(s=g),(function r(a,o,c){var l=c||a.type;s[l](a,o,r),e[l]&&e[l](a,o)})(t,i,n)}function Ss(t,e,s,i,n){var r=[];s||(s=g),(function a(o,c,l){var h=l||o.type,p=o!==r[r.length-1];p&&r.push(o),s[h](o,c,a),e[h]&&e[h](o,c||r,r),p&&r.pop()})(t,i,n)}function Xe(t,e,s){s(t,e)}function re(t,e,s){}var g={};g.Program=g.BlockStatement=g.StaticBlock=function(t,e,s){for(var i=0,n=t.body;i<n.length;i+=1){var r=n[i];s(r,e,"Statement")}};g.Statement=Xe;g.EmptyStatement=re;g.ExpressionStatement=g.ParenthesizedExpression=g.ChainExpression=function(t,e,s){return s(t.expression,e,"Expression")};g.IfStatement=function(t,e,s){s(t.test,e,"Expression"),s(t.consequent,e,"Statement"),t.alternate&&s(t.alternate,e,"Statement")};g.LabeledStatement=function(t,e,s){return s(t.body,e,"Statement")};g.BreakStatement=g.ContinueStatement=re;g.WithStatement=function(t,e,s){s(t.object,e,"Expression"),s(t.body,e,"Statement")};g.SwitchStatement=function(t,e,s){s(t.discriminant,e,"Expression");for(var i=0,n=t.cases;i<n.length;i+=1){var r=n[i];s(r,e)}};g.SwitchCase=function(t,e,s){t.test&&s(t.test,e,"Expression");for(var i=0,n=t.consequent;i<n.length;i+=1){var r=n[i];s(r,e,"Statement")}};g.ReturnStatement=g.YieldExpression=g.AwaitExpression=function(t,e,s){t.argument&&s(t.argument,e,"Expression")};g.ThrowStatement=g.SpreadElement=function(t,e,s){return s(t.argument,e,"Expression")};g.TryStatement=function(t,e,s){s(t.block,e,"Statement"),t.handler&&s(t.handler,e),t.finalizer&&s(t.finalizer,e,"Statement")};g.CatchClause=function(t,e,s){t.param&&s(t.param,e,"Pattern"),s(t.body,e,"Statement")};g.WhileStatement=g.DoWhileStatement=function(t,e,s){s(t.test,e,"Expression"),s(t.body,e,"Statement")};g.ForStatement=function(t,e,s){t.init&&s(t.init,e,"ForInit"),t.test&&s(t.test,e,"Expression"),t.update&&s(t.update,e,"Expression"),s(t.body,e,"Statement")};g.ForInStatement=g.ForOfStatement=function(t,e,s){s(t.left,e,"ForInit"),s(t.right,e,"Expression"),s(t.body,e,"Statement")};g.ForInit=function(t,e,s){t.type==="VariableDeclaration"?s(t,e):s(t,e,"Expression")};g.DebuggerStatement=re;g.FunctionDeclaration=function(t,e,s){return s(t,e,"Function")};g.VariableDeclaration=function(t,e,s){for(var i=0,n=t.declarations;i<n.length;i+=1){var r=n[i];s(r,e)}};g.VariableDeclarator=function(t,e,s){s(t.id,e,"Pattern"),t.init&&s(t.init,e,"Expression")};g.Function=function(t,e,s){t.id&&s(t.id,e,"Pattern");for(var i=0,n=t.params;i<n.length;i+=1){var r=n[i];s(r,e,"Pattern")}s(t.body,e,t.expression?"Expression":"Statement")};g.Pattern=function(t,e,s){t.type==="Identifier"?s(t,e,"VariablePattern"):t.type==="MemberExpression"?s(t,e,"MemberPattern"):s(t,e)};g.VariablePattern=re;g.MemberPattern=Xe;g.RestElement=function(t,e,s){return s(t.argument,e,"Pattern")};g.ArrayPattern=function(t,e,s){for(var i=0,n=t.elements;i<n.length;i+=1){var r=n[i];r&&s(r,e,"Pattern")}};g.ObjectPattern=function(t,e,s){for(var i=0,n=t.properties;i<n.length;i+=1){var r=n[i];r.type==="Property"?(r.computed&&s(r.key,e,"Expression"),s(r.value,e,"Pattern")):r.type==="RestElement"&&s(r.argument,e,"Pattern")}};g.Expression=Xe;g.ThisExpression=g.Super=g.MetaProperty=re;g.ArrayExpression=function(t,e,s){for(var i=0,n=t.elements;i<n.length;i+=1){var r=n[i];r&&s(r,e,"Expression")}};g.ObjectExpression=function(t,e,s){for(var i=0,n=t.properties;i<n.length;i+=1){var r=n[i];s(r,e)}};g.FunctionExpression=g.ArrowFunctionExpression=g.FunctionDeclaration;g.SequenceExpression=function(t,e,s){for(var i=0,n=t.expressions;i<n.length;i+=1){var r=n[i];s(r,e,"Expression")}};g.TemplateLiteral=function(t,e,s){for(var i=0,n=t.quasis;i<n.length;i+=1){var r=n[i];s(r,e)}for(var a=0,o=t.expressions;a<o.length;a+=1){var c=o[a];s(c,e,"Expression")}};g.TemplateElement=re;g.UnaryExpression=g.UpdateExpression=function(t,e,s){s(t.argument,e,"Expression")};g.BinaryExpression=g.LogicalExpression=function(t,e,s){s(t.left,e,"Expression"),s(t.right,e,"Expression")};g.AssignmentExpression=g.AssignmentPattern=function(t,e,s){s(t.left,e,"Pattern"),s(t.right,e,"Expression")};g.ConditionalExpression=function(t,e,s){s(t.test,e,"Expression"),s(t.consequent,e,"Expression"),s(t.alternate,e,"Expression")};g.NewExpression=g.CallExpression=function(t,e,s){if(s(t.callee,e,"Expression"),t.arguments)for(var i=0,n=t.arguments;i<n.length;i+=1){var r=n[i];s(r,e,"Expression")}};g.MemberExpression=function(t,e,s){s(t.object,e,"Expression"),t.computed&&s(t.property,e,"Expression")};g.ExportNamedDeclaration=g.ExportDefaultDeclaration=function(t,e,s){t.declaration&&s(t.declaration,e,t.type==="ExportNamedDeclaration"||t.declaration.id?"Statement":"Expression"),t.source&&s(t.source,e,"Expression")};g.ExportAllDeclaration=function(t,e,s){t.exported&&s(t.exported,e),s(t.source,e,"Expression")};g.ImportDeclaration=function(t,e,s){for(var i=0,n=t.specifiers;i<n.length;i+=1){var r=n[i];s(r,e)}s(t.source,e,"Expression")};g.ImportExpression=function(t,e,s){s(t.source,e,"Expression")};g.ImportSpecifier=g.ImportDefaultSpecifier=g.ImportNamespaceSpecifier=g.Identifier=g.PrivateIdentifier=g.Literal=re;g.TaggedTemplateExpression=function(t,e,s){s(t.tag,e,"Expression"),s(t.quasi,e,"Expression")};g.ClassDeclaration=g.ClassExpression=function(t,e,s){return s(t,e,"Class")};g.Class=function(t,e,s){t.id&&s(t.id,e,"Pattern"),t.superClass&&s(t.superClass,e,"Expression"),s(t.body,e)};g.ClassBody=function(t,e,s){for(var i=0,n=t.body;i<n.length;i+=1){var r=n[i];s(r,e)}};g.MethodDefinition=g.PropertyDefinition=g.Property=function(t,e,s){t.computed&&s(t.key,e,"Expression"),t.value&&s(t.value,e,"Expression")};const d={ATTR_PREFIXES:{COMPONENT:"pp-component",CONTEXT:"pp-context",LOOP:"pp-for",SPREAD:"pp-spread",REF:"pp-ref"},SCRIPT_TYPE:"text/pp",MAX_CACHE_SIZE:2e3,DEBOUNCE_MS:16,POOL_SIZE:10,MUSTACHE_PATTERN:/\{((?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*)\}/,MUSTACHE_SINGLE_PATTERN:/^\{((?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*)\}$/},Ae=new Set(["true","false","null","undefined","this","window","document","console","Math","Date","JSON","Object","Array","return","let","const","var","if","else","for","while","switch","case","break","continue","function","new","in","of","typeof","instanceof","void","delete","try","catch","finally","class","extends","super","thisElement","eventObject","arguments"]);function As(t,e){let s;return(...i)=>{clearTimeout(s),s=window.setTimeout(()=>t(...i),e)}}function Vt(t){return t.charAt(0).toUpperCase()+t.slice(1)}function ie(t){if(t==null||typeof t=="boolean"||typeof t=="function"||Array.isArray(t)&&t.length===0||typeof t=="object"&&Object.keys(t).length===0)return"";if(typeof t=="number")return String(t);if(typeof t=="string")return t;if(Array.isArray(t))return t.map(e=>ie(e)).filter(e=>e!=="").join("");if(typeof t=="object")try{return JSON.stringify(t)}catch{return"[object Object]"}return String(t)}class ae{static instance;walkerPool=[];traversalCache=new WeakMap;lastCacheTime=new WeakMap;CACHE_TTL=250;trackedElements=new Set;static getInstance(){return ae.instance||(ae.instance=new ae),ae.instance}acquireWalker(e,s,i){return document.createTreeWalker(e,s,i)}releaseWalker(e){this.walkerPool.length<3&&this.walkerPool.push(e)}getCachedTraversal(e,s,i){const n=Date.now(),r=this.traversalCache.get(e),a=this.lastCacheTime.get(e);if(r&&a&&n-a<this.CACHE_TTL){const c=r.get(s);if(c)return c}const o=i();return this.traversalCache.has(e)||(this.traversalCache.set(e,new Map),this.trackedElements.add(e)),this.traversalCache.get(e).set(s,o),this.lastCacheTime.set(e,n),o}traverseElementsAndText(e,s,i){const n=this.acquireWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT),r=[],a=[];let o;for(;o=n.nextNode();)if(o.nodeType===Node.ELEMENT_NODE){const c=o;(!s||s(c))&&r.push(c)}else if(o.nodeType===Node.TEXT_NODE){const c=o;(!i||i(c))&&a.push(c)}return this.releaseWalker(n),{elements:r,textNodes:a}}cleanupCache(){const e=[];for(const s of this.trackedElements)document.contains(s)||e.push(s);e.forEach(s=>{this.traversalCache.delete(s),this.lastCacheTime.delete(s),this.trackedElements.delete(s)})}}class L{static instance;componentElementsCache=new $(100);scriptElementsCache=new $(50);templateElementsCache=new $(50);selectorCache=new $(200);elementComponentCache=new WeakMap;parentComponentCache=new WeakMap;contextComponentCache=new WeakMap;elementDepthCache=new WeakMap;elementChildrenCache=new WeakMap;cacheHits=0;cacheMisses=0;static CACHE_KEYS={COMPONENT_ELEMENTS:e=>`comp:${e}`,SCRIPTS:(e,s)=>`scripts:${e}:${s}`,TEMPLATES:(e,s)=>`templates:${e}:${s}`,SELECTOR:e=>`sel:${e}`};static getInstance(){return L.instance||(L.instance=new L),L.instance}queryComponentElements(e){const s=L.CACHE_KEYS.COMPONENT_ELEMENTS(e);if(this.componentElementsCache.has(s))return this.cacheHits++,this.componentElementsCache.get(s);this.cacheMisses++;const i=Array.from(document.querySelectorAll(`[${d.ATTR_PREFIXES.COMPONENT}="${e}"]`));return i.forEach(n=>{this.elementComponentCache.set(n,e)}),this.componentElementsCache.set(s,i),i}querySelectorAll(e){const s=L.CACHE_KEYS.SELECTOR(e);if(this.selectorCache.has(s))return this.cacheHits++,this.selectorCache.get(s);this.cacheMisses++;const i=Array.from(document.querySelectorAll(e));return this.selectorCache.set(s,i),i}getElementComponent(e){if(this.elementComponentCache.has(e))return this.cacheHits++,this.elementComponentCache.get(e);this.cacheMisses++;const s=e.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(s)return this.elementComponentCache.set(e,s),s;let i=e.parentElement;for(;i;){const n=i.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(n)return this.elementComponentCache.set(e,n),n;i=i.parentElement}return this.elementComponentCache.set(e,"app"),"app"}getContextComponent(e){if(this.contextComponentCache.has(e))return this.cacheHits++,this.contextComponentCache.get(e);this.cacheMisses++;const s=e.getAttribute(d.ATTR_PREFIXES.CONTEXT);let i;if(s)if(s==="parent"){const n=this.getElementComponent(e);i=this.getParentOfComponent(n,e)}else s==="app"?i="app":i=s;else i=this.getElementComponent(e);return this.contextComponentCache.set(e,i),i}getParentOfComponent(e,s){if(this.parentComponentCache.has(s))return this.cacheHits++,this.parentComponentCache.get(s);if(this.cacheMisses++,e==="app")return this.parentComponentCache.set(s,"app"),"app";let i=s;for(;i&&i.getAttribute(d.ATTR_PREFIXES.COMPONENT)!==e;)i=i.parentElement;if(!i)return this.parentComponentCache.set(s,"app"),"app";let n=i.parentElement;for(;n;){const r=n.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(r)return this.parentComponentCache.set(s,r),r;n=n.parentElement}return this.parentComponentCache.set(s,"app"),"app"}getElementDepthCached(e){if(this.elementDepthCache.has(e))return this.cacheHits++,this.elementDepthCache.get(e);this.cacheMisses++;let s=0,i=e.parentElement;for(;i&&i!==document.body;)s++,i=i.parentElement;return this.elementDepthCache.set(e,s),s}getFirstComponentElement(e){const s=this.queryComponentElements(e);return s.length>0?s[0]:null}getComponentScripts(e,s){const i=L.CACHE_KEYS.SCRIPTS(e,s?.tagName||"global");if(this.scriptElementsCache.has(i))return this.cacheHits++,this.scriptElementsCache.get(i);this.cacheMisses++;let n=[];if(s){const r=s.querySelectorAll(`script[type="${d.SCRIPT_TYPE}"]`);for(const a of r)a instanceof HTMLScriptElement&&n.push(a)}else{const r=document.querySelectorAll(`script[type="${d.SCRIPT_TYPE}"]`);for(const a of r)if(a instanceof HTMLScriptElement){const o=a.getAttribute(d.ATTR_PREFIXES.COMPONENT);(o===e||!o&&!a.closest(`[${d.ATTR_PREFIXES.COMPONENT}]`))&&n.push(a)}}return this.scriptElementsCache.set(i,n),n}getComponentTemplates(e,s){const i=L.CACHE_KEYS.TEMPLATES(e,s?.tagName||"global");if(this.templateElementsCache.has(i))return this.cacheHits++,this.templateElementsCache.get(i);this.cacheMisses++;let n=[];if(s){const r=s.querySelectorAll("template[pp-for]");for(const a of r)a instanceof HTMLTemplateElement&&this.getElementComponent(a)===e&&n.push(a)}else{const r=document.querySelectorAll("template[pp-for]");for(const a of r)a instanceof HTMLTemplateElement&&this.getElementComponent(a)===e&&n.push(a)}return this.templateElementsCache.set(i,n),n}querySelector(e){const s=this.querySelectorAll(e);return s.length>0?s[0]:null}findElementForComponent(e,s){if(s==="app")return document.body;const i=this.queryComponentElements(s);return i.length>0?i[0]:null}invalidateCache(e){switch(e){case"components":this.componentElementsCache.clear();break;case"selectors":this.selectorCache.clear();break;case"scripts":this.scriptElementsCache.clear();break;case"templates":this.templateElementsCache.clear();break;default:this.clearAllCaches()}}invalidateByComponent(e){const s=L.CACHE_KEYS.COMPONENT_ELEMENTS(e);this.componentElementsCache.delete(s);const i=L.CACHE_KEYS.SCRIPTS(e,"global");this.scriptElementsCache.delete(i);const n=L.CACHE_KEYS.TEMPLATES(e,"global");this.templateElementsCache.delete(n),this.selectorCache.clear()}invalidateByPrefix(e){this.invalidateByComponent(e)}invalidateElement(e){this.elementComponentCache.delete(e),this.contextComponentCache.delete(e),this.parentComponentCache.delete(e),this.elementDepthCache.delete(e),this.elementChildrenCache.delete(e)}clearAllCaches(){this.componentElementsCache.clear(),this.scriptElementsCache.clear(),this.templateElementsCache.clear(),this.selectorCache.clear(),this.elementComponentCache=new WeakMap,this.parentComponentCache=new WeakMap,this.contextComponentCache=new WeakMap,this.elementDepthCache=new WeakMap,this.elementChildrenCache=new WeakMap}getCacheStats(){const e=this.cacheHits+this.cacheMisses;return{componentElements:this.componentElementsCache.getStats(),scriptElements:this.scriptElementsCache.getStats(),templateElements:this.templateElementsCache.getStats(),selectors:this.selectorCache.getStats(),global:{size:0,maxSize:-1,hitRate:e>0?this.cacheHits/e*100:0,hits:this.cacheHits,misses:this.cacheMisses}}}resetStats(){this.cacheHits=0,this.cacheMisses=0}}class Ts{subscriptions=new Map;elementSubscriptions=new WeakMap;keyIndex=new Map;cleanupQueue=new Set;cleanupScheduled=!1;addSubscription(e){this.subscriptions.set(e.id,e),e.element&&(this.elementSubscriptions.has(e.element)||this.elementSubscriptions.set(e.element,new Set),this.elementSubscriptions.get(e.element).add(e.id));for(const s of e.dependencies)this.keyIndex.has(s)||this.keyIndex.set(s,new Set),this.keyIndex.get(s).add(e.id)}removeSubscription(e){const s=this.subscriptions.get(e);if(s){if(this.subscriptions.delete(e),s.element){const i=this.elementSubscriptions.get(s.element);i&&(i.delete(e),i.size===0&&this.elementSubscriptions.delete(s.element))}for(const i of s.dependencies){const n=this.keyIndex.get(i);n&&(n.delete(e),n.size===0&&this.keyIndex.delete(i))}}}cleanupElement(e){const s=this.elementSubscriptions.get(e);s&&(s.forEach(i=>this.cleanupQueue.add(i)),this.scheduleCleanup())}scheduleCleanup(){this.cleanupScheduled||(this.cleanupScheduled=!0,queueMicrotask(()=>{this.processCleanupQueue(),this.cleanupScheduled=!1}))}processCleanupQueue(){for(const e of this.cleanupQueue)this.removeSubscription(e);this.cleanupQueue.clear()}getSubscription(e){return this.subscriptions.get(e)}getSubscriptionsForKey(e){return this.keyIndex.get(e)}getAllSubscriptions(){return new Map(this.subscriptions)}cleanupStaleSubscriptions(){const e=[];for(const[s,i]of this.subscriptions)i.element&&!document.contains(i.element)&&e.push(s);e.forEach(s=>this.removeSubscription(s))}getStats(){return{totalSubscriptions:this.subscriptions.size,elementSubscriptions:this.elementSubscriptions instanceof WeakMap?-1:0,keyIndexes:this.keyIndex.size}}}class z{static instance;stateVariables=new Set;static FUNCTIONS_NEEDING_VALUE_TRANSFORM=new Set(["console.log","console.warn","console.error","console.info","console.debug","console.dir","console.table","console.trace","console.assert","JSON.stringify","JSON.parse","Object.keys","Object.values","Object.entries","Array.from","Array.isArray","Math.max","Math.min","Math.abs","Math.floor","Math.ceil","Math.round","alert","confirm","prompt","parseInt","parseFloat","Number","String","Boolean"]);static getInstance(){return z.instance||(z.instance=new z),z.instance}extractFunctionNames(e){const s=[];try{const i=U(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0});H(i,{FunctionDeclaration:n=>{n.id?.type==="Identifier"&&s.push(n.id.name)},VariableDeclarator:n=>{n.id?.type==="Identifier"&&(n.init?.type==="ArrowFunctionExpression"||n.init?.type==="FunctionExpression")&&s.push(n.id.name)},AssignmentExpression:n=>{n.left?.type==="Identifier"&&(n.right?.type==="ArrowFunctionExpression"||n.right?.type==="FunctionExpression")&&s.push(n.left.name)}})}catch(i){console.error("AST function extraction error:",i)}return Array.from(new Set(s))}transformEffectDeclarations(e){try{const s=U(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0});let i=e;const n=[];return H(s,{CallExpression:r=>{const a=this.transformEffectCall(r,e);a&&n.push(a)}}),n.sort((r,a)=>a.start-r.start).forEach(r=>{i=i.slice(0,r.start)+r.replacement+i.slice(r.end)}),i}catch(s){return console.error("Effect transformation error:",s),e}}transformEffectCall(e,s){if(!this.isPPEffectCall(e))return null;const i=e.arguments;if(i.length<2)return null;const n=i[1];if(n.type!=="ArrayExpression"||!n.elements.some(p=>p?p.type==="Identifier"||p.type==="MemberExpression":!1))return null;const a=n.elements.map(p=>p?p.type==="Identifier"?`"${p.name}"`:p.type==="MemberExpression"?`"${this.extractMemberExpression(p,s)}"`:s.slice(p.start,p.end):"null"),o=s.slice(i[0].start,i[0].end),c=i.slice(2).map(p=>s.slice(p.start,p.end)).join(", "),l=`[${a.join(", ")}]`,h=c?`pp.effect(${o}, ${l}, ${c})`:`pp.effect(${o}, ${l})`;return{start:e.start,end:e.end,replacement:h}}extractMemberExpression(e,s){if(e.type!=="MemberExpression")return e.type==="Identifier"?e.name:s.slice(e.start,e.end);const i=this.extractMemberExpression(e.object,s);if(e.computed){const n=s.slice(e.property.start,e.property.end);return`${i}[${n}]`}else{const n=e.property.name||s.slice(e.property.start,e.property.end);return`${i}.${n}`}}isPPEffectCall(e){return e.callee?.type==="MemberExpression"&&e.callee.object?.type==="Identifier"&&e.callee.object.name==="pp"&&e.callee.property?.type==="Identifier"&&e.callee.property.name==="effect"}transformStateDeclarations(e){this.stateVariables.clear();let s=this.transformStateDeclarationsOnly(e);return s=this.transformEffectDeclarations(s),s=this.transformUnsupportedStateUsages(s),s}transformStateDeclarationsOnlyOriginal(e){try{const s=U(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0});let i=e;const n=[];return H(s,{VariableDeclarator:r=>{const a=this.transformStateDeclarator(r,e);a&&n.push(a)}}),n.sort((r,a)=>a.start-r.start).forEach(r=>{i=i.slice(0,r.start)+r.replacement+i.slice(r.end)}),i}catch(s){return console.error("AST transformation error:",s),e}}transformStateDeclarationsOnly(e){let s=this.transformStateDeclarationsOnlyOriginal(e);return s=this.transformDestructuringAssignments(s),s}transformUnsupportedStateUsages(e){try{const s=U(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0});this.collectStateVariables(s);let i=this.transformShorthandProperties(e);const n=U(i,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0}),r=[];return H(n,{SpreadElement:a=>{const o=this.transformSpreadElement(a,i);o&&r.push(o)},UnaryExpression:a=>{const o=this.transformUnaryExpression(a,i);o&&r.push(o)},BinaryExpression:a=>{const o=this.transformBinaryExpression(a,i);o&&r.push(o)},LogicalExpression:a=>{const o=this.transformLogicalExpression(a,i);o&&r.push(o)},ConditionalExpression:a=>{const o=this.transformConditionalExpression(a,i);o&&r.push(o)},IfStatement:a=>{const o=this.transformIfStatement(a,i);o&&r.push(o)},WhileStatement:a=>{const o=this.transformWhileStatement(a,i);o&&r.push(o)},ForStatement:a=>{const o=this.transformForStatement(a,i);o&&r.push(o)},ReturnStatement:a=>{const o=this.transformReturnStatement(a,i);o&&r.push(o)},VariableDeclarator:a=>{const o=this.transformVariableDeclarator(a,i);o&&r.push(o)},AssignmentExpression:a=>{const o=this.transformAssignmentExpression(a,i);o&&r.push(o)},CallExpression:a=>{const o=this.transformGeneralCallExpression(a,i);o&&r.push(o)}}),Ss(n,{Identifier:(a,o)=>{r.some(l=>a.start>=l.start&&a.end<=l.end)||this.stateVariables.has(a.name)&&(this.alreadyHasValue(a,i)||this.isPartOfStateDeclaration(a,o)||this.isPropertyName(a,o)||this.isMethodCallObject(a,o)||this.isPartOfPPCall(a,o)||this.isPartOfDestructuring(a,o)||r.push({start:a.start,end:a.end,replacement:`${a.name}.value`}))}}),r.sort((a,o)=>o.start-a.start).forEach(a=>{i=i.slice(0,a.start)+a.replacement+i.slice(a.end)}),i=this.transformMultipleCallArguments(i),i}catch(s){return console.error("State usage transformation error:",s),e}}transformShorthandProperties(e){try{const s=U(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0});let i=e;const n=[];return H(s,{Property:r=>{if(r.shorthand&&r.key?.type==="Identifier"&&this.stateVariables.has(r.key.name)){const a=r.key.name,o=`${a}: ${a}.value`;n.push({start:r.start,end:r.end,replacement:o})}}}),n.sort((r,a)=>a.start-r.start).forEach(r=>{i=i.slice(0,r.start)+r.replacement+i.slice(r.end)}),i}catch(s){return console.error("Shorthand property transformation error:",s),e}}transformLogicalExpression(e,s){return e.left?.type==="Identifier"&&this.stateVariables.has(e.left.name)&&!this.alreadyHasValue(e.left,s)?{start:e.left.start,end:e.left.end,replacement:`${e.left.name}.value`}:e.right?.type==="Identifier"&&this.stateVariables.has(e.right.name)&&!this.alreadyHasValue(e.right,s)?{start:e.right.start,end:e.right.end,replacement:`${e.right.name}.value`}:null}transformConditionalExpression(e,s){return e.test?.type==="Identifier"&&this.stateVariables.has(e.test.name)&&!this.alreadyHasValue(e.test,s)?{start:e.test.start,end:e.test.end,replacement:`${e.test.name}.value`}:e.consequent?.type==="Identifier"&&this.stateVariables.has(e.consequent.name)&&!this.alreadyHasValue(e.consequent,s)?{start:e.consequent.start,end:e.consequent.end,replacement:`${e.consequent.name}.value`}:e.alternate?.type==="Identifier"&&this.stateVariables.has(e.alternate.name)&&!this.alreadyHasValue(e.alternate,s)?{start:e.alternate.start,end:e.alternate.end,replacement:`${e.alternate.name}.value`}:null}transformIfStatement(e,s){return this.transformExpressionNode(e.test,s)}transformWhileStatement(e,s){return this.transformExpressionNode(e.test,s)}transformForStatement(e,s){return e.test?this.transformExpressionNode(e.test,s):null}transformReturnStatement(e,s){return e.argument?this.transformExpressionNode(e.argument,s):null}transformVariableDeclarator(e,s){return this.isStateDeclaration(e)||e.id?.type==="ArrayPattern"||e.id?.type==="ObjectPattern"?null:e.init?.type==="Identifier"&&this.stateVariables.has(e.init.name)&&!this.alreadyHasValue(e.init,s)?{start:e.init.start,end:e.init.end,replacement:`${e.init.name}.value`}:null}transformAssignmentExpression(e,s){return e.left?.type==="ArrayPattern"||e.left?.type==="ObjectPattern"?null:e.right?.type==="Identifier"&&this.stateVariables.has(e.right.name)&&!this.alreadyHasValue(e.right,s)?{start:e.right.start,end:e.right.end,replacement:`${e.right.name}.value`}:null}transformGeneralCallExpression(e,s){const i=s.slice(e.callee.start,e.callee.end);if(e.callee?.type==="MemberExpression"&&e.callee.object?.type==="Identifier"&&this.stateVariables.has(e.callee.object.name)||this.isPPCall(e))return null;if(!z.isFunctionNeedingValueTransform(i)&&e.arguments.length>0){for(const r of e.arguments)if(r.type==="Identifier"&&this.stateVariables.has(r.name)&&!this.alreadyHasValue(r,s))return{start:r.start,end:r.end,replacement:`${r.name}.value`}}return null}static isFunctionNeedingValueTransform(e){if(this.FUNCTIONS_NEEDING_VALUE_TRANSFORM.has(e))return!0;const s=e.lastIndexOf(".");if(s>-1){const i=e.slice(s+1);if(this.FUNCTIONS_NEEDING_VALUE_TRANSFORM.has(i))return!0}return!1}transformExpressionNode(e,s){return e?.type==="Identifier"&&this.stateVariables.has(e.name)&&!this.alreadyHasValue(e,s)?{start:e.start,end:e.end,replacement:`${e.name}.value`}:null}isPPCall(e){return e.callee?.type==="MemberExpression"&&e.callee.object?.type==="Identifier"&&e.callee.object.name==="pp"&&e.callee.property?.type==="Identifier"&&(e.callee.property.name==="state"||e.callee.property.name==="effect")}isPartOfStateDeclaration(e,s){if(!s||!Array.isArray(s))return!1;for(const i of s)if(i.type==="VariableDeclarator"&&i.id?.type==="ArrayPattern"&&i.init?.type==="CallExpression"&&this.isPPStateCall(i.init))return!0;return!1}isPropertyName(e,s){if(!s||s.length===0)return!1;const i=s[s.length-1];return!!(i?.type==="Property"&&i.key===e||i?.type==="Property"&&i.shorthand&&i.value===e||i?.type==="MemberExpression"&&i.property===e&&!i.computed)}isMethodCallObject(e,s){if(!s||s.length===0)return!1;const i=s[s.length-1];if(i?.type==="MemberExpression"&&i.object===e&&s.length>=2){const n=s[s.length-2];if(n?.type==="CallExpression"&&n.callee===i)return!0}return!1}isPartOfPPCall(e,s){if(!s||!Array.isArray(s))return!1;for(const i of s)if(i.type==="CallExpression"&&i.callee?.type==="MemberExpression"&&i.callee.object?.type==="Identifier"&&i.callee.object.name==="pp"&&i.callee.property?.type==="Identifier"&&(i.callee.property.name==="state"||i.callee.property.name==="effect"))return!0;return!1}isPartOfDestructuring(e,s){if(!s||!Array.isArray(s))return!1;for(let i=0;i<s.length;i++){const n=s[i];if(n.type==="ArrayPattern"||n.type==="ObjectPattern"){if(i+1<s.length){const r=s[i+1];if(r?.type==="VariableDeclarator"&&r.id===n&&r.init===e)return!1}return!0}}return!1}collectStateVariables(e){H(e,{VariableDeclarator:s=>{if(this.isStateDeclaration(s)){const i=s.id.elements[0];i?.type==="Identifier"&&this.stateVariables.add(i.name)}}})}isStateDeclaration(e){return e.id?.type==="ArrayPattern"&&e.init?.type==="CallExpression"&&this.isPPStateCall(e.init)}transformSpreadElement(e,s){return e.argument?.type==="Identifier"&&this.stateVariables.has(e.argument.name)?this.alreadyHasValue(e.argument,s)?null:{start:e.argument.start,end:e.argument.end,replacement:`${e.argument.name}.value`}:null}transformUnaryExpression(e,s){return e.argument?.type==="Identifier"&&this.stateVariables.has(e.argument.name)&&["typeof","!","+","-","~","void","delete"].includes(e.operator)&&!this.alreadyHasValue(e.argument,s)?{start:e.argument.start,end:e.argument.end,replacement:`${e.argument.name}.value`}:null}transformBinaryExpression(e,s){if(["===","!==","==","!=",">","<",">=","<=","+","-","*","/","%","**","&","|","^","<<",">>",">>>","in","instanceof"].includes(e.operator)){if(e.left?.type==="Identifier"&&this.stateVariables.has(e.left.name)&&!this.alreadyHasValue(e.left,s))return{start:e.left.start,end:e.left.end,replacement:`${e.left.name}.value`};if(e.right?.type==="Identifier"&&this.stateVariables.has(e.right.name)&&!this.alreadyHasValue(e.right,s))return{start:e.right.start,end:e.right.end,replacement:`${e.right.name}.value`}}return null}transformMultipleCallArguments(e){try{const s=U(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0});let i=e;const n=[];return H(s,{CallExpression:r=>{const a=i.slice(r.callee.start,r.callee.end);if(z.isFunctionNeedingValueTransform(a)&&r.arguments.length>0)for(const c of r.arguments)c.type==="Identifier"&&this.stateVariables.has(c.name)&&(this.alreadyHasValue(c,i)||n.push({start:c.start,end:c.end,replacement:`${c.name}.value`}))}}),n.sort((r,a)=>a.start-r.start).forEach(r=>{i=i.slice(0,r.start)+r.replacement+i.slice(r.end)}),i}catch(s){return console.error("Multiple call arguments transformation error:",s),e}}transformDestructuringAssignments(e){try{const s=U(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0});let i=e;const n=[];return H(s,{VariableDeclarator:r=>{this.isStateDeclaration(r)||(r.id?.type==="ArrayPattern"||r.id?.type==="ObjectPattern")&&r.init?.type==="Identifier"&&this.stateVariables.has(r.init.name)&&(this.alreadyHasValue(r.init,e)||n.push({start:r.init.start,end:r.init.end,replacement:`${r.init.name}.value`}))},AssignmentExpression:r=>{(r.left?.type==="ArrayPattern"||r.left?.type==="ObjectPattern")&&r.right?.type==="Identifier"&&this.stateVariables.has(r.right.name)&&(this.alreadyHasValue(r.right,e)||n.push({start:r.right.start,end:r.right.end,replacement:`${r.right.name}.value`}))}}),n.sort((r,a)=>a.start-r.start).forEach(r=>{i=i.slice(0,r.start)+r.replacement+i.slice(r.end)}),i}catch(s){return console.error("Destructuring transformation error:",s),e}}alreadyHasValue(e,s){const i=e.end;return s.slice(i,i+6).startsWith(".value")}transformStateDeclarator(e,s){if(e.id?.type!=="ArrayPattern"||e.init?.type!=="CallExpression")return null;const i=e.init;if(!this.isPPStateCall(i))return null;const n=e.id.elements[0];if(!n||n.type!=="Identifier")return null;const r=n.name,a=`set${this.capitalize(r)}`,o=e.id.elements[1];return o?.type==="Identifier"&&o.name!==a&&console.warn(`Setter name mismatch: expected ${a}, got ${o.name}`),this.createTransformation(i,r,s)}isPPStateCall(e){return e.callee?.type==="MemberExpression"&&e.callee.object?.type==="Identifier"&&e.callee.object.name==="pp"&&e.callee.property?.type==="Identifier"&&e.callee.property.name==="state"}createTransformation(e,s,i){const n=e.arguments;if(n.length===0){const c=`pp.state("${s}")`;return{start:e.start,end:e.end,replacement:c}}const r=n[0];if(r.type==="Literal"&&typeof r.value=="string"&&r.value===s)return null;if(n.length===1){const c=i.slice(r.start,r.end),l=`pp.state("${s}", ${c})`;return{start:e.start,end:e.end,replacement:l}}const a=i.slice(e.arguments[0].start,e.arguments[e.arguments.length-1].end),o=`pp.state("${s}", ${a})`;return{start:e.start,end:e.end,replacement:o}}looksLikeVariableName(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)&&e.length<=50&&!e.includes(" ")}extractStateDeclarations(e){const s=[];try{const i=U(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0,locations:!0});H(i,{VariableDeclarator:n=>{const r=this.extractStateFromDeclarator(n,e);r&&s.push(r)}})}catch(i){console.error("State extraction error:",i)}return s}extractStateFromDeclarator(e,s){if(e.id?.type!=="ArrayPattern"||e.init?.type!=="CallExpression"||!this.isPPStateCall(e.init))return null;const i=e.id.elements[0],n=e.id.elements[1];if(i?.type!=="Identifier"||n?.type!=="Identifier")return null;const r=e.init.arguments;let a=i.name,o;return r.length>=1&&(r[0].type==="Literal"&&typeof r[0].value=="string"?this.looksLikeVariableName(r[0].value)?(a=r[0].value,r.length>=2&&(o=this.extractLiteralValue(r[1]))):(a=i.name,o=this.extractLiteralValue(r[0])):o=this.extractLiteralValue(r[0])),{variableName:i.name,setterName:n.name,stateKey:a,initialValue:o,line:e.loc?.start.line||0,column:e.loc?.start.column||0}}extractFunctionDeclarations(e){const s=[];try{const i=U(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0,locations:!0});H(i,{FunctionDeclaration:n=>{n.id?.type==="Identifier"&&s.push({name:n.id.name,type:"function",params:n.params.map(r=>r.type==="Identifier"?r.name:""),line:n.loc?.start.line||0})},VariableDeclarator:n=>{if(n.id?.type==="Identifier"&&(n.init?.type==="ArrowFunctionExpression"||n.init?.type==="FunctionExpression")){const r=n.init;s.push({name:n.id.name,type:r.type==="ArrowFunctionExpression"?"arrow":"function",params:r.params.map(a=>a.type==="Identifier"?a.name:""),line:n.loc?.start.line||0})}}})}catch(i){console.error("Function extraction error:",i)}return s}extractLiteralValue(e){if(e.type==="Literal")return e.value;e.type==="Identifier"&&e.name}capitalize(e){return e.charAt(0).toUpperCase()+e.slice(1)}}class Ke{constructor(e){this.evaluator=e}render(e,s,i){const n=_.isSingleExpression(e);if(n)return this.evaluator.evaluateExpression(n,s,i);let r="";for(const a of _.parse(e))if(a.type==="static")r+=a.content;else if(a.expression)try{r+=ie(this.evaluator.evaluateExpression(a.expression,s,i))}catch{}return r}dependencies(e,s,i){const n=_.extractExpressions(e),r=new Set;for(const a of n)for(const o of this.evaluator.extractDependencies(a,s,i))r.add(o);return[...r]}}class ws{static containsMustacheExpression(e){if(d.MUSTACHE_PATTERN.test(e))return!0;const i=_.decodeEntities(e);return d.MUSTACHE_PATTERN.test(i)}}class y{static FRAMEWORK_ATTRIBUTES=new Set(["pp-component","pp-context","pp-for","pp-spread","pp-ref","key"]);static domCache;static getDOMCache(){return this.domCache||(this.domCache=L.getInstance()),this.domCache}static isFrameworkAttribute(e){return y.FRAMEWORK_ATTRIBUTES.has(e)}static isEventAttribute(e){return e.startsWith("on")&&e.length>2&&!e.includes("-")}static shouldBeDirectBinding(e,s){const i=e.getAttribute(d.ATTR_PREFIXES.CONTEXT),n=e.getAttribute(d.ATTR_PREFIXES.COMPONENT);return!i||!n||i===n?!1:y.isDOMProperty(e,s)}static isDOMProperty(e,s){const i=e.tagName.toLowerCase(),n=document.createElement(i);return y.attributeToPropertyName(s)in n}static attributeToPropertyName(e){const s={class:"className",for:"htmlFor",readonly:"readOnly",maxlength:"maxLength",minlength:"minLength",tabindex:"tabIndex",contenteditable:"contentEditable",formnovalidate:"formNoValidate",novalidate:"noValidate",allowfullscreen:"allowFullscreen",itemscope:"itemScope"};return s[e]?s[e]:e.replace(/-([a-z])/g,(i,n)=>n.toUpperCase())}static isBooleanAttribute(e){return["checked","disabled","hidden","readonly","required","multiple","selected","autofocus","autoplay","controls","defer","loop","muted","open","reversed","async","default","formnovalidate","novalidate","allowfullscreen","capture","itemscope"].includes(e)}static getContextComponent(e){return this.getDOMCache().getContextComponent(e)}static getParentOfComponent(e,s){return this.getDOMCache().getParentOfComponent(e,s)}static findElementForComponent(e,s){return this.getDOMCache().findElementForComponent(e,s)}static getElementDepth(e){return this.getDOMCache().getElementDepthCached(e)}static getParentComponentForElement(e){let s=e.parentElement;for(;s;){const i=s.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(i)return i;s=s.parentElement}return"app"}static isTextNodeInsideScript(e){let s=e.parentElement;for(;s&&s!==document.body;){const i=s.tagName.toLowerCase();if(i==="script"||i==="style")return!0;s=s.parentElement}return!1}static getComponentForNode(e){let s=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return s?this.getDOMCache().getElementComponent(s):"app"}static getElementComponent(e){return this.getDOMCache().getElementComponent(e)}}class oe{static isEventAttribute(e){return e.startsWith("on")&&e.length>2&&!e.includes("-")}}class Be{static findExistingStateKey(e,s,i){return[`${s}.${e}`,`app.${e}`,e].find(r=>r in i)||null}}class et{pendingUpdates=new Map;batchTimeout=null;componentManager;domBindingManager;setManagers(e,s){this.componentManager=e,this.domBindingManager=s}scheduleUpdate(e,s){this.pendingUpdates.has(e)||this.pendingUpdates.set(e,new Set),this.pendingUpdates.get(e).add(s),this.batchTimeout===null&&(this.batchTimeout=requestAnimationFrame(()=>{this.processBatchedUpdates(),this.batchTimeout=null}))}processBatchedUpdates(){const e=new Map(this.pendingUpdates);this.pendingUpdates.clear(),this.batchTimeout=null;const s=this.sortUpdatesByDependency(e);for(const[i,n]of s)this.processComponentUpdate(i,n)}sortUpdatesByDependency(e){const s=new WeakMap,i=n=>{let r=s.get(n);return r==null&&(r=y.getElementDepth(n),s.set(n,r)),r};return Array.from(e.entries()).sort(([,n],[,r])=>{const a=Math.min(...Array.from(n,i)),o=Math.min(...Array.from(r,i));return a-o})}processComponentUpdate(e,s){if(!this.componentManager||!this.domBindingManager)return;this.componentManager.invalidateComponent(e);const i=[],n=[],r=[];for(const a of s){if(!document.contains(a))continue;const o=document.createTreeWalker(a,NodeFilter.SHOW_TEXT,null);let c;for(;c=o.nextNode();)i.push(c);const l=this.domBindingManager.loopManager;if(l){const h=l.getAllLoops();for(const[p,f]of h)f.component===e&&a.contains(p)&&n.push([p,f])}r.push(a)}this.updateTextNodesBatch(i,e),this.updateLoopsBatch(n),this.updateElementsBatch(r,e)}updateTextNodesBatch(e,s){const i=this.domBindingManager.textNodeManager;i&&e.forEach(n=>{document.contains(n)&&y.getComponentForNode(n)===s&&i.updateTextNode(n)})}updateLoopsBatch(e){const s=this.domBindingManager.loopManager;if(!s)return;const i=new Map;e.forEach(([r,a])=>{const o=y.getElementDepth(r);i.has(o)||i.set(o,[]),i.get(o).push([r,a])});const n=Array.from(i.keys()).sort((r,a)=>r-a);for(const r of n)i.get(r).forEach(([o,c])=>{document.contains(o)&&s.renderLoop(c,c.iterableExpr)})}updateElementsBatch(e,s){e.forEach(i=>{document.contains(i)&&this.domBindingManager.processElementBindings(i,!0)})}}class Ft{loopBindings=new Map;stateManager;expressionEvaluator;componentManager;domBindingManager;cleanupObserver;loopCounter=0;pendingTemplates=[];loopItemElements=new WeakSet;loopItemContexts=new WeakMap;templateRenderer;constructor(e,s){this.stateManager=e,this.expressionEvaluator=s,this.cleanupObserver=new MutationObserver(i=>{this.cleanupDetachedTemplates(i)}),this.cleanupObserver.observe(document.body,{childList:!0,subtree:!0}),this.templateRenderer=new Ke(s)}getLoopContextForElement(e){if(!this.domBindingManager)return null;const s=this.domBindingManager.loopManager;if(!s)return null;let i=e.parentElement;for(;i;){if(s.isLoopItem&&s.isLoopItem(i))return s.getLoopItemContext(i);i=i.parentElement}const n=s.getAllLoops();for(const[r,a]of n)for(const o of a.renderedItems)if(o.element.contains(e))return o.context;return null}setDependencies(e,s){this.componentManager=e,this.domBindingManager=s}queueTemplate(e,s){this.loopBindings.has(e)||this.pendingTemplates.push({template:e,component:s})}processPendingTemplates(){const e=[...this.pendingTemplates];this.pendingTemplates=[];for(const{template:s,component:i}of e)document.contains(s)&&this.processTemplate(s,i)}processTemplate(e,s){const i=e.getAttribute("pp-for");if(!i||this.loopBindings.has(e))return;const n=this.parseLoopExpression(i);if(!n){console.error(`Invalid pp-for syntax: "${i}"`);return}const r=e.parentElement,a=document.createComment(`pp-for: ${i}`);r.insertBefore(a,e);const o={template:e,expression:i,itemVar:n.itemVar,indexVar:n.indexVar,component:s,subscriptionIds:[],renderedItems:[],keyExpression:void 0,parentElement:r,placeholder:a,iterableExpr:n.iterableExpr};this.loopBindings.set(e,o),this.setupLoopReactivity(o,n.iterableExpr),this.renderLoop(o,n.iterableExpr)}parseLoopExpression(e){const s=e.match(/^\s*([a-zA-Z_$][\w$]*)\s+in\s+(.+)$/);if(s)return{itemVar:s[1],iterableExpr:s[2].trim()};const i=e.match(/^\s*\(\s*([a-zA-Z_$][\w$]*)\s*,\s*([a-zA-Z_$][\w$]*)\s*\)\s+in\s+(.+)$/);return i?{itemVar:i[1],indexVar:i[2],iterableExpr:i[3].trim()}:null}setupLoopReactivity(e,s){const i=`loop_${Date.now()}_${++this.loopCounter}`,n=this.expressionEvaluator.extractDependencies(s,e.component,this.stateManager),r=this.findComponentElementForLoop(e);if(r&&this.componentManager){const o=this.componentManager.getComponentPropDependencies(r,e.component);n.push(...o)}const a={id:i,selector:"",dependencies:new Set(n),callback:()=>{this.renderLoop(e,e.iterableExpr)},element:e.parentElement,component:e.component};this.stateManager.addSubscription(a),e.subscriptionIds.push(i)}renderLoop(e,s){if(!(!this.componentManager||!this.domBindingManager))try{const i=this.findComponentElementForLoop(e);let n;const r=this.findParentLoopContext(e.template);r?n={...this.componentManager.buildComponentContextWithProps(e.component,i),...r}:n=this.componentManager.buildComponentContextWithProps(e.component,i);const a=this.expressionEvaluator.evaluateExpression(s,n,e.component);if(!Array.isArray(a)){console.warn(`Loop expression "${s}" did not return an array:`,a,`Available context keys: [${Object.keys(n).join(", ")}]`,"Parent loop context:",r),this.clearRenderedItems(e);return}this.updateRenderedItems(e,a)}catch(i){console.error(`Error evaluating loop expression "${s}":`,i),this.clearRenderedItems(e)}}findParentLoopContext(e){const s=[];let i=e.parentElement;for(;i&&i!==document.body;){if(this.loopItemElements.has(i)){const n=this.loopItemContexts.get(i);n&&s.unshift(n)}for(const[n,r]of this.loopBindings)if(r.template!==e){for(const a of r.renderedItems)if(a.element===i||a.element.contains(e)){s.unshift(a.context);break}}i=i.parentElement}return s.length>0?s.reduce((n,r)=>({...n,...r}),{}):null}findComponentElementForLoop(e){let s=e.parentElement;for(;s;){if(s.getAttribute(d.ATTR_PREFIXES.COMPONENT)===e.component)return s;s=s.parentElement}return document.querySelectorAll(`[${d.ATTR_PREFIXES.COMPONENT}="${e.component}"]`)[0]||void 0}updateRenderedItems(e,s){const i=e.renderedItems,n=[],r=new Set,a=new Map;i.forEach(o=>{a.set(o.key,o)}),s.forEach((o,c)=>{const l=this.generateItemKey(e,o,c),h=a.get(l);if(h&&!r.has(h.element))r.add(h.element),this.updateItemContext(e,h,o,c),n.push(h);else{const p=this.createLoopItem(e,o,c,l);p&&(n.push(p),this.processNestedLoopsInItem(p,e.component))}}),i.forEach(o=>{r.has(o.element)||this.cleanupLoopItem(o)}),this.updateDOMOrder(e,n),e.renderedItems=n}processNestedLoopsInItem(e,s){e.element.querySelectorAll("template[pp-for]").forEach(n=>{const r=n;this.loopBindings.has(r)||this.processNestedTemplate(r,s,e.context)})}generateItemKey(e,s,i){const r=e.template.content.firstElementChild;if(r&&r.hasAttribute("key")){const a=r.getAttribute("key");try{const o=this.createItemContextWithParentContext(e,s,i),c=_.isSingleExpression(a);if(c){const l=this.expressionEvaluator.evaluateExpression(c,o,e.component);return String(l)}else{const l=_.parse(a);let h="";for(const p of l)if(p.type==="static")h+=p.content;else if(p.expression){const f=this.expressionEvaluator.evaluateExpression(p.expression,o,e.component);h+=ie(f)}return h}}catch(o){console.warn(`Error evaluating key expression "${a}":`,o,"Available context keys:",Object.keys(this.createItemContextWithParentContext(e,s,i)))}}return s&&typeof s=="object"&&"id"in s?String(s.id):`${e.expression}_${i}`}createItemContextWithParentContext(e,s,i){if(!this.componentManager)return{};const n=this.componentManager.buildComponentContext(e.component),r=this.getAllParentLoopContexts(e.template),a={...n,...r,[e.itemVar]:s};return e.indexVar&&(a[e.indexVar]=i),a}getAllParentLoopContexts(e){const s=[];let i=e.parentElement;for(;i&&i!==document.body;){if(this.loopItemElements.has(i)){const n=this.loopItemContexts.get(i);n&&s.unshift(n)}for(const[n,r]of this.loopBindings)if(n!==e){for(const a of r.renderedItems)if(a.element===i||a.element.contains(e)){s.unshift(a.context);break}}i=i.parentElement}return s.reduce((n,r)=>({...n,...r}),{})}createItemContext(e,s,i){if(!this.componentManager)return{};const n=this.componentManager.buildComponentContext(e.component),r=this.findAllParentLoopContexts(e.template),a={...n,...r,[e.itemVar]:s};return e.indexVar&&(a[e.indexVar]=i),a}findAllParentLoopContexts(e){const s={};let i=e.parentElement;for(;i&&i!==document.body;){if(this.loopItemElements.has(i)){const n=this.loopItemContexts.get(i);if(n)for(const[r,a]of Object.entries(n))r in s||(s[r]=a)}for(const[n,r]of this.loopBindings)if(n!==e){for(const a of r.renderedItems)if(a.element===i){for(const[o,c]of Object.entries(a.context))o in s||(s[o]=c);break}}i=i.parentElement}return s}createLoopItem(e,s,i,n){if(!this.domBindingManager)return null;try{const r=this.createItemContextWithParentContext(e,s,i),a=document.importNode(e.template.content,!0),o=document.createElement("div");o.appendChild(a);const c=o.firstElementChild;if(!c)return console.warn("Template content must contain exactly one root element"),null;o.removeChild(c),this.loopItemElements.add(c),this.loopItemContexts.set(c,r),c.getAttribute("key")&&c.removeAttribute("key");const h={key:n,element:c,context:r,subscriptionIds:[],textNodeTemplates:new Map,attributeTemplates:new Map};return this.executeComponentScriptsInLoopItem(c),this.processRefsInLoopItem(c,r,e.component),this.processElementWithContext(c,r,e.component,h),this.cleanupRawMustacheAttributes(c),h}catch(r){return console.error("Error creating loop item:",r),null}}processRefsInLoopItem(e,s,i){if(e.hasAttribute("pp-ref")){const o=e.getAttribute("pp-ref");this.processRefAttribute(e,o,s,i)}const n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:o=>o.hasAttribute("pp-ref")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});let r;const a=[];for(;r=n.nextNode();)a.push(r);a.forEach(o=>{const c=o.getAttribute("pp-ref");this.processRefAttribute(o,c,s,i)})}processRefAttribute(e,s,i,n){try{const r=_.decodeEntities(s),a=_.isSingleExpression(r)||r,o=this.expressionEvaluator.evaluateExpression(a,i,n);typeof o=="function"?o(e):o&&typeof o=="object"&&"current"in o?o.current=e:console.warn("⚠️ Invalid ref result:",o),e.removeAttribute("pp-ref")}catch(r){console.error("❌ Failed to process ref:",r)}}executeComponentScriptsInLoopItem(e){if(!this.componentManager)return;const s=[e],i=e.querySelectorAll(`[${d.ATTR_PREFIXES.COMPONENT}]`);s.push(...Array.from(i)),s.forEach(n=>{if(n.hasAttribute(d.ATTR_PREFIXES.COMPONENT)){const r=n.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(r){const a=this.getLoopItemContextForElement(n),o=this.generateInstanceId(a),c=`${r}_${o}`;n.setAttribute(d.ATTR_PREFIXES.COMPONENT,c),n.__originalComponentName=r,n.__uniqueComponentName=c,this.componentManager.pushComponent(c),this.getComponentScripts(n).forEach(h=>{this.componentManager.executeScript(h)}),this.componentManager.popComponent()}}})}getLoopItemContextForElement(e){let s=e;for(;s;){if(this.loopItemElements.has(s)){const i=this.loopItemContexts.get(s);if(i)return i}s=s.parentElement}for(const[i,n]of this.loopBindings)for(const r of n.renderedItems)if(r.element===e||r.element.contains(e))return r.context;return console.warn("⚠️ No loop item context found, using empty context"),{}}generateInstanceId(e){const s={};for(const[a,o]of Object.entries(e))typeof o=="function"||a.startsWith("set")||a.endsWith("Getter")||a==="getContext"||a==="withContext"||a==="__getProp"||(o&&typeof o=="object"&&"id"in o||typeof o!="object"||Array.isArray(o))&&(s[a]=o);return Object.keys(s).length===0?`${Date.now()}_${Math.random().toString(36).substring(2,7)}`:Object.keys(s).sort().map(a=>{const o=s[a];return o&&typeof o=="object"&&"id"in o?`${a}_${o.id}`:typeof o=="string"||typeof o=="number"?`${a}_${o}`:`${a}_${JSON.stringify(o)}`}).join("_").replace(/[^a-zA-Z0-9_]/g,"").substring(0,20)||`fallback_${Date.now()}`}getComponentScripts(e){const s=[];return e.querySelectorAll(`script[type="${d.SCRIPT_TYPE}"]`).forEach(n=>{const r=n;let a=r.parentElement,o=!1;for(;a&&a!==e.parentElement;){if(a===e){o=!0;break}if(a.hasAttribute(d.ATTR_PREFIXES.COMPONENT)&&a!==e)break;a=a.parentElement}o&&s.push(r)}),s}cleanupRawMustacheAttributes(e){this.cleanupElementMustacheAttributes(e);const s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,null);let i;for(;i=s.nextNode();)this.cleanupElementMustacheAttributes(i)}cleanupElementMustacheAttributes(e){const s=Array.from(e.attributes);for(const i of s)i.value&&d.MUSTACHE_PATTERN.test(i.value)&&(y.isBooleanAttribute(i.name),e.removeAttribute(i.name))}processElementWithContext(e,s,i,n){if(!this.domBindingManager||!this.componentManager)return;const r=(o,c)=>{const l=this.componentManager.buildComponentContext(c),h=o.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(h&&h!==c){const f=this.componentManager.buildComponentContext(h);return{...s,...l,...f}}return{...s,...l}},a=this.componentManager.buildComponentContextWithProps.bind(this.componentManager);this.componentManager.buildComponentContextWithProps=(o,c)=>c&&(c===e||e.contains(c))?r(c,o):a(o,c);try{if(e.hasAttribute("pp-ref")){const m=e.getAttribute("pp-ref");this.processRefInLoopContext(e,m,s,i)}const o=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:m=>m===e?NodeFilter.FILTER_SKIP:NodeFilter.FILTER_ACCEPT}),c=[];let l;for(;l=o.nextNode();){const m=l;if(m.hasAttribute("pp-ref")){const x=m.getAttribute("pp-ref");c.push({element:m,expression:x})}}c.forEach(({element:m,expression:x})=>{this.processRefInLoopContext(m,x,s,i)}),this.bindLoopItemElement(e,s,i,n),this.setupEventBindingsForLoopItem(e,i);const h=document.createTreeWalker(e,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,{acceptNode:m=>{if(m===e)return NodeFilter.FILTER_SKIP;if(m.nodeType===Node.TEXT_NODE){const x=m;if(y.isTextNodeInsideScript(x))return NodeFilter.FILTER_REJECT;if(x.textContent&&d.MUSTACHE_PATTERN.test(x.textContent))return NodeFilter.FILTER_ACCEPT}else if(m.nodeType===Node.ELEMENT_NODE)return m.tagName.toLowerCase()==="script"?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT;return NodeFilter.FILTER_SKIP}});let p;for(;p=h.nextNode();)if(p.nodeType===Node.TEXT_NODE){const m=p;if(m.textContent&&d.MUSTACHE_PATTERN.test(m.textContent)){const x=this.getComponentForTextNode(m),C=r(m.parentElement,x);this.processTextNodeWithLoopContext(m,C,x,n)}}else if(p.nodeType===Node.ELEMENT_NODE){const m=p,x=y.getElementComponent(m),C=r(m,x);this.bindLoopItemElement(m,C,x,n),this.setupEventBindingsForLoopItem(m,x)}e.querySelectorAll("template[pp-for]").forEach(m=>{this.processNestedTemplate(m,i,s)})}finally{this.componentManager.buildComponentContextWithProps=a}}processRefInLoopContext(e,s,i,n){try{const r=_.decodeEntities(s),a=_.isSingleExpression(r)||r,o=this.expressionEvaluator.evaluateExpression(a,i,n);typeof o=="function"?o(e):o&&typeof o=="object"&&"current"in o?o.current=e:console.warn("⚠️ Invalid ref result:",o),e.removeAttribute("pp-ref")}catch(r){console.error("❌ processRefInLoopContext error:",r)}}getComponentForTextNode(e){let s=e.parentElement;for(;s;){const i=s.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(i)return i;s=s.parentElement}return"app"}processNestedTemplate(e,s,i){const n=e.getAttribute("pp-for");if(!n||this.loopBindings.has(e))return;const r=this.parseLoopExpression(n);if(!r){console.error(`Invalid pp-for syntax: "${n}"`);return}const a=e.parentElement,o=document.createComment(`pp-for: ${n}`);a.insertBefore(o,e);const c=this.findComponentElementForTemplate(e);let l={...i};const h=this.findParentLoopContextForNestedTemplate(e);if(h&&(l={...l,...h}),c&&this.componentManager){const f=c.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(f){const m=y.getParentComponentForElement(c);this.componentManager.hasStoredProps(c)||this.componentManager.setupProps(c,m);const x=this.evaluateComponentPropsWithContext(c,l);l={...this.componentManager.buildComponentContext(f),...x,...l}}}const p={template:e,expression:n,itemVar:r.itemVar,indexVar:r.indexVar,iterableExpr:r.iterableExpr,component:s,subscriptionIds:[],renderedItems:[],keyExpression:void 0,parentElement:a,placeholder:o};this.loopBindings.set(e,p),this.setupNestedLoopReactivity(p,r.iterableExpr,l),this.renderNestedLoop(p,r.iterableExpr,l)}findParentLoopContextForNestedTemplate(e){let s=e.parentElement;const i={};let n=0;for(;s&&s!==document.body&&n<10;){if(n++,this.loopItemElements.has(s)){const r=this.loopItemContexts.get(s);if(r)for(const[a,o]of Object.entries(r))a in i||(i[a]=o)}for(const[r,a]of this.loopBindings)for(const o of a.renderedItems)(o.element.contains(e)||o.element===s)&&(a.itemVar in i||(i[a.itemVar]=o.context[a.itemVar]),a.indexVar&&!(a.indexVar in i)&&(i[a.indexVar]=o.context[a.indexVar]));s=s.parentElement}return Object.keys(i).length>0?i:null}evaluateComponentPropsWithContext(e,s){const i={};if(!this.componentManager||!this.expressionEvaluator)return i;const n=this.componentManager.extractProps(e,"app");for(const[r,a]of n)try{const o=this.templateRenderer.render(a.expression,s,a.component);i[r]=o}catch(o){console.error(`Failed to evaluate prop "${r}":`,o),i[r]=void 0}return i}findComponentElementForTemplate(e){let s=e.parentElement;for(;s;){if(s.hasAttribute(d.ATTR_PREFIXES.COMPONENT))return s;s=s.parentElement}return null}setupNestedLoopReactivity(e,s,i){const n=`nested_loop_${Date.now()}_${++this.loopCounter}`;let r=this.expressionEvaluator.extractDependencies(s,e.component,this.stateManager);const a={id:n,selector:"",dependencies:new Set(r),callback:()=>{const o=e.template,c=this.findComponentElementForTemplate(o);let l=i;if(o.parentElement){const p=this.getParentLoopContextForElement(o);p&&(l={...l,...p})}if(c&&this.componentManager){const p=c.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(p){const f=this.extractParentLoopContextFromBinding(e,i),m=this.evaluateComponentPropsWithContext(c,f),x=this.componentManager.buildComponentContext(p);l={...f,...x,...m}}}this.renderNestedLoop(e,s,l)},element:e.parentElement,component:e.component};this.stateManager.addSubscription(a),e.subscriptionIds.push(n)}getParentLoopContextForElement(e){let s=e.parentElement;for(;s;){if(this.loopItemElements.has(s)){const i=this.loopItemContexts.get(s);if(i)return i}s=s.parentElement}return null}extractParentLoopContextFromBinding(e,s){const i=new Set;for(const[r,a]of this.loopBindings)if(a!==e){for(const o of a.renderedItems)if(o.element.contains(e.template)){i.add(a.itemVar),a.indexVar&&i.add(a.indexVar);break}}const n={};for(const[r,a]of Object.entries(s))(i.has(r)||r.startsWith("users")||r.startsWith("set")||r.includes("Getter")||typeof a=="function")&&(n[r]=a);return n}renderNestedLoop(e,s,i){if(!(!this.componentManager||!this.domBindingManager))try{const n=this.expressionEvaluator.evaluateExpression(s,i,e.component);if(!Array.isArray(n)){console.warn(`Nested loop expression "${s}" did not return an array:`,n,`Available context keys: [${Object.keys(i).join(", ")}]`),this.clearRenderedItems(e);return}this.updateNestedRenderedItems(e,n,i)}catch(n){console.error(`Error evaluating nested loop expression "${s}":`,n,`Available context keys: [${Object.keys(i).join(", ")}]`),this.clearRenderedItems(e)}}updateNestedRenderedItems(e,s,i){const n=e.renderedItems,r=[],a=new Set,o=new Map;n.forEach(c=>{o.set(c.key,c)}),s.forEach((c,l)=>{const h=this.generateNestedItemKey(e,c,l,i),p=o.get(h);if(p&&!a.has(p.element))a.add(p.element),this.updateNestedItemContext(e,p,c,l,i),r.push(p);else{const f=this.createNestedLoopItem(e,c,l,h,i);f&&r.push(f)}}),n.forEach(c=>{a.has(c.element)||this.cleanupLoopItem(c)}),this.updateDOMOrder(e,r),e.renderedItems=r}generateNestedItemKey(e,s,i,n){return s&&typeof s=="object"&&"id"in s?String(s.id):`${e.expression}_${i}_${JSON.stringify(n[e.itemVar]||{})}`}createNestedLoopItem(e,s,i,n,r){if(!this.domBindingManager)return null;try{const a={...r,[e.itemVar]:s};e.indexVar&&(a[e.indexVar]=i);const o=document.importNode(e.template.content,!0),c=document.createElement("div");c.appendChild(o);const l=c.firstElementChild;if(!l)return console.warn("Template content must contain exactly one root element"),null;c.removeChild(l),this.loopItemElements.add(l),this.loopItemContexts.set(l,a),l.getAttribute("key")&&l.removeAttribute("key");const p={key:n,element:l,context:a,subscriptionIds:[],textNodeTemplates:new Map,attributeTemplates:new Map};return this.processElementWithContext(l,a,e.component,p),this.cleanupRawMustacheAttributes(l),p}catch(a){return console.error("Error creating nested loop item:",a),null}}updateNestedItemContext(e,s,i,n,r){const a={...r};a[e.itemVar]=i,e.indexVar&&(a[e.indexVar]=n);const o=this.gatherAllComponentContextsInLoopItem(s.element),c={...a,...o};if(s.context=c,this.loopItemContexts.set(s.element,c),s.textNodeTemplates)for(const[l,h]of s.textNodeTemplates)document.contains(l)&&this.updateTextNodeWithContext(l,h,c,this.getTextNodeComponent(l));if(s.attributeTemplates)for(const[l,h]of s.attributeTemplates)document.contains(l)&&h.forEach((p,f)=>{try{const m=y.getElementComponent(l),x=this.buildElementSpecificContext(l,c),C=this.templateRenderer.render(p,x,m);this.domBindingManager?.updateElementProperty(l,f,C)}catch(m){console.error(`Nested binding update error for "${p}":`,m)}})}bindLoopItemElement(e,s,i,n){const r=this.extractMustacheBindings(e);n&&r.size>0&&(n.attributeTemplates||(n.attributeTemplates=new Map),n.attributeTemplates.set(e,new Map(r))),r.forEach((a,o)=>{this.createLoopItemBinding(e,o,a,s,i,n)})}setupEventBindingsForLoopItem(e,s){const i=this.domBindingManager.eventDelegation;if(!i){console.warn("No event delegation manager available");return}const n=Array.from(e.attributes);for(const r of n)if(oe.isEventAttribute(r.name)){const a=r.name.substring(2);i.registerEventHandler(e,a,r.value,s),e.removeAttribute(r.name)}}processTextNodeWithLoopContext(e,s,i,n){if(y.isTextNodeInsideScript(e))return;const r=e.textContent||"";if(!_.parse(r).some(x=>x.type==="expression"))return;n&&(n.textNodeTemplates||(n.textNodeTemplates=new Map),n.textNodeTemplates.set(e,r));const c=this.findActualComponentForTextNode(e);this.updateTextNodeWithContext(e,r,s,c);const l=`loop_text_${Date.now()}_${Math.random()}`,h=this.templateRenderer.dependencies(r,c,this.stateManager),p=new Set(h),m={id:l,selector:"",dependencies:p,callback:()=>{if(!document.contains(e)){this.stateManager.removeSubscription(l);return}let x={};if(this.componentManager&&(x=this.componentManager.buildComponentContext(c)),n){const C={};let S=null;for(const[P,M]of this.loopBindings)if(M.renderedItems.includes(n)){S=M;break}if(S){C[S.itemVar]=n.context[S.itemVar],S.indexVar&&(C[S.indexVar]=n.context[S.indexVar]);const P=this.findParentLoopContext(S.template);P&&Object.assign(C,P)}x={...x,...C}}this.updateTextNodeWithContext(e,r,x,c)},component:c};this.stateManager.addSubscription(m),n&&n.subscriptionIds.push(l)}findActualComponentForTextNode(e){let s=e.parentElement;for(;s;){const i=s.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(i){const n=s.__uniqueComponentName;return n||i}s=s.parentElement}return"app"}updateTextNodeWithContext(e,s,i,n){const r=_.parse(s);let a="";for(const o of r)if(o.type==="static")a+=o.content;else if(o.expression)try{const c=this.expressionEvaluator.evaluateExpression(o.expression,i,n);a+=ie(c)}catch(c){console.warn(`Loop text evaluation error for "${o.expression}":`,c,"Available context keys:",Object.keys(i)),a+=""}e.textContent!==a&&(e.textContent=a)}extractMustacheBindings(e){const s=new Map,i=e.attributes;for(let n=0;n<i.length;n++){const r=i[n];if(!(r.name===d.ATTR_PREFIXES.COMPONENT||r.name==="key"||r.name.startsWith("on"))&&r.value){const a=d.MUSTACHE_PATTERN.test(r.value),o=_.decodeEntities(r.value),c=d.MUSTACHE_PATTERN.test(o);(a||c)&&s.set(r.name,o)}}return s}createLoopItemBinding(e,s,i,n,r,a){const o=`loop_item_${Date.now()}_${Math.random()}`,c=this.templateRenderer.dependencies(i,r,this.stateManager),l=new Set(c);let h=!1,p=0;const f=5,m=()=>{if(h)return;if(!document.contains(e)){if(p++,p<f){const P=10*Math.pow(2,p-1);setTimeout(()=>{h||m()},P)}else h=!0,this.stateManager.removeSubscription(o);return}p=0;try{const P=this.componentManager.buildComponentContext(r);let M;if(a){M={...P};let te=null;for(const[Ne,be]of this.loopBindings)if(be.renderedItems.includes(a)){te=be;break}te&&(M[te.itemVar]=a.context[te.itemVar],te.indexVar&&(M[te.indexVar]=a.context[te.indexVar]));for(const[Ne,be]of Object.entries(a.context))Ne in M||(M[Ne]=be)}else M=n;const fe=this.templateRenderer.render(i,M,r);this.domBindingManager?.updateElementProperty(e,s,fe)}catch(P){console.error(`Loop item binding evaluation error for "${i}":`,P),console.error("Available context keys:",Object.keys(n))}},x={id:o,selector:"",dependencies:l,callback:()=>{h||m()},element:e,component:r};if(this.stateManager.addSubscription(x),a){a.subscriptionIds.push(o);const S=this.cleanupLoopItem.bind(this);this.cleanupLoopItem=P=>{P===a&&(h=!0),S(P)}}(()=>{document.contains(e)?m():Promise.resolve().then(()=>{if(!h&&document.contains(e))m();else if(!h&&p<f){p++;const S=10*Math.pow(2,p-1);setTimeout(()=>{h||m()},S)}else!h&&p>=f&&(h=!0,this.stateManager.removeSubscription(o))})})()}updateItemContext(e,s,i,n){const r=this.createItemContext(e,i,n),a=this.gatherAllComponentContextsInLoopItem(s.element),o={...r,...a};if(s.context=o,this.loopItemContexts.set(s.element,o),s.textNodeTemplates)for(const[c,l]of s.textNodeTemplates)document.contains(c)&&this.updateTextNodeWithContext(c,l,o,this.getTextNodeComponent(c));if(s.attributeTemplates)for(const[c,l]of s.attributeTemplates)document.contains(c)&&l.forEach((h,p)=>{try{const f=y.getElementComponent(c),m=this.buildElementSpecificContext(c,o),x=this.templateRenderer.render(h,m,f);this.domBindingManager?.updateElementProperty(c,p,x)}catch(f){console.error(`Attribute binding update error for "${h}":`,f)}})}gatherAllComponentContextsInLoopItem(e){if(!this.componentManager)return{};const s={};if(e.hasAttribute(d.ATTR_PREFIXES.COMPONENT)){const n=e.getAttribute(d.ATTR_PREFIXES.COMPONENT),r=this.componentManager.buildComponentContext(n);Object.assign(s,r)}return e.querySelectorAll(`[${d.ATTR_PREFIXES.COMPONENT}]`).forEach(n=>{const r=n.getAttribute(d.ATTR_PREFIXES.COMPONENT),a=this.componentManager?.buildComponentContext(r);Object.assign(s,a)}),s}buildElementSpecificContext(e,s){if(!this.componentManager)return s;const i=y.getElementComponent(e),n=this.componentManager.buildComponentContext(i);return{...s,...n}}getTextNodeComponent(e){let s=e.parentElement;for(;s;){const i=s.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(i)return i;s=s.parentElement}return"app"}updateDOMOrder(e,s){let i=e.placeholder;s.forEach(n=>{(n.element.parentElement!==e.parentElement||n.element!==i.nextSibling)&&e.parentElement.insertBefore(n.element,i.nextSibling),i=n.element})}clearRenderedItems(e){e.renderedItems.forEach(s=>{this.cleanupLoopItem(s)}),e.renderedItems=[]}cleanupLoopItem(e){this.loopItemElements.delete(e.element),this.loopItemContexts.delete(e.element),e.element.parentElement&&e.element.parentElement.removeChild(e.element),e.subscriptionIds.forEach(s=>{this.stateManager.removeSubscription(s)})}isLoopItem(e){return this.loopItemElements.has(e)}getLoopItemContext(e){return this.loopItemContexts.get(e)}cleanupDetachedTemplates(e){for(const s of e)s.type==="childList"&&s.removedNodes.forEach(i=>{if(i.nodeType===Node.ELEMENT_NODE){const n=i;n.tagName==="TEMPLATE"&&n.hasAttribute("pp-for")&&this.cleanupTemplate(n),n.querySelectorAll("template[pp-for]").forEach(a=>{this.cleanupTemplate(a)})}})}cleanupTemplate(e){const s=this.loopBindings.get(e);s&&(this.clearRenderedItems(s),s.subscriptionIds.forEach(i=>{this.stateManager.removeSubscription(i)}),s.placeholder.parentElement&&s.placeholder.parentElement.removeChild(s.placeholder),this.loopBindings.delete(e))}getAllLoops(){return new Map(this.loopBindings)}destroy(){this.cleanupObserver.disconnect(),Array.from(this.loopBindings.keys()).forEach(e=>{this.cleanupTemplate(e)}),this.loopItemContexts=new WeakMap}}class ${cache=new Map;maxSize;hits=0;misses=0;constructor(e){this.maxSize=e}keys(){return Array.from(this.cache.keys())}deleteByPrefix(e){let s=0;const i=[];return this.cache.forEach((n,r)=>{typeof r=="string"&&r.startsWith(e)&&i.push(r)}),i.forEach(n=>{this.cache.delete(n)&&s++}),s}getKeysByPrefix(e){const s=[];return this.cache.forEach((i,n)=>{typeof n=="string"&&n.startsWith(e)&&s.push(n)}),s}get(e){const s=this.cache.get(e);if(s!==void 0)return this.hits++,this.cache.delete(e),this.cache.set(e,s),s;this.misses++}set(e,s){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){const i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i)}this.cache.set(e,s)}size(){return this.cache.size}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear(),this.hits=0,this.misses=0}getStats(){const e=this.hits+this.misses;return{size:this.cache.size,maxSize:this.maxSize,hitRate:e>0?this.hits/e*100:0,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}}class _{static EXPRESSION_CACHE=new $(1e3);static parseSpreadDirective(e){const s=e.replace(/^\s*\{\s*|\s*\}\s*$/g,""),i=this.parseSpreadParts(s),n=[],r=[];for(const a of i){const o=a.trim();if(o.startsWith("..."))n.push(o.substring(3).trim());else if(o.startsWith("{")&&o.endsWith("}")){const c=o.slice(1,-1).trim();if(c){const l=this.parseObjectProperties(c);r.push(l)}}else console.warn(`Invalid spread directive part: "${o}". Expected ...spread or {object}`)}return{spreads:n,objects:r}}static parseSpreadParts(e){const s=[];let i="",n=0,r=!1,a="",o=0;for(;o<e.length;){const c=e[o],l=o>0?e[o-1]:"";if(!r&&(c==='"'||c==="'")?(r=!0,a=c):r&&c===a&&l!=="\\"&&(r=!1,a=""),!r){if(c==="{")n++;else if(c==="}")n--;else if(c===","&&n===0){s.push(i.trim()),i="",o++;continue}}i+=c,o++}return i.trim()&&s.push(i.trim()),s}static parseObjectProperties(e){const s=[],i=this.parseObjectParts(e);for(const n of i){const r=n.trim(),a=this.findPropertySeparator(r);if(a!==-1){const o=r.substring(0,a).trim().replace(/['"]/g,""),c=r.substring(a+1).trim();s.push({key:o,value:c})}else console.warn(`Invalid object property: "${r}". Expected key: value format.`)}return s}static parseObjectParts(e){const s=[];let i="",n=0,r=!1,a="";for(let o=0;o<e.length;o++){const c=e[o],l=o>0?e[o-1]:"";if(!r&&(c==='"'||c==="'")?(r=!0,a=c):r&&c===a&&l!=="\\"&&(r=!1,a=""),!r){if(c==="{"||c==="["||c==="(")n++;else if(c==="}"||c==="]"||c===")")n--;else if(c===","&&n===0){s.push(i.trim()),i="";continue}}i+=c}return i.trim()&&s.push(i.trim()),s}static findPropertySeparator(e){let s=0,i=!1,n="";for(let r=0;r<e.length;r++){const a=e[r],o=r>0?e[r-1]:"";if(!i&&(a==='"'||a==="'")?(i=!0,n=a):i&&a===n&&o!=="\\"&&(i=!1,n=""),!i){if(a==="{"||a==="["||a==="(")s++;else if(a==="}"||a==="]"||a===")")s--;else if(a===":"&&s===0)return r}}return-1}static decodeEntities=e=>{const s=document.createElement("textarea");s.innerHTML=e;let i=s.value;for(;i.includes("&");){s.innerHTML=i;const n=s.value;if(n===i)break;i=n}return i};static parse(e){const s=_.decodeEntities(e);if(_.EXPRESSION_CACHE.has(s))return _.EXPRESSION_CACHE.get(s);const i=_.parseContentWithNesting(s);return _.EXPRESSION_CACHE.set(s,i),i}static parseContentWithNesting(e){const s=[],i=e.length;let n=0,r=0;for(;n<i;)if(e[n]==="{"){n>r&&s.push({type:"static",content:e.substring(r,n),expression:null});const o=this.extractNestedExpression(e,n);o.endIndex!==-1?(s.push({type:"expression",content:e.substring(n,o.endIndex+1),expression:o.expression.trim()}),n=o.endIndex+1,r=n):n++}else n++;return r<i&&s.push({type:"static",content:e.substring(r),expression:null}),s}static extractNestedExpression(e,s){let i=1,n=s+1,r=!1,a="",o=!1;for(;n<e.length&&i>0;){const c=e[n],l=n>0?e[n-1]:"";!r&&(c==='"'||c==="'")?(r=!0,a=c):r&&c===a&&l!=="\\"&&(r=!1,a=""),!r&&c==="`"&&l!=="\\"&&(o=!o),!r&&!o&&(c==="{"?i++:c==="}"&&i--),n++}if(i===0){const c=e.slice(s+1,n-1);return{endIndex:n-1,expression:c}}return{endIndex:-1,expression:""}}static isSingleExpression(e){const s=_.decodeEntities(e),i=_.parseContentWithNesting(s);return i.length===1&&i[0].type==="expression"?i[0].expression:null}static extractExpressions(e){const s=_.decodeEntities(e);return _.parseContentWithNesting(s).filter(n=>n.type==="expression").map(n=>n.expression).filter(n=>n)}}class Ps{textNodeBindings=new Map;expressionEvaluator;stateManager;componentManager;cleanupObserver;bindingCount=0;constructor(e,s){this.expressionEvaluator=e,this.stateManager=s,this.cleanupObserver=new MutationObserver(i=>{this.cleanupDetachedNodes(i)}),this.cleanupObserver.observe(document.body,{childList:!0,subtree:!0})}cleanupDetachedNodes(e){for(const i of e)i.type==="childList"&&i.removedNodes.forEach(n=>{if(n.nodeType===Node.TEXT_NODE)this.cleanupTextNode(n);else if(n.nodeType===Node.ELEMENT_NODE){const r=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null);let a;for(;a=r.nextNode();)this.cleanupTextNode(a)}});const s=[];for(const[i]of this.textNodeBindings)document.contains(i)||s.push(i);s.forEach(i=>this.cleanupTextNode(i))}processTextNode(e,s){if(this.textNodeBindings.has(e)||y.isTextNodeInsideScript(e)||this.isInsideLoopItem(e))return;const i=e.parentElement,n=i?y.getContextComponent(i):s,r=e.textContent||"",a=_.parse(r);if(!a.some(l=>l.type==="expression"))return;const c={originalContent:r,expressions:a,subscriptionIds:[]};a.filter(l=>l.type==="expression").forEach(l=>{if(!l.expression)return;const h=`text_${Date.now()}_${Math.random()}`,p=this.expressionEvaluator.extractDependencies(l.expression,n,this.stateManager),f={id:h,selector:"",dependencies:new Set(p),callback:()=>{this.updateTextNode(e)},element:e.parentElement??void 0,component:n};this.stateManager.addSubscription(f),c.subscriptionIds.push(h)}),this.textNodeBindings.set(e,c),this.bindingCount++,this.updateTextNode(e)}isInsideLoopItem(e){let s=e.parentElement;for(;s&&s!==document.body;){const i=s.previousSibling;if(i&&i.nodeType===Node.COMMENT_NODE&&i.textContent?.startsWith("pp-for:"))return!0;let n=s.parentElement?.firstChild||null;for(;n;){if(n.nodeType===Node.COMMENT_NODE&&n.textContent?.startsWith("pp-for:")&&n!==s)return!0;n=n.nextSibling}s=s.parentElement}return!1}updateTextNode(e){const s=this.textNodeBindings.get(e);if(!s||!e.parentElement)return;const i=e.parentElement,n=y.getContextComponent(i),r=this.resolveComponentRootForElement(e,n),a=this.getContextForComponent(n,r);let o="";for(const c of s.expressions)if(c.type==="static")o+=c.content;else if(c.expression)try{const l=this.expressionEvaluator.evaluateExpression(c.expression,a,n);o+=ie(l)}catch(l){const h=typeof l=="object"&&l!==null&&"message"in l?l.message:String(l);console.warn(`Text binding evaluation warning for "${c.expression}": ${h}`),o+=""}e.textContent!==o&&(e.textContent=o)}resolveComponentRootForElement(e,s){let i=e.parentElement;for(;i&&i.nodeType===Node.ELEMENT_NODE;){const n=i;if(n.getAttribute(d.ATTR_PREFIXES.COMPONENT)===s)return n;i=i.parentElement}}getContextForComponent(e,s){return this.componentManager?this.componentManager.buildComponentContextWithProps(e,s):{}}cleanupTextNode(e){const s=this.textNodeBindings.get(e);s&&(s.subscriptionIds.forEach(i=>{this.stateManager.removeSubscription(i)}),this.textNodeBindings.delete(e),this.bindingCount=Math.max(0,this.bindingCount-1))}getBindingCount(){return this.textNodeBindings.size}getAllBindings(){return new Map(this.textNodeBindings)}clearAllBindings(){for(const[e]of this.textNodeBindings)this.cleanupTextNode(e)}destroy(){this.cleanupObserver.disconnect(),this.clearAllBindings()}}class _s{listeners=new Map;on(e,s){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(s),()=>this.off(e,s)}off(e,s){this.listeners.get(e)?.delete(s)}emit(e,...s){const i=this.listeners.get(e);i&&i.forEach(n=>{try{n(...s)}catch(r){console.error(`Event listener error for ${e}:`,r)}})}}class ks{stateStore={};subscriptions=new Map;updateQueue=new Set;isUpdating=!1;eventBus=new _s;contextCache=new Map;previousValues=new Map;_subscriptionManager=new Ts;originalStateStore={};domUpdateCallbacks=[];domUpdateScheduled=!1;constructor(){this.setupGlobalStateProxy(),setInterval(()=>{this.subscriptionManager.cleanupStaleSubscriptions()},3e4)}onDOMUpdateComplete(e){this.domUpdateCallbacks.push(e),this.domUpdateScheduled||(this.domUpdateScheduled=!0,requestAnimationFrame(()=>{requestAnimationFrame(()=>{const s=[...this.domUpdateCallbacks];this.domUpdateCallbacks=[],this.domUpdateScheduled=!1,s.forEach(i=>{try{i()}catch(n){console.error("DOM update callback error:",n)}})})}))}setInitialState(e,s){if(this.previousValues.set(e,void 0),this.originalStateStore[e]=s,this.previousValues.size>100){const i=this.previousValues.keys().next().value;typeof i=="string"&&this.previousValues.delete(i)}}get subscriptionManager(){return this._subscriptionManager}batchStateUpdates(e){const s=this.isUpdating;this.isUpdating=!0;try{return e()}finally{this.isUpdating=s,!this.isUpdating&&this.updateQueue.size>0&&this.scheduleFlush()}}invalidateContextCache(){this.contextCache.clear()}setupGlobalStateProxy(){this.originalStateStore=this.stateStore,this.stateStore=new Proxy(this.stateStore,{set:(e,s,i,n)=>{const r=e[s],a=Reflect.set(e,s,i,n);return r!==i&&this.notifySubscribers(s),a},get:(e,s)=>Reflect.get(e,s)})}notifySubscribers(e){if(this.eventBus.emit("stateChanged",e),this.updateQueue.add(e),e.includes(".")){const s=e.split(".")[0];this.updateQueue.add(s)}this.notifyPathBasedSubscribers(e),this.isUpdating||this.scheduleFlush()}notifyPathBasedSubscribers(e){const s=this.stateStore[e],i=this.previousValues?.get(e);for(const[n,r]of this.subscriptions)for(const a of r.dependencies)if(this.isPathDependency(a)&&a.startsWith(e+".")){const o=a.substring(e.length+1),c=this.getPathValue(i,o),l=this.getPathValue(s,o);this.deepEqual(c,l)||this.updateQueue.add(a)}}isPathDependency(e){return e.includes(".")&&e.split(".").length>1}getPathValue(e,s){if(!e||typeof e!="object")return;const i=s.split(".");let n=e;for(const r of i){if(n==null)return;if(Array.isArray(n))return r==="length"?n.length:n.map(a=>a?.[r]).filter(a=>a!==void 0);n=n[r]}return n}deepEqual(e,s){if(e===s)return!0;if(e==null||s==null)return!1;if(Array.isArray(e)&&Array.isArray(s))return e.length!==s.length?!1:e.every((i,n)=>this.deepEqual(i,s[n]));if(typeof e=="object"&&typeof s=="object"){const i=Object.keys(e),n=Object.keys(s);return i.length!==n.length?!1:i.every(r=>this.deepEqual(e[r],s[r]))}return!1}scheduleFlush=As(()=>{this.flushUpdates()},d.DEBOUNCE_MS);flushUpdates(){if(!this.isUpdating){this.isUpdating=!0;try{const e=new Set,s=this.subscriptionManager.getSubscriptionsForKey("*");if(s&&s.size>0&&this.updateQueue.size>0)for(const i of s){const n=this.subscriptionManager.getSubscription(i);if(!n)continue;if(n.element&&!document.contains(n.element)){this.subscriptionManager.removeSubscription(i);continue}const r=n.element??document.body;try{const a=Array.from(this.updateQueue)[0];n.callback(r,{key:a})}catch(a){console.error("Wildcard subscription callback failed:",a)}}for(const i of this.updateQueue){if(e.has(i))continue;e.add(i);const n=this.subscriptionManager.getSubscriptionsForKey(i);if(n)for(const r of n){const a=this.subscriptionManager.getSubscription(r);if(!a)continue;if(a.element&&!document.contains(a.element)){this.subscriptionManager.removeSubscription(r);continue}const o=a.element??document.body;try{a.callback(o,{key:i})}catch(c){console.error("Subscription callback failed:",c)}}}}finally{this.updateQueue.clear(),this.isUpdating=!1}}}getState(){return this.stateStore}setState(e,s){if(this.previousValues.set(e,this.stateStore[e]),this.stateStore[e]=s,this.previousValues.size>100){const i=this.previousValues.keys().next().value;typeof i=="string"&&this.previousValues.delete(i)}}hasState(e){return e in this.originalStateStore}addSubscription(e){this._subscriptionManager.addSubscription(e)}removeSubscription(e){this._subscriptionManager.removeSubscription(e)}onStateChange(e){return this.eventBus.on("stateChanged",e)}batch(e){const s=this.isUpdating;this.isUpdating=!0;try{return e()}finally{this.isUpdating=s,!this.isUpdating&&this.updateQueue.size&&this.flushUpdates()}}getSubscriptions(){return this.subscriptionManager.getAllSubscriptions()}getKeyIndex(){const e=new Map,s=this.subscriptionManager.getAllSubscriptions();for(const[i,n]of s)for(const r of n.dependencies)e.has(r)||e.set(r,new Set),e.get(r).add(i);return e}}class ce{expressionCache=new $(d.MAX_CACHE_SIZE);dependencyCache=new $(d.MAX_CACHE_SIZE);commonExpressionsCache=new $(100);dependencyParser=new Is;static CACHE_KEYS={EXPRESSION:(e,s)=>`expr:${e}:${s}`,DEPENDENCY:(e,s)=>`deps:${e}:${s}`,COMMON:e=>`common:${e}`};constructor(){this.precompileCommonExpressions()}normalizeExpression(e){return e.replace(/\r\n/g," ").replace(/\r/g," ").replace(/\n/g," ").replace(/\s+/g," ").trim()}precompileCommonExpressions(){["true","false","null","undefined"].forEach(s=>{const i={fn:new Function("return "+s),contextMap:new Map,dependencies:[s],timestamp:Date.now(),hitCount:0},n=ce.CACHE_KEYS.COMMON(s);this.commonExpressionsCache.set(n,i)})}extractDependencies(e,s,i){const n=this.normalizeExpression(e),r=ce.CACHE_KEYS.DEPENDENCY(s,n);let a=this.dependencyCache.get(r);return a||(a=this.dependencyParser.extract(n,s,i),this.dependencyCache.set(r,a),a)}evaluateExpression(e,s,i){const n=this.normalizeExpression(e),r=ce.CACHE_KEYS.COMMON(n);let a=this.commonExpressionsCache.get(r);if(a){a.hitCount++;try{return a.fn()}catch(c){console.error(`Common expression evaluation failed: "${n}"`,c);return}}const o=ce.CACHE_KEYS.EXPRESSION(i,n);a=this.expressionCache.get(o),(!a||this.isStale(a))&&(a=this.compileExpression(n,s,i),this.expressionCache.set(o,a)),a.hitCount++;try{const c=this.buildArguments(a.contextMap,s);return a.fn(...c)}catch(c){console.error(`Expression evaluation failed: "${n}"`,c),console.error("Available context:",Object.keys(s));return}}compileExpression(e,s,i){const n=this.prepareSafeContext(s),r=new Map,a=[];Object.keys(n).forEach((c,l)=>{r.set(c,l),a.push(c)});const o=this.dependencyParser.extract(e,i);return{fn:new Function(...a,`return (${e})`),contextMap:r,dependencies:o,timestamp:Date.now(),hitCount:0}}buildArguments(e,s){const i=new Array(e.size);for(const[n,r]of e)i[r]=s[n];return i}isStale(e){return Date.now()-e.timestamp>3e5}prepareSafeContext(e){const s={};for(const[i,n]of Object.entries(e))Ae.has(i)||!this.isValidJavaScriptIdentifier(i)||(s[i]=n);return s}isValidJavaScriptIdentifier(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)&&!Ae.has(e)}invalidateCache(e){switch(e){case"expressions":this.expressionCache.clear();break;case"dependencies":this.dependencyCache.clear();break;case"common":this.commonExpressionsCache.clear(),this.precompileCommonExpressions();break;case"parser":this.dependencyParser.clearCache();break;default:this.clearAllCaches()}}invalidateByComponent(e){this.expressionCache.deleteByPrefix(`expr:${e}:`),this.dependencyCache.deleteByPrefix(`deps:${e}:`)}clearAllCaches(){this.expressionCache.clear(),this.dependencyCache.clear(),this.commonExpressionsCache.clear(),this.dependencyParser.clearCache(),this.precompileCommonExpressions()}getCacheStats(){return{expressions:this.expressionCache.getStats(),dependencies:this.dependencyCache.getStats(),commonExpressions:this.commonExpressionsCache.getStats(),dependencyParser:this.getDependencyParserStats()}}getDependencyParserStats(){return this.dependencyParser.getCacheSize?{size:this.dependencyParser.getCacheSize(),maxSize:500,hitRate:0,hits:0,misses:0}:{size:0,maxSize:0,hitRate:0,hits:0,misses:0}}cleanupStaleExpressions(){let e=0;return this.expressionCache.keys().forEach(i=>{const n=this.expressionCache.get(i);n&&this.isStale(n)&&(this.expressionCache.delete(i),e++)}),e}}class Is{parseCache=new $(500);extract(e,s,i){const n=this.normalizeExpression(e),r=`${s}:${n}`;if(this.parseCache.has(r))return this.parseCache.get(r);const a=this.parseExpression(n,s,i);return this.parseCache.set(r,a),a}normalizeExpression(e){return e.replace(/\r\n/g," ").replace(/\r/g," ").replace(/\n/g," ").replace(/\s+/g," ").trim()}parseExpression(e,s,i){const n=this.extractIdentifiers(e),r=[],a=i?.getState()||{};for(const c of n){if(Ae.has(c))continue;const l=c.indexOf("."),h=l===-1?c:c.substring(0,l),p=Be.findExistingStateKey(h,s,a);if(p)r.push(p);else{const f=s==="app"?[`app.${h}`]:[`${s}.${h}`,`app.${h}`];r.push(...f)}if(l!==-1){const f=s==="app"?[`app.${h}`]:[`${s}.${h}`,`app.${h}`];r.push(...f)}}return Array.from(new Set(r))}extractIdentifiers(e){const s=[];let i=0;for(;i<e.length;){const n=e[i];if(n==="'"){i=this.skipString(e,i,"'");continue}if(n==='"'){i=this.skipString(e,i,'"');continue}if(n==="`"){i=this.skipTemplateLiteral(e,i,s);continue}if(this.isIdentifierStart(n)){const r=this.extractIdentifier(e,i);s.push(r.value),i=r.endIndex;continue}i++}return s}skipString(e,s,i){let n=s+1;for(;n<e.length&&e[n]!==i;)e[n]==="\\"&&n++,n++;return n+1}skipTemplateLiteral(e,s,i){let n=s+1;for(;n<e.length&&e[n]!=="`";){if(e[n]==="$"&&n+1<e.length&&e[n+1]==="{"){n+=2;let r=1;for(;n<e.length&&r>0;){const a=e[n];if(a==='"'||a==="'"){n=this.skipString(e,n,a);continue}if(a==="{"?r++:a==="}"&&r--,r>0&&this.isIdentifierStart(a)){const o=this.extractIdentifier(e,n);i.push(o.value),n=o.endIndex-1}n++}continue}e[n]==="\\"&&n++,n++}return n+1}extractIdentifier(e,s){let i=s;for(;i<e.length&&(this.isIdentifierPart(e[i])||e[i]===".");)i++;return{value:e.substring(s,i),endIndex:i}}isIdentifierStart(e){return/[a-zA-Z_$]/.test(e)}isIdentifierPart(e){return/[a-zA-Z0-9_$]/.test(e)}clearCache(){this.parseCache.clear()}getCacheSize(){return this.parseCache.cache.size}}class Ns{componentStack=["app"];elementProps=new WeakMap;contextCache=new $(100);contextIndex=new Map;contextInvalidated=new Set;stateManager;processedScripts=new WeakSet;componentFunctions=new Map;expressionEvaluator;domBindingManager;loopManager;templateRenderer;updateTimeouts;updateBatcher=new et;propDependencyCache=new Map;constructor(e){this.stateManager=e,this.updateBatcher=new et,this.stateManager.onStateChange(s=>this.invalidateContextCache(s))}getPropDependencies(e,s){const i=this.findElementWithProps(s);if(!i)return[];const n=this.elementProps.get(i);if(!n||!n.has(e))return[];const r=n.get(e);return this.templateRenderer?.dependencies(r.expression,r.component,this.stateManager)||[]}buildRestrictedComponentContext(e,s=!1){const i={};window[e]&&Object.assign(i,window[e]);const n=this.componentFunctions.get(e);if(n)for(const[a,o]of n)i[a]=o;const r=this.stateManager.getState();for(const a of Object.keys(r))if(a.startsWith(e+".")){const o=a.substring(e.length+1);o in i||(i[o]=r[a])}if(s){if(window.app)for(const[o,c]of Object.entries(window.app))o in i||(i[o]=c);const a=this.componentFunctions.get("app");if(a)for(const[o,c]of a)o in i||(i[o]=c);for(const o of Object.keys(r))if(o.startsWith("app.")){const c=o.substring(4);c in i||(i[c]=r[o])}}return i}getComponentPropDependencies(e,s){if(this.propDependencyCache.has(e))return this.propDependencyCache.get(e);const i=[],n=this.elementProps.get(e);n&&this.templateRenderer&&n.forEach(a=>{const o=this.templateRenderer?.dependencies(a.expression,a.component,this.stateManager);i.push(...o??[])});const r=Array.from(new Set(i));return this.propDependencyCache.set(e,r),r}setDOMBindingManager(e){this.domBindingManager=e,this.updateBatcher.setManagers(this,e)}hasStoredProps(e){return this.elementProps.has(e)&&this.elementProps.get(e).size>0}setExpressionEvaluator(e){this.expressionEvaluator=e,this.templateRenderer=new Ke(e),this.loopManager=new Ft(this.stateManager,e)}extractProps(e,s){const i=new Map,n=e.attributes,r=e.getAttribute(d.ATTR_PREFIXES.CONTEXT),a=e.getAttribute(d.ATTR_PREFIXES.COMPONENT);let o=s;r&&(r==="app"?o="app":r==="parent"?o=y.getParentOfComponent(a||"app",e):o=r);for(let c=0;c<n.length;c++){const l=n[c];if(!(l.name===d.ATTR_PREFIXES.COMPONENT||l.name===d.ATTR_PREFIXES.CONTEXT||l.name===d.ATTR_PREFIXES.SPREAD||l.name===d.ATTR_PREFIXES.LOOP)&&!oe.isEventAttribute(l.name)&&l.value&&ws.containsMustacheExpression(l.value)){if(a&&this.mightReferenceSelfProps(l.value,e))continue;const h=this.attributeToPropName(l.name),p={name:h,expression:l.value,component:o,subscriptionIds:[]};i.set(h,p)}}return i}mightReferenceSelfProps(e,s){const i=this.elementProps.get(s);return i?Array.from(i.keys()).some(r=>e.includes(r)&&r!=="dataState"):!1}attributeToPropName(e){return e.replace(/-([a-z])/g,(s,i)=>i.toUpperCase())}setupProps(e,s){const i=this.extractProps(e,s);i.size!==0&&(this.elementProps.set(e,i),this.expressionEvaluator&&i.forEach((n,r)=>{this.setupPropBinding(e,n)}))}setupPropBinding(e,s){if(!this.expressionEvaluator)return;const i=`prop_${Date.now()}_${Math.random()}`,n=this.templateRenderer?.dependencies(s.expression,s.component,this.stateManager)||[],r={id:i,selector:"",dependencies:new Set(n),callback:()=>{const a=e.getAttribute(d.ATTR_PREFIXES.COMPONENT);a&&(this.updateBatcher.scheduleUpdate(a,e),this.refreshComponentBindings(e,a))},element:e,component:s.component};this.stateManager.addSubscription(r),s.subscriptionIds.push(i)}refreshComponentBindings(e,s){this.contextInvalidated.add(s),this.contextCache.delete(s),this.domBindingManager&&this.domBindingManager.refreshComponentElement(e,s)}evaluateProps(e){const s={},i=this.elementProps.get(e);if(!i||!this.expressionEvaluator)return s;const n=i.values().next().value;if(!n)return s;const r=this.buildComponentContext(n.component);return i.forEach((a,o)=>{try{const c=this.templateRenderer?.render(a.expression,r,a.component);typeof c=="function"?s[o]=(...l)=>c.apply(this,l):s[o]=c}catch(c){console.error(`❌ Failed to evaluate prop "${o}":`,c),s[o]=void 0}}),s}cleanupProps(e){const s=this.elementProps.get(e);s&&(s.forEach(i=>{i.subscriptionIds.forEach(n=>{this.stateManager.removeSubscription(n)})}),this.elementProps.delete(e))}buildComponentContextWithProps(e,s){const i=this.buildComponentContext(e);let n=this.findElementWithProps(e);if(s&&this.elementProps.has(s)&&(n=s),n)try{const r=this.evaluatePropsWithContext(n,e,s);Object.keys(r).length>0&&Object.keys(r).forEach(a=>{i[a]=r[a]})}catch(r){console.error(`❌ Error evaluating props for ${e}:`,r)}return i}evaluatePropsWithContext(e,s,i){const n={},r=this.elementProps.get(e);if(!r||!this.expressionEvaluator)return n;const a=r.values().next().value;if(!a)return n;let o;const c=e.getAttribute(d.ATTR_PREFIXES.CONTEXT),l=e.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(c)if(c==="app")o=this.buildComponentContext("app");else if(c==="parent"){const C=y.getParentOfComponent(l||"app",e);o=this.buildComponentContext(C)}else o=this.buildComponentContext(c);else o=this.buildComponentContext(a.component);const h=this.loopManager?.getLoopContextForElement(e);h&&(o={...o,...h});const p=new Map,f=new Map,m=Array.from(r.keys());r.forEach((C,S)=>{m.some(M=>M!==S&&C.expression.includes(M))?f.set(S,C):p.set(S,C)}),p.forEach((C,S)=>{try{const P=this.templateRenderer?.render(C.expression,o,c||C.component);typeof P=="function"?this.isFunctionExplicitlyPassed(C.expression)?n[S]=(...fe)=>P.apply(this,fe):(console.warn(`⚠️ Function "${S}" not passed - not from shared namespace or explicitly passed`),n[S]=void 0):n[S]=P}catch(P){console.error(`❌ Failed to evaluate simple prop "${S}":`,P),console.error("Expression:",C.expression),console.error("Available context keys:",Object.keys(o)),n[S]=void 0}});const x={...o,...n};return f.forEach((C,S)=>{try{const P=this.templateRenderer?.render(C.expression,x,c||C.component);typeof P=="function"?this.isFunctionExplicitlyPassed(C.expression)?n[S]=(...fe)=>P.apply(this,fe):(console.warn(`⚠️ Function "${S}" not passed - not from shared namespace or explicitly passed`),n[S]=void 0):n[S]=P}catch(P){console.error(`❌ Failed to evaluate complex prop "${S}":`,P),console.error("Expression:",C.expression),console.error("Available context keys:",Object.keys(x)),n[S]=void 0}}),n}isFunctionExplicitlyPassed(e){const s=_.isSingleExpression(e);return s?/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(s.trim()):!1}findElementWithProps(e){const s=document.querySelectorAll(`[${d.ATTR_PREFIXES.COMPONENT}="${e}"]`);for(const i of s){const n=this.elementProps.get(i);if(n&&n.size>0)return i}return null}pushComponent(e){this.componentStack.push(e)}popComponent(){return this.componentStack.pop()}getCurrentComponent(){return this.componentStack[this.componentStack.length-1]}buildComponentContext(e){if(!this.contextInvalidated.has(e)&&this.contextCache.has(e))return this.contextCache.get(e);const s=this.computeComponentContext(e);return this.contextCache.set(e,s),this.contextInvalidated.delete(e),s}computeComponentContext(e){const s={};e!=="app"&&window[e]&&Object.assign(s,window[e]),e==="app"&&window.app&&Object.assign(s,window.app);const i=this.componentFunctions.get(e);if(i)for(const[r,a]of i)s[r]=a;if(e!=="app"){const r=this.componentFunctions.get("app");if(r)for(const[a,o]of r)a in s||(s[a]=o)}const n=this.stateManager.getState();for(const r of Object.keys(n))if(r.startsWith(e+".")){const a=r.substring(e.length+1);a in s||(s[a]=n[r])}if(e!=="app"){for(const r of Object.keys(n))if(r.startsWith("app.")){const a=r.substring(4);a in s||(s[a]=n[r])}}return s}invalidateContextCache(e){if(e.startsWith("app.")){this.contextCache.clear();for(const i of this.contextInvalidated.keys())this.contextInvalidated.add(i);return}const s=e.indexOf(".");if(s!==-1){const i=e.slice(0,s);this.invalidateComponent(i)}}invalidateComponent(e){this.contextInvalidated.add(e),this.contextIndex.delete(e)}executePhpScripts(e){const s=this.componentStack.length,i=e.getAttribute(d.ATTR_PREFIXES.COMPONENT),n=e===document.body;if(i||n){if(i){this.pushComponent(i);const a=this.getParentComponent(e);this.setupProps(e,a)}this.getRelevantScripts(e,n).forEach(a=>{const o=a.getAttribute(d.ATTR_PREFIXES.COMPONENT);o&&o!==i?(this.pushComponent(o),this.executeScript(a),this.popComponent()):this.executeScript(a)})}for(Array.from(e.children).forEach(r=>this.executePhpScripts(r));this.componentStack.length>s;)this.popComponent()}getParentComponent(e){let s=e.parentElement;for(;s;){const i=s.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(i)return i;s=s.parentElement}return"app"}getRelevantScripts(e,s){return Array.from(e.querySelectorAll(`script[type="${d.SCRIPT_TYPE}"]`)).filter(i=>{if(this.processedScripts.has(i))return!1;if(s)return i.hasAttribute(d.ATTR_PREFIXES.COMPONENT)?!0:!i.closest(`[${d.ATTR_PREFIXES.COMPONENT}]`);let n=i.parentElement;for(;n&&n!==e;){if(n.hasAttribute(d.ATTR_PREFIXES.COMPONENT))return!1;n=n.parentElement}return n===e||e.contains(i)})}executeScript(e){if(this.processedScripts.has(e))return;this.processedScripts.add(e);const s=this.getCurrentComponent(),i=e.textContent||"",n=_.decodeEntities(i);try{const r=this.findComponentElementForScript(e,s);if(r===e){const o=this.getParentComponent(e);this.setupProps(e,o)}const a=this.buildComponentContextWithProps(s,r);window[s]||(window[s]={}),this.executeScriptFunctions(n,s,a)}catch(r){console.error(`Script execution failed in component ${s}:`,r),console.error("Script content:",n)}}findComponentElementForScript(e,s){if(e.getAttribute(d.ATTR_PREFIXES.COMPONENT)===s)return e;let i=e.parentElement;for(;i;){if(i.getAttribute(d.ATTR_PREFIXES.COMPONENT)===s)return i;i=i.parentElement}const n=document.querySelectorAll(`[${d.ATTR_PREFIXES.COMPONENT}="${s}"]`);for(const r of n)if(this.elementProps.has(r))return r;return n[0]||void 0}executeScriptFunctions(e,s,i){const n=this.extractFunctionNames(e),r=this.findElementWithProps(s),a=this.extractVariableDeclarations(e);let o={...i};if(a.forEach(x=>{delete o[x];const C=`set${Vt(x)}`,S=`${x}Getter`;delete o[C],delete o[S]}),r){const x=this.evaluateProps(r);Object.assign(o,x)}o.getContext=()=>this.buildComponentContextWithProps(s),o.withContext=x=>{const C=this.buildComponentContextWithProps(s);return x.call(C,C)},o.__getProp=x=>{if(r)return this.evaluateProps(r)[x]};let l=z.getInstance().transformStateDeclarations(e);l=this.modifyScriptForReactiveProps(l,s,r||void 0);const h=`
|
|
9
|
+
`;case 114:return"\r";case 120:return String.fromCharCode(this.readHexChar(2));case 117:return G(this.readCodePoint());case 116:return" ";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 13:this.input.charCodeAt(this.pos)===10&&++this.pos;case 10:return this.options.locations&&(this.lineStart=this.pos,++this.curLine),"";case 56:case 57:if(this.strict&&this.invalidStringToken(this.pos-1,"Invalid escape sequence"),t){var s=this.pos-1;this.invalidStringToken(s,"Invalid escape sequence in template string")}default:if(e>=48&&e<=55){var i=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],n=parseInt(i,8);return n>255&&(i=i.slice(0,-1),n=parseInt(i,8)),this.pos+=i.length-1,e=this.input.charCodeAt(this.pos),(i!=="0"||e===56||e===57)&&(this.strict||t)&&this.invalidStringToken(this.pos-1-i.length,t?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(n)}return ue(e)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(e)}};A.readHexChar=function(t){var e=this.pos,s=this.readInt(16,t);return s===null&&this.invalidStringToken(e,"Bad character escape sequence"),s};A.readWord1=function(){this.containsEsc=!1;for(var t="",e=!0,s=this.pos,i=this.options.ecmaVersion>=6;this.pos<this.input.length;){var n=this.fullCharCodeAtPos();if(J(n,i))this.pos+=n<=65535?1:2;else if(n===92){this.containsEsc=!0,t+=this.input.slice(s,this.pos);var r=this.pos;this.input.charCodeAt(++this.pos)!==117&&this.invalidStringToken(this.pos,"Expecting Unicode escape sequence \\uXXXX"),++this.pos;var a=this.readCodePoint();(e?q:J)(a,i)||this.invalidStringToken(r,"Invalid Unicode escape"),t+=G(a),s=this.pos}else break;e=!1}return t+this.input.slice(s,this.pos)};A.readWord=function(){var t=this.readWord1(),e=u.name;return this.keywords.test(t)&&(e=$e[t]),this.finishToken(e,t)};var vs="8.15.0";I.acorn={Parser:I,version:vs,defaultOptions:Ve,Position:me,SourceLocation:Te,getLineInfo:at,Node:ke,TokenType:w,tokTypes:u,keywordTypes:$e,TokContext:H,tokContexts:k,isIdentifierChar:J,isIdentifierStart:q,Token:qe,isNewLine:ue,lineBreak:V,lineBreakG:Ht,nonASCIIwhitespace:nt};function W(t,e){return I.parse(t,e)}function U(t,e,s,i,n){s||(s=g),(function r(a,o,c){var l=c||a.type;s[l](a,o,r),e[l]&&e[l](a,o)})(t,i,n)}function Ss(t,e,s,i,n){var r=[];s||(s=g),(function a(o,c,l){var h=l||o.type,p=o!==r[r.length-1];p&&r.push(o),s[h](o,c,a),e[h]&&e[h](o,c||r,r),p&&r.pop()})(t,i,n)}function Xe(t,e,s){s(t,e)}function re(t,e,s){}var g={};g.Program=g.BlockStatement=g.StaticBlock=function(t,e,s){for(var i=0,n=t.body;i<n.length;i+=1){var r=n[i];s(r,e,"Statement")}};g.Statement=Xe;g.EmptyStatement=re;g.ExpressionStatement=g.ParenthesizedExpression=g.ChainExpression=function(t,e,s){return s(t.expression,e,"Expression")};g.IfStatement=function(t,e,s){s(t.test,e,"Expression"),s(t.consequent,e,"Statement"),t.alternate&&s(t.alternate,e,"Statement")};g.LabeledStatement=function(t,e,s){return s(t.body,e,"Statement")};g.BreakStatement=g.ContinueStatement=re;g.WithStatement=function(t,e,s){s(t.object,e,"Expression"),s(t.body,e,"Statement")};g.SwitchStatement=function(t,e,s){s(t.discriminant,e,"Expression");for(var i=0,n=t.cases;i<n.length;i+=1){var r=n[i];s(r,e)}};g.SwitchCase=function(t,e,s){t.test&&s(t.test,e,"Expression");for(var i=0,n=t.consequent;i<n.length;i+=1){var r=n[i];s(r,e,"Statement")}};g.ReturnStatement=g.YieldExpression=g.AwaitExpression=function(t,e,s){t.argument&&s(t.argument,e,"Expression")};g.ThrowStatement=g.SpreadElement=function(t,e,s){return s(t.argument,e,"Expression")};g.TryStatement=function(t,e,s){s(t.block,e,"Statement"),t.handler&&s(t.handler,e),t.finalizer&&s(t.finalizer,e,"Statement")};g.CatchClause=function(t,e,s){t.param&&s(t.param,e,"Pattern"),s(t.body,e,"Statement")};g.WhileStatement=g.DoWhileStatement=function(t,e,s){s(t.test,e,"Expression"),s(t.body,e,"Statement")};g.ForStatement=function(t,e,s){t.init&&s(t.init,e,"ForInit"),t.test&&s(t.test,e,"Expression"),t.update&&s(t.update,e,"Expression"),s(t.body,e,"Statement")};g.ForInStatement=g.ForOfStatement=function(t,e,s){s(t.left,e,"ForInit"),s(t.right,e,"Expression"),s(t.body,e,"Statement")};g.ForInit=function(t,e,s){t.type==="VariableDeclaration"?s(t,e):s(t,e,"Expression")};g.DebuggerStatement=re;g.FunctionDeclaration=function(t,e,s){return s(t,e,"Function")};g.VariableDeclaration=function(t,e,s){for(var i=0,n=t.declarations;i<n.length;i+=1){var r=n[i];s(r,e)}};g.VariableDeclarator=function(t,e,s){s(t.id,e,"Pattern"),t.init&&s(t.init,e,"Expression")};g.Function=function(t,e,s){t.id&&s(t.id,e,"Pattern");for(var i=0,n=t.params;i<n.length;i+=1){var r=n[i];s(r,e,"Pattern")}s(t.body,e,t.expression?"Expression":"Statement")};g.Pattern=function(t,e,s){t.type==="Identifier"?s(t,e,"VariablePattern"):t.type==="MemberExpression"?s(t,e,"MemberPattern"):s(t,e)};g.VariablePattern=re;g.MemberPattern=Xe;g.RestElement=function(t,e,s){return s(t.argument,e,"Pattern")};g.ArrayPattern=function(t,e,s){for(var i=0,n=t.elements;i<n.length;i+=1){var r=n[i];r&&s(r,e,"Pattern")}};g.ObjectPattern=function(t,e,s){for(var i=0,n=t.properties;i<n.length;i+=1){var r=n[i];r.type==="Property"?(r.computed&&s(r.key,e,"Expression"),s(r.value,e,"Pattern")):r.type==="RestElement"&&s(r.argument,e,"Pattern")}};g.Expression=Xe;g.ThisExpression=g.Super=g.MetaProperty=re;g.ArrayExpression=function(t,e,s){for(var i=0,n=t.elements;i<n.length;i+=1){var r=n[i];r&&s(r,e,"Expression")}};g.ObjectExpression=function(t,e,s){for(var i=0,n=t.properties;i<n.length;i+=1){var r=n[i];s(r,e)}};g.FunctionExpression=g.ArrowFunctionExpression=g.FunctionDeclaration;g.SequenceExpression=function(t,e,s){for(var i=0,n=t.expressions;i<n.length;i+=1){var r=n[i];s(r,e,"Expression")}};g.TemplateLiteral=function(t,e,s){for(var i=0,n=t.quasis;i<n.length;i+=1){var r=n[i];s(r,e)}for(var a=0,o=t.expressions;a<o.length;a+=1){var c=o[a];s(c,e,"Expression")}};g.TemplateElement=re;g.UnaryExpression=g.UpdateExpression=function(t,e,s){s(t.argument,e,"Expression")};g.BinaryExpression=g.LogicalExpression=function(t,e,s){s(t.left,e,"Expression"),s(t.right,e,"Expression")};g.AssignmentExpression=g.AssignmentPattern=function(t,e,s){s(t.left,e,"Pattern"),s(t.right,e,"Expression")};g.ConditionalExpression=function(t,e,s){s(t.test,e,"Expression"),s(t.consequent,e,"Expression"),s(t.alternate,e,"Expression")};g.NewExpression=g.CallExpression=function(t,e,s){if(s(t.callee,e,"Expression"),t.arguments)for(var i=0,n=t.arguments;i<n.length;i+=1){var r=n[i];s(r,e,"Expression")}};g.MemberExpression=function(t,e,s){s(t.object,e,"Expression"),t.computed&&s(t.property,e,"Expression")};g.ExportNamedDeclaration=g.ExportDefaultDeclaration=function(t,e,s){t.declaration&&s(t.declaration,e,t.type==="ExportNamedDeclaration"||t.declaration.id?"Statement":"Expression"),t.source&&s(t.source,e,"Expression")};g.ExportAllDeclaration=function(t,e,s){t.exported&&s(t.exported,e),s(t.source,e,"Expression")};g.ImportDeclaration=function(t,e,s){for(var i=0,n=t.specifiers;i<n.length;i+=1){var r=n[i];s(r,e)}s(t.source,e,"Expression")};g.ImportExpression=function(t,e,s){s(t.source,e,"Expression")};g.ImportSpecifier=g.ImportDefaultSpecifier=g.ImportNamespaceSpecifier=g.Identifier=g.PrivateIdentifier=g.Literal=re;g.TaggedTemplateExpression=function(t,e,s){s(t.tag,e,"Expression"),s(t.quasi,e,"Expression")};g.ClassDeclaration=g.ClassExpression=function(t,e,s){return s(t,e,"Class")};g.Class=function(t,e,s){t.id&&s(t.id,e,"Pattern"),t.superClass&&s(t.superClass,e,"Expression"),s(t.body,e)};g.ClassBody=function(t,e,s){for(var i=0,n=t.body;i<n.length;i+=1){var r=n[i];s(r,e)}};g.MethodDefinition=g.PropertyDefinition=g.Property=function(t,e,s){t.computed&&s(t.key,e,"Expression"),t.value&&s(t.value,e,"Expression")};const d={ATTR_PREFIXES:{COMPONENT:"pp-component",CONTEXT:"pp-context",LOOP:"pp-for",SPREAD:"pp-spread",REF:"pp-ref"},SCRIPT_TYPE:"text/pp",MAX_CACHE_SIZE:2e3,DEBOUNCE_MS:16,POOL_SIZE:10,MUSTACHE_PATTERN:/\{((?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*)\}/,MUSTACHE_SINGLE_PATTERN:/^\{((?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*)\}$/},Ae=new Set(["true","false","null","undefined","this","window","document","console","Math","Date","JSON","Object","Array","return","let","const","var","if","else","for","while","switch","case","break","continue","function","new","in","of","typeof","instanceof","void","delete","try","catch","finally","class","extends","super","thisElement","eventObject","arguments"]);function As(t,e){let s;return(...i)=>{clearTimeout(s),s=window.setTimeout(()=>t(...i),e)}}function Vt(t){return t.charAt(0).toUpperCase()+t.slice(1)}function ie(t){if(t==null||typeof t=="boolean"||typeof t=="function"||Array.isArray(t)&&t.length===0||typeof t=="object"&&Object.keys(t).length===0)return"";if(typeof t=="number")return String(t);if(typeof t=="string")return t;if(Array.isArray(t))return t.map(e=>ie(e)).filter(e=>e!=="").join("");if(typeof t=="object")try{return JSON.stringify(t)}catch{return"[object Object]"}return String(t)}class ae{static instance;walkerPool=[];traversalCache=new WeakMap;lastCacheTime=new WeakMap;CACHE_TTL=250;trackedElements=new Set;static getInstance(){return ae.instance||(ae.instance=new ae),ae.instance}acquireWalker(e,s,i){return document.createTreeWalker(e,s,i)}releaseWalker(e){this.walkerPool.length<3&&this.walkerPool.push(e)}getCachedTraversal(e,s,i){const n=Date.now(),r=this.traversalCache.get(e),a=this.lastCacheTime.get(e);if(r&&a&&n-a<this.CACHE_TTL){const c=r.get(s);if(c)return c}const o=i();return this.traversalCache.has(e)||(this.traversalCache.set(e,new Map),this.trackedElements.add(e)),this.traversalCache.get(e).set(s,o),this.lastCacheTime.set(e,n),o}traverseElementsAndText(e,s,i){const n=this.acquireWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT),r=[],a=[];let o;for(;o=n.nextNode();)if(o.nodeType===Node.ELEMENT_NODE){const c=o;(!s||s(c))&&r.push(c)}else if(o.nodeType===Node.TEXT_NODE){const c=o;(!i||i(c))&&a.push(c)}return this.releaseWalker(n),{elements:r,textNodes:a}}cleanupCache(){const e=[];for(const s of this.trackedElements)document.contains(s)||e.push(s);e.forEach(s=>{this.traversalCache.delete(s),this.lastCacheTime.delete(s),this.trackedElements.delete(s)})}}class L{static instance;componentElementsCache=new $(100);scriptElementsCache=new $(50);templateElementsCache=new $(50);selectorCache=new $(200);elementComponentCache=new WeakMap;parentComponentCache=new WeakMap;contextComponentCache=new WeakMap;elementDepthCache=new WeakMap;elementChildrenCache=new WeakMap;cacheHits=0;cacheMisses=0;static CACHE_KEYS={COMPONENT_ELEMENTS:e=>`comp:${e}`,SCRIPTS:(e,s)=>`scripts:${e}:${s}`,TEMPLATES:(e,s)=>`templates:${e}:${s}`,SELECTOR:e=>`sel:${e}`};static getInstance(){return L.instance||(L.instance=new L),L.instance}queryComponentElements(e){const s=L.CACHE_KEYS.COMPONENT_ELEMENTS(e);if(this.componentElementsCache.has(s))return this.cacheHits++,this.componentElementsCache.get(s);this.cacheMisses++;const i=Array.from(document.querySelectorAll(`[${d.ATTR_PREFIXES.COMPONENT}="${e}"]`));return i.forEach(n=>{this.elementComponentCache.set(n,e)}),this.componentElementsCache.set(s,i),i}querySelectorAll(e){const s=L.CACHE_KEYS.SELECTOR(e);if(this.selectorCache.has(s))return this.cacheHits++,this.selectorCache.get(s);this.cacheMisses++;const i=Array.from(document.querySelectorAll(e));return this.selectorCache.set(s,i),i}getElementComponent(e){if(this.elementComponentCache.has(e))return this.cacheHits++,this.elementComponentCache.get(e);this.cacheMisses++;const s=e.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(s)return this.elementComponentCache.set(e,s),s;let i=e.parentElement;for(;i;){const n=i.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(n)return this.elementComponentCache.set(e,n),n;i=i.parentElement}return this.elementComponentCache.set(e,"app"),"app"}getContextComponent(e){if(this.contextComponentCache.has(e))return this.cacheHits++,this.contextComponentCache.get(e);this.cacheMisses++;const s=e.getAttribute(d.ATTR_PREFIXES.CONTEXT);let i;if(s)if(s==="parent"){const n=this.getElementComponent(e);i=this.getParentOfComponent(n,e)}else s==="app"?i="app":i=s;else i=this.getElementComponent(e);return this.contextComponentCache.set(e,i),i}getParentOfComponent(e,s){if(this.parentComponentCache.has(s))return this.cacheHits++,this.parentComponentCache.get(s);if(this.cacheMisses++,e==="app")return this.parentComponentCache.set(s,"app"),"app";let i=s;for(;i&&i.getAttribute(d.ATTR_PREFIXES.COMPONENT)!==e;)i=i.parentElement;if(!i)return this.parentComponentCache.set(s,"app"),"app";let n=i.parentElement;for(;n;){const r=n.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(r)return this.parentComponentCache.set(s,r),r;n=n.parentElement}return this.parentComponentCache.set(s,"app"),"app"}getElementDepthCached(e){if(this.elementDepthCache.has(e))return this.cacheHits++,this.elementDepthCache.get(e);this.cacheMisses++;let s=0,i=e.parentElement;for(;i&&i!==document.body;)s++,i=i.parentElement;return this.elementDepthCache.set(e,s),s}getFirstComponentElement(e){const s=this.queryComponentElements(e);return s.length>0?s[0]:null}getComponentScripts(e,s){const i=L.CACHE_KEYS.SCRIPTS(e,s?.tagName||"global");if(this.scriptElementsCache.has(i))return this.cacheHits++,this.scriptElementsCache.get(i);this.cacheMisses++;let n=[];if(s){const r=s.querySelectorAll(`script[type="${d.SCRIPT_TYPE}"]`);for(const a of r)a instanceof HTMLScriptElement&&n.push(a)}else{const r=document.querySelectorAll(`script[type="${d.SCRIPT_TYPE}"]`);for(const a of r)if(a instanceof HTMLScriptElement){const o=a.getAttribute(d.ATTR_PREFIXES.COMPONENT);(o===e||!o&&!a.closest(`[${d.ATTR_PREFIXES.COMPONENT}]`))&&n.push(a)}}return this.scriptElementsCache.set(i,n),n}getComponentTemplates(e,s){const i=L.CACHE_KEYS.TEMPLATES(e,s?.tagName||"global");if(this.templateElementsCache.has(i))return this.cacheHits++,this.templateElementsCache.get(i);this.cacheMisses++;let n=[];if(s){const r=s.querySelectorAll("template[pp-for]");for(const a of r)a instanceof HTMLTemplateElement&&this.getElementComponent(a)===e&&n.push(a)}else{const r=document.querySelectorAll("template[pp-for]");for(const a of r)a instanceof HTMLTemplateElement&&this.getElementComponent(a)===e&&n.push(a)}return this.templateElementsCache.set(i,n),n}querySelector(e){const s=this.querySelectorAll(e);return s.length>0?s[0]:null}findElementForComponent(e,s){if(s==="app")return document.body;const i=this.queryComponentElements(s);return i.length>0?i[0]:null}invalidateCache(e){switch(e){case"components":this.componentElementsCache.clear();break;case"selectors":this.selectorCache.clear();break;case"scripts":this.scriptElementsCache.clear();break;case"templates":this.templateElementsCache.clear();break;default:this.clearAllCaches()}}invalidateByComponent(e){const s=L.CACHE_KEYS.COMPONENT_ELEMENTS(e);this.componentElementsCache.delete(s);const i=L.CACHE_KEYS.SCRIPTS(e,"global");this.scriptElementsCache.delete(i);const n=L.CACHE_KEYS.TEMPLATES(e,"global");this.templateElementsCache.delete(n),this.selectorCache.clear()}invalidateByPrefix(e){this.invalidateByComponent(e)}invalidateElement(e){this.elementComponentCache.delete(e),this.contextComponentCache.delete(e),this.parentComponentCache.delete(e),this.elementDepthCache.delete(e),this.elementChildrenCache.delete(e)}clearAllCaches(){this.componentElementsCache.clear(),this.scriptElementsCache.clear(),this.templateElementsCache.clear(),this.selectorCache.clear(),this.elementComponentCache=new WeakMap,this.parentComponentCache=new WeakMap,this.contextComponentCache=new WeakMap,this.elementDepthCache=new WeakMap,this.elementChildrenCache=new WeakMap}getCacheStats(){const e=this.cacheHits+this.cacheMisses;return{componentElements:this.componentElementsCache.getStats(),scriptElements:this.scriptElementsCache.getStats(),templateElements:this.templateElementsCache.getStats(),selectors:this.selectorCache.getStats(),global:{size:0,maxSize:-1,hitRate:e>0?this.cacheHits/e*100:0,hits:this.cacheHits,misses:this.cacheMisses}}}resetStats(){this.cacheHits=0,this.cacheMisses=0}}class Ts{subscriptions=new Map;elementSubscriptions=new WeakMap;keyIndex=new Map;cleanupQueue=new Set;cleanupScheduled=!1;addSubscription(e){this.subscriptions.set(e.id,e),e.element&&(this.elementSubscriptions.has(e.element)||this.elementSubscriptions.set(e.element,new Set),this.elementSubscriptions.get(e.element).add(e.id));for(const s of e.dependencies)this.keyIndex.has(s)||this.keyIndex.set(s,new Set),this.keyIndex.get(s).add(e.id)}removeSubscription(e){const s=this.subscriptions.get(e);if(s){if(this.subscriptions.delete(e),s.element){const i=this.elementSubscriptions.get(s.element);i&&(i.delete(e),i.size===0&&this.elementSubscriptions.delete(s.element))}for(const i of s.dependencies){const n=this.keyIndex.get(i);n&&(n.delete(e),n.size===0&&this.keyIndex.delete(i))}}}cleanupElement(e){const s=this.elementSubscriptions.get(e);s&&(s.forEach(i=>this.cleanupQueue.add(i)),this.scheduleCleanup())}scheduleCleanup(){this.cleanupScheduled||(this.cleanupScheduled=!0,queueMicrotask(()=>{this.processCleanupQueue(),this.cleanupScheduled=!1}))}processCleanupQueue(){for(const e of this.cleanupQueue)this.removeSubscription(e);this.cleanupQueue.clear()}getSubscription(e){return this.subscriptions.get(e)}getSubscriptionsForKey(e){return this.keyIndex.get(e)}getAllSubscriptions(){return new Map(this.subscriptions)}cleanupStaleSubscriptions(){const e=[];for(const[s,i]of this.subscriptions)i.element&&!document.contains(i.element)&&e.push(s);e.forEach(s=>this.removeSubscription(s))}getStats(){return{totalSubscriptions:this.subscriptions.size,elementSubscriptions:this.elementSubscriptions instanceof WeakMap?-1:0,keyIndexes:this.keyIndex.size}}}class z{static instance;stateVariables=new Set;static FUNCTIONS_NEEDING_VALUE_TRANSFORM=new Set(["console.log","console.warn","console.error","console.info","console.debug","console.dir","console.table","console.trace","console.assert","JSON.stringify","JSON.parse","Object.keys","Object.values","Object.entries","Array.from","Array.isArray","Math.max","Math.min","Math.abs","Math.floor","Math.ceil","Math.round","alert","confirm","prompt","parseInt","parseFloat","Number","String","Boolean"]);transformRefDeclarations(e){try{const s=W(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0});let i=e;const n=[];return U(s,{VariableDeclarator:r=>{if(this.isRefDeclaration(r)){const a=r.id.name,o=this.findStatementEnd(e,r.end);n.push({start:o,end:o,replacement:`; this.${a} = ${a}`})}}}),n.sort((r,a)=>a.start-r.start).forEach(r=>{i=i.slice(0,r.start)+r.replacement+i.slice(r.end)}),i}catch(s){return console.error("Ref transformation error:",s),e}}isRefDeclaration(e){return e.id?.type==="Identifier"&&e.init?.type==="CallExpression"&&e.init.callee?.type==="MemberExpression"&&e.init.callee.object?.type==="Identifier"&&e.init.callee.object.name==="pp"&&e.init.callee.property?.type==="Identifier"&&e.init.callee.property.name==="ref"}findStatementEnd(e,s){let i=s;for(;i<e.length&&e[i]!==";"&&e[i]!==`
|
|
10
|
+
`;)i++;return i}static getInstance(){return z.instance||(z.instance=new z),z.instance}extractFunctionNames(e){const s=[];try{const i=W(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0});U(i,{FunctionDeclaration:n=>{n.id?.type==="Identifier"&&s.push(n.id.name)},VariableDeclarator:n=>{n.id?.type==="Identifier"&&(n.init?.type==="ArrowFunctionExpression"||n.init?.type==="FunctionExpression")&&s.push(n.id.name)},AssignmentExpression:n=>{n.left?.type==="Identifier"&&(n.right?.type==="ArrowFunctionExpression"||n.right?.type==="FunctionExpression")&&s.push(n.left.name)}})}catch(i){console.error("AST function extraction error:",i)}return Array.from(new Set(s))}transformEffectDeclarations(e){try{const s=W(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0});let i=e;const n=[];return U(s,{CallExpression:r=>{const a=this.transformEffectCall(r,e);a&&n.push(a)}}),n.sort((r,a)=>a.start-r.start).forEach(r=>{i=i.slice(0,r.start)+r.replacement+i.slice(r.end)}),i}catch(s){return console.error("Effect transformation error:",s),e}}transformEffectCall(e,s){if(!this.isPPEffectCall(e))return null;const i=e.arguments;if(i.length<2)return null;const n=i[1];if(n.type!=="ArrayExpression"||!n.elements.some(p=>p?p.type==="Identifier"||p.type==="MemberExpression":!1))return null;const a=n.elements.map(p=>p?p.type==="Identifier"?`"${p.name}"`:p.type==="MemberExpression"?`"${this.extractMemberExpression(p,s)}"`:s.slice(p.start,p.end):"null"),o=s.slice(i[0].start,i[0].end),c=i.slice(2).map(p=>s.slice(p.start,p.end)).join(", "),l=`[${a.join(", ")}]`,h=c?`pp.effect(${o}, ${l}, ${c})`:`pp.effect(${o}, ${l})`;return{start:e.start,end:e.end,replacement:h}}extractMemberExpression(e,s){if(e.type!=="MemberExpression")return e.type==="Identifier"?e.name:s.slice(e.start,e.end);const i=this.extractMemberExpression(e.object,s);if(e.computed){const n=s.slice(e.property.start,e.property.end);return`${i}[${n}]`}else{const n=e.property.name||s.slice(e.property.start,e.property.end);return`${i}.${n}`}}isPPEffectCall(e){return e.callee?.type==="MemberExpression"&&e.callee.object?.type==="Identifier"&&e.callee.object.name==="pp"&&e.callee.property?.type==="Identifier"&&e.callee.property.name==="effect"}transformStateDeclarations(e){this.stateVariables.clear();let s=this.transformStateDeclarationsOnly(e);return s=this.transformEffectDeclarations(s),s=this.transformRefDeclarations(s),s=this.transformUnsupportedStateUsages(s),s}transformStateDeclarationsOnlyOriginal(e){try{const s=W(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0});let i=e;const n=[];return U(s,{VariableDeclarator:r=>{const a=this.transformStateDeclarator(r,e);a&&n.push(a)}}),n.sort((r,a)=>a.start-r.start).forEach(r=>{i=i.slice(0,r.start)+r.replacement+i.slice(r.end)}),i}catch(s){return console.error("AST transformation error:",s),e}}transformStateDeclarationsOnly(e){let s=this.transformStateDeclarationsOnlyOriginal(e);return s=this.transformDestructuringAssignments(s),s}transformUnsupportedStateUsages(e){try{const s=W(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0});this.collectStateVariables(s);let i=this.transformShorthandProperties(e);const n=W(i,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0}),r=[];return U(n,{SpreadElement:a=>{const o=this.transformSpreadElement(a,i);o&&r.push(o)},UnaryExpression:a=>{const o=this.transformUnaryExpression(a,i);o&&r.push(o)},BinaryExpression:a=>{const o=this.transformBinaryExpression(a,i);o&&r.push(o)},LogicalExpression:a=>{const o=this.transformLogicalExpression(a,i);o&&r.push(o)},ConditionalExpression:a=>{const o=this.transformConditionalExpression(a,i);o&&r.push(o)},IfStatement:a=>{const o=this.transformIfStatement(a,i);o&&r.push(o)},WhileStatement:a=>{const o=this.transformWhileStatement(a,i);o&&r.push(o)},ForStatement:a=>{const o=this.transformForStatement(a,i);o&&r.push(o)},ReturnStatement:a=>{const o=this.transformReturnStatement(a,i);o&&r.push(o)},VariableDeclarator:a=>{const o=this.transformVariableDeclarator(a,i);o&&r.push(o)},AssignmentExpression:a=>{const o=this.transformAssignmentExpression(a,i);o&&r.push(o)},CallExpression:a=>{const o=this.transformGeneralCallExpression(a,i);o&&r.push(o)}}),Ss(n,{Identifier:(a,o)=>{r.some(l=>a.start>=l.start&&a.end<=l.end)||this.stateVariables.has(a.name)&&(this.alreadyHasValue(a,i)||this.isPartOfStateDeclaration(a,o)||this.isPropertyName(a,o)||this.isMethodCallObject(a,o)||this.isPartOfPPCall(a,o)||this.isPartOfDestructuring(a,o)||r.push({start:a.start,end:a.end,replacement:`${a.name}.value`}))}}),r.sort((a,o)=>o.start-a.start).forEach(a=>{i=i.slice(0,a.start)+a.replacement+i.slice(a.end)}),i=this.transformMultipleCallArguments(i),i}catch(s){return console.error("State usage transformation error:",s),e}}transformShorthandProperties(e){try{const s=W(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0});let i=e;const n=[];return U(s,{Property:r=>{if(r.shorthand&&r.key?.type==="Identifier"&&this.stateVariables.has(r.key.name)){const a=r.key.name,o=`${a}: ${a}.value`;n.push({start:r.start,end:r.end,replacement:o})}}}),n.sort((r,a)=>a.start-r.start).forEach(r=>{i=i.slice(0,r.start)+r.replacement+i.slice(r.end)}),i}catch(s){return console.error("Shorthand property transformation error:",s),e}}transformLogicalExpression(e,s){return e.left?.type==="Identifier"&&this.stateVariables.has(e.left.name)&&!this.alreadyHasValue(e.left,s)?{start:e.left.start,end:e.left.end,replacement:`${e.left.name}.value`}:e.right?.type==="Identifier"&&this.stateVariables.has(e.right.name)&&!this.alreadyHasValue(e.right,s)?{start:e.right.start,end:e.right.end,replacement:`${e.right.name}.value`}:null}transformConditionalExpression(e,s){return e.test?.type==="Identifier"&&this.stateVariables.has(e.test.name)&&!this.alreadyHasValue(e.test,s)?{start:e.test.start,end:e.test.end,replacement:`${e.test.name}.value`}:e.consequent?.type==="Identifier"&&this.stateVariables.has(e.consequent.name)&&!this.alreadyHasValue(e.consequent,s)?{start:e.consequent.start,end:e.consequent.end,replacement:`${e.consequent.name}.value`}:e.alternate?.type==="Identifier"&&this.stateVariables.has(e.alternate.name)&&!this.alreadyHasValue(e.alternate,s)?{start:e.alternate.start,end:e.alternate.end,replacement:`${e.alternate.name}.value`}:null}transformIfStatement(e,s){return this.transformExpressionNode(e.test,s)}transformWhileStatement(e,s){return this.transformExpressionNode(e.test,s)}transformForStatement(e,s){return e.test?this.transformExpressionNode(e.test,s):null}transformReturnStatement(e,s){return e.argument?this.transformExpressionNode(e.argument,s):null}transformVariableDeclarator(e,s){return this.isStateDeclaration(e)||e.id?.type==="ArrayPattern"||e.id?.type==="ObjectPattern"?null:e.init?.type==="Identifier"&&this.stateVariables.has(e.init.name)&&!this.alreadyHasValue(e.init,s)?{start:e.init.start,end:e.init.end,replacement:`${e.init.name}.value`}:null}transformAssignmentExpression(e,s){return e.left?.type==="ArrayPattern"||e.left?.type==="ObjectPattern"?null:e.right?.type==="Identifier"&&this.stateVariables.has(e.right.name)&&!this.alreadyHasValue(e.right,s)?{start:e.right.start,end:e.right.end,replacement:`${e.right.name}.value`}:null}transformGeneralCallExpression(e,s){const i=s.slice(e.callee.start,e.callee.end);if(e.callee?.type==="MemberExpression"&&e.callee.object?.type==="Identifier"&&this.stateVariables.has(e.callee.object.name)||this.isPPCall(e))return null;if(!z.isFunctionNeedingValueTransform(i)&&e.arguments.length>0){for(const r of e.arguments)if(r.type==="Identifier"&&this.stateVariables.has(r.name)&&!this.alreadyHasValue(r,s))return{start:r.start,end:r.end,replacement:`${r.name}.value`}}return null}static isFunctionNeedingValueTransform(e){if(this.FUNCTIONS_NEEDING_VALUE_TRANSFORM.has(e))return!0;const s=e.lastIndexOf(".");if(s>-1){const i=e.slice(s+1);if(this.FUNCTIONS_NEEDING_VALUE_TRANSFORM.has(i))return!0}return!1}transformExpressionNode(e,s){return e?.type==="Identifier"&&this.stateVariables.has(e.name)&&!this.alreadyHasValue(e,s)?{start:e.start,end:e.end,replacement:`${e.name}.value`}:null}isPPCall(e){return e.callee?.type==="MemberExpression"&&e.callee.object?.type==="Identifier"&&e.callee.object.name==="pp"&&e.callee.property?.type==="Identifier"&&(e.callee.property.name==="state"||e.callee.property.name==="effect")}isPartOfStateDeclaration(e,s){if(!s||!Array.isArray(s))return!1;for(const i of s)if(i.type==="VariableDeclarator"&&i.id?.type==="ArrayPattern"&&i.init?.type==="CallExpression"&&this.isPPStateCall(i.init))return!0;return!1}isPropertyName(e,s){if(!s||s.length===0)return!1;const i=s[s.length-1];return!!(i?.type==="Property"&&i.key===e||i?.type==="Property"&&i.shorthand&&i.value===e||i?.type==="MemberExpression"&&i.property===e&&!i.computed)}isMethodCallObject(e,s){if(!s||s.length===0)return!1;const i=s[s.length-1];if(i?.type==="MemberExpression"&&i.object===e&&s.length>=2){const n=s[s.length-2];if(n?.type==="CallExpression"&&n.callee===i)return!0}return!1}isPartOfPPCall(e,s){if(!s||!Array.isArray(s))return!1;for(const i of s)if(i.type==="CallExpression"&&i.callee?.type==="MemberExpression"&&i.callee.object?.type==="Identifier"&&i.callee.object.name==="pp"&&i.callee.property?.type==="Identifier"&&(i.callee.property.name==="state"||i.callee.property.name==="effect"))return!0;return!1}isPartOfDestructuring(e,s){if(!s||!Array.isArray(s))return!1;for(let i=0;i<s.length;i++){const n=s[i];if(n.type==="ArrayPattern"||n.type==="ObjectPattern"){if(i+1<s.length){const r=s[i+1];if(r?.type==="VariableDeclarator"&&r.id===n&&r.init===e)return!1}return!0}}return!1}collectStateVariables(e){U(e,{VariableDeclarator:s=>{if(this.isStateDeclaration(s)){const i=s.id.elements[0];i?.type==="Identifier"&&this.stateVariables.add(i.name)}}})}isStateDeclaration(e){return e.id?.type==="ArrayPattern"&&e.init?.type==="CallExpression"&&this.isPPStateCall(e.init)}transformSpreadElement(e,s){return e.argument?.type==="Identifier"&&this.stateVariables.has(e.argument.name)?this.alreadyHasValue(e.argument,s)?null:{start:e.argument.start,end:e.argument.end,replacement:`${e.argument.name}.value`}:null}transformUnaryExpression(e,s){return e.argument?.type==="Identifier"&&this.stateVariables.has(e.argument.name)&&["typeof","!","+","-","~","void","delete"].includes(e.operator)&&!this.alreadyHasValue(e.argument,s)?{start:e.argument.start,end:e.argument.end,replacement:`${e.argument.name}.value`}:null}transformBinaryExpression(e,s){if(["===","!==","==","!=",">","<",">=","<=","+","-","*","/","%","**","&","|","^","<<",">>",">>>","in","instanceof"].includes(e.operator)){if(e.left?.type==="Identifier"&&this.stateVariables.has(e.left.name)&&!this.alreadyHasValue(e.left,s))return{start:e.left.start,end:e.left.end,replacement:`${e.left.name}.value`};if(e.right?.type==="Identifier"&&this.stateVariables.has(e.right.name)&&!this.alreadyHasValue(e.right,s))return{start:e.right.start,end:e.right.end,replacement:`${e.right.name}.value`}}return null}transformMultipleCallArguments(e){try{const s=W(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0});let i=e;const n=[];return U(s,{CallExpression:r=>{const a=i.slice(r.callee.start,r.callee.end);if(z.isFunctionNeedingValueTransform(a)&&r.arguments.length>0)for(const c of r.arguments)c.type==="Identifier"&&this.stateVariables.has(c.name)&&(this.alreadyHasValue(c,i)||n.push({start:c.start,end:c.end,replacement:`${c.name}.value`}))}}),n.sort((r,a)=>a.start-r.start).forEach(r=>{i=i.slice(0,r.start)+r.replacement+i.slice(r.end)}),i}catch(s){return console.error("Multiple call arguments transformation error:",s),e}}transformDestructuringAssignments(e){try{const s=W(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0});let i=e;const n=[];return U(s,{VariableDeclarator:r=>{this.isStateDeclaration(r)||(r.id?.type==="ArrayPattern"||r.id?.type==="ObjectPattern")&&r.init?.type==="Identifier"&&this.stateVariables.has(r.init.name)&&(this.alreadyHasValue(r.init,e)||n.push({start:r.init.start,end:r.init.end,replacement:`${r.init.name}.value`}))},AssignmentExpression:r=>{(r.left?.type==="ArrayPattern"||r.left?.type==="ObjectPattern")&&r.right?.type==="Identifier"&&this.stateVariables.has(r.right.name)&&(this.alreadyHasValue(r.right,e)||n.push({start:r.right.start,end:r.right.end,replacement:`${r.right.name}.value`}))}}),n.sort((r,a)=>a.start-r.start).forEach(r=>{i=i.slice(0,r.start)+r.replacement+i.slice(r.end)}),i}catch(s){return console.error("Destructuring transformation error:",s),e}}alreadyHasValue(e,s){const i=e.end;return s.slice(i,i+6).startsWith(".value")}transformStateDeclarator(e,s){if(e.id?.type!=="ArrayPattern"||e.init?.type!=="CallExpression")return null;const i=e.init;if(!this.isPPStateCall(i))return null;const n=e.id.elements[0];if(!n||n.type!=="Identifier")return null;const r=n.name,a=`set${this.capitalize(r)}`,o=e.id.elements[1];return o?.type==="Identifier"&&o.name!==a&&console.warn(`Setter name mismatch: expected ${a}, got ${o.name}`),this.createTransformation(i,r,s)}isPPStateCall(e){return e.callee?.type==="MemberExpression"&&e.callee.object?.type==="Identifier"&&e.callee.object.name==="pp"&&e.callee.property?.type==="Identifier"&&e.callee.property.name==="state"}createTransformation(e,s,i){const n=e.arguments;if(n.length===0){const c=`pp.state("${s}")`;return{start:e.start,end:e.end,replacement:c}}const r=n[0];if(r.type==="Literal"&&typeof r.value=="string"&&r.value===s)return null;if(n.length===1){const c=i.slice(r.start,r.end),l=`pp.state("${s}", ${c})`;return{start:e.start,end:e.end,replacement:l}}const a=i.slice(e.arguments[0].start,e.arguments[e.arguments.length-1].end),o=`pp.state("${s}", ${a})`;return{start:e.start,end:e.end,replacement:o}}looksLikeVariableName(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)&&e.length<=50&&!e.includes(" ")}extractStateDeclarations(e){const s=[];try{const i=W(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0,locations:!0});U(i,{VariableDeclarator:n=>{const r=this.extractStateFromDeclarator(n,e);r&&s.push(r)}})}catch(i){console.error("State extraction error:",i)}return s}extractStateFromDeclarator(e,s){if(e.id?.type!=="ArrayPattern"||e.init?.type!=="CallExpression"||!this.isPPStateCall(e.init))return null;const i=e.id.elements[0],n=e.id.elements[1];if(i?.type!=="Identifier"||n?.type!=="Identifier")return null;const r=e.init.arguments;let a=i.name,o;return r.length>=1&&(r[0].type==="Literal"&&typeof r[0].value=="string"?this.looksLikeVariableName(r[0].value)?(a=r[0].value,r.length>=2&&(o=this.extractLiteralValue(r[1]))):(a=i.name,o=this.extractLiteralValue(r[0])):o=this.extractLiteralValue(r[0])),{variableName:i.name,setterName:n.name,stateKey:a,initialValue:o,line:e.loc?.start.line||0,column:e.loc?.start.column||0}}extractFunctionDeclarations(e){const s=[];try{const i=W(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0,locations:!0});U(i,{FunctionDeclaration:n=>{n.id?.type==="Identifier"&&s.push({name:n.id.name,type:"function",params:n.params.map(r=>r.type==="Identifier"?r.name:""),line:n.loc?.start.line||0})},VariableDeclarator:n=>{if(n.id?.type==="Identifier"&&(n.init?.type==="ArrowFunctionExpression"||n.init?.type==="FunctionExpression")){const r=n.init;s.push({name:n.id.name,type:r.type==="ArrowFunctionExpression"?"arrow":"function",params:r.params.map(a=>a.type==="Identifier"?a.name:""),line:n.loc?.start.line||0})}}})}catch(i){console.error("Function extraction error:",i)}return s}extractLiteralValue(e){if(e.type==="Literal")return e.value;e.type==="Identifier"&&e.name}capitalize(e){return e.charAt(0).toUpperCase()+e.slice(1)}}class Ke{constructor(e){this.evaluator=e}render(e,s,i){const n=_.isSingleExpression(e);if(n)return this.evaluator.evaluateExpression(n,s,i);let r="";for(const a of _.parse(e))if(a.type==="static")r+=a.content;else if(a.expression)try{r+=ie(this.evaluator.evaluateExpression(a.expression,s,i))}catch{}return r}dependencies(e,s,i){const n=_.extractExpressions(e),r=new Set;for(const a of n)for(const o of this.evaluator.extractDependencies(a,s,i))r.add(o);return[...r]}}class ws{static containsMustacheExpression(e){if(d.MUSTACHE_PATTERN.test(e))return!0;const i=_.decodeEntities(e);return d.MUSTACHE_PATTERN.test(i)}}class y{static FRAMEWORK_ATTRIBUTES=new Set(["pp-component","pp-context","pp-for","pp-spread","pp-ref","key"]);static domCache;static getDOMCache(){return this.domCache||(this.domCache=L.getInstance()),this.domCache}static isFrameworkAttribute(e){return y.FRAMEWORK_ATTRIBUTES.has(e)}static isEventAttribute(e){return e.startsWith("on")&&e.length>2&&!e.includes("-")}static shouldBeDirectBinding(e,s){const i=e.getAttribute(d.ATTR_PREFIXES.CONTEXT),n=e.getAttribute(d.ATTR_PREFIXES.COMPONENT);return!i||!n||i===n?!1:y.isDOMProperty(e,s)}static isDOMProperty(e,s){const i=e.tagName.toLowerCase(),n=document.createElement(i);return y.attributeToPropertyName(s)in n}static attributeToPropertyName(e){const s={class:"className",for:"htmlFor",readonly:"readOnly",maxlength:"maxLength",minlength:"minLength",tabindex:"tabIndex",contenteditable:"contentEditable",formnovalidate:"formNoValidate",novalidate:"noValidate",allowfullscreen:"allowFullscreen",itemscope:"itemScope"};return s[e]?s[e]:e.replace(/-([a-z])/g,(i,n)=>n.toUpperCase())}static isBooleanAttribute(e){return["checked","disabled","hidden","readonly","required","multiple","selected","autofocus","autoplay","controls","defer","loop","muted","open","reversed","async","default","formnovalidate","novalidate","allowfullscreen","capture","itemscope"].includes(e)}static getContextComponent(e){return this.getDOMCache().getContextComponent(e)}static getParentOfComponent(e,s){return this.getDOMCache().getParentOfComponent(e,s)}static findElementForComponent(e,s){return this.getDOMCache().findElementForComponent(e,s)}static getElementDepth(e){return this.getDOMCache().getElementDepthCached(e)}static getParentComponentForElement(e){let s=e.parentElement;for(;s;){const i=s.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(i)return i;s=s.parentElement}return"app"}static isTextNodeInsideScript(e){let s=e.parentElement;for(;s&&s!==document.body;){const i=s.tagName.toLowerCase();if(i==="script"||i==="style")return!0;s=s.parentElement}return!1}static getComponentForNode(e){let s=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return s?this.getDOMCache().getElementComponent(s):"app"}static getElementComponent(e){return this.getDOMCache().getElementComponent(e)}}class oe{static isEventAttribute(e){return e.startsWith("on")&&e.length>2&&!e.includes("-")}}class Be{static findExistingStateKey(e,s,i){return[`${s}.${e}`,`app.${e}`,e].find(r=>r in i)||null}}class et{pendingUpdates=new Map;batchTimeout=null;componentManager;domBindingManager;setManagers(e,s){this.componentManager=e,this.domBindingManager=s}scheduleUpdate(e,s){this.pendingUpdates.has(e)||this.pendingUpdates.set(e,new Set),this.pendingUpdates.get(e).add(s),this.batchTimeout===null&&(this.batchTimeout=requestAnimationFrame(()=>{this.processBatchedUpdates(),this.batchTimeout=null}))}processBatchedUpdates(){const e=new Map(this.pendingUpdates);this.pendingUpdates.clear(),this.batchTimeout=null;const s=this.sortUpdatesByDependency(e);for(const[i,n]of s)this.processComponentUpdate(i,n)}sortUpdatesByDependency(e){const s=new WeakMap,i=n=>{let r=s.get(n);return r==null&&(r=y.getElementDepth(n),s.set(n,r)),r};return Array.from(e.entries()).sort(([,n],[,r])=>{const a=Math.min(...Array.from(n,i)),o=Math.min(...Array.from(r,i));return a-o})}processComponentUpdate(e,s){if(!this.componentManager||!this.domBindingManager)return;this.componentManager.invalidateComponent(e);const i=[],n=[],r=[];for(const a of s){if(!document.contains(a))continue;const o=document.createTreeWalker(a,NodeFilter.SHOW_TEXT,null);let c;for(;c=o.nextNode();)i.push(c);const l=this.domBindingManager.loopManager;if(l){const h=l.getAllLoops();for(const[p,f]of h)f.component===e&&a.contains(p)&&n.push([p,f])}r.push(a)}this.updateTextNodesBatch(i,e),this.updateLoopsBatch(n),this.updateElementsBatch(r,e)}updateTextNodesBatch(e,s){const i=this.domBindingManager.textNodeManager;i&&e.forEach(n=>{document.contains(n)&&y.getComponentForNode(n)===s&&i.updateTextNode(n)})}updateLoopsBatch(e){const s=this.domBindingManager.loopManager;if(!s)return;const i=new Map;e.forEach(([r,a])=>{const o=y.getElementDepth(r);i.has(o)||i.set(o,[]),i.get(o).push([r,a])});const n=Array.from(i.keys()).sort((r,a)=>r-a);for(const r of n)i.get(r).forEach(([o,c])=>{document.contains(o)&&s.renderLoop(c,c.iterableExpr)})}updateElementsBatch(e,s){e.forEach(i=>{document.contains(i)&&this.domBindingManager.processElementBindings(i,!0)})}}class Ft{loopBindings=new Map;stateManager;expressionEvaluator;componentManager;domBindingManager;cleanupObserver;loopCounter=0;pendingTemplates=[];loopItemElements=new WeakSet;loopItemContexts=new WeakMap;templateRenderer;constructor(e,s){this.stateManager=e,this.expressionEvaluator=s,this.cleanupObserver=new MutationObserver(i=>{this.cleanupDetachedTemplates(i)}),this.cleanupObserver.observe(document.body,{childList:!0,subtree:!0}),this.templateRenderer=new Ke(s)}getLoopContextForElement(e){if(!this.domBindingManager)return null;const s=this.domBindingManager.loopManager;if(!s)return null;let i=e.parentElement;for(;i;){if(s.isLoopItem&&s.isLoopItem(i))return s.getLoopItemContext(i);i=i.parentElement}const n=s.getAllLoops();for(const[r,a]of n)for(const o of a.renderedItems)if(o.element.contains(e))return o.context;return null}setDependencies(e,s){this.componentManager=e,this.domBindingManager=s}queueTemplate(e,s){this.loopBindings.has(e)||this.pendingTemplates.push({template:e,component:s})}processPendingTemplates(){const e=[...this.pendingTemplates];this.pendingTemplates=[];for(const{template:s,component:i}of e)document.contains(s)&&this.processTemplate(s,i)}processTemplate(e,s){const i=e.getAttribute("pp-for");if(!i||this.loopBindings.has(e))return;const n=this.parseLoopExpression(i);if(!n){console.error(`Invalid pp-for syntax: "${i}"`);return}const r=e.parentElement,a=document.createComment(`pp-for: ${i}`);r.insertBefore(a,e);const o={template:e,expression:i,itemVar:n.itemVar,indexVar:n.indexVar,component:s,subscriptionIds:[],renderedItems:[],keyExpression:void 0,parentElement:r,placeholder:a,iterableExpr:n.iterableExpr};this.loopBindings.set(e,o),this.setupLoopReactivity(o,n.iterableExpr),this.renderLoop(o,n.iterableExpr)}parseLoopExpression(e){const s=e.match(/^\s*([a-zA-Z_$][\w$]*)\s+in\s+(.+)$/);if(s)return{itemVar:s[1],iterableExpr:s[2].trim()};const i=e.match(/^\s*\(\s*([a-zA-Z_$][\w$]*)\s*,\s*([a-zA-Z_$][\w$]*)\s*\)\s+in\s+(.+)$/);return i?{itemVar:i[1],indexVar:i[2],iterableExpr:i[3].trim()}:null}setupLoopReactivity(e,s){const i=`loop_${Date.now()}_${++this.loopCounter}`,n=this.expressionEvaluator.extractDependencies(s,e.component,this.stateManager),r=this.findComponentElementForLoop(e);if(r&&this.componentManager){const o=this.componentManager.getComponentPropDependencies(r,e.component);n.push(...o)}const a={id:i,selector:"",dependencies:new Set(n),callback:()=>{this.renderLoop(e,e.iterableExpr)},element:e.parentElement,component:e.component};this.stateManager.addSubscription(a),e.subscriptionIds.push(i)}renderLoop(e,s){if(!(!this.componentManager||!this.domBindingManager))try{const i=this.findComponentElementForLoop(e);let n;const r=this.findParentLoopContext(e.template);r?n={...this.componentManager.buildComponentContextWithProps(e.component,i),...r}:n=this.componentManager.buildComponentContextWithProps(e.component,i);const a=this.expressionEvaluator.evaluateExpression(s,n,e.component);if(!Array.isArray(a)){console.warn(`Loop expression "${s}" did not return an array:`,a,`Available context keys: [${Object.keys(n).join(", ")}]`,"Parent loop context:",r),this.clearRenderedItems(e);return}this.updateRenderedItems(e,a)}catch(i){console.error(`Error evaluating loop expression "${s}":`,i),this.clearRenderedItems(e)}}findParentLoopContext(e){const s=[];let i=e.parentElement;for(;i&&i!==document.body;){if(this.loopItemElements.has(i)){const n=this.loopItemContexts.get(i);n&&s.unshift(n)}for(const[n,r]of this.loopBindings)if(r.template!==e){for(const a of r.renderedItems)if(a.element===i||a.element.contains(e)){s.unshift(a.context);break}}i=i.parentElement}return s.length>0?s.reduce((n,r)=>({...n,...r}),{}):null}findComponentElementForLoop(e){let s=e.parentElement;for(;s;){if(s.getAttribute(d.ATTR_PREFIXES.COMPONENT)===e.component)return s;s=s.parentElement}return document.querySelectorAll(`[${d.ATTR_PREFIXES.COMPONENT}="${e.component}"]`)[0]||void 0}updateRenderedItems(e,s){const i=e.renderedItems,n=[],r=new Set,a=new Map;i.forEach(o=>{a.set(o.key,o)}),s.forEach((o,c)=>{const l=this.generateItemKey(e,o,c),h=a.get(l);if(h&&!r.has(h.element))r.add(h.element),this.updateItemContext(e,h,o,c),n.push(h);else{const p=this.createLoopItem(e,o,c,l);p&&(n.push(p),this.processNestedLoopsInItem(p,e.component))}}),i.forEach(o=>{r.has(o.element)||this.cleanupLoopItem(o)}),this.updateDOMOrder(e,n),e.renderedItems=n}processNestedLoopsInItem(e,s){e.element.querySelectorAll("template[pp-for]").forEach(n=>{const r=n;this.loopBindings.has(r)||this.processNestedTemplate(r,s,e.context)})}generateItemKey(e,s,i){const r=e.template.content.firstElementChild;if(r&&r.hasAttribute("key")){const a=r.getAttribute("key");try{const o=this.createItemContextWithParentContext(e,s,i),c=_.isSingleExpression(a);if(c){const l=this.expressionEvaluator.evaluateExpression(c,o,e.component);return String(l)}else{const l=_.parse(a);let h="";for(const p of l)if(p.type==="static")h+=p.content;else if(p.expression){const f=this.expressionEvaluator.evaluateExpression(p.expression,o,e.component);h+=ie(f)}return h}}catch(o){console.warn(`Error evaluating key expression "${a}":`,o,"Available context keys:",Object.keys(this.createItemContextWithParentContext(e,s,i)))}}return s&&typeof s=="object"&&"id"in s?String(s.id):`${e.expression}_${i}`}createItemContextWithParentContext(e,s,i){if(!this.componentManager)return{};const n=this.componentManager.buildComponentContext(e.component),r=this.getAllParentLoopContexts(e.template),a={...n,...r,[e.itemVar]:s};return e.indexVar&&(a[e.indexVar]=i),a}getAllParentLoopContexts(e){const s=[];let i=e.parentElement;for(;i&&i!==document.body;){if(this.loopItemElements.has(i)){const n=this.loopItemContexts.get(i);n&&s.unshift(n)}for(const[n,r]of this.loopBindings)if(n!==e){for(const a of r.renderedItems)if(a.element===i||a.element.contains(e)){s.unshift(a.context);break}}i=i.parentElement}return s.reduce((n,r)=>({...n,...r}),{})}createItemContext(e,s,i){if(!this.componentManager)return{};const n=this.componentManager.buildComponentContext(e.component),r=this.findAllParentLoopContexts(e.template),a={...n,...r,[e.itemVar]:s};return e.indexVar&&(a[e.indexVar]=i),a}findAllParentLoopContexts(e){const s={};let i=e.parentElement;for(;i&&i!==document.body;){if(this.loopItemElements.has(i)){const n=this.loopItemContexts.get(i);if(n)for(const[r,a]of Object.entries(n))r in s||(s[r]=a)}for(const[n,r]of this.loopBindings)if(n!==e){for(const a of r.renderedItems)if(a.element===i){for(const[o,c]of Object.entries(a.context))o in s||(s[o]=c);break}}i=i.parentElement}return s}createLoopItem(e,s,i,n){if(!this.domBindingManager)return null;try{const r=this.createItemContextWithParentContext(e,s,i),a=document.importNode(e.template.content,!0),o=document.createElement("div");o.appendChild(a);const c=o.firstElementChild;if(!c)return console.warn("Template content must contain exactly one root element"),null;o.removeChild(c),this.loopItemElements.add(c),this.loopItemContexts.set(c,r),c.getAttribute("key")&&c.removeAttribute("key");const h={key:n,element:c,context:r,subscriptionIds:[],textNodeTemplates:new Map,attributeTemplates:new Map};return this.executeComponentScriptsInLoopItem(c),this.processRefsInLoopItem(c,r,e.component),this.processElementWithContext(c,r,e.component,h),this.cleanupRawMustacheAttributes(c),h}catch(r){return console.error("Error creating loop item:",r),null}}processRefsInLoopItem(e,s,i){if(e.hasAttribute("pp-ref")){const o=e.getAttribute("pp-ref");this.processRefAttribute(e,o,s,i)}const n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:o=>o.hasAttribute("pp-ref")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});let r;const a=[];for(;r=n.nextNode();)a.push(r);a.forEach(o=>{const c=o.getAttribute("pp-ref");this.processRefAttribute(o,c,s,i)})}processRefAttribute(e,s,i,n){try{const r=_.decodeEntities(s),a=_.isSingleExpression(r)||r,o=this.expressionEvaluator.evaluateExpression(a,i,n);typeof o=="function"?o(e):o&&typeof o=="object"&&"current"in o?o.current=e:console.warn("⚠️ Invalid ref result:",o),e.removeAttribute("pp-ref")}catch(r){console.error("❌ Failed to process ref:",r)}}executeComponentScriptsInLoopItem(e){if(!this.componentManager)return;const s=[e],i=e.querySelectorAll(`[${d.ATTR_PREFIXES.COMPONENT}]`);s.push(...Array.from(i)),s.forEach(n=>{if(n.hasAttribute(d.ATTR_PREFIXES.COMPONENT)){const r=n.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(r){const a=this.getLoopItemContextForElement(n),o=this.generateInstanceId(a),c=`${r}_${o}`;n.setAttribute(d.ATTR_PREFIXES.COMPONENT,c),n.__originalComponentName=r,n.__uniqueComponentName=c,this.componentManager.pushComponent(c),this.getComponentScripts(n).forEach(h=>{this.componentManager.executeScript(h)}),this.componentManager.popComponent()}}})}getLoopItemContextForElement(e){let s=e;for(;s;){if(this.loopItemElements.has(s)){const i=this.loopItemContexts.get(s);if(i)return i}s=s.parentElement}for(const[i,n]of this.loopBindings)for(const r of n.renderedItems)if(r.element===e||r.element.contains(e))return r.context;return console.warn("⚠️ No loop item context found, using empty context"),{}}generateInstanceId(e){const s={};for(const[a,o]of Object.entries(e))typeof o=="function"||a.startsWith("set")||a.endsWith("Getter")||a==="getContext"||a==="withContext"||a==="__getProp"||(o&&typeof o=="object"&&"id"in o||typeof o!="object"||Array.isArray(o))&&(s[a]=o);return Object.keys(s).length===0?`${Date.now()}_${Math.random().toString(36).substring(2,7)}`:Object.keys(s).sort().map(a=>{const o=s[a];return o&&typeof o=="object"&&"id"in o?`${a}_${o.id}`:typeof o=="string"||typeof o=="number"?`${a}_${o}`:`${a}_${JSON.stringify(o)}`}).join("_").replace(/[^a-zA-Z0-9_]/g,"").substring(0,20)||`fallback_${Date.now()}`}getComponentScripts(e){const s=[];return e.querySelectorAll(`script[type="${d.SCRIPT_TYPE}"]`).forEach(n=>{const r=n;let a=r.parentElement,o=!1;for(;a&&a!==e.parentElement;){if(a===e){o=!0;break}if(a.hasAttribute(d.ATTR_PREFIXES.COMPONENT)&&a!==e)break;a=a.parentElement}o&&s.push(r)}),s}cleanupRawMustacheAttributes(e){this.cleanupElementMustacheAttributes(e);const s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,null);let i;for(;i=s.nextNode();)this.cleanupElementMustacheAttributes(i)}cleanupElementMustacheAttributes(e){const s=Array.from(e.attributes);for(const i of s)i.value&&d.MUSTACHE_PATTERN.test(i.value)&&(y.isBooleanAttribute(i.name),e.removeAttribute(i.name))}processElementWithContext(e,s,i,n){if(!this.domBindingManager||!this.componentManager)return;const r=(o,c)=>{const l=this.componentManager.buildComponentContext(c),h=o.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(h&&h!==c){const f=this.componentManager.buildComponentContext(h);return{...s,...l,...f}}return{...s,...l}},a=this.componentManager.buildComponentContextWithProps.bind(this.componentManager);this.componentManager.buildComponentContextWithProps=(o,c)=>c&&(c===e||e.contains(c))?r(c,o):a(o,c);try{if(e.hasAttribute("pp-ref")){const m=e.getAttribute("pp-ref");this.processRefInLoopContext(e,m,s,i)}const o=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:m=>m===e?NodeFilter.FILTER_SKIP:NodeFilter.FILTER_ACCEPT}),c=[];let l;for(;l=o.nextNode();){const m=l;if(m.hasAttribute("pp-ref")){const x=m.getAttribute("pp-ref");c.push({element:m,expression:x})}}c.forEach(({element:m,expression:x})=>{this.processRefInLoopContext(m,x,s,i)}),this.bindLoopItemElement(e,s,i,n),this.setupEventBindingsForLoopItem(e,i);const h=document.createTreeWalker(e,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,{acceptNode:m=>{if(m===e)return NodeFilter.FILTER_SKIP;if(m.nodeType===Node.TEXT_NODE){const x=m;if(y.isTextNodeInsideScript(x))return NodeFilter.FILTER_REJECT;if(x.textContent&&d.MUSTACHE_PATTERN.test(x.textContent))return NodeFilter.FILTER_ACCEPT}else if(m.nodeType===Node.ELEMENT_NODE)return m.tagName.toLowerCase()==="script"?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT;return NodeFilter.FILTER_SKIP}});let p;for(;p=h.nextNode();)if(p.nodeType===Node.TEXT_NODE){const m=p;if(m.textContent&&d.MUSTACHE_PATTERN.test(m.textContent)){const x=this.getComponentForTextNode(m),C=r(m.parentElement,x);this.processTextNodeWithLoopContext(m,C,x,n)}}else if(p.nodeType===Node.ELEMENT_NODE){const m=p,x=y.getElementComponent(m),C=r(m,x);this.bindLoopItemElement(m,C,x,n),this.setupEventBindingsForLoopItem(m,x)}e.querySelectorAll("template[pp-for]").forEach(m=>{this.processNestedTemplate(m,i,s)})}finally{this.componentManager.buildComponentContextWithProps=a}}processRefInLoopContext(e,s,i,n){try{const r=_.decodeEntities(s),a=_.isSingleExpression(r)||r,o=this.expressionEvaluator.evaluateExpression(a,i,n);typeof o=="function"?o(e):o&&typeof o=="object"&&"current"in o?o.current=e:console.warn("⚠️ Invalid ref result:",o),e.removeAttribute("pp-ref")}catch(r){console.error("❌ processRefInLoopContext error:",r)}}getComponentForTextNode(e){let s=e.parentElement;for(;s;){const i=s.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(i)return i;s=s.parentElement}return"app"}processNestedTemplate(e,s,i){const n=e.getAttribute("pp-for");if(!n||this.loopBindings.has(e))return;const r=this.parseLoopExpression(n);if(!r){console.error(`Invalid pp-for syntax: "${n}"`);return}const a=e.parentElement,o=document.createComment(`pp-for: ${n}`);a.insertBefore(o,e);const c=this.findComponentElementForTemplate(e);let l={...i};const h=this.findParentLoopContextForNestedTemplate(e);if(h&&(l={...l,...h}),c&&this.componentManager){const f=c.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(f){const m=y.getParentComponentForElement(c);this.componentManager.hasStoredProps(c)||this.componentManager.setupProps(c,m);const x=this.evaluateComponentPropsWithContext(c,l);l={...this.componentManager.buildComponentContext(f),...x,...l}}}const p={template:e,expression:n,itemVar:r.itemVar,indexVar:r.indexVar,iterableExpr:r.iterableExpr,component:s,subscriptionIds:[],renderedItems:[],keyExpression:void 0,parentElement:a,placeholder:o};this.loopBindings.set(e,p),this.setupNestedLoopReactivity(p,r.iterableExpr,l),this.renderNestedLoop(p,r.iterableExpr,l)}findParentLoopContextForNestedTemplate(e){let s=e.parentElement;const i={};let n=0;for(;s&&s!==document.body&&n<10;){if(n++,this.loopItemElements.has(s)){const r=this.loopItemContexts.get(s);if(r)for(const[a,o]of Object.entries(r))a in i||(i[a]=o)}for(const[r,a]of this.loopBindings)for(const o of a.renderedItems)(o.element.contains(e)||o.element===s)&&(a.itemVar in i||(i[a.itemVar]=o.context[a.itemVar]),a.indexVar&&!(a.indexVar in i)&&(i[a.indexVar]=o.context[a.indexVar]));s=s.parentElement}return Object.keys(i).length>0?i:null}evaluateComponentPropsWithContext(e,s){const i={};if(!this.componentManager||!this.expressionEvaluator)return i;const n=this.componentManager.extractProps(e,"app");for(const[r,a]of n)try{const o=this.templateRenderer.render(a.expression,s,a.component);i[r]=o}catch(o){console.error(`Failed to evaluate prop "${r}":`,o),i[r]=void 0}return i}findComponentElementForTemplate(e){let s=e.parentElement;for(;s;){if(s.hasAttribute(d.ATTR_PREFIXES.COMPONENT))return s;s=s.parentElement}return null}setupNestedLoopReactivity(e,s,i){const n=`nested_loop_${Date.now()}_${++this.loopCounter}`;let r=this.expressionEvaluator.extractDependencies(s,e.component,this.stateManager);const a={id:n,selector:"",dependencies:new Set(r),callback:()=>{const o=e.template,c=this.findComponentElementForTemplate(o);let l=i;if(o.parentElement){const p=this.getParentLoopContextForElement(o);p&&(l={...l,...p})}if(c&&this.componentManager){const p=c.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(p){const f=this.extractParentLoopContextFromBinding(e,i),m=this.evaluateComponentPropsWithContext(c,f),x=this.componentManager.buildComponentContext(p);l={...f,...x,...m}}}this.renderNestedLoop(e,s,l)},element:e.parentElement,component:e.component};this.stateManager.addSubscription(a),e.subscriptionIds.push(n)}getParentLoopContextForElement(e){let s=e.parentElement;for(;s;){if(this.loopItemElements.has(s)){const i=this.loopItemContexts.get(s);if(i)return i}s=s.parentElement}return null}extractParentLoopContextFromBinding(e,s){const i=new Set;for(const[r,a]of this.loopBindings)if(a!==e){for(const o of a.renderedItems)if(o.element.contains(e.template)){i.add(a.itemVar),a.indexVar&&i.add(a.indexVar);break}}const n={};for(const[r,a]of Object.entries(s))(i.has(r)||r.startsWith("users")||r.startsWith("set")||r.includes("Getter")||typeof a=="function")&&(n[r]=a);return n}renderNestedLoop(e,s,i){if(!(!this.componentManager||!this.domBindingManager))try{const n=this.expressionEvaluator.evaluateExpression(s,i,e.component);if(!Array.isArray(n)){console.warn(`Nested loop expression "${s}" did not return an array:`,n,`Available context keys: [${Object.keys(i).join(", ")}]`),this.clearRenderedItems(e);return}this.updateNestedRenderedItems(e,n,i)}catch(n){console.error(`Error evaluating nested loop expression "${s}":`,n,`Available context keys: [${Object.keys(i).join(", ")}]`),this.clearRenderedItems(e)}}updateNestedRenderedItems(e,s,i){const n=e.renderedItems,r=[],a=new Set,o=new Map;n.forEach(c=>{o.set(c.key,c)}),s.forEach((c,l)=>{const h=this.generateNestedItemKey(e,c,l,i),p=o.get(h);if(p&&!a.has(p.element))a.add(p.element),this.updateNestedItemContext(e,p,c,l,i),r.push(p);else{const f=this.createNestedLoopItem(e,c,l,h,i);f&&r.push(f)}}),n.forEach(c=>{a.has(c.element)||this.cleanupLoopItem(c)}),this.updateDOMOrder(e,r),e.renderedItems=r}generateNestedItemKey(e,s,i,n){return s&&typeof s=="object"&&"id"in s?String(s.id):`${e.expression}_${i}_${JSON.stringify(n[e.itemVar]||{})}`}createNestedLoopItem(e,s,i,n,r){if(!this.domBindingManager)return null;try{const a={...r,[e.itemVar]:s};e.indexVar&&(a[e.indexVar]=i);const o=document.importNode(e.template.content,!0),c=document.createElement("div");c.appendChild(o);const l=c.firstElementChild;if(!l)return console.warn("Template content must contain exactly one root element"),null;c.removeChild(l),this.loopItemElements.add(l),this.loopItemContexts.set(l,a),l.getAttribute("key")&&l.removeAttribute("key");const p={key:n,element:l,context:a,subscriptionIds:[],textNodeTemplates:new Map,attributeTemplates:new Map};return this.processElementWithContext(l,a,e.component,p),this.cleanupRawMustacheAttributes(l),p}catch(a){return console.error("Error creating nested loop item:",a),null}}updateNestedItemContext(e,s,i,n,r){const a={...r};a[e.itemVar]=i,e.indexVar&&(a[e.indexVar]=n);const o=this.gatherAllComponentContextsInLoopItem(s.element),c={...a,...o};if(s.context=c,this.loopItemContexts.set(s.element,c),s.textNodeTemplates)for(const[l,h]of s.textNodeTemplates)document.contains(l)&&this.updateTextNodeWithContext(l,h,c,this.getTextNodeComponent(l));if(s.attributeTemplates)for(const[l,h]of s.attributeTemplates)document.contains(l)&&h.forEach((p,f)=>{try{const m=y.getElementComponent(l),x=this.buildElementSpecificContext(l,c),C=this.templateRenderer.render(p,x,m);this.domBindingManager?.updateElementProperty(l,f,C)}catch(m){console.error(`Nested binding update error for "${p}":`,m)}})}bindLoopItemElement(e,s,i,n){const r=this.extractMustacheBindings(e);n&&r.size>0&&(n.attributeTemplates||(n.attributeTemplates=new Map),n.attributeTemplates.set(e,new Map(r))),r.forEach((a,o)=>{this.createLoopItemBinding(e,o,a,s,i,n)})}setupEventBindingsForLoopItem(e,s){const i=this.domBindingManager.eventDelegation;if(!i){console.warn("No event delegation manager available");return}const n=Array.from(e.attributes);for(const r of n)if(oe.isEventAttribute(r.name)){const a=r.name.substring(2);i.registerEventHandler(e,a,r.value,s),e.removeAttribute(r.name)}}processTextNodeWithLoopContext(e,s,i,n){if(y.isTextNodeInsideScript(e))return;const r=e.textContent||"";if(!_.parse(r).some(x=>x.type==="expression"))return;n&&(n.textNodeTemplates||(n.textNodeTemplates=new Map),n.textNodeTemplates.set(e,r));const c=this.findActualComponentForTextNode(e);this.updateTextNodeWithContext(e,r,s,c);const l=`loop_text_${Date.now()}_${Math.random()}`,h=this.templateRenderer.dependencies(r,c,this.stateManager),p=new Set(h),m={id:l,selector:"",dependencies:p,callback:()=>{if(!document.contains(e)){this.stateManager.removeSubscription(l);return}let x={};if(this.componentManager&&(x=this.componentManager.buildComponentContext(c)),n){const C={};let S=null;for(const[P,M]of this.loopBindings)if(M.renderedItems.includes(n)){S=M;break}if(S){C[S.itemVar]=n.context[S.itemVar],S.indexVar&&(C[S.indexVar]=n.context[S.indexVar]);const P=this.findParentLoopContext(S.template);P&&Object.assign(C,P)}x={...x,...C}}this.updateTextNodeWithContext(e,r,x,c)},component:c};this.stateManager.addSubscription(m),n&&n.subscriptionIds.push(l)}findActualComponentForTextNode(e){let s=e.parentElement;for(;s;){const i=s.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(i){const n=s.__uniqueComponentName;return n||i}s=s.parentElement}return"app"}updateTextNodeWithContext(e,s,i,n){const r=_.parse(s);let a="";for(const o of r)if(o.type==="static")a+=o.content;else if(o.expression)try{const c=this.expressionEvaluator.evaluateExpression(o.expression,i,n);a+=ie(c)}catch(c){console.warn(`Loop text evaluation error for "${o.expression}":`,c,"Available context keys:",Object.keys(i)),a+=""}e.textContent!==a&&(e.textContent=a)}extractMustacheBindings(e){const s=new Map,i=e.attributes;for(let n=0;n<i.length;n++){const r=i[n];if(!(r.name===d.ATTR_PREFIXES.COMPONENT||r.name==="key"||r.name.startsWith("on"))&&r.value){const a=d.MUSTACHE_PATTERN.test(r.value),o=_.decodeEntities(r.value),c=d.MUSTACHE_PATTERN.test(o);(a||c)&&s.set(r.name,o)}}return s}createLoopItemBinding(e,s,i,n,r,a){const o=`loop_item_${Date.now()}_${Math.random()}`,c=this.templateRenderer.dependencies(i,r,this.stateManager),l=new Set(c);let h=!1,p=0;const f=5,m=()=>{if(h)return;if(!document.contains(e)){if(p++,p<f){const P=10*Math.pow(2,p-1);setTimeout(()=>{h||m()},P)}else h=!0,this.stateManager.removeSubscription(o);return}p=0;try{const P=this.componentManager.buildComponentContext(r);let M;if(a){M={...P};let te=null;for(const[Ne,be]of this.loopBindings)if(be.renderedItems.includes(a)){te=be;break}te&&(M[te.itemVar]=a.context[te.itemVar],te.indexVar&&(M[te.indexVar]=a.context[te.indexVar]));for(const[Ne,be]of Object.entries(a.context))Ne in M||(M[Ne]=be)}else M=n;const fe=this.templateRenderer.render(i,M,r);this.domBindingManager?.updateElementProperty(e,s,fe)}catch(P){console.error(`Loop item binding evaluation error for "${i}":`,P),console.error("Available context keys:",Object.keys(n))}},x={id:o,selector:"",dependencies:l,callback:()=>{h||m()},element:e,component:r};if(this.stateManager.addSubscription(x),a){a.subscriptionIds.push(o);const S=this.cleanupLoopItem.bind(this);this.cleanupLoopItem=P=>{P===a&&(h=!0),S(P)}}(()=>{document.contains(e)?m():Promise.resolve().then(()=>{if(!h&&document.contains(e))m();else if(!h&&p<f){p++;const S=10*Math.pow(2,p-1);setTimeout(()=>{h||m()},S)}else!h&&p>=f&&(h=!0,this.stateManager.removeSubscription(o))})})()}updateItemContext(e,s,i,n){const r=this.createItemContext(e,i,n),a=this.gatherAllComponentContextsInLoopItem(s.element),o={...r,...a};if(s.context=o,this.loopItemContexts.set(s.element,o),s.textNodeTemplates)for(const[c,l]of s.textNodeTemplates)document.contains(c)&&this.updateTextNodeWithContext(c,l,o,this.getTextNodeComponent(c));if(s.attributeTemplates)for(const[c,l]of s.attributeTemplates)document.contains(c)&&l.forEach((h,p)=>{try{const f=y.getElementComponent(c),m=this.buildElementSpecificContext(c,o),x=this.templateRenderer.render(h,m,f);this.domBindingManager?.updateElementProperty(c,p,x)}catch(f){console.error(`Attribute binding update error for "${h}":`,f)}})}gatherAllComponentContextsInLoopItem(e){if(!this.componentManager)return{};const s={};if(e.hasAttribute(d.ATTR_PREFIXES.COMPONENT)){const n=e.getAttribute(d.ATTR_PREFIXES.COMPONENT),r=this.componentManager.buildComponentContext(n);Object.assign(s,r)}return e.querySelectorAll(`[${d.ATTR_PREFIXES.COMPONENT}]`).forEach(n=>{const r=n.getAttribute(d.ATTR_PREFIXES.COMPONENT),a=this.componentManager?.buildComponentContext(r);Object.assign(s,a)}),s}buildElementSpecificContext(e,s){if(!this.componentManager)return s;const i=y.getElementComponent(e),n=this.componentManager.buildComponentContext(i);return{...s,...n}}getTextNodeComponent(e){let s=e.parentElement;for(;s;){const i=s.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(i)return i;s=s.parentElement}return"app"}updateDOMOrder(e,s){let i=e.placeholder;s.forEach(n=>{(n.element.parentElement!==e.parentElement||n.element!==i.nextSibling)&&e.parentElement.insertBefore(n.element,i.nextSibling),i=n.element})}clearRenderedItems(e){e.renderedItems.forEach(s=>{this.cleanupLoopItem(s)}),e.renderedItems=[]}cleanupLoopItem(e){this.loopItemElements.delete(e.element),this.loopItemContexts.delete(e.element),e.element.parentElement&&e.element.parentElement.removeChild(e.element),e.subscriptionIds.forEach(s=>{this.stateManager.removeSubscription(s)})}isLoopItem(e){return this.loopItemElements.has(e)}getLoopItemContext(e){return this.loopItemContexts.get(e)}cleanupDetachedTemplates(e){for(const s of e)s.type==="childList"&&s.removedNodes.forEach(i=>{if(i.nodeType===Node.ELEMENT_NODE){const n=i;n.tagName==="TEMPLATE"&&n.hasAttribute("pp-for")&&this.cleanupTemplate(n),n.querySelectorAll("template[pp-for]").forEach(a=>{this.cleanupTemplate(a)})}})}cleanupTemplate(e){const s=this.loopBindings.get(e);s&&(this.clearRenderedItems(s),s.subscriptionIds.forEach(i=>{this.stateManager.removeSubscription(i)}),s.placeholder.parentElement&&s.placeholder.parentElement.removeChild(s.placeholder),this.loopBindings.delete(e))}getAllLoops(){return new Map(this.loopBindings)}destroy(){this.cleanupObserver.disconnect(),Array.from(this.loopBindings.keys()).forEach(e=>{this.cleanupTemplate(e)}),this.loopItemContexts=new WeakMap}}class ${cache=new Map;maxSize;hits=0;misses=0;constructor(e){this.maxSize=e}keys(){return Array.from(this.cache.keys())}deleteByPrefix(e){let s=0;const i=[];return this.cache.forEach((n,r)=>{typeof r=="string"&&r.startsWith(e)&&i.push(r)}),i.forEach(n=>{this.cache.delete(n)&&s++}),s}getKeysByPrefix(e){const s=[];return this.cache.forEach((i,n)=>{typeof n=="string"&&n.startsWith(e)&&s.push(n)}),s}get(e){const s=this.cache.get(e);if(s!==void 0)return this.hits++,this.cache.delete(e),this.cache.set(e,s),s;this.misses++}set(e,s){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){const i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i)}this.cache.set(e,s)}size(){return this.cache.size}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear(),this.hits=0,this.misses=0}getStats(){const e=this.hits+this.misses;return{size:this.cache.size,maxSize:this.maxSize,hitRate:e>0?this.hits/e*100:0,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}}class _{static EXPRESSION_CACHE=new $(1e3);static parseSpreadDirective(e){const s=e.replace(/^\s*\{\s*|\s*\}\s*$/g,""),i=this.parseSpreadParts(s),n=[],r=[];for(const a of i){const o=a.trim();if(o.startsWith("..."))n.push(o.substring(3).trim());else if(o.startsWith("{")&&o.endsWith("}")){const c=o.slice(1,-1).trim();if(c){const l=this.parseObjectProperties(c);r.push(l)}}else console.warn(`Invalid spread directive part: "${o}". Expected ...spread or {object}`)}return{spreads:n,objects:r}}static parseSpreadParts(e){const s=[];let i="",n=0,r=!1,a="",o=0;for(;o<e.length;){const c=e[o],l=o>0?e[o-1]:"";if(!r&&(c==='"'||c==="'")?(r=!0,a=c):r&&c===a&&l!=="\\"&&(r=!1,a=""),!r){if(c==="{")n++;else if(c==="}")n--;else if(c===","&&n===0){s.push(i.trim()),i="",o++;continue}}i+=c,o++}return i.trim()&&s.push(i.trim()),s}static parseObjectProperties(e){const s=[],i=this.parseObjectParts(e);for(const n of i){const r=n.trim(),a=this.findPropertySeparator(r);if(a!==-1){const o=r.substring(0,a).trim().replace(/['"]/g,""),c=r.substring(a+1).trim();s.push({key:o,value:c})}else console.warn(`Invalid object property: "${r}". Expected key: value format.`)}return s}static parseObjectParts(e){const s=[];let i="",n=0,r=!1,a="";for(let o=0;o<e.length;o++){const c=e[o],l=o>0?e[o-1]:"";if(!r&&(c==='"'||c==="'")?(r=!0,a=c):r&&c===a&&l!=="\\"&&(r=!1,a=""),!r){if(c==="{"||c==="["||c==="(")n++;else if(c==="}"||c==="]"||c===")")n--;else if(c===","&&n===0){s.push(i.trim()),i="";continue}}i+=c}return i.trim()&&s.push(i.trim()),s}static findPropertySeparator(e){let s=0,i=!1,n="";for(let r=0;r<e.length;r++){const a=e[r],o=r>0?e[r-1]:"";if(!i&&(a==='"'||a==="'")?(i=!0,n=a):i&&a===n&&o!=="\\"&&(i=!1,n=""),!i){if(a==="{"||a==="["||a==="(")s++;else if(a==="}"||a==="]"||a===")")s--;else if(a===":"&&s===0)return r}}return-1}static decodeEntities=e=>{const s=document.createElement("textarea");s.innerHTML=e;let i=s.value;for(;i.includes("&");){s.innerHTML=i;const n=s.value;if(n===i)break;i=n}return i};static parse(e){const s=_.decodeEntities(e);if(_.EXPRESSION_CACHE.has(s))return _.EXPRESSION_CACHE.get(s);const i=_.parseContentWithNesting(s);return _.EXPRESSION_CACHE.set(s,i),i}static parseContentWithNesting(e){const s=[],i=e.length;let n=0,r=0;for(;n<i;)if(e[n]==="{"){n>r&&s.push({type:"static",content:e.substring(r,n),expression:null});const o=this.extractNestedExpression(e,n);o.endIndex!==-1?(s.push({type:"expression",content:e.substring(n,o.endIndex+1),expression:o.expression.trim()}),n=o.endIndex+1,r=n):n++}else n++;return r<i&&s.push({type:"static",content:e.substring(r),expression:null}),s}static extractNestedExpression(e,s){let i=1,n=s+1,r=!1,a="",o=!1;for(;n<e.length&&i>0;){const c=e[n],l=n>0?e[n-1]:"";!r&&(c==='"'||c==="'")?(r=!0,a=c):r&&c===a&&l!=="\\"&&(r=!1,a=""),!r&&c==="`"&&l!=="\\"&&(o=!o),!r&&!o&&(c==="{"?i++:c==="}"&&i--),n++}if(i===0){const c=e.slice(s+1,n-1);return{endIndex:n-1,expression:c}}return{endIndex:-1,expression:""}}static isSingleExpression(e){const s=_.decodeEntities(e),i=_.parseContentWithNesting(s);return i.length===1&&i[0].type==="expression"?i[0].expression:null}static extractExpressions(e){const s=_.decodeEntities(e);return _.parseContentWithNesting(s).filter(n=>n.type==="expression").map(n=>n.expression).filter(n=>n)}}class Ps{textNodeBindings=new Map;expressionEvaluator;stateManager;componentManager;cleanupObserver;bindingCount=0;constructor(e,s){this.expressionEvaluator=e,this.stateManager=s,this.cleanupObserver=new MutationObserver(i=>{this.cleanupDetachedNodes(i)}),this.cleanupObserver.observe(document.body,{childList:!0,subtree:!0})}cleanupDetachedNodes(e){for(const i of e)i.type==="childList"&&i.removedNodes.forEach(n=>{if(n.nodeType===Node.TEXT_NODE)this.cleanupTextNode(n);else if(n.nodeType===Node.ELEMENT_NODE){const r=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null);let a;for(;a=r.nextNode();)this.cleanupTextNode(a)}});const s=[];for(const[i]of this.textNodeBindings)document.contains(i)||s.push(i);s.forEach(i=>this.cleanupTextNode(i))}processTextNode(e,s){if(this.textNodeBindings.has(e)||y.isTextNodeInsideScript(e)||this.isInsideLoopItem(e))return;const i=e.parentElement,n=i?y.getContextComponent(i):s,r=e.textContent||"",a=_.parse(r);if(!a.some(l=>l.type==="expression"))return;const c={originalContent:r,expressions:a,subscriptionIds:[]};a.filter(l=>l.type==="expression").forEach(l=>{if(!l.expression)return;const h=`text_${Date.now()}_${Math.random()}`,p=this.expressionEvaluator.extractDependencies(l.expression,n,this.stateManager),f={id:h,selector:"",dependencies:new Set(p),callback:()=>{this.updateTextNode(e)},element:e.parentElement??void 0,component:n};this.stateManager.addSubscription(f),c.subscriptionIds.push(h)}),this.textNodeBindings.set(e,c),this.bindingCount++,this.updateTextNode(e)}isInsideLoopItem(e){let s=e.parentElement;for(;s&&s!==document.body;){const i=s.previousSibling;if(i&&i.nodeType===Node.COMMENT_NODE&&i.textContent?.startsWith("pp-for:"))return!0;let n=s.parentElement?.firstChild||null;for(;n;){if(n.nodeType===Node.COMMENT_NODE&&n.textContent?.startsWith("pp-for:")&&n!==s)return!0;n=n.nextSibling}s=s.parentElement}return!1}updateTextNode(e){const s=this.textNodeBindings.get(e);if(!s||!e.parentElement)return;const i=e.parentElement,n=y.getContextComponent(i),r=this.resolveComponentRootForElement(e,n),a=this.getContextForComponent(n,r);let o="";for(const c of s.expressions)if(c.type==="static")o+=c.content;else if(c.expression)try{const l=this.expressionEvaluator.evaluateExpression(c.expression,a,n);o+=ie(l)}catch(l){const h=typeof l=="object"&&l!==null&&"message"in l?l.message:String(l);console.warn(`Text binding evaluation warning for "${c.expression}": ${h}`),o+=""}e.textContent!==o&&(e.textContent=o)}resolveComponentRootForElement(e,s){let i=e.parentElement;for(;i&&i.nodeType===Node.ELEMENT_NODE;){const n=i;if(n.getAttribute(d.ATTR_PREFIXES.COMPONENT)===s)return n;i=i.parentElement}}getContextForComponent(e,s){return this.componentManager?this.componentManager.buildComponentContextWithProps(e,s):{}}cleanupTextNode(e){const s=this.textNodeBindings.get(e);s&&(s.subscriptionIds.forEach(i=>{this.stateManager.removeSubscription(i)}),this.textNodeBindings.delete(e),this.bindingCount=Math.max(0,this.bindingCount-1))}getBindingCount(){return this.textNodeBindings.size}getAllBindings(){return new Map(this.textNodeBindings)}clearAllBindings(){for(const[e]of this.textNodeBindings)this.cleanupTextNode(e)}destroy(){this.cleanupObserver.disconnect(),this.clearAllBindings()}}class _s{listeners=new Map;on(e,s){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(s),()=>this.off(e,s)}off(e,s){this.listeners.get(e)?.delete(s)}emit(e,...s){const i=this.listeners.get(e);i&&i.forEach(n=>{try{n(...s)}catch(r){console.error(`Event listener error for ${e}:`,r)}})}}class ks{stateStore={};subscriptions=new Map;updateQueue=new Set;isUpdating=!1;eventBus=new _s;contextCache=new Map;previousValues=new Map;_subscriptionManager=new Ts;originalStateStore={};domUpdateCallbacks=[];domUpdateScheduled=!1;constructor(){this.setupGlobalStateProxy(),setInterval(()=>{this.subscriptionManager.cleanupStaleSubscriptions()},3e4)}onDOMUpdateComplete(e){this.domUpdateCallbacks.push(e),this.domUpdateScheduled||(this.domUpdateScheduled=!0,requestAnimationFrame(()=>{requestAnimationFrame(()=>{const s=[...this.domUpdateCallbacks];this.domUpdateCallbacks=[],this.domUpdateScheduled=!1,s.forEach(i=>{try{i()}catch(n){console.error("DOM update callback error:",n)}})})}))}setInitialState(e,s){if(this.previousValues.set(e,void 0),this.originalStateStore[e]=s,this.previousValues.size>100){const i=this.previousValues.keys().next().value;typeof i=="string"&&this.previousValues.delete(i)}}get subscriptionManager(){return this._subscriptionManager}batchStateUpdates(e){const s=this.isUpdating;this.isUpdating=!0;try{return e()}finally{this.isUpdating=s,!this.isUpdating&&this.updateQueue.size>0&&this.scheduleFlush()}}invalidateContextCache(){this.contextCache.clear()}setupGlobalStateProxy(){this.originalStateStore=this.stateStore,this.stateStore=new Proxy(this.stateStore,{set:(e,s,i,n)=>{const r=e[s],a=Reflect.set(e,s,i,n);return r!==i&&this.notifySubscribers(s),a},get:(e,s)=>Reflect.get(e,s)})}notifySubscribers(e){if(this.eventBus.emit("stateChanged",e),this.updateQueue.add(e),e.includes(".")){const s=e.split(".")[0];this.updateQueue.add(s)}this.notifyPathBasedSubscribers(e),this.isUpdating||this.scheduleFlush()}notifyPathBasedSubscribers(e){const s=this.stateStore[e],i=this.previousValues?.get(e);for(const[n,r]of this.subscriptions)for(const a of r.dependencies)if(this.isPathDependency(a)&&a.startsWith(e+".")){const o=a.substring(e.length+1),c=this.getPathValue(i,o),l=this.getPathValue(s,o);this.deepEqual(c,l)||this.updateQueue.add(a)}}isPathDependency(e){return e.includes(".")&&e.split(".").length>1}getPathValue(e,s){if(!e||typeof e!="object")return;const i=s.split(".");let n=e;for(const r of i){if(n==null)return;if(Array.isArray(n))return r==="length"?n.length:n.map(a=>a?.[r]).filter(a=>a!==void 0);n=n[r]}return n}deepEqual(e,s){if(e===s)return!0;if(e==null||s==null)return!1;if(Array.isArray(e)&&Array.isArray(s))return e.length!==s.length?!1:e.every((i,n)=>this.deepEqual(i,s[n]));if(typeof e=="object"&&typeof s=="object"){const i=Object.keys(e),n=Object.keys(s);return i.length!==n.length?!1:i.every(r=>this.deepEqual(e[r],s[r]))}return!1}scheduleFlush=As(()=>{this.flushUpdates()},d.DEBOUNCE_MS);flushUpdates(){if(!this.isUpdating){this.isUpdating=!0;try{const e=new Set,s=this.subscriptionManager.getSubscriptionsForKey("*");if(s&&s.size>0&&this.updateQueue.size>0)for(const i of s){const n=this.subscriptionManager.getSubscription(i);if(!n)continue;if(n.element&&!document.contains(n.element)){this.subscriptionManager.removeSubscription(i);continue}const r=n.element??document.body;try{const a=Array.from(this.updateQueue)[0];n.callback(r,{key:a})}catch(a){console.error("Wildcard subscription callback failed:",a)}}for(const i of this.updateQueue){if(e.has(i))continue;e.add(i);const n=this.subscriptionManager.getSubscriptionsForKey(i);if(n)for(const r of n){const a=this.subscriptionManager.getSubscription(r);if(!a)continue;if(a.element&&!document.contains(a.element)){this.subscriptionManager.removeSubscription(r);continue}const o=a.element??document.body;try{a.callback(o,{key:i})}catch(c){console.error("Subscription callback failed:",c)}}}}finally{this.updateQueue.clear(),this.isUpdating=!1}}}getState(){return this.stateStore}setState(e,s){if(this.previousValues.set(e,this.stateStore[e]),this.stateStore[e]=s,this.previousValues.size>100){const i=this.previousValues.keys().next().value;typeof i=="string"&&this.previousValues.delete(i)}}hasState(e){return e in this.originalStateStore}addSubscription(e){this._subscriptionManager.addSubscription(e)}removeSubscription(e){this._subscriptionManager.removeSubscription(e)}onStateChange(e){return this.eventBus.on("stateChanged",e)}batch(e){const s=this.isUpdating;this.isUpdating=!0;try{return e()}finally{this.isUpdating=s,!this.isUpdating&&this.updateQueue.size&&this.flushUpdates()}}getSubscriptions(){return this.subscriptionManager.getAllSubscriptions()}getKeyIndex(){const e=new Map,s=this.subscriptionManager.getAllSubscriptions();for(const[i,n]of s)for(const r of n.dependencies)e.has(r)||e.set(r,new Set),e.get(r).add(i);return e}}class ce{expressionCache=new $(d.MAX_CACHE_SIZE);dependencyCache=new $(d.MAX_CACHE_SIZE);commonExpressionsCache=new $(100);dependencyParser=new Is;static CACHE_KEYS={EXPRESSION:(e,s)=>`expr:${e}:${s}`,DEPENDENCY:(e,s)=>`deps:${e}:${s}`,COMMON:e=>`common:${e}`};constructor(){this.precompileCommonExpressions()}normalizeExpression(e){return e.replace(/\r\n/g," ").replace(/\r/g," ").replace(/\n/g," ").replace(/\s+/g," ").trim()}precompileCommonExpressions(){["true","false","null","undefined"].forEach(s=>{const i={fn:new Function("return "+s),contextMap:new Map,dependencies:[s],timestamp:Date.now(),hitCount:0},n=ce.CACHE_KEYS.COMMON(s);this.commonExpressionsCache.set(n,i)})}extractDependencies(e,s,i){const n=this.normalizeExpression(e),r=ce.CACHE_KEYS.DEPENDENCY(s,n);let a=this.dependencyCache.get(r);return a||(a=this.dependencyParser.extract(n,s,i),this.dependencyCache.set(r,a),a)}evaluateExpression(e,s,i){const n=this.normalizeExpression(e),r=ce.CACHE_KEYS.COMMON(n);let a=this.commonExpressionsCache.get(r);if(a){a.hitCount++;try{return a.fn()}catch(c){console.error(`Common expression evaluation failed: "${n}"`,c);return}}const o=ce.CACHE_KEYS.EXPRESSION(i,n);a=this.expressionCache.get(o),(!a||this.isStale(a))&&(a=this.compileExpression(n,s,i),this.expressionCache.set(o,a)),a.hitCount++;try{const c=this.buildArguments(a.contextMap,s);return a.fn(...c)}catch(c){console.error(`Expression evaluation failed: "${n}"`,c),console.error("Available context:",Object.keys(s));return}}compileExpression(e,s,i){const n=this.prepareSafeContext(s),r=new Map,a=[];Object.keys(n).forEach((c,l)=>{r.set(c,l),a.push(c)});const o=this.dependencyParser.extract(e,i);return{fn:new Function(...a,`return (${e})`),contextMap:r,dependencies:o,timestamp:Date.now(),hitCount:0}}buildArguments(e,s){const i=new Array(e.size);for(const[n,r]of e)i[r]=s[n];return i}isStale(e){return Date.now()-e.timestamp>3e5}prepareSafeContext(e){const s={};for(const[i,n]of Object.entries(e))Ae.has(i)||!this.isValidJavaScriptIdentifier(i)||(s[i]=n);return s}isValidJavaScriptIdentifier(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)&&!Ae.has(e)}invalidateCache(e){switch(e){case"expressions":this.expressionCache.clear();break;case"dependencies":this.dependencyCache.clear();break;case"common":this.commonExpressionsCache.clear(),this.precompileCommonExpressions();break;case"parser":this.dependencyParser.clearCache();break;default:this.clearAllCaches()}}invalidateByComponent(e){this.expressionCache.deleteByPrefix(`expr:${e}:`),this.dependencyCache.deleteByPrefix(`deps:${e}:`)}clearAllCaches(){this.expressionCache.clear(),this.dependencyCache.clear(),this.commonExpressionsCache.clear(),this.dependencyParser.clearCache(),this.precompileCommonExpressions()}getCacheStats(){return{expressions:this.expressionCache.getStats(),dependencies:this.dependencyCache.getStats(),commonExpressions:this.commonExpressionsCache.getStats(),dependencyParser:this.getDependencyParserStats()}}getDependencyParserStats(){return this.dependencyParser.getCacheSize?{size:this.dependencyParser.getCacheSize(),maxSize:500,hitRate:0,hits:0,misses:0}:{size:0,maxSize:0,hitRate:0,hits:0,misses:0}}cleanupStaleExpressions(){let e=0;return this.expressionCache.keys().forEach(i=>{const n=this.expressionCache.get(i);n&&this.isStale(n)&&(this.expressionCache.delete(i),e++)}),e}}class Is{parseCache=new $(500);extract(e,s,i){const n=this.normalizeExpression(e),r=`${s}:${n}`;if(this.parseCache.has(r))return this.parseCache.get(r);const a=this.parseExpression(n,s,i);return this.parseCache.set(r,a),a}normalizeExpression(e){return e.replace(/\r\n/g," ").replace(/\r/g," ").replace(/\n/g," ").replace(/\s+/g," ").trim()}parseExpression(e,s,i){const n=this.extractIdentifiers(e),r=[],a=i?.getState()||{};for(const c of n){if(Ae.has(c))continue;const l=c.indexOf("."),h=l===-1?c:c.substring(0,l),p=Be.findExistingStateKey(h,s,a);if(p)r.push(p);else{const f=s==="app"?[`app.${h}`]:[`${s}.${h}`,`app.${h}`];r.push(...f)}if(l!==-1){const f=s==="app"?[`app.${h}`]:[`${s}.${h}`,`app.${h}`];r.push(...f)}}return Array.from(new Set(r))}extractIdentifiers(e){const s=[];let i=0;for(;i<e.length;){const n=e[i];if(n==="'"){i=this.skipString(e,i,"'");continue}if(n==='"'){i=this.skipString(e,i,'"');continue}if(n==="`"){i=this.skipTemplateLiteral(e,i,s);continue}if(this.isIdentifierStart(n)){const r=this.extractIdentifier(e,i);s.push(r.value),i=r.endIndex;continue}i++}return s}skipString(e,s,i){let n=s+1;for(;n<e.length&&e[n]!==i;)e[n]==="\\"&&n++,n++;return n+1}skipTemplateLiteral(e,s,i){let n=s+1;for(;n<e.length&&e[n]!=="`";){if(e[n]==="$"&&n+1<e.length&&e[n+1]==="{"){n+=2;let r=1;for(;n<e.length&&r>0;){const a=e[n];if(a==='"'||a==="'"){n=this.skipString(e,n,a);continue}if(a==="{"?r++:a==="}"&&r--,r>0&&this.isIdentifierStart(a)){const o=this.extractIdentifier(e,n);i.push(o.value),n=o.endIndex-1}n++}continue}e[n]==="\\"&&n++,n++}return n+1}extractIdentifier(e,s){let i=s;for(;i<e.length&&(this.isIdentifierPart(e[i])||e[i]===".");)i++;return{value:e.substring(s,i),endIndex:i}}isIdentifierStart(e){return/[a-zA-Z_$]/.test(e)}isIdentifierPart(e){return/[a-zA-Z0-9_$]/.test(e)}clearCache(){this.parseCache.clear()}getCacheSize(){return this.parseCache.cache.size}}class Ns{componentStack=["app"];elementProps=new WeakMap;contextCache=new $(100);contextIndex=new Map;contextInvalidated=new Set;stateManager;processedScripts=new WeakSet;componentFunctions=new Map;expressionEvaluator;domBindingManager;loopManager;templateRenderer;updateTimeouts;updateBatcher=new et;propDependencyCache=new Map;constructor(e){this.stateManager=e,this.updateBatcher=new et,this.stateManager.onStateChange(s=>this.invalidateContextCache(s))}getPropDependencies(e,s){const i=this.findElementWithProps(s);if(!i)return[];const n=this.elementProps.get(i);if(!n||!n.has(e))return[];const r=n.get(e);return this.templateRenderer?.dependencies(r.expression,r.component,this.stateManager)||[]}buildRestrictedComponentContext(e,s=!1){const i={};window[e]&&Object.assign(i,window[e]);const n=this.componentFunctions.get(e);if(n)for(const[a,o]of n)i[a]=o;const r=this.stateManager.getState();for(const a of Object.keys(r))if(a.startsWith(e+".")){const o=a.substring(e.length+1);o in i||(i[o]=r[a])}if(s){if(window.app)for(const[o,c]of Object.entries(window.app))o in i||(i[o]=c);const a=this.componentFunctions.get("app");if(a)for(const[o,c]of a)o in i||(i[o]=c);for(const o of Object.keys(r))if(o.startsWith("app.")){const c=o.substring(4);c in i||(i[c]=r[o])}}return i}getComponentPropDependencies(e,s){if(this.propDependencyCache.has(e))return this.propDependencyCache.get(e);const i=[],n=this.elementProps.get(e);n&&this.templateRenderer&&n.forEach(a=>{const o=this.templateRenderer?.dependencies(a.expression,a.component,this.stateManager);i.push(...o??[])});const r=Array.from(new Set(i));return this.propDependencyCache.set(e,r),r}setDOMBindingManager(e){this.domBindingManager=e,this.updateBatcher.setManagers(this,e)}hasStoredProps(e){return this.elementProps.has(e)&&this.elementProps.get(e).size>0}setExpressionEvaluator(e){this.expressionEvaluator=e,this.templateRenderer=new Ke(e),this.loopManager=new Ft(this.stateManager,e)}extractProps(e,s){const i=new Map,n=e.attributes,r=e.getAttribute(d.ATTR_PREFIXES.CONTEXT),a=e.getAttribute(d.ATTR_PREFIXES.COMPONENT);let o=s;r&&(r==="app"?o="app":r==="parent"?o=y.getParentOfComponent(a||"app",e):o=r);for(let c=0;c<n.length;c++){const l=n[c];if(!(l.name===d.ATTR_PREFIXES.COMPONENT||l.name===d.ATTR_PREFIXES.CONTEXT||l.name===d.ATTR_PREFIXES.SPREAD||l.name===d.ATTR_PREFIXES.LOOP)&&!oe.isEventAttribute(l.name)&&l.value&&ws.containsMustacheExpression(l.value)){if(a&&this.mightReferenceSelfProps(l.value,e))continue;const h=this.attributeToPropName(l.name),p={name:h,expression:l.value,component:o,subscriptionIds:[]};i.set(h,p)}}return i}mightReferenceSelfProps(e,s){const i=this.elementProps.get(s);return i?Array.from(i.keys()).some(r=>e.includes(r)&&r!=="dataState"):!1}attributeToPropName(e){return e.replace(/-([a-z])/g,(s,i)=>i.toUpperCase())}setupProps(e,s){const i=this.extractProps(e,s);i.size!==0&&(this.elementProps.set(e,i),this.expressionEvaluator&&i.forEach((n,r)=>{this.setupPropBinding(e,n)}))}setupPropBinding(e,s){if(!this.expressionEvaluator)return;const i=`prop_${Date.now()}_${Math.random()}`,n=this.templateRenderer?.dependencies(s.expression,s.component,this.stateManager)||[],r={id:i,selector:"",dependencies:new Set(n),callback:()=>{const a=e.getAttribute(d.ATTR_PREFIXES.COMPONENT);a&&(this.updateBatcher.scheduleUpdate(a,e),this.refreshComponentBindings(e,a))},element:e,component:s.component};this.stateManager.addSubscription(r),s.subscriptionIds.push(i)}refreshComponentBindings(e,s){this.contextInvalidated.add(s),this.contextCache.delete(s),this.domBindingManager&&this.domBindingManager.refreshComponentElement(e,s)}evaluateProps(e){const s={},i=this.elementProps.get(e);if(!i||!this.expressionEvaluator)return s;const n=i.values().next().value;if(!n)return s;const r=this.buildComponentContext(n.component);return i.forEach((a,o)=>{try{const c=this.templateRenderer?.render(a.expression,r,a.component);typeof c=="function"?s[o]=(...l)=>c.apply(this,l):s[o]=c}catch(c){console.error(`❌ Failed to evaluate prop "${o}":`,c),s[o]=void 0}}),s}cleanupProps(e){const s=this.elementProps.get(e);s&&(s.forEach(i=>{i.subscriptionIds.forEach(n=>{this.stateManager.removeSubscription(n)})}),this.elementProps.delete(e))}buildComponentContextWithProps(e,s){const i=this.buildComponentContext(e);let n=this.findElementWithProps(e);if(s&&this.elementProps.has(s)&&(n=s),n)try{const r=this.evaluatePropsWithContext(n,e,s);Object.keys(r).length>0&&Object.keys(r).forEach(a=>{i[a]=r[a]})}catch(r){console.error(`❌ Error evaluating props for ${e}:`,r)}return i}evaluatePropsWithContext(e,s,i){const n={},r=this.elementProps.get(e);if(!r||!this.expressionEvaluator)return n;const a=r.values().next().value;if(!a)return n;let o;const c=e.getAttribute(d.ATTR_PREFIXES.CONTEXT),l=e.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(c)if(c==="app")o=this.buildComponentContext("app");else if(c==="parent"){const C=y.getParentOfComponent(l||"app",e);o=this.buildComponentContext(C)}else o=this.buildComponentContext(c);else o=this.buildComponentContext(a.component);const h=this.loopManager?.getLoopContextForElement(e);h&&(o={...o,...h});const p=new Map,f=new Map,m=Array.from(r.keys());r.forEach((C,S)=>{m.some(M=>M!==S&&C.expression.includes(M))?f.set(S,C):p.set(S,C)}),p.forEach((C,S)=>{try{const P=this.templateRenderer?.render(C.expression,o,c||C.component);typeof P=="function"?this.isFunctionExplicitlyPassed(C.expression)?n[S]=(...fe)=>P.apply(this,fe):(console.warn(`⚠️ Function "${S}" not passed - not from shared namespace or explicitly passed`),n[S]=void 0):n[S]=P}catch(P){console.error(`❌ Failed to evaluate simple prop "${S}":`,P),console.error("Expression:",C.expression),console.error("Available context keys:",Object.keys(o)),n[S]=void 0}});const x={...o,...n};return f.forEach((C,S)=>{try{const P=this.templateRenderer?.render(C.expression,x,c||C.component);typeof P=="function"?this.isFunctionExplicitlyPassed(C.expression)?n[S]=(...fe)=>P.apply(this,fe):(console.warn(`⚠️ Function "${S}" not passed - not from shared namespace or explicitly passed`),n[S]=void 0):n[S]=P}catch(P){console.error(`❌ Failed to evaluate complex prop "${S}":`,P),console.error("Expression:",C.expression),console.error("Available context keys:",Object.keys(x)),n[S]=void 0}}),n}isFunctionExplicitlyPassed(e){const s=_.isSingleExpression(e);return s?/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(s.trim()):!1}findElementWithProps(e){const s=document.querySelectorAll(`[${d.ATTR_PREFIXES.COMPONENT}="${e}"]`);for(const i of s){const n=this.elementProps.get(i);if(n&&n.size>0)return i}return null}pushComponent(e){this.componentStack.push(e)}popComponent(){return this.componentStack.pop()}getCurrentComponent(){return this.componentStack[this.componentStack.length-1]}buildComponentContext(e){if(!this.contextInvalidated.has(e)&&this.contextCache.has(e))return this.contextCache.get(e);const s=this.computeComponentContext(e);return this.contextCache.set(e,s),this.contextInvalidated.delete(e),s}computeComponentContext(e){const s={};e!=="app"&&window[e]&&Object.assign(s,window[e]),e==="app"&&window.app&&Object.assign(s,window.app);const i=this.componentFunctions.get(e);if(i)for(const[r,a]of i)s[r]=a;if(e!=="app"){const r=this.componentFunctions.get("app");if(r)for(const[a,o]of r)a in s||(s[a]=o)}const n=this.stateManager.getState();for(const r of Object.keys(n))if(r.startsWith(e+".")){const a=r.substring(e.length+1);a in s||(s[a]=n[r])}if(e!=="app"){for(const r of Object.keys(n))if(r.startsWith("app.")){const a=r.substring(4);a in s||(s[a]=n[r])}}return s}invalidateContextCache(e){if(e.startsWith("app.")){this.contextCache.clear();for(const i of this.contextInvalidated.keys())this.contextInvalidated.add(i);return}const s=e.indexOf(".");if(s!==-1){const i=e.slice(0,s);this.invalidateComponent(i)}}invalidateComponent(e){this.contextInvalidated.add(e),this.contextIndex.delete(e)}executePhpScripts(e){const s=this.componentStack.length,i=e.getAttribute(d.ATTR_PREFIXES.COMPONENT),n=e===document.body;if(i||n){if(i){this.pushComponent(i);const a=this.getParentComponent(e);this.setupProps(e,a)}this.getRelevantScripts(e,n).forEach(a=>{const o=a.getAttribute(d.ATTR_PREFIXES.COMPONENT);o&&o!==i?(this.pushComponent(o),this.executeScript(a),this.popComponent()):this.executeScript(a)})}for(Array.from(e.children).forEach(r=>this.executePhpScripts(r));this.componentStack.length>s;)this.popComponent()}getParentComponent(e){let s=e.parentElement;for(;s;){const i=s.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(i)return i;s=s.parentElement}return"app"}getRelevantScripts(e,s){return Array.from(e.querySelectorAll(`script[type="${d.SCRIPT_TYPE}"]`)).filter(i=>{if(this.processedScripts.has(i))return!1;if(s)return i.hasAttribute(d.ATTR_PREFIXES.COMPONENT)?!0:!i.closest(`[${d.ATTR_PREFIXES.COMPONENT}]`);let n=i.parentElement;for(;n&&n!==e;){if(n.hasAttribute(d.ATTR_PREFIXES.COMPONENT))return!1;n=n.parentElement}return n===e||e.contains(i)})}executeScript(e){if(this.processedScripts.has(e))return;this.processedScripts.add(e);const s=this.getCurrentComponent(),i=e.textContent||"",n=_.decodeEntities(i);try{const r=this.findComponentElementForScript(e,s);if(r===e){const o=this.getParentComponent(e);this.setupProps(e,o)}const a=this.buildComponentContextWithProps(s,r);window[s]||(window[s]={}),this.executeScriptFunctions(n,s,a)}catch(r){console.error(`Script execution failed in component ${s}:`,r),console.error("Script content:",n)}}findComponentElementForScript(e,s){if(e.getAttribute(d.ATTR_PREFIXES.COMPONENT)===s)return e;let i=e.parentElement;for(;i;){if(i.getAttribute(d.ATTR_PREFIXES.COMPONENT)===s)return i;i=i.parentElement}const n=document.querySelectorAll(`[${d.ATTR_PREFIXES.COMPONENT}="${s}"]`);for(const r of n)if(this.elementProps.has(r))return r;return n[0]||void 0}executeScriptFunctions(e,s,i){const n=this.extractFunctionNames(e),r=this.findElementWithProps(s),a=this.extractVariableDeclarations(e);let o={...i};if(a.forEach(x=>{delete o[x];const C=`set${Vt(x)}`,S=`${x}Getter`;delete o[C],delete o[S]}),r){const x=this.evaluateProps(r);Object.assign(o,x)}o.getContext=()=>this.buildComponentContextWithProps(s),o.withContext=x=>{const C=this.buildComponentContextWithProps(s);return x.call(C,C)},o.__getProp=x=>{if(r)return this.evaluateProps(r)[x]};let l=z.getInstance().transformStateDeclarations(e);l=this.modifyScriptForReactiveProps(l,s,r||void 0);const h=`
|
|
10
11
|
${l}
|
|
11
12
|
|
|
12
13
|
${n.map(x=>`
|