create-prisma-php-app 4.0.0-alpha.80 → 4.0.0-alpha.81
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/app-gitignore +1 -1
- package/dist/bootstrap.php +12 -12
- package/dist/index.js +6 -6
- package/dist/settings/project-name.ts +1 -1
- package/dist/settings/swagger-config.ts +2 -2
- package/dist/src/Lib/Auth/Auth.php +4 -4
- package/dist/src/Lib/Middleware/AuthMiddleware.php +1 -1
- package/dist/src/app/error.php +1 -1
- package/dist/src/app/index.php +1 -1
- package/dist/src/app/js/index.js +1 -1
- package/dist/src/app/layout.php +3 -3
- package/package.json +1 -1
package/dist/app-gitignore
CHANGED
package/dist/bootstrap.php
CHANGED
|
@@ -18,18 +18,18 @@ if (session_status() === PHP_SESSION_NONE) {
|
|
|
18
18
|
session_start();
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
-
use
|
|
22
|
-
use
|
|
23
|
-
use
|
|
21
|
+
use PP\Request;
|
|
22
|
+
use PP\PrismaPHPSettings;
|
|
23
|
+
use PP\StateManager;
|
|
24
24
|
use Lib\Middleware\AuthMiddleware;
|
|
25
25
|
use Lib\Auth\Auth;
|
|
26
|
-
use
|
|
27
|
-
use
|
|
28
|
-
use
|
|
29
|
-
use
|
|
26
|
+
use PP\MainLayout;
|
|
27
|
+
use PP\PHPX\TemplateCompiler;
|
|
28
|
+
use PP\CacheHandler;
|
|
29
|
+
use PP\ErrorHandler;
|
|
30
30
|
use Firebase\JWT\JWT;
|
|
31
31
|
use Firebase\JWT\Key;
|
|
32
|
-
use
|
|
32
|
+
use PP\PartialRenderer;
|
|
33
33
|
|
|
34
34
|
final class Bootstrap extends RuntimeException
|
|
35
35
|
{
|
|
@@ -77,7 +77,7 @@ final class Bootstrap extends RuntimeException
|
|
|
77
77
|
ErrorHandler::registerHandlers();
|
|
78
78
|
|
|
79
79
|
// Set a local store key as a cookie (before any output)
|
|
80
|
-
setcookie("
|
|
80
|
+
setcookie("pp_local_store_key", PrismaPHPSettings::$localStoreKey, [
|
|
81
81
|
'expires' => time() + 3600, // 1 hour expiration
|
|
82
82
|
'path' => '/', // Cookie path
|
|
83
83
|
'domain' => '', // Specify your domain
|
|
@@ -127,7 +127,7 @@ final class Bootstrap extends RuntimeException
|
|
|
127
127
|
}
|
|
128
128
|
|
|
129
129
|
self::$isPartialRequest =
|
|
130
|
-
!empty(Request::$data['
|
|
130
|
+
!empty(Request::$data['ppSync71163'])
|
|
131
131
|
&& !empty(Request::$data['selectors'])
|
|
132
132
|
&& self::$secondRequestC69CD;
|
|
133
133
|
|
|
@@ -180,7 +180,7 @@ final class Bootstrap extends RuntimeException
|
|
|
180
180
|
$jwt = JWT::encode($payload, $hmacSecret, 'HS256');
|
|
181
181
|
|
|
182
182
|
setcookie(
|
|
183
|
-
'
|
|
183
|
+
'pp_function_call_jwt',
|
|
184
184
|
$jwt,
|
|
185
185
|
[
|
|
186
186
|
'expires' => time() + 3600,
|
|
@@ -655,7 +655,7 @@ final class Bootstrap extends RuntimeException
|
|
|
655
655
|
|
|
656
656
|
private static function getAesKeyFromJwt(): string
|
|
657
657
|
{
|
|
658
|
-
$token = $_COOKIE['
|
|
658
|
+
$token = $_COOKIE['pp_function_call_jwt'] ?? null;
|
|
659
659
|
$jwtSecret = $_ENV['FUNCTION_CALL_SECRET'] ?? null;
|
|
660
660
|
|
|
661
661
|
if (!$token || !$jwtSecret) {
|
package/dist/index.js
CHANGED
|
@@ -218,8 +218,8 @@ export async function installComposerDependencies(baseDir, dependencies) {
|
|
|
218
218
|
"--no-interaction",
|
|
219
219
|
...dependencies,
|
|
220
220
|
].join(" ")}`;
|
|
221
|
-
console.log(`Executing: ${requireCmd}`);
|
|
222
|
-
console.log(`Working directory: ${baseDir}`);
|
|
221
|
+
// console.log(`Executing: ${requireCmd}`);
|
|
222
|
+
// console.log(`Working directory: ${baseDir}`);
|
|
223
223
|
execSync(requireCmd, {
|
|
224
224
|
stdio: "inherit",
|
|
225
225
|
cwd: baseDir,
|
|
@@ -268,12 +268,12 @@ export async function installComposerDependencies(baseDir, dependencies) {
|
|
|
268
268
|
}
|
|
269
269
|
}
|
|
270
270
|
const npmPinnedVersions = {
|
|
271
|
-
"@tailwindcss/postcss": "^4.1.
|
|
271
|
+
"@tailwindcss/postcss": "^4.1.13",
|
|
272
272
|
"@types/browser-sync": "^2.29.0",
|
|
273
|
-
"@types/node": "^24.
|
|
273
|
+
"@types/node": "^24.5.2",
|
|
274
274
|
"@types/prompts": "^2.4.9",
|
|
275
275
|
"browser-sync": "^3.0.4",
|
|
276
|
-
chalk: "^5.6.
|
|
276
|
+
chalk: "^5.6.2",
|
|
277
277
|
"chokidar-cli": "^3.0.0",
|
|
278
278
|
cssnano: "^7.1.1",
|
|
279
279
|
"http-proxy-middleware": "^3.0.5",
|
|
@@ -282,7 +282,7 @@ const npmPinnedVersions = {
|
|
|
282
282
|
postcss: "^8.5.6",
|
|
283
283
|
"postcss-cli": "^11.0.1",
|
|
284
284
|
prompts: "^2.4.2",
|
|
285
|
-
tailwindcss: "^4.1.
|
|
285
|
+
tailwindcss: "^4.1.13",
|
|
286
286
|
tsx: "^4.20.5",
|
|
287
287
|
typescript: "^5.9.2",
|
|
288
288
|
};
|
|
@@ -11,7 +11,7 @@ const { __dirname } = getFileMeta();
|
|
|
11
11
|
export async function swaggerConfig(): Promise<void> {
|
|
12
12
|
const outputPath = join(
|
|
13
13
|
__dirname,
|
|
14
|
-
"../src/app/swagger-docs/apis/
|
|
14
|
+
"../src/app/swagger-docs/apis/pp-swagger.json"
|
|
15
15
|
);
|
|
16
16
|
|
|
17
17
|
const options = {
|
|
@@ -58,7 +58,7 @@ export async function swaggerConfig(): Promise<void> {
|
|
|
58
58
|
writeFileSync(outputPath, swaggerSpec, "utf-8");
|
|
59
59
|
console.log(
|
|
60
60
|
`Swagger JSON has been generated and saved to ${chalk.blue(
|
|
61
|
-
"src/app/swagger-docs/apis/
|
|
61
|
+
"src/app/swagger-docs/apis/pp-swagger.json"
|
|
62
62
|
)}`
|
|
63
63
|
);
|
|
64
64
|
} catch (error) {
|
|
@@ -8,10 +8,10 @@ use Firebase\JWT\JWT;
|
|
|
8
8
|
use Firebase\JWT\Key;
|
|
9
9
|
use DateInterval;
|
|
10
10
|
use DateTime;
|
|
11
|
-
use
|
|
11
|
+
use PP\Validator;
|
|
12
12
|
use GuzzleHttp\Client;
|
|
13
13
|
use GuzzleHttp\Exception\RequestException;
|
|
14
|
-
use
|
|
14
|
+
use PP\Request;
|
|
15
15
|
use Exception;
|
|
16
16
|
use InvalidArgumentException;
|
|
17
17
|
use ArrayObject;
|
|
@@ -25,7 +25,7 @@ class Auth
|
|
|
25
25
|
public static string $cookieName = '';
|
|
26
26
|
|
|
27
27
|
private static ?Auth $instance = null;
|
|
28
|
-
private const
|
|
28
|
+
private const PPAUTH = 'ppauth';
|
|
29
29
|
private string $secretKey;
|
|
30
30
|
private string $defaultTokenValidity = '1h'; // Default to 1 hour
|
|
31
31
|
|
|
@@ -347,7 +347,7 @@ class Auth
|
|
|
347
347
|
*/
|
|
348
348
|
public function authProviders(...$providers)
|
|
349
349
|
{
|
|
350
|
-
$dynamicRouteParams = Request::$dynamicParams[self::
|
|
350
|
+
$dynamicRouteParams = Request::$dynamicParams[self::PPAUTH] ?? [];
|
|
351
351
|
|
|
352
352
|
if (Request::$isGet && in_array('signin', $dynamicRouteParams)) {
|
|
353
353
|
foreach ($providers as $provider) {
|
package/dist/src/app/error.php
CHANGED
package/dist/src/app/index.php
CHANGED
package/dist/src/app/js/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{const e=EventTarget.prototype.addEventListener,t=EventTarget.prototype.removeEventListener,r=new Map,n=new WeakMap,s=new Set(["wheel","mousewheel","touchstart","touchmove","touchend","touchcancel","scroll"]);function i(e){const t=e.currentTarget;if(t instanceof Element)return t;if(t instanceof Document||t===window)return document.body||document.documentElement||null;const r=e.target;if(r instanceof Element)return r;if(r&&"number"==typeof r.nodeType){const e=r;return e.parentElement||e.ownerDocument?.body||null}const n=e.composedPath?.();if(Array.isArray(n))for(const e of n)if(e instanceof Element)return e;return document.body||document.documentElement||null}function o(e,t){const r=globalThis.pphp??globalThis.PPHP?.instance??null;if(!r||!e)return t();let n=["app"];try{n=r.detectElementHierarchy(e)||["app"]}catch{n=["app"]}const s={eff:r._currentEffectContext,proc:r._currentProcessingHierarchy,evt:r._currentEventTarget};try{return r._currentEffectContext=n.join("."),r._currentProcessingHierarchy=n,r._currentEventTarget=e,t()}finally{r._currentEffectContext=s.eff,r._currentProcessingHierarchy=s.proc,r._currentEventTarget=s.evt}}function a(e,t,r){const s=function(e,t){let r=n.get(e);r||(r=new Map,n.set(e,r));let s=r.get(t);return s||(s=new Map,r.set(t,s)),s}(e,t),a=s.get(r);if(a)return a;let c;if("function"==typeof r){const e=r;c=function(t){return o(i(t),(()=>e.call(this,t)))}}else{const e=r;c={handleEvent:t=>o(i(t),(()=>e.handleEvent(t)))}}return s.set(r,c),c}EventTarget.prototype.addEventListener=function(t,n,i){let o=i;s.has(t)&&(void 0===o?o={passive:!0}:"boolean"==typeof o?o={capture:o,passive:!0}:void 0===o.passive&&(o={...o,passive:!0})),r.has(this)||r.set(this,new Map);const c=r.get(this),l=c.get(t)||new Set;l.add(n),c.set(t,l);const h=a(this,t,n);return e.call(this,t,h,o)},EventTarget.prototype.removeEventListener=function(e,s,i){if(r.has(this)&&r.get(this).has(e)){const t=r.get(this).get(e);t.delete(s),0===t.size&&r.get(this).delete(e)}const o=n.get(this)?.get(e),a=o?.get(s)??s;t.call(this,e,a,i),o?.delete(s)},EventTarget.prototype.removeAllEventListeners=function(e){const s=r.get(this);if(s){if(e){const r=s.get(e);if(!r)return;const i=n.get(this)?.get(e);return r.forEach((r=>{const n=i?.get(r)??r;t.call(this,e,n),i?.delete(r)})),void s.delete(e)}s.forEach(((e,r)=>{const s=n.get(this)?.get(r);e.forEach((e=>{const n=s?.get(e)??e;t.call(this,r,n)}))})),r.delete(this),n.delete(this)}}})(),function(){const e=console.log;console.log=(...t)=>{const r=t.map((e=>"function"==typeof e&&e.__isReactiveProxy?e():e));e.apply(console,r)}}();class PPHP{props={};_isNavigating=!1;_responseData=null;_elementState={checkedElements:new Set};_activeAbortController=null;_reservedWords;_declaredStateRoots=new Set;_arrayMethodCache=new WeakMap;_updateScheduled=!1;_pendingBindings=new Set;_effects=new Set;_pendingEffects=new Set;_processedPhpScripts=new WeakSet;_bindings=[];_templateStore=new WeakMap;_inlineDepth=0;_proxyCache=new WeakMap;_rawProps={};_refs=new Map;_wheelHandlersStashed=!1;_evaluatorCache=new Map;_depsCache=new Map;_dirtyDeps=new Set;_handlerCache=new Map;_handlerProxyCache=new WeakMap;_sharedStateMap=new Set;_processedLoops=new WeakSet;_hydrated=!1;_currentProcessingHierarchy=null;_stateHierarchy=new Map;_inlineModuleFns=new Map;_currentExecutionScope=null;_transitionStyleInjected=!1;_currentEffectContext=null;_currentEventTarget=null;_eventContextStack=[];_currentProcessingElement=null;_hydrationListeners=new Set;_isInitialHydrationComplete=!1;_lastNavigationTime=0;_navigationThrottleMs=1e3;_bindingUpdateCount=0;_maxBindingUpdates=100;_bindingUpdateResetTimeout=null;_errorCounts=new Map;_maxErrorsPerFunction=3;_errorResetTimeout=3e4;_lastRequestTime=new Map;_requestThrottleMs=1e3;_eventHandlers;_redirectRegex=/redirect_7F834\s*=\s*(\/[^\s]*)/;_assignmentRe=/^\s*[\w.]+\s*=(?!=)/;_mustacheRe=/\{\{\s*([\s\S]+?)\s*\}\}/gu;_mutators;_boolAttrs=new Set(["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected","truespeed"]);static _instance;static _effectCleanups;static _debounceTimers=new Map;static _shared=new Map;static _cryptoKey=null;static _cancelableEvents=new Set(["click","submit","change"]);static _mustacheTest=/\{\{\s*[\s\S]+?\s*\}\}/;static _mustachePattern=/\{\{\s*([\s\S]+?)\s*\}\}/g;static _passiveEvents=new Set(["wheel","mousewheel","touchstart","touchmove","touchend","touchcancel","scroll"]);constructor(){const e=Object.getOwnPropertyNames(HTMLElement.prototype).filter((e=>e.startsWith("on"))),t=Object.getOwnPropertyNames(Document.prototype).filter((e=>e.startsWith("on"))),r=Object.getOwnPropertyNames(Window.prototype).filter((e=>e.startsWith("on")));this._eventHandlers=new Set([...e,...t,...r].map((e=>e.toLowerCase()))),this._reservedWords=new Set(["null","undefined","true","false","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","finally","for","function","if","import","in","instanceof","let","new","return","super","switch","this","throw","try","typeof","var","void","while","with","yield","async","await","implements","interface","event","NaN","Infinity","Number","String","Boolean","Object","Array","Function","Date","RegExp","Error","JSON","Math","Map","Set"]),this._mutators=new Set(["push","pop","shift","unshift","splice","sort","reverse","copyWithin","fill"]),this.handlePopState(),this._proxyCache=new WeakMap,this._evaluatorCache.clear(),this._depsCache.clear(),this._rawProps={},this.props=this.makeReactive({}),this.setupGlobalEventTracking(),this.scheduleInitialHydration()}static get instance(){return PPHP._instance||(PPHP._instance=new PPHP),PPHP._instance}debugProps(){console.group("%cPPHP Debug Snapshot","font-weight:bold; color:teal"),console.groupCollapsed("📦 Raw props"),console.log(JSON.stringify(this.props,null,2)),console.groupEnd(),console.groupCollapsed("🌐 Shared state (pphp.share)"),0===PPHP._shared.size?console.log("(none)"):console.table(Array.from(PPHP._shared.entries()).map((([e,{getter:t}])=>({key:e,value:this.formatValue(t()),type:typeof t()})))),console.groupEnd(),console.groupCollapsed("🔗 Shared keys declared this run"),0===this._sharedStateMap.size?console.log("(none)"):console.log([...this._sharedStateMap]),console.groupEnd(),console.groupCollapsed("🔖 State hierarchy"),console.table(Array.from(this._stateHierarchy.entries()).map((([e,t])=>({scopedKey:e,originalKey:t.originalKey,level:t.level,value:this.formatValue(this.getNested(this.props,e)),path:t.hierarchy.join(" → ")})))),console.groupEnd(),console.groupCollapsed("⚙️ Reactive internals"),console.log("Bindings total:",this._bindings.length),console.log("Pending bindings:",this._pendingBindings.size),console.log("Effects:",this._effects.size),console.log("Pending effects:",this._pendingEffects.size),console.log("Dirty deps:",Array.from(this._dirtyDeps).join(", ")||"(none)"),console.groupEnd(),console.groupCollapsed("🔗 Refs"),console.table(Array.from(this._refs.entries()).map((([e,t])=>({key:e,count:t.length,selectors:t.map((e=>e.tagName.toLowerCase())).join(", ")})))),console.groupEnd(),console.groupCollapsed("📦 Inline modules"),this._inlineModuleFns.forEach(((e,t)=>{console.log(`${t}:`,[...e.keys()])})),console.groupEnd(),console.log("Hydrated:",this._hydrated),console.groupCollapsed("🔀 Conditionals (pp-if chains)");Array.from(document.querySelectorAll("[pp-if], [pp-elseif], [pp-else]")).forEach(((e,t)=>{const r=e.hasAttribute("pp-if")?"if":e.hasAttribute("pp-elseif")?"elseif":"else",n=e.getAttribute(`pp-${r}`)??null;let s=null;if(n){const t=n.replace(/^{\s*|\s*}$/g,""),r=this.detectElementHierarchy(e);try{s=!!this.makeScopedEvaluator(t,r)(this._createScopedPropsContext(r))}catch{s=null}}console.log(`#${t}`,{element:e.tagName+(e.id?`#${e.id}`:""),type:r,expr:n,visible:!e.hasAttribute("hidden"),result:s})})),console.groupEnd(),console.groupCollapsed("🔁 Loops (pp-for)");const e=Array.from(document.querySelectorAll("template[pp-for]"));if(0===e.length)console.log("(none)");else{const t=e.map(((e,t)=>{const{itemName:r,idxName:n,arrExpr:s}=this.parseForExpression(e);let i=0;const o=e.previousSibling;if(o?.nodeType===Node.COMMENT_NODE&&"pp-for"===o.data){let e=o.nextSibling;for(;e&&!(e instanceof HTMLTemplateElement&&e.hasAttribute("pp-for"));)i+=1,e=e.nextSibling}return{"#":t,"(expr)":s,item:r||"(default)",idx:n||"(—)",rendered:i}}));console.table(t)}console.groupEnd(),console.groupEnd()}setupGlobalEventTracking(){const e=EventTarget.prototype.addEventListener,t=this;EventTarget.prototype.addEventListener=function(r,n,s){return e.call(this,r,(function(e){return t.trackEventContext&&t.trackEventContext(e),"function"==typeof n?n.call(this,e):n&&"function"==typeof n.handleEvent?n.handleEvent(e):void 0}),s)}}onHydrationComplete(e){return this._hydrationListeners.add(e),this._isInitialHydrationComplete&&e(),()=>{this._hydrationListeners.delete(e)}}notifyHydrationComplete(){this._hydrationListeners.forEach((e=>{try{e()}catch(e){console.error("Hydration completion callback error:",e)}}));const e=new CustomEvent("pphp:hydration-complete",{bubbles:!0,detail:{timestamp:Date.now()}});document.dispatchEvent(e)}scheduleInitialHydration(){const e=()=>new Promise((e=>setTimeout(e,0))),t=async()=>{try{await Promise.all([this.initRefs(),this.bootstrapDeclarativeState(),this.processInlineModuleScripts(),this._hydrated=!0]),await e(),await this.initializeAllReferencedProps(),await e(),await this.manageAttributeBindings(),await e(),await this.processIfChains(),await e(),await this.initLoopBindings(),await e(),await this.attachWireFunctionEvents();const t=250;for(let r=0;r<this._bindings.length;r+=t)this._bindings.slice(r,r+t).forEach((e=>{try{e.update()}catch(e){console.error("Initial binding update error:",e)}})),await e();document.body.removeAttribute("hidden"),this._isInitialHydrationComplete=!0,this.notifyHydrationComplete()}catch(e){console.error("Hydration failed:",e),document.body.removeAttribute("hidden")}};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t,{once:!0}):t()}async hydratePortal(e=document.body){await this.initReactiveOn(e,{wire:!0,preserveHierarchy:!0})}getPreservedPortalHierarchy(e){let t=e;for(;t&&t!==document.documentElement;){const e=t.getAttribute("data-pphp-original-hierarchy");if(e)try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch(e){console.warn("Failed to parse preserved portal hierarchy:",e)}t=t.parentElement}return[]}async initCryptoKey(){const e=document.cookie.split("; ").find((e=>e.startsWith("pphp_function_call_jwt=")))?.split("=",2)[1];if(!e)throw new Error("Missing function-call token");const[,t]=e.split("."),r=atob(t.replace(/-/g,"+").replace(/_/g,"/")),{k:n,exp:s}=JSON.parse(r);if(Date.now()/1e3>s)throw new Error("Function-call token expired");const i=Uint8Array.from(atob(n),(e=>e.charCodeAt(0)));PPHP._cryptoKey=await crypto.subtle.importKey("raw",i,{name:"AES-CBC"},!1,["encrypt","decrypt"])}async encryptCallbackName(e){await this.initCryptoKey();const t=crypto.getRandomValues(new Uint8Array(16)),r=(new TextEncoder).encode(e),n=await crypto.subtle.encrypt({name:"AES-CBC",iv:t},PPHP._cryptoKey,r);return`${btoa(String.fromCharCode(...t))}:${btoa(String.fromCharCode(...new Uint8Array(n)))}`}async decryptCallbackName(e){await this.initCryptoKey();const[t,r]=e.split(":",2),n=Uint8Array.from(atob(t),(e=>e.charCodeAt(0))),s=Uint8Array.from(atob(r),(e=>e.charCodeAt(0))).buffer,i=await crypto.subtle.decrypt({name:"AES-CBC",iv:n},PPHP._cryptoKey,s);return(new TextDecoder).decode(i)}qsa(e,t){try{if(e)return e.querySelectorAll(t)}catch(e){console.error("qsa() failed:",e)}return document.createDocumentFragment().querySelectorAll(t)}async bootstrapDeclarativeState(e=document.body){this.qsa(e,"[pp-init-state]").forEach((e=>{let t,r=e.getAttribute("pp-init-state").trim();if(!r)return void e.removeAttribute("pp-init-state");try{t=JSON5.parse(r)}catch(e){return void console.error("Bad pp-init-state JSON:",r)}const n=this.detectElementHierarchy(e),s=this._currentProcessingHierarchy;this._currentProcessingHierarchy=n,Object.entries(t).forEach((([e,t])=>{this.state(e,t)})),this._currentProcessingHierarchy=s,e.removeAttribute("pp-init-state")}))}detectComponentHierarchy(e){const t=[];let r=e;for(;r&&r!==document.documentElement;){const e=r.getAttribute("pp-component");e&&t.unshift(e),r=r.parentElement}return 0===t.length?(console.warn('PPHP: No component hierarchy found - ensure <body data-component="app"> exists'),["app"]):t}detectElementHierarchy(e){if(!e)return["app"];const t=this.getPreservedPortalHierarchy(e);if(t.length>0)return t;const r=[];let n=e instanceof Element?e:document.body||null;for(;n&&n!==document.documentElement;){const e=n.getAttribute("pp-component");e&&"__shared"!==e&&r.unshift(e),n=n.parentElement}return r.length?r:["app"]}generateScopedKey(e,t){return e.join(".")+"."+t}ref(e,t){const r=this._refs.get(e)??[];if(null!=t){const n=r[t];if(!n)throw new Error(`pphp.ref('${e}', ${t}) — no element at that index`);return n}if(0===r.length)throw new Error(`pphp.ref('${e}') failed — no element was found`);return 1===r.length?r[0]:r}processRefsInFragment(e,t){e.querySelectorAll("[pp-ref]").forEach((e=>{const t=e.getAttribute("pp-ref"),r=this._refs.get(t)??[];r.push(e),this._refs.set(t,r),e.setAttribute("data-ref-key",t),e.removeAttribute("pp-ref")}))}effect(e,t){const r=Array.isArray(t),n=r?t:[],s=r&&0===n.length,i=this._currentProcessingHierarchy||(this._currentEffectContext?this._currentEffectContext.split("."):["app"]),o=i.join("."),a=n.map((e=>{if("function"==typeof e){const t=e.__pphp_key;if(t)return t;try{const t=e();for(const[r,n]of PPHP._shared.entries())try{if(n.getter()===t)return Object.defineProperty(e,"__pphp_key",{value:`__shared.${r}`,writable:!1,enumerable:!1}),`__shared.${r}`}catch(e){}const r=e.toString().match(/([a-zA-Z_$][a-zA-Z0-9_$]*(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*)*)/);if(r){const t=r[1],n=t.split(".")[0];if(PPHP._shared.has(n)){const r=`__shared.${t}`;return Object.defineProperty(e,"__pphp_key",{value:r,writable:!1,enumerable:!1}),r}}}catch(e){}return null}return"string"==typeof e?this.resolveDependencyPath(e,i):null})).filter((e=>Boolean(e))),c=n.filter((e=>"function"==typeof e)),l=new Set(a),h=new Map,d=new Map;for(const e of a)try{const t=this.getResolvedValue(e);h.set(e,t)}catch(t){h.set(e,void 0)}for(const e of c)try{const t=e();d.set(e,t)}catch(t){d.set(e,Symbol("error"))}let p=0,u=0;PPHP._effectCleanups||(PPHP._effectCleanups=new WeakMap);const f=PPHP._effectCleanups,m=()=>{const t=f.get(m);if(t){try{t()}catch(e){console.error("cleanup error:",e)}f.delete(m)}const n=performance.now();if(n-u<16)return void requestAnimationFrame((()=>{performance.now()-u>=16&&m()}));if(u=n,++p>100)throw console.error("PPHP: effect exceeded 100 runs - possible infinite loop"),console.error("Effect function:",e.toString()),console.error("Dependencies:",Array.from(l)),new Error("PPHP: effect ran >100 times — possible loop");if(!s){let e=!1;const t=[];for(const r of a)try{const n=this.getResolvedValue(r),s=h.get(r);this.hasValueChanged(n,s)&&(e=!0,t.push(r),h.set(r,n))}catch(n){e=!0,t.push(r),h.set(r,void 0)}for(const r of c)try{const n=r(),s=d.get(r);this.hasValueChanged(n,s)&&(e=!0,t.push("(function)"),d.set(r,n))}catch(n){d.get(r)!==Symbol("error")&&(e=!0,t.push("(function-error)"),d.set(r,Symbol("error")))}if(r&&(a.length>0||c.length>0)&&!e)return}const i=this._currentEffectContext;this._currentEffectContext=o;try{const t=e();"function"==typeof t&&f.set(m,t),p=0}catch(t){console.error("effect error:",t),console.error("Effect function:",e.toString())}finally{this._currentEffectContext=i}};Object.assign(m,{__deps:l,__static:s,__functionDeps:c,__hierarchy:i,__isEffect:!0});const y=this._currentEffectContext;this._currentEffectContext=o;try{const t=e();"function"==typeof t&&f.set(m,t),p=0}catch(e){console.error("effect error (initial):",e)}finally{this._currentEffectContext=y}const g=r&&this._inlineDepth>0?this._pendingEffects:this._effects;return s?this._effects.add(m):g.add(m),()=>{const e=f.get(m);if(e){try{e()}catch(e){console.error("cleanup error:",e)}f.delete(m)}this._effects.delete(m),this._pendingEffects.delete(m)}}resolveDependencyPath(e,t){const r=e.startsWith("app.")?e.substring(4):e,n=r.split(".")[0];if(PPHP._shared.has(n))return`__shared.${r}`;const s=t.join(".")+"."+e;if(this.hasNested(this.props,s))return s;if(this.hasNested(this.props,e))return e;for(let r=t.length-1;r>=0;r--){const n=t.slice(0,r).join("."),s=n?n+"."+e:e;if(this.hasNested(this.props,s))return s}return e}getResolvedValue(e){const t=(e.startsWith("app.")?e.substring(4):e).split("."),r=t[0],n=PPHP._shared.get(r);if(n){if(1===t.length)return n.getter();{const e=n.getter(),r=t.slice(1).join(".");return this.getNested(e,r)}}return this.getNested(this.props,e)}hasValueChanged(e,t){if(e===t)return!1;if(null==e||null==t)return e!==t;if("object"!=typeof e||"object"!=typeof t)return e!==t;try{return JSON.stringify(e)!==JSON.stringify(t)}catch(e){return!0}}resetProps(){this._isNavigating=!1,this._activeAbortController&&this._activeAbortController.abort(),this._activeAbortController=null,this._responseData=null,Object.keys(this._rawProps).forEach((e=>{if(window.hasOwnProperty(e)){const t=Object.getOwnPropertyDescriptor(window,e);t?.configurable&&delete window[e]}})),this._rawProps={},this.clearShare(),this._proxyCache=new WeakMap,this._templateStore=new WeakMap,this._arrayMethodCache=new WeakMap,this._handlerProxyCache=new WeakMap,this._processedLoops=new WeakSet,this._depsCache.clear(),this._dirtyDeps.clear(),this._evaluatorCache.clear(),this._handlerCache.clear(),this._sharedStateMap.clear(),this._currentProcessingElement=null,this._transitionStyleInjected=!1,this._isInitialHydrationComplete=!1,this._hydrationListeners=new Set,this._processedPhpScripts=new WeakSet,this._declaredStateRoots.clear(),this._inlineModuleFns.clear(),this._inlineDepth=0,this._currentProcessingHierarchy=null,this._currentExecutionScope=null,this._stateHierarchy.clear(),this._currentEventTarget=null,this._eventContextStack=[],this._bindings=[],this._pendingBindings.clear(),this._effects.clear(),this._pendingEffects.clear(),PPHP._effectCleanups=new WeakMap,this._refs.clear(),PPHP._debounceTimers.forEach((e=>clearTimeout(e))),PPHP._debounceTimers.clear(),this._updateScheduled=!1,this._wheelHandlersStashed=!1,this._currentEffectContext=null;try{const e=window;Object.getOwnPropertyNames(e).forEach((t=>{if(t.startsWith("__pphp_")||t.startsWith("_temp_"))try{delete e[t]}catch(e){}}))}catch(e){}this.props=this.makeReactive({}),this._hydrated=!1;const e=document.createNodeIterator(document.body,NodeFilter.SHOW_COMMENT,{acceptNode:e=>"pp-for"===e.data?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT});let t;for(;t=e.nextNode();){let e=t.nextSibling;for(;e&&!(e instanceof HTMLTemplateElement&&e.hasAttribute("pp-for"));){const t=e.nextSibling;e.parentNode?.removeChild(e),e=t}t.parentNode?.removeChild(t)}}async initReactiveOn(e=document.body,t={}){const{wire:r=!0,preserveHierarchy:n=!1}=t,s=()=>new Promise((e=>setTimeout(e,0)));n&&e instanceof Element&&this.markPortalChildrenWithHierarchy(e),await Promise.all([this.initRefs(e),this.bootstrapDeclarativeState(e)]),await s(),await this.processInlineModuleScripts(e),await s(),this._hydrated=!0,await s(),await this.initializeAllReferencedProps(e),await s(),await this.manageAttributeBindings(e),await s(),await this.processIfChains(e),await s(),await this.initLoopBindings(e),await s(),r&&(e===document.body||e.isConnected)&&(await this.attachWireFunctionEvents(e),await s());for(let e=0;e<this._bindings.length;e+=250)this._bindings.slice(e,e+250).forEach((e=>e.update())),await s();this.notifyHydrationComplete()}markPortalChildrenWithHierarchy(e){const t=e.getAttribute("data-pphp-original-hierarchy");if(!t)return;const r=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,null);for(;r.nextNode();){const e=r.currentNode;e.hasAttribute("data-pphp-original-hierarchy")||e.setAttribute("data-pphp-original-hierarchy",t)}}async removeAllEventListenersOnNavigation(){document.removeAllEventListeners(),this._refs.forEach((e=>e.forEach((e=>e.removeAllEventListeners?.())))),document.querySelectorAll("*").forEach((e=>e.removeAllEventListeners?.()))}async initLoopBindings(e=document.body){this.qsa(e,"template[pp-for]").forEach((e=>{this._processedLoops.has(e)||(this._processedLoops.add(e),this.registerLoop(e))}))}registerLoop(e){const t=this.parseForExpression(e),{marker:r,parent:n,templateHierarchy:s}=this.setupLoopMarker(e),i=this.initializeLoopState(),o=this.createLoopUpdater(e,t,r,n,s,i),a={dependencies:this.extractComprehensiveLoopDependencies(e,t,s),update:o,__isLoop:!0};this._bindings.push(a)}processIfChainsInFragment(e,t,r,n,s,i){const o=new WeakSet;e.querySelectorAll("[pp-if]").forEach((e=>{if(o.has(e))return;const a=[];let c=e;for(;c;){if(c.hasAttribute("pp-if"))a.push({el:c,expr:c.getAttribute("pp-if")});else if(c.hasAttribute("pp-elseif"))a.push({el:c,expr:c.getAttribute("pp-elseif")});else{if(!c.hasAttribute("pp-else"))break;a.push({el:c,expr:null})}o.add(c),c=c.nextElementSibling}a.forEach((e=>{if(null!==e.expr){const i=e.expr.replace(/^{\s*|\s*}$/g,"");e.deps=this.extractScopedDependencies(i,r);const o=this.makeScopedEvaluator(i,r);e.evaluate=()=>{const e={...this._createScopedPropsContext(r),[t.itemName]:n};return t.idxName&&(e[t.idxName]=s),!!o(e)}}}));let l=!1;for(const{el:e,expr:t,evaluate:r}of a)!l&&null!==t&&r()?(e.removeAttribute("hidden"),l=!0):l||null!==t?e.setAttribute("hidden",""):(e.removeAttribute("hidden"),l=!0);const h=new Set;a.forEach((e=>e.deps?.forEach((e=>h.add(e)))));const d=r.join("."),p=d?`${d}.${t.arrExpr}`:t.arrExpr;h.add(p);i.push({dependencies:h,update:()=>{const e=this.makeScopedEvaluator(t.arrExpr,r)(this._createScopedPropsContext(r));if(Array.isArray(e)){const i=this.getItemKey(n,s),o=this.findItemByKey(e,i,n),c=e.findIndex((t=>this.getItemKey(t,e.indexOf(t))===i));if(o&&-1!==c){let e=!1;for(const{el:n,expr:s}of a)if(null!==s){const i=this.makeScopedEvaluator(s.replace(/^{\s*|\s*}$/g,""),r),a={...this._createScopedPropsContext(r),[t.itemName]:o};t.idxName&&(a[t.idxName]=c);const l=!!i(a);!e&&l?(n.removeAttribute("hidden"),e=!0):n.setAttribute("hidden","")}else e?n.setAttribute("hidden",""):(n.removeAttribute("hidden"),e=!0)}}},__isLoop:!0})}))}extractComprehensiveLoopDependencies(e,t,r){const n=new Set,s=t.arrExpr.split(".")[0];let i=null;if(PPHP._shared.has(s)){i=`__shared.${t.arrExpr}`;try{const e=this.getNested(this.props,i);Array.isArray(e)||(i=null)}catch{i=null}}if(!i)for(let e=r.length;e>=0;e--){const n=r.slice(0,e),s=n.length>0?`${n.join(".")}.${t.arrExpr}`:t.arrExpr;try{const e=this.getNested(this.props,s);if(Array.isArray(e)){i=s;break}}catch{}}i||(i=t.arrExpr);const o=i;n.add(o);const a=this.extractItemPropertiesFromTemplate(e,t);for(const e of a){n.add(`${o}.*`),n.add(`${o}.*.${e}`);try{const t=this.getNested(this.props,o);if(Array.isArray(t))for(let r=0;r<t.length;r++)n.add(`${o}.${r}.${e}`)}catch{}}return Array.from(n).some((e=>e.includes("*")))||n.add(`${o}.*`),n}extractItemPropertiesFromTemplate(e,t){const r=new Set,n=new RegExp(`\\b${t.itemName}\\.(\\w+(?:\\.\\w+)*)`,"g"),s=document.createTreeWalker(e.content,NodeFilter.SHOW_ALL,null);for(;s.nextNode();){const e=s.currentNode;let t="";if(e.nodeType===Node.TEXT_NODE)t=e.nodeValue||"";else if(e.nodeType===Node.ELEMENT_NODE){const r=e;for(const e of Array.from(r.attributes))t+=" "+e.value}const i=t.matchAll(n);for(const e of i)r.add(e[1])}return r}parseForExpression(e){const t=e.getAttribute("pp-for").trim(),[r,n]=t.split(/\s+in\s+/),[s,i]=r.replace(/^\(|\)$/g,"").split(",").map((e=>e.trim()));return{forExpr:t,vars:r,arrExpr:n,itemName:s,idxName:i}}setupLoopMarker(e){const t=e.parentNode,r=document.createComment("pp-for"),n=this.detectElementHierarchy(e);return t.insertBefore(r,e),t.removeChild(e),{marker:r,parent:t,templateHierarchy:n}}initializeLoopState(){return{previousList:[],renderedItems:new Map}}createItemNodes(e,t,r,n,s){const i={...this._createScopedPropsContext(s),[n.itemName]:t};n.idxName&&(i[n.idxName]=r);const o=e.content.cloneNode(!0),a=[],c=this.getItemKey(t,r);return this.processTextNodesInFragment(o,n,s,c,t,r,a),this.processElementBindingsInFragment(o,n,s,c,t,r,a),this.processEventHandlersInFragment(o,n,s,t,r),this.processRefsInFragment(o,a),this.processIfChainsInFragment(o,n,s,t,r,a),this.processNestedLoopsInFragment(o,n,s,t,r),a.forEach((e=>{e.__isLoop=!0,this._bindings.push(e)})),{nodes:Array.from(o.childNodes),bindings:a}}processNestedLoopsInFragment(e,t,r,n,s){e.querySelectorAll("template[pp-for]").forEach((e=>{const i=this.parseForExpression(e),o={...this._createScopedPropsContext(r),[t.itemName]:n};t.idxName&&(o[t.idxName]=s);let a=[];try{const e=this.makeScopedEvaluator(i.arrExpr,r)(o);a=Array.isArray(e)?e:[]}catch(e){console.error("Error evaluating nested loop array:",e),a=[]}const c=document.createComment(`pp-for-nested-${i.itemName}`);e.parentNode?.insertBefore(c,e),e.parentNode?.removeChild(e),a.forEach(((t,n)=>{const s=e.content.cloneNode(!0),a={...o,[i.itemName]:t};i.idxName&&(a[i.idxName]=n),this.processTextNodesInNestedFragment(s,i,r,a),this.processElementBindingsInNestedFragment(s,i,r,a),this.processEventHandlersInNestedFragment(s,i,r,t,n);Array.from(s.childNodes).forEach((e=>{c.parentNode?.insertBefore(e,c.nextSibling)}))}))}))}processTextNodesInNestedFragment(e,t,r,n){const s=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);for(;s.nextNode();){const e=s.currentNode,t=e.nodeValue||"";if(PPHP._mustacheTest.test(t)){const s=this.renderMustacheText(t,r,n);e.nodeValue=s}}}processElementBindingsInNestedFragment(e,t,r,n){e.querySelectorAll("*").forEach((e=>{for(const{name:t,value:s}of Array.from(e.attributes))if(PPHP._mustacheTest.test(s)){const i=s.replace(PPHP._mustachePattern,((e,t)=>{try{const e=this.makeScopedEvaluator(t,r);return this.formatValue(e(n))}catch(e){return console.error("PPHP: mustache token error:",t,e),""}}));e.getAttribute(t)!==i&&e.setAttribute(t,i)}for(const{name:t,value:s}of Array.from(e.attributes))if("pp-bind"===t)try{const t=this.makeScopedEvaluator(s,r)(n),i=this.formatValue(t);e.textContent!==i&&(e.textContent=i)}catch(e){console.error("Error processing pp-bind in nested loop:",e)}else if(t.startsWith("pp-bind-")){const i=t.replace(/^pp-bind-/,"");try{const t=this.makeScopedEvaluator(s,r)(n),o=this.formatValue(t);if(this._boolAttrs.has(i)){!!t?e.setAttribute(i,""):e.removeAttribute(i)}else e.setAttribute(i,o)}catch(e){console.error("Error processing pp-bind attribute in nested loop:",e)}}}))}processEventHandlersInNestedFragment(e,t,r,n,s){e.querySelectorAll("*").forEach((e=>{for(const{name:i,value:o}of Array.from(e.attributes)){const a=i.toLowerCase();if(!this._eventHandlers.has(a))continue;let c=o;const l=`globalThis.pphp._getDynamicLoopItem('${this.getItemKey(n,s)}', 'group.fields', ${JSON.stringify(r)})`;if(c=c.replace(new RegExp(`\\b${t.itemName}\\b`,"g"),l),t.idxName){const e=`globalThis.pphp._idxOf(${l}, 'group.fields', ${JSON.stringify(r)})`;c=c.replace(new RegExp(`\\b${t.idxName}\\b`,"g"),e)}e.setAttribute(i,c)}}))}processTextNodesInFragment(e,t,r,n,s,i,o){const a=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);for(;a.nextNode();){const e=a.currentNode,c=e.nodeValue||"";if(PPHP._mustacheTest.test(c)){const a=new Set,l=r.join("."),h=l?`${l}.${t.arrExpr}`:t.arrExpr;a.add(h);for(const e of c.matchAll(PPHP._mustachePattern))this.extractScopedDependencies(e[1],r).forEach((e=>a.add(e)));const d=this.createTextNodeUpdaterWithItemKey(e,c,t,r,n,s);o.push({dependencies:a,update:d}),this.renderTextNode(e,c,t,r,s,i)}}}createTextNodeUpdaterWithItemKey(e,t,r,n,s,i){const o=this.makeScopedEvaluator(r.arrExpr,n);return()=>{const a=o(this._createScopedPropsContext(n));if(Array.isArray(a)){const o=this.findItemByKey(a,s,i),c=a.findIndex((e=>this.getItemKey(e,a.indexOf(e))===s));if(o&&-1!==c){const s={...this._createScopedPropsContext(n),[r.itemName]:o};r.idxName&&(s[r.idxName]=c);const i=this.renderMustacheText(t,n,s);e.nodeValue!==i&&(e.nodeValue=i)}}}}findItemByKey(e,t,r){for(let r=0;r<e.length;r++){const n=e[r];if(this.getItemKey(n,r)===t)return n}return r&&"object"==typeof r&&r.id?e.find((e=>e&&e.id===r.id)):null}processElementBindingsInFragment(e,t,r,n,s,i,o){e.querySelectorAll("*").forEach((e=>{this.processElementBindings(e,t,r,n,s,i,o)}))}processElementBindings(e,t,r,n,s,i,o){const a=new Set,c=new Set;for(const{name:t,value:r}of Array.from(e.attributes))if(PPHP._mustacheTest.test(r)&&!t.startsWith("pp-bind"))a.add(t);else if(t.startsWith("pp-bind-")){const e=t.replace(/^pp-bind-/,"");c.add(e)}for(const{name:c,value:l}of Array.from(e.attributes))if("pp-bind"===c)this.createElementBindingWithItemKey(e,l,"text",t,r,n,s,i,o);else if("pp-bind-expr"===c){const a=this.decodeEntities(l);this.createElementBindingWithItemKey(e,a,"text",t,r,n,s,i,o)}else if(c.startsWith("pp-bind-")){const h=c.replace(/^pp-bind-/,"");if(a.has(h)){if(!this._boolAttrs.has(h))continue;e.removeAttribute(h)}this.createElementBindingWithItemKey(e,l,h,t,r,n,s,i,o)}else PPHP._mustacheTest.test(l)&&this.createElementAttributeTemplateBindingWithItemKey(e,c,l,t,r,n,s,i,o)}createElementAttributeTemplateBindingWithItemKey(e,t,r,n,s,i,o,a,c){const l=new Set,h=s.join("."),d=h?`${h}.${n.arrExpr}`:n.arrExpr;l.add(d);for(const e of r.matchAll(PPHP._mustachePattern))this.extractScopedDependencies(e[1],s).forEach((e=>l.add(e)));const p=this.createAttributeTemplateUpdaterWithItemKey(e,t,r,n,s,i,o);c.push({dependencies:l,update:p}),this.renderAttributeTemplate(e,t,r,n,s,o,a)}createAttributeTemplateUpdaterWithItemKey(e,t,r,n,s,i,o){const a=this.makeScopedEvaluator(n.arrExpr,s);return()=>{const c=a(this._createScopedPropsContext(s));if(Array.isArray(c)){const a=this.findItemByKey(c,i,o),l=c.findIndex((e=>this.getItemKey(e,c.indexOf(e))===i));a&&-1!==l&&this.renderAttributeTemplate(e,t,r,n,s,a,l)}}}renderAttributeTemplate(e,t,r,n,s,i,o){const a={...this._createScopedPropsContext(s),[n.itemName]:i};n.idxName&&(a[n.idxName]=o);const c=r.replace(PPHP._mustachePattern,((e,t)=>{try{const e=this.makeScopedEvaluator(t,s);return this.formatValue(e(a))}catch(e){return console.error("PPHP: mustache token error:",t,e),""}}));e.getAttribute(t)!==c&&e.setAttribute(t,c)}createElementBindingWithItemKey(e,t,r,n,s,i,o,a,c){const l=new Set,h=s.join("."),d=h?`${h}.${n.arrExpr}`:n.arrExpr;l.add(d),this.extractScopedDependencies(t,s).forEach((e=>l.add(e)));const p=this.createElementBindingUpdaterWithItemKey(e,t,r,n,s,i,o);c.push({dependencies:l,update:p}),this.renderElementBinding(e,t,r,n,s,o,a)}createElementBindingUpdaterWithItemKey(e,t,r,n,s,i,o){const a=this.makeScopedEvaluator(n.arrExpr,s);return()=>{const c=a(this._createScopedPropsContext(s));if(Array.isArray(c)){const a=this.findItemByKey(c,i,o),l=c.findIndex((e=>this.getItemKey(e,c.indexOf(e))===i));if(a&&-1!==l){const i={...this._createScopedPropsContext(s),[n.itemName]:a};n.idxName&&(i[n.idxName]=l),this.updateElementBinding(e,t,r,s,i)}}}}getItemKey(e,t){if(e&&"object"==typeof e){if("id"in e&&null!=e.id)return`id_${e.id}`;if("key"in e&&null!=e.key)return`key_${e.key}`;if("_id"in e&&null!=e._id)return`_id_${e._id}`;const t=Object.keys(e).filter((t=>(t.toLowerCase().includes("id")||t.toLowerCase().includes("uuid"))&&null!=e[t]&&("string"==typeof e[t]||"number"==typeof e[t])));if(t.length>0){const r=t[0];return`${r}_${e[r]}`}}return`idx_${t}`}renderTextNode(e,t,r,n,s,i){const o={...this._createScopedPropsContext(n),[r.itemName]:s};r.idxName&&(o[r.idxName]=i),e.nodeValue=this.renderMustacheText(t,n,o)}renderMustacheText(e,t,r){return e.replace(PPHP._mustachePattern,((e,n)=>{try{const e=this.makeScopedEvaluator(n,t);return this.formatValue(e(r))}catch{return""}}))}updateElementBinding(e,t,r,n,s){const i=this.makeScopedEvaluator(t,n)(s);if("text"===r){const t=this.formatValue(i);e.textContent!==t&&(e.textContent=t)}else this.applyAttributeBinding(e,r,i)}renderElementBinding(e,t,r,n,s,i,o){const a={...this._createScopedPropsContext(s),[n.itemName]:i};n.idxName&&(a[n.idxName]=o),this.updateElementBinding(e,t,r,s,a)}applyAttributeBinding(e,t,r){if(this._boolAttrs.has(t)){const n=!!r;n!==e.hasAttribute(t)&&(n?e.setAttribute(t,""):e.removeAttribute(t)),t in e&&e[t]!==n&&(e[t]=n)}else{const n=String(r);t in e&&e[t]!==n&&(e[t]=n),e.getAttribute(t)!==n&&e.setAttribute(t,n)}}processEventHandlersInFragment(e,t,r,n,s){e.querySelectorAll("*").forEach((e=>{const i=this.getItemKey(n,s);for(const{name:n,value:s}of Array.from(e.attributes)){const o=n.toLowerCase();if(!this._eventHandlers.has(o))continue;let a=s;const c=`globalThis.pphp._getDynamicLoopItem('${i}', '${t.arrExpr}', ${JSON.stringify(r)})`;if(a=a.replace(new RegExp(`\\b${t.itemName}\\b`,"g"),c),t.idxName){const e=`globalThis.pphp._idxOf(${c}, '${t.arrExpr}', ${JSON.stringify(r)})`;a=a.replace(new RegExp(`\\b${t.idxName}\\b`,"g"),e)}e.setAttribute(n,a)}}))}_getDynamicLoopItem(e,t,r){try{const n=this.makeScopedEvaluator(t,r)(this._createScopedPropsContext(r));if(!Array.isArray(n))return null;for(let t=0;t<n.length;t++){const r=n[t];if(this.getItemKey(r,t)===e)return r}return null}catch{return null}}_idxOf(e,t,r){try{const n=this.makeScopedEvaluator(t,r)(this._createScopedPropsContext(r));if(!Array.isArray(n))return-1;let s=n.findIndex((t=>t===e));if(-1!==s)return s;const i=this.getItemKey(e,-1);return s=n.findIndex(((e,t)=>this.getItemKey(e,t)===i)),s}catch{return-1}}updateItemNodes(e,t,r,n,s,i){if(t===r)return;if("object"==typeof t&&"object"==typeof r&&JSON.stringify(t)===JSON.stringify(r))return;const o={...this._createScopedPropsContext(i),[s.itemName]:r};s.idxName&&(o[s.idxName]=n),this.updateNodesContent(e,i,o),this.updateConditionalNodes(e,i,o)}updateConditionalNodes(e,t,r){e.forEach((e=>{if(e.nodeType===Node.ELEMENT_NODE){e.querySelectorAll("[pp-if], [pp-elseif], [pp-else]").forEach((e=>{const n=e.getAttribute("pp-if")||e.getAttribute("pp-elseif");if(n){const s=n.replace(/^{\s*|\s*}$/g,"");try{const n=this.makeScopedEvaluator(s,t);!!n(r)?e.removeAttribute("hidden"):e.setAttribute("hidden","")}catch(e){console.error("Error evaluating pp-if condition:",s,e)}}else if(e.hasAttribute("pp-else")){const t=e.previousElementSibling;t&&t.hasAttribute("hidden")?e.removeAttribute("hidden"):e.setAttribute("hidden","")}}))}}))}updateNodesContent(e,t,r){e.forEach((e=>{e.nodeType===Node.ELEMENT_NODE&&this.updateElementContent(e,t,r)}))}updateElementContent(e,t,r){const n=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>{const t=e.nodeValue||"";return t.includes("{{")&&t.includes("}}")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT}});for(;n.nextNode();){const e=n.nextNode(),s=e.nodeValue||"",i=this.renderMustacheText(s,t,r);e.nodeValue!==i&&(e.nodeValue=i)}e.querySelectorAll("*").forEach((e=>{this.updateElementBindingsContent(e,t,r),this.updateElementTemplateAttributes(e,t,r)}))}updateElementTemplateAttributes(e,t,r){for(const{name:n,value:s}of Array.from(e.attributes))if(!n.startsWith("pp-bind")&&PPHP._mustacheTest.test(s)){const i=s.replace(PPHP._mustachePattern,((e,n)=>{try{const e=this.makeScopedEvaluator(n,t);return this.formatValue(e(r))}catch(e){return console.error("PPHP: mustache token error:",n,e),""}}));e.getAttribute(n)!==i&&e.setAttribute(n,i)}}updateElementBindingsContent(e,t,r){for(const{name:n,value:s}of Array.from(e.attributes))if("pp-bind"===n)this.updateElementBinding(e,s,"text",t,r);else if(n.startsWith("pp-bind-")){const i=n.replace(/^pp-bind-/,"");this.updateElementBinding(e,s,i,t,r)}}createLoopUpdater(e,t,r,n,s,i){const o=(()=>{const e=t.arrExpr.split(".")[0];return r=>{if(PPHP._shared.has(e))try{const e=`__shared.${t.arrExpr}`,r=this.getNested(this.props,e);if(Array.isArray(r))return r}catch{}for(let e=s.length;e>=0;e--){const r=s.slice(0,e);try{const e=this.makeScopedEvaluator(t.arrExpr,r),n=e(this._createScopedPropsContext(r));if(Array.isArray(n))return n}catch{}}try{const e=this.makeScopedEvaluator(t.arrExpr,s)(r);return Array.isArray(e)?e:[]}catch{return[]}}})();return()=>{this.performLoopUpdate(e,t,r,n,s,i,o)}}captureFocusState(e){const t=document.activeElement,r=t&&e.contains(t),n=r?t.closest("[key]")?.getAttribute("key"):null;return{active:t,hadFocus:r,focusKey:n,caretPos:r&&t instanceof HTMLInputElement?t.selectionStart:null}}restoreFocusState(e,t){if(e.focusKey){const r=t.querySelector(`[key="${e.focusKey}"]`),n=r?.querySelector("input,textarea");if(n&&(n.focus({preventScroll:!0}),null!==e.caretPos&&n instanceof HTMLInputElement)){const t=Math.min(e.caretPos,n.value.length);n.setSelectionRange(t,t)}}}calculateLoopDiff(e,t){const r=new Map,n=new Map;e.forEach(((e,t)=>{const n=this.getItemKey(e,t);r.set(n,{item:e,index:t})})),t.forEach(((e,t)=>{const r=this.getItemKey(e,t);n.set(r,{item:e,index:t})}));const s=new Set,i=new Map,o=new Map;for(const[e]of r)n.has(e)||s.add(e);for(const[e,{item:t,index:s}]of n)if(r.has(e)){const n=r.get(e);n.item===t&&n.index===s||o.set(e,{oldItem:n.item,newItem:t,newIndex:s,oldIndex:n.index})}else i.set(e,{item:t,index:s});return{toDelete:s,toInsert:i,toUpdate:o}}applyLoopChanges(e,t,r,n,s,i,o){this.applyLoopDeletions(e.toDelete,t),this.applyLoopUpdates(e.toUpdate,t,r,i),this.applyLoopInsertions(e.toInsert,t,r,n,s,i,o)}applyLoopUpdates(e,t,r,n){for(const[s,{oldItem:i,newItem:o,newIndex:a}]of e){const e=t.renderedItems.get(s);e&&(this.updateItemNodes(e.nodes,i,o,a,r,n),e.item=o,e.index=a,e.bindings.forEach((e=>{e.update()})))}}applyLoopInsertions(e,t,r,n,s,i,o){if(0===e.size)return;const a=Array.from(e.entries()).sort((([,e],[,t])=>e.index-t.index));for(const[e,{item:c,index:l}]of a){if(t.renderedItems.has(e)){console.warn(`Item with key ${e} already exists, skipping insertion`);continue}const{nodes:a,bindings:h}=this.createItemNodes(o,c,l,r,i);let d=n;const p=Array.from(t.renderedItems.entries()).map((([e,t])=>({key:e,...t}))).sort(((e,t)=>e.index-t.index));for(let e=p.length-1;e>=0;e--)if(p[e].index<l){d=p[e].nodes[p[e].nodes.length-1];break}a.forEach((e=>{s.insertBefore(e,d.nextSibling),d=e})),t.renderedItems.set(e,{nodes:a,item:c,index:l,bindings:h})}}performLoopUpdate(e,t,r,n,s,i,o){const a=this.captureFocusState(n);let c,l=[];for(let e=s.length;e>=0;e--){const t=s.slice(0,e);try{c=this._createScopedPropsContext(t);const e=o(c);if(Array.isArray(e)&&e.length>=0){l=e;break}}catch(e){console.error("🔥 Debug: Failed to evaluate at hierarchy:",t,e)}}if(!c){c=this._createScopedPropsContext(s);const e=o(c);l=Array.isArray(e)?e:[]}if(!Array.isArray(l))return void console.warn("Loop expression did not return an array:",l);const h=this.calculateLoopDiff(i.previousList,l);this.applyLoopChanges(h,i,t,r,n,s,e),i.previousList=[...l],this.restoreFocusState(a,n),this.attachWireFunctionEvents()}applyLoopDeletions(e,t){for(const r of e){const e=t.renderedItems.get(r);e&&(e.bindings.forEach((e=>{const t=this._bindings.indexOf(e);t>-1&&this._bindings.splice(t,1)})),e.nodes.forEach((e=>{this.cleanupRefsInNode(e),e.parentNode&&e.parentNode.removeChild(e)})),t.renderedItems.delete(r))}}cleanupRefsInNode(e){if(e.nodeType===Node.ELEMENT_NODE){[e,...e.querySelectorAll("[data-ref-key]")].forEach((e=>{for(const[t,r]of this._refs.entries()){const n=r.indexOf(e);n>-1&&(r.splice(n,1),0===r.length&&this._refs.delete(t))}}))}}async initRefs(e=document.body){this.qsa(e,"[pp-ref]").forEach((e=>{const t=e.getAttribute("pp-ref"),r=this._refs.get(t)??[];r.push(e),this._refs.set(t,r),e.removeAttribute("pp-ref")}))}scheduleBindingUpdate(e){this._pendingBindings.add(e),this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this.flushBindings()})))}makeReactive(e,t=[]){if(this.shouldUnwrapValue(e))return e;const r=this._proxyCache.get(e);if(r)return r;if(e instanceof Map||e instanceof Set||"object"!=typeof e||null===e)return e;if(e.__isReactiveProxy)return e;const n=this,s=new Proxy(e,{get(e,r,s){if("__isReactiveProxy"===r)return!0;const i=Reflect.get(e,r,s);if(null===i||"object"!=typeof i)return i;if(Array.isArray(e)&&"string"==typeof r&&n._mutators.has(r)){let o=n._arrayMethodCache.get(e);if(o||(o=new Map,n._arrayMethodCache.set(e,o)),!o.has(r)){const e=i.bind(s),a=t.join("."),c=function(...t){const r=e(...t);return queueMicrotask((()=>{n._bindings.forEach((e=>{const t=n.getBindingType(e);for(const r of e.dependencies)if(n.dependencyMatches(a,r,t)){n.scheduleBindingUpdate(e);break}}))})),r};o.set(r,c)}return o.get(r)}if(null!==i&&"object"==typeof i&&!i.__isReactiveProxy&&!n.shouldUnwrapValue(i))return n.makeReactive(i,[...t,r]);if(Array.isArray(e)&&"function"==typeof i){let t=n._arrayMethodCache.get(e);return t||(t=new Map,n._arrayMethodCache.set(e,t)),t.has(r)||t.set(r,i.bind(e)),t.get(r)}return i},set(e,r,s,i){if("__isReactiveProxy"===r)return!0;let o=s;null===s||"object"!=typeof s||s.__isReactiveProxy||n.shouldUnwrapValue(s)||(o=n.makeReactive(s,[...t,r]));const a=e[r],c=Reflect.set(e,r,o,i);if(a===o)return c;const l=[...t,r].join(".");if(n._dirtyDeps.add(l),l.startsWith("app.")){const e=l.substring(4),t=e.split(".")[0];PPHP._shared.has(t)&&n._dirtyDeps.add(e)}if(Array.isArray(e)&&/^\d+$/.test(String(r))){const e=t.join(".");if(n._dirtyDeps.add(`${e}.*`),e.startsWith("app.")){const t=e.substring(4),r=t.split(".")[0];PPHP._shared.has(r)&&n._dirtyDeps.add(`${t}.*`)}o&&"object"==typeof o&&Object.keys(o).forEach((t=>{if(n._dirtyDeps.add(`${e}.*.${t}`),e.startsWith("app.")){const r=e.substring(4),s=r.split(".")[0];PPHP._shared.has(s)&&n._dirtyDeps.add(`${r}.*.${t}`)}}))}if(t.length>=2&&/^\d+$/.test(t[t.length-1])){const e=t.slice(0,-1).join(".");if(n._dirtyDeps.add(`${e}.*.${String(r)}`),e.startsWith("app.")){const t=e.substring(4),s=t.split(".")[0];PPHP._shared.has(s)&&n._dirtyDeps.add(`${t}.*.${String(r)}`)}}return n._bindings.forEach((e=>{const t=n.getBindingType(e);for(const r of e.dependencies){if(n.dependencyMatches(l,r,t)){n.scheduleBindingUpdate(e);break}if(l.startsWith("app.")){const s=l.substring(4),i=s.split(".")[0];if(PPHP._shared.has(i)&&n.dependencyMatches(s,r,t)){n.scheduleBindingUpdate(e);break}}}})),n._hydrated&&n.scheduleFlush(),c}});return this._proxyCache.set(e,s),s}shouldUnwrapValue(e){return e instanceof Date||e instanceof RegExp||e instanceof Error||e instanceof URLSearchParams||e instanceof URL||e instanceof Promise||e instanceof ArrayBuffer||e instanceof DataView||"object"==typeof e&&null!==e&&e.constructor!==Object&&e.constructor!==Array}getBindingType(e){if(e.__isEffect)return"effect";if(e.__isLoop)return"loop";for(const t of e.dependencies)if(t.includes("*")||t.match(/\.\d+\./)||t.endsWith(".*"))return"loop";for(const t of e.dependencies)try{const e=this.getNested(this.props,t);if(Array.isArray(e))return"loop"}catch{}return"binding"}makeAttrTemplateUpdater(e,t,r,n){let s=this._templateStore.get(e);s||(s=new Map,this._templateStore.set(e,s)),s.has(t)||s.set(t,e.getAttribute(t)||"");const i=n??s.get(t),o=this.detectElementHierarchy(e);return(i.match(this._mustacheRe)||[]).forEach((e=>{const t=e.replace(/^\{\{\s*|\s*\}\}$/g,"");this.extractScopedDependencies(t,o).forEach((e=>r.add(e)))})),()=>{try{const r=i.replace(this._mustacheRe,((e,t)=>{try{const e=this.makeScopedEvaluator(t,o),r=this._createScopedPropsContext(o);return this.formatValue(e(r))}catch(e){return console.error("PPHP: mustache token error:",t,e),""}}));e.getAttribute(t)!==r&&e.setAttribute(t,r)}catch(e){console.error(`PPHP: failed to render attribute "${t}" with template "${i}"`,e)}}}formatValue(e){if(e instanceof Date)return e.toISOString();if("function"==typeof e){if(e.__isReactiveProxy)try{return this.formatValue(e())}catch{}return""}if(e&&"object"==typeof e){if(e.__isReactiveProxy&&"value"in e)try{return this.formatValue(e.value)}catch{return String(e)}if(e.__isReactiveProxy)try{const t={};for(const r in e)if("__isReactiveProxy"!==r&&"__pphp_key"!==r)try{t[r]=e[r]}catch{}return Object.keys(t).length?JSON.stringify(t,null,2):""}catch{return String(e)}try{return JSON.stringify(e,((e,t)=>{if("__isReactiveProxy"!==e&&"__pphp_key"!==e)return t&&"object"==typeof t&&t.__isReactiveProxy?"function"==typeof t&&"value"in t?t.value:"[Reactive Object]":t}),2)}catch{return String(e)}}return null!==e&&"object"==typeof e&&1===Object.keys(e).length&&Object.prototype.hasOwnProperty.call(e,"value")?this.formatValue(e.value):"boolean"==typeof e?e?"true":"false":Array.isArray(e)?e.map((e=>"object"==typeof e&&null!==e?(()=>{try{return JSON.stringify(e)}catch{return String(e)}})():String(e))).join(", "):e?.toString()??""}registerBinding(e,t,r="text",n){if(this._assignmentRe.test(t))return;const s=this.detectElementHierarchy(e),i=this.extractScopedDependencies(t,s),o=this.makeScopedEvaluator(t,s);if("value"===n||"checked"===n){const t=()=>{try{const t=this._createScopedPropsContext(s),r=o(t),i=this.formatValue(r);let a=!1;if("value"===n){const t=e;"value"in e&&t.value!==i?(t.value=i,a=!0):"value"in e||(e.setAttribute("value",i),a=!0)}else{const t=e,r="true"===i;"checked"in e&&t.checked!==r?(t.checked=r,a=!0):"checked"in e||(e.setAttribute("checked",i),a=!0)}if(!a||!this._hydrated||e instanceof HTMLInputElement&&("hidden"===e.type||e.disabled||e.readOnly))return;const c={};this._eventHandlers.forEach((e=>{if(e.startsWith("on")){const t=e.slice(2);c[t]=t}})),c.value="input",c.checked="change";const l=c[n]||n,h="click"===l?new MouseEvent(l,{bubbles:!0,cancelable:!0}):new Event(l,{bubbles:!0});e.dispatchEvent(h)}catch(e){console.error(`Error evaluating attribute "${n}":`,e)}};return void this._bindings.push({dependencies:i,update:t})}if(n){const r=n.toLowerCase();if(this._boolAttrs.has(r)){e.removeAttribute(r);const a=()=>{try{const t=this._createScopedPropsContext(s),i=!!o(t);e[n]!==i&&(e[n]=i),i?e.setAttribute(r,""):e.removeAttribute(r)}catch(e){console.error(`PPHP: error evaluating boolean attribute ${n}="${t}"`,e)}};return void this._bindings.push({dependencies:i,update:a})}const a=e.getAttribute(n)??"";if(this._mustacheRe.test(t)||this._mustacheRe.test(a)){const t=this.makeAttrTemplateUpdater(e,n,i,a);return void this._bindings.push({dependencies:i,update:t})}const c=()=>{try{const t=this._createScopedPropsContext(s),r=o(t),i=this.formatValue(r);n in e&&(e[n]=i),e.setAttribute(n,i)}catch(e){console.error(`Error evaluating attribute ${n}="${t}"`,e)}};return void this._bindings.push({dependencies:i,update:c})}const a={text(e,t){e.textContent!==t&&(e.textContent=t)},value(e,t){e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement?e.value!==t&&(e.value=t):e.setAttribute("value",t)},checked(e,t){e instanceof HTMLInputElement?e.checked="true"===t:e.setAttribute("checked",t)},attr(e,t){e.setAttribute("attr",t)}};this._bindings.push({dependencies:i,update:()=>{try{const t=this._createScopedPropsContext(s),n=o(t),i=this.formatValue(n);a[r](e,i)}catch(e){console.error(`Error evaluating expression "${t}"`,e)}}})}makeSafeEvaluator(e){const t=e.trim(),r=`\n try {\n with (ctx) {\n ${/^\s*[\w.]+\s*=(?!=)/.test(t)?`${t}; return "";`:`return (${t});`}\n }\n } catch {\n return "";\n }\n `;let n;try{n=new Function("ctx",r)}catch(t){const r=JSON.stringify(e);n=new Function("ctx",`try { return ${r}; } catch { return ""; }`)}return e=>{try{const t=n(e);return null==t?"":t}catch{return""}}}makeScopedEvaluator(e,t){const r=e.trim(),n=`\n try {\n with (ctx) {\n ${/^\s*[\w.]+\s*=(?!=)/.test(r)?`${r}; return "";`:`return (${r});`}\n }\n } catch (error) {\n return "";\n }\n `;let s;try{s=new Function("ctx",n)}catch(t){console.error("Expression compilation error:",t.message,"Expression:",r);const n=JSON.stringify(e);s=new Function("ctx",`try { return ${n}; } catch { return ""; }`)}return e=>{try{const r=this._createScopedPropsContext(t,e),n=s(r);return null==n?"":n}catch(e){return""}}}_createScopedPropsContext(e,t={}){const r=e.join("."),n=this.getNested(this.props,r)||{},s=this,i=(e,t)=>{if("function"==typeof e&&e.__isReactiveProxy)try{return e()}catch(r){return console.error(`Failed to unwrap reactive proxy function for ${t}:`,r),e}if(e&&"object"==typeof e&&e.__isReactiveProxy){const n=r?`${r}.${t}`:t;try{const r=n.split(".");let i=s._rawProps;for(const e of r){if(!i||"object"!=typeof i||!(e in i)){i=void 0;break}i=i[e]}if(void 0!==i){if(null===i||"object"!=typeof i)return i;if(Array.isArray(i))return e;try{const t=Object.keys(i);if(t.length>0){const r=t[0];return void 0!==e[r]?e:i}}catch(e){console.warn(`Error testing reactive proxy for ${t}:`,e)}return e}}catch(e){console.warn(`Clean path traversal failed for ${t}:`,e)}if(e&&"object"==typeof e&&"value"in e)return e.value;if("function"==typeof e)try{return e()}catch(e){console.warn(`Failed to call malformed proxy for ${t}:`,e)}return e}return e};return new Proxy(t,{get(t,o,a){if("string"!=typeof o)return Reflect.get(t,o,a);if(o in t){const e=Reflect.get(t,o,a);return i(e,o)}if(PPHP._shared.has(o)){const e=PPHP._shared.get(o);if(e)try{return e.getter()}catch(e){console.warn(`Failed to get shared state for ${o}:`,e)}}const c=s.getScopedFunction(o,e);if(c)return c;const l=r?`${r}.${o}`:o;if(s.hasNested(s.props,l)){const e=s.getNested(s.props,l);return i(e,o)}if(n&&o in n){const e=n[o];return i(e,o)}for(let t=e.length-1;t>=0;t--){const r=e.slice(0,t).join("."),n=s.getScopedFunction(o,e.slice(0,t));if(n)return n;const a=r?s.getNested(s.props,r):s.props;if(a&&o in a){const e=a[o];return i(e,o)}}if(PPHP._shared.has(o)){const e=PPHP._shared.get(o);if(e)try{return e.getter()}catch(e){console.warn(`Failed to get shared state for ${o}:`,e)}}return o in globalThis?globalThis[o]:void 0},set(t,n,i,o){if("string"!=typeof n)return Reflect.set(t,n,i,o);if(n in t)return Reflect.set(t,n,i,o);for(let t=e.length;t>=0;t--){const r=e.slice(0,t).join("."),o=r?`${r}.${n}`:n;if(s.hasNested(s.props,o))return s.setNested(s.props,o,i),s._dirtyDeps.add(o),s.scheduleFlush(),!0}const a=r?`${r}.${n}`:n;return s.setNested(s.props,a,i),s._dirtyDeps.add(a),s.scheduleFlush(),!0},has:(t,i)=>"string"==typeof i&&(i in t||!!s.getScopedFunction(i,e)||s.hasNested(s.props,r?`${r}.${i}`:i)||n&&i in n||PPHP._shared.has(i)||i in globalThis||e.some(((t,r)=>{const n=e.slice(0,r).join("."),o=n?s.getNested(s.props,n):s.props;return o&&i in o}))),ownKeys(t){const i=new Set;Object.keys(t).forEach((e=>i.add(e))),n&&"object"==typeof n&&Object.keys(n).forEach((e=>i.add(e)));const o=r?s.getNested(s.props,r):s.props;o&&"object"==typeof o&&Object.keys(o).forEach((e=>i.add(e)));for(let t=e.length-1;t>=0;t--){const r=e.slice(0,t).join("."),n=r?s.getNested(s.props,r):s.props;n&&"object"==typeof n&&Object.keys(n).forEach((e=>i.add(e)))}return PPHP._shared.forEach(((e,t)=>i.add(t))),Array.from(i)},getOwnPropertyDescriptor(e,t){return"string"!=typeof t?Reflect.getOwnPropertyDescriptor(e,t):this.has(e,t)?{enumerable:!0,configurable:!0,writable:!0}:void 0}})}extractScopedDependencies(e,t){const r=this.extractDependencies(e),n=new Set,s=t.join(".");for(const i of r){if(this._reservedWords.has(i.split(".")[0]))continue;const r=i.split(".")[0];if(new RegExp(`\\b${r}\\s*\\(`).test(e))continue;if(this._sharedStateMap.has(r)){n.add(`__shared.${i}`);continue}const o=s+"."+i;if(this._stateHierarchy.has(o)){n.add(o);continue}if(this.hasNested(this.props,o)){n.add(o);continue}let a=!1;for(let e=t.length-1;e>=0&&!a;e--){const r=t.slice(0,e).join("."),s=r?r+"."+i:i;this._stateHierarchy.has(s)?(n.add(s),a=!0):this.hasNested(this.props,s)&&(n.add(s),a=!0)}if(!a){const e=s+"."+i;n.add(e)}}return n}async processIfChains(e=document.body){const t=new WeakSet;this.qsa(e,"[pp-if]").forEach((e=>{if(t.has(e))return;const r=this.detectElementHierarchy(e),n=[];let s=e;for(;s;){if(s.hasAttribute("pp-if"))n.push({el:s,expr:s.getAttribute("pp-if")});else if(s.hasAttribute("pp-elseif"))n.push({el:s,expr:s.getAttribute("pp-elseif")});else{if(!s.hasAttribute("pp-else"))break;n.push({el:s,expr:null})}t.add(s),s=s.nextElementSibling}n.forEach((e=>{if(null!==e.expr){const t=e.expr.replace(/^{\s*|\s*}$/g,"");e.deps=this.extractScopedDependencies(t,r);const n=this.makeScopedEvaluator(t,r);e.evaluate=()=>{const e=this._createScopedPropsContext(r);return!!n(e)}}}));const i=new Set;n.forEach((e=>e.deps?.forEach((e=>i.add(e)))));this._bindings.push({dependencies:i,update:()=>{let e=!1;for(const{el:t,expr:r,evaluate:s}of n)!e&&null!==r&&s()?(t.removeAttribute("hidden"),e=!0):e||null!==r?t.setAttribute("hidden",""):(t.removeAttribute("hidden"),e=!0)}})}))}async manageAttributeBindings(e=document.body){this.qsa(e,"*").forEach((e=>{const t=new Map;Array.from(e.attributes).forEach((e=>{if(e.name.startsWith("pp-bind"))return;const r=this.decodeEntities(e.value);PPHP._mustacheTest.test(r)&&t.set(e.name.toLowerCase(),r)})),["pp-bind","pp-bind-expr"].forEach((t=>{const r=e.getAttribute(t);r&&this.registerBinding(e,r,"text")})),Array.from(e.attributes).forEach((t=>{const r=t.name.toLowerCase(),n=t.value.trim();this._boolAttrs.has(r)&&!t.name.startsWith("pp-bind-")&&/^[A-Za-z_$][\w$]*$/.test(n)&&(e.removeAttribute(t.name),this.registerBinding(e,n,"text",r))})),Array.from(e.attributes).forEach((r=>{if(!r.name.startsWith("pp-bind-"))return;if(["pp-bind","pp-bind-expr","pp-bind-spread"].includes(r.name))return;const n=r.name.replace(/^pp-bind-/,"").toLowerCase(),s=this.decodeEntities(r.value).replace(/^{{\s*|\s*}}$/g,""),i="value"===n?"value":"checked"===n?"checked":"text";if(t.has(n)){const o=t.get(n).replace(PPHP._mustachePattern,"").trim(),a=o.length>0?`\`${o} \${${s}}\``:s;e.setAttribute(r.name,a);try{const t=this._createScopedPropsContext(this.detectElementHierarchy(e)),r=this.formatValue(this.makeScopedEvaluator(a,this.detectElementHierarchy(e))(t));e.setAttribute(n,r)}catch{}return this.registerBinding(e,a,i,n),void t.delete(n)}this.registerBinding(e,s,i,n)})),Array.from(e.attributes).forEach((t=>{if("pp-bind-spread"!==t.name)return;const r=this.detectElementHierarchy(e),n=this.decodeEntities(t.value).split(",").map((e=>e.trim())).filter(Boolean),s=new Set;n.forEach((e=>this.extractScopedDependencies(e,r).forEach((e=>s.add(e)))));const i=new Set;this._bindings.push({dependencies:s,update:()=>{try{const t={},s=this._createScopedPropsContext(r);n.forEach((e=>Object.assign(t,this.makeScopedEvaluator(e,r)(s)??{}))),i.forEach((r=>{r in t||e.hasAttribute(r)||(e.removeAttribute(r),i.delete(r))})),Object.entries(t).forEach((([t,r])=>{if(!i.has(t)&&e.hasAttribute(t))return;if(null==r||!1===r)return void(i.has(t)&&(e.removeAttribute(t),i.delete(t)));const n="object"==typeof r?JSON.stringify(r):String(r);e.getAttribute(t)!==n&&e.setAttribute(t,n),i.add(t)}))}catch(e){console.error("pp-bind-spread error:",e)}}})})),t.forEach(((t,r)=>{this.registerBinding(e,t,"text",r)}))}))}callInlineModule(e,...t){const r=this._currentProcessingHierarchy||["app"],n=this.getScopedFunction(e,r);if(!n)throw new Error(`PPHP: no inline module named "${e}" in scope ${r.join(".")}`);return n(...t)}getScopedFunction(e,t){if("string"!=typeof e)return null;if(e.startsWith("set")){const t=e.charAt(3).toLowerCase()+e.slice(4);if(PPHP._shared.has(t)){const e=PPHP._shared.get(t);return e?.setter||null}}for(let r=t.length;r>=0;r--){const n=t.slice(0,r).join("."),s=this._inlineModuleFns.get(n);if(s&&s.has(e))return s.get(e)}if(e.startsWith("set")){const r=e.charAt(3).toLowerCase()+e.slice(4);for(let e=t.length;e>=0;e--){const n=t.slice(0,e).join("."),s=n?`${n}.${r}`:r;if(this.hasNested(this.props,s))return e=>{this.setNested(this.props,s,e),this._dirtyDeps.add(s),this.scheduleFlush()}}}return null}async processInlineModuleScripts(e=document.body){this._inlineDepth++;try{const t=Array.from(this.qsa(e,'script[type="text/php"]:not([src])')).filter((e=>!this._processedPhpScripts.has(e)));if(0===t.length)return;const r=t.map((e=>{const t=this.detectComponentHierarchy(e);return{script:e,hierarchy:t,depth:t.length}})).sort(((e,t)=>e.depth-t.depth));for(const{script:e,hierarchy:t}of r){this._currentProcessingHierarchy=t,this._currentEffectContext=t.join(".");const r=t.join(".");let n=(e.textContent||"").trim();n=this.decodeEntities(n),n=this.stripComments(n),n=this.transformStateDeclarations(n),n=this.transformEffectDependencies(n),n=this.injectScopedVariables(n,t);const s=this.extractSetters(n);if(s.length){n+="\n\n";for(const e of s)n+=`pphp._registerScopedFunction('${r}', '${e}', ${e});\n`}n=this.stateDeclarations(n);const i=[];for(const[,e]of[...n.matchAll(/export\s+function\s+([A-Za-z_$]\w*)/g),...n.matchAll(/export\s+const\s+([A-Za-z_$]\w*)/g)])i.push(`pphp._registerScopedFunction('${r}', '${e}', ${e});`);i.length&&(n+="\n\n"+i.join("\n"));const o=new Blob([n],{type:"application/javascript"}),a=URL.createObjectURL(o);try{const e=await import(a);this._inlineModuleFns.has(r)||this._inlineModuleFns.set(r,new Map);const t=this._inlineModuleFns.get(r);for(const[r,n]of Object.entries(e))"function"!=typeof n||t.has(r)||t.set(r,n)}catch(e){console.error("❌ Inline module import failed:",e),console.error("📄 Generated source:",n)}finally{URL.revokeObjectURL(a),this._processedPhpScripts.add(e),this._currentProcessingHierarchy=null}this._currentProcessingHierarchy=null,this._currentEffectContext=null}}finally{this._inlineDepth--,0===this._inlineDepth&&requestAnimationFrame((()=>{this._pendingEffects.forEach((e=>this._effects.add(e))),this._pendingEffects.clear()}))}}transformEffectDependencies(e){let t=e,r=0;for(;;){const e=t.indexOf("pphp.effect(",r);if(-1===e)break;let n=1,s=e+12,i=!1,o="",a=-1;for(;s<t.length&&n>0;){const e=t[s],r=s>0?t[s-1]:"";if(i||'"'!==e&&"'"!==e&&"`"!==e){if(i&&e===o&&"\\"!==r)i=!1,o="";else if(!i)if("("===e||"{"===e||"["===e)n++;else if(")"===e||"}"===e||"]"===e){if(n--,0===n&&")"===e)break}else","===e&&1===n&&-1===a&&(a=s)}else i=!0,o=e;s++}if(0===n&&-1!==a){const n=s,i=t.substring(a+1,n).trim().match(/^\[\s*([^\]]*?)\s*\]$/);if(i){const s=i[1].trim();if(s){const e=`[${this.smartSplitDependencies(s).map((e=>{const t=e.trim();return/^['"`]/.test(t)?e:/^[a-zA-Z_$][a-zA-Z0-9_$]*(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$/.test(t)?`'${t}'`:e})).join(", ")}]`,i=t.substring(0,a+1),o=t.substring(n);t=i+" "+e+o,r=i.length+e.length}else r=e+12}else r=e+12}else r=e+12}return t}smartSplitDependencies(e){if(!e.trim())return[];const t=[];let r="",n=0,s=!1,i="";for(let o=0;o<e.length;o++){const a=e[o],c=o>0?e[o-1]:"";if(s||'"'!==a&&"'"!==a&&"`"!==a?s&&a===i&&"\\"!==c&&(s=!1,i=""):(s=!0,i=a),!s)if("([{".includes(a))n++;else if(")]}".includes(a))n--;else if(","===a&&0===n){r.trim()&&t.push(r.trim()),r="";continue}r+=a}return r.trim()&&t.push(r.trim()),t}stateDeclarations(e){const t="pphp.",r=["state","share"];let n=e;for(const e of r){let r=0;for(;-1!==(r=n.indexOf(`${t}${e}(`,r));){const t=r+5+e.length+1,s=n.slice(t).match(/^(['"])([^'" ]+)\1\s*,/);if(s){const[e]=s;r=t+e.length}else{const e=n.slice(t),s=e.indexOf(",");if(-1===s)break;{const i=`'${e.slice(0,s).trim()}', `;n=n.slice(0,t)+i+n.slice(t),r=t+i.length+s}}}}return n}injectScopedVariables(e,t){const r=this.extractVariableReferences(e),n=this.extractDeclaredVariables(e),s=this.extractStateVariables(e),i=new Set([...n,...s]),o=[],a=new Set;for(const e of r)if(!a.has(e)&&!i.has(e)&&this.hasInScopedContext(e,t)){const r=this.findScopedKeyForVariable(e,t);o.push(`\nconst ${e} = (() => {\n const fn = () => {\n const ctx = globalThis.pphp._createScopedPropsContext(${JSON.stringify(t)});\n return ctx.${e};\n };\n \n fn.__isReactiveProxy = true;\n fn.__pphp_key = '${r}';\n \n Object.defineProperty(fn, 'value', {\n get() {\n const ctx = globalThis.pphp._createScopedPropsContext(${JSON.stringify(t)});\n return ctx.${e};\n },\n configurable: true\n });\n \n fn.valueOf = function() { return this.value; };\n fn.toString = function() { return String(this.value); };\n \n return fn;\n})();`),a.add(e);const n=`set${e.charAt(0).toUpperCase()}${e.slice(1)}`;this.hasInScopedContext(n,t)&&!i.has(n)&&(o.push(`\nconst ${n} = (...args) => {\n const ctx = globalThis.pphp._createScopedPropsContext(${JSON.stringify(t)});\n return ctx.${n}(...args);\n};`),a.add(n))}return o.length>0?o.join("\n")+"\n\n"+e:e}extractStateVariables(e){const t=new Set,r=/\b(?:const|let|var)\s+\[\s*([^,\]]+)(?:\s*,\s*([^,\]]+))?\s*\]\s*=\s*pphp\.state/g;let n;for(;null!==(n=r.exec(e));){const e=n[1]?.trim(),r=n[2]?.trim();e&&t.add(e),r&&t.add(r)}const s=/pphp\.state\s*\(\s*['"]([^'"]+)['"]/g;for(;null!==(n=s.exec(e));){const e=n[1];if(e){t.add(e);const r=`set${e.charAt(0).toUpperCase()}${e.slice(1)}`;t.add(r)}}return t}extractDeclaredVariables(e){const t=new Set;let r=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"").replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g,"");const n=[/\b(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,/\b(?:const|let|var)\s+\[\s*([^\]]+?)\s*\]/g,/\b(?:const|let|var)\s+\{\s*([^}]+?)\s*\}/g,/\bfunction\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,/\bexport\s+function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g,/\b(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*(?:\([^)]*\))?\s*=>/g,/\bexport\s+(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g];for(const e of n){let n;for(;null!==(n=e.exec(r));){const r=n[1]||n[2];if(e.source.includes("\\[")&&!e.source.includes("\\{")){const e=r.split(",").map((e=>e.trim())).filter(Boolean).map((e=>e.startsWith("...")?e.substring(3).trim():e));for(const r of e)/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(r)&&t.add(r)}else if(e.source.includes("\\{")&&!e.source.includes("\\[")){const e=r.split(",").map((e=>e.trim())).filter(Boolean).map((e=>{const t=e.indexOf(":");return-1!==t?e.substring(t+1).trim():e.startsWith("...")?e.substring(3).trim():e}));for(const r of e)/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(r)&&t.add(r)}else r&&t.add(r)}}return t}findScopedKeyForVariable(e,t){const r=t.join("."),n=this.getNested(this.props,r)||{};if(n&&e in n)return`${r}.${e}`;for(let r=t.length-1;r>=0;r--){const n=t.slice(0,r).join("."),s=n?this.getNested(this.props,n):this.props;if(s&&"object"==typeof s&&e in s)return n?`${n}.${e}`:e}return`${r}.${e}`}extractVariableReferences(e){const t=new Set;let r=e.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/.*$/gm," ").replace(/(['"`])(?:\\.|(?!\1)[^\\])*\1/g," ");const n=/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g;let s;for(;null!==(s=n.exec(r));){const e=s[1],n=s.index;if(this._reservedWords.has(e))continue;const i=r.substring(n+e.length,n+e.length+20);if(/^\s*\(/.test(i))continue;const o=r.substring(Math.max(0,n-50),n);/\b(?:const|let|var|function|class|export)\s+$/.test(o)||(n>0&&"."===r[n-1]||/^\s*:/.test(i)||this.isActualFunctionParameter(r,n,e)||this.isInDestructuringDeclaration(r,n,e)||this.shouldSkipVariableInjection(e,r,n)||t.add(e))}return t}shouldSkipVariableInjection(e,t,r){if(this._reservedWords.has(e))return!0;if(new Set(["window","document","console","navigator","location","history","localStorage","sessionStorage","setTimeout","setInterval","clearTimeout","clearInterval","fetch","XMLHttpRequest","Date","Math","JSON","Object","Array","String","Number","Boolean","RegExp","Error","Promise","Map","Set","WeakMap","WeakSet","Symbol","BigInt","Proxy","Reflect","pphp","globalThis","self","top","parent"]).has(e))return!0;if(e.length<=2&&/^[a-z_$][\w$]*$/.test(e))return!0;if(e.startsWith("_"))return!0;const n=t.substring(r+e.length,r+e.length+20);return r>0&&"."===t[r-1]||(!!/^\s*:/.test(n)||!!this.isInDestructuringPattern(t,r))}isInDestructuringPattern(e,t){let r=Math.max(0,t-50),n=e.substring(r,t+20);return[/(?:const|let|var)\s*\{[^}]*$/,/(?:const|let|var)\s*\[[^\]]*$/].some((e=>e.test(n)))}isActualFunctionParameter(e,t,r){let n=-1,s=-1,i=0;for(let r=t-1;r>=0;r--){const t=e[r];if(")"===t)i++;else if("("===t){if(0===i){n=r;break}i--}}if(-1===n)return!1;i=0;for(let n=t+r.length;n<e.length;n++){const t=e[n];if("("===t)i++;else if(")"===t){if(0===i){s=n;break}i--}}if(-1===s)return!1;const o=e.substring(Math.max(0,n-20),n).trim(),a=e.substring(s+1,Math.min(e.length,s+10)).trim(),c=/\bfunction(?:\s+[a-zA-Z_$]\w*)?\s*$/.test(o),l=a.startsWith("=>");if(c||l){const n=e.substring(t+r.length,s);return!n.includes("=>")&&!n.includes("{")}return!1}isInDestructuringDeclaration(e,t,r){const n=e.substring(Math.max(0,t-100),t);if(n.match(/\b(?:const|let|var)\s+\[\s*[^\]]*$/)){const n=e.substring(t+r.length,Math.min(e.length,t+r.length+100));if(/[^\]]*\]\s*=/.test(n))return!0}if(n.match(/\b(?:const|let|var)\s+\{\s*[^}]*$/)){const n=e.substring(t+r.length,Math.min(e.length,t+r.length+100));if(/[^}]*\}\s*=/.test(n))return!0}return!1}hasInScopedContext(e,t){if(this.getScopedFunction(e,t))return!0;for(let r=t.length;r>=0;r--){const n=t.slice(0,r).join("."),s=this._inlineModuleFns.get(n);if(s&&s.has(e))return!0}const r=t.join("."),n=this.getNested(this.props,r)||{};if(n&&e in n)return!0;for(let r=t.length-1;r>=0;r--){const n=t.slice(0,r).join("."),s=n?this.getNested(this.props,n):this.props;if(s&&"object"==typeof s&&e in s)return!0;const i=n?`${n}.${e}`:e;if(this._stateHierarchy.has(i))return!0}return!!PPHP._shared.has(e)}_registerScopedFunction(e,t,r){this._inlineModuleFns.has(e)||this._inlineModuleFns.set(e,new Map);this._inlineModuleFns.get(e).set(t,((...n)=>{const s=this._currentExecutionScope;this._currentExecutionScope=e;try{return t.startsWith("set")&&n.length>0?r(n[0]):r(...n)}finally{this._currentExecutionScope=s}}))}extractSetters(e){const t=[],r=/\[\s*([A-Za-z_$]\w*)\s*,\s*([A-Za-z_$]\w*)\s*\]\s*=\s*pphp\.(state|share)\(/g;let n;for(;n=r.exec(e);){const[,e,r,s]=n;"share"===s&&this.markShared(e),this._sharedStateMap.has(e)||t.push(r)}return t}markShared(e){this._sharedStateMap.add(e)}transformStateDeclarations(e){return e=(e=(e=e.replace(/(\b(?:const|let|var)\s+\[\s*)([A-Za-z_$]\w*)\s*,\s*([A-Za-z_$]\w*)\s*(\]\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,r,n,s)=>`${t}${r}, ${n}${s}'${r}', `))).replace(/(\b(?:const|let|var)\s+\[\s*)([A-Za-z_$]\w*)(\s*\]\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,r,n)=>`${t}${r}${n}'${r}', `))).replace(/(\b(?:const|let|var)\s+)([A-Za-z_$]\w*)(\s*=\s*pphp\.(?:state|share)\s*\(\s*)/g,((e,t,r)=>`${t}[${r}] = pphp.state('${r}', `))}stripComments(e){let t="",r=0,n=!1,s=!1;for(;r<e.length;){const i=e[r],o=e[r+1];if(s||"'"!==i&&'"'!==i&&"`"!==i||"\\"===e[r-1])if(n)t+=i,r++;else if(s||"/"!==i||"*"!==o)if(s)"*"===i&&"/"===o?(s=!1,r+=2):r++;else if("/"!==i||"/"!==o)t+=i,r++;else for(;r<e.length&&"\n"!==e[r];)r++;else s=!0,r+=2;else n=!n,t+=i,r++}return t}flushBindings(){const e=new Set(this._dirtyDeps);this._bindings.forEach((t=>{let r=!1;const n=this.getBindingType(t);for(const s of t.dependencies){for(const t of e)if(this.dependencyMatches(t,s,n)){r=!0;break}if(r)break}if(r)try{t.update()}catch(e){console.error("Binding update error:",e)}})),this._pendingBindings.forEach((e=>{try{e.update()}catch(e){console.error("Pending binding update error:",e)}})),this._pendingBindings.clear(),this._dirtyDeps.clear(),this._updateScheduled=!1,this._effects.forEach((t=>{if(t.__static)return;const r=t.__deps||new Set,n=t.__functionDeps||[];if(0===r.size&&0===n.length){try{t()}catch(e){console.error("effect error:",e)}return}const s=[...r].some((t=>[...e].some((e=>this.dependencyMatches(e,t,"effect"))))),i=n.length>0;if(s||i)try{t()}catch(e){console.error("effect error:",e)}}))}static ARRAY_INTRINSICS=(()=>{const e=new Set(["push","pop","shift","unshift","splice","sort","reverse","copyWithin","fill"]);return new Set(Object.getOwnPropertyNames(Array.prototype).filter((t=>!e.has(t))))})();static headMatch(e,t){return e===t||e.startsWith(t+".")}dependencyMatches(e,t,r="binding"){const n=e=>{if(e.startsWith("__shared."))return e.slice(9);if(e.startsWith("app.")){const t=e.slice(4),r=t.split(".")[0];if(PPHP._shared.has(r))return t}return e},s=n(e),i=n(t);if(s===i||e===t)return!0;if(e.startsWith("__shared.")&&t.startsWith("__shared.")&&e===t)return!0;if(e.startsWith("__shared.")&&t===e.slice(9))return!0;if(t.startsWith("__shared.")&&e===t.slice(9))return!0;const o=i.split(".");if(o.length>1&&PPHP.ARRAY_INTRINSICS.has(o.at(-1))&&PPHP.headMatch(s,o.slice(0,-1).join(".")))return!0;let a=!1;switch(r){case"effect":a=this.matchEffectDependency(s,i);break;case"loop":PPHP.headMatch(s,i)||PPHP.headMatch(i,s)?a=!0:(i.includes("*")||this.matchesArrayIndexPattern(s,i))&&(a=this.matchLoopDependency(s,i));break;default:PPHP.headMatch(s,i)?a=!0:(i.includes("*")||this.matchesArrayIndexPattern(s,i))&&(a=this.matchBindingDependency(s,i))}return a}matchEffectDependency(e,t){if(e===t)return!0;const r=t.startsWith("__shared."),n=e.startsWith("__shared.");if(r&&n){const r=t.substring(9),n=e.substring(9);if(n.startsWith(r+"."))return!0;if(r.startsWith(n+"."))return!0}if(e.startsWith(t+".")){return!e.substring(t.length+1).includes(".")}return!!t.includes("*")&&this.matchesWildcardPattern(e,t)}matchLoopDependency(e,t){return!(!e.startsWith(t+".")&&!t.startsWith(e+"."))||(!(!this.isArrayPath(t)||!this.isArrayItemPath(e,t))||(t.includes("*")?this.matchesWildcardPattern(e,t):this.matchesArrayIndexPattern(e,t)))}isArrayPath(e){try{const t=this.getNested(this.props,e);return Array.isArray(t)}catch{return!1}}isArrayItemPath(e,t){return new RegExp(`^${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\.\\d+($|\\.)`).test(e)}matchBindingDependency(e,t){if(e.startsWith(t+".")){return e.substring(t.length+1).split(".").length<=2}return t.includes("*")?this.matchesWildcardPattern(e,t):this.matchesArrayIndexPattern(e,t)}matchesWildcardPattern(e,t){const r=e.split("."),n=t.split(".");if(r.length!==n.length)return!1;for(let e=0;e<n.length;e++){const t=n[e],s=r[e];if("*"!==t&&t!==s)return!1}return!0}matchesArrayIndexPattern(e,t){const r=e.split("."),n=t.split(".");if(r.length!==n.length)return!1;for(let e=0;e<n.length;e++){const t=r[e],s=n[e];if(t!==s&&(!/^\d+$/.test(t)||!/^\d+$/.test(s)))return!1}return!0}scheduleFlush(){this._updateScheduled||(this._bindingUpdateResetTimeout&&clearTimeout(this._bindingUpdateResetTimeout),this._bindingUpdateResetTimeout=setTimeout((()=>{this._bindingUpdateCount=0}),5e3),this._bindingUpdateCount++,this._bindingUpdateCount>this._maxBindingUpdates?console.error("PPHP: Maximum binding updates exceeded, preventing infinite loop"):(this._updateScheduled=!0,requestAnimationFrame((()=>{this._updateScheduled=!1,this.flushBindings()}))))}getNested(e,t){const r=t.split(".").reduce(((e,t)=>e?e[t]:void 0),e);return r}setNested(e,t,r){const n=t.split("."),s=n.pop(),i=n.reduce(((e,t)=>e[t]??={}),e);try{const e=t.split("."),n=e.pop();let s=this._rawProps;for(const t of e)s[t]&&"object"==typeof s[t]||(s[t]={}),s=s[t];if(r&&"object"==typeof r&&!Array.isArray(r))try{s[n]=JSON.parse(JSON.stringify(r))}catch(e){s[n]={...r}}else s[n]=r}catch(e){console.warn(`Failed to store raw value for ${t}:`,e)}null!==r&&"object"==typeof r?"function"==typeof r&&r.__isReactiveProxy||r.__isReactiveProxy?i[s]=r:i[s]=this.makeReactive(r,n.concat(s)):i[s]=r}hasNested(e,t){const r=t.split(".");let n=e;for(let e=0;e<r.length;e++){const t=r[e];if(null==n||"object"!=typeof n)return!1;if(!(t in n))return!1;n=n[t]}return!0}share(e,t){if("string"!=typeof e||""===e.trim())throw new Error("PPHP.share: key must be a non‑empty string.");if(this._reservedWords.has(e))throw new Error(`'${e}' is reserved – choose another share key.`);const r=PPHP._shared.get(e);if(r)return[r.getter,r.setter];const n=Array.from(this._stateHierarchy.entries()).filter((([t,r])=>r.originalKey===e));n.length>0&&console.warn(`⚠️ PPHP Share Conflict Warning:\n • Creating shared state "${e}"\n • Found existing local state(s) with same key:\n`+n.map((([e,t])=>` - "${e}" (${t.hierarchy.join(" → ")})`)).join("\n")+`\n • Setter "set${e.charAt(0).toUpperCase()}${e.slice(1)}" will prioritize THIS shared state\n • Consider using different variable names to avoid confusion`),this._sharedStateMap.add(e);const s=this._currentProcessingHierarchy;this._currentProcessingHierarchy=["__shared"];const[i,o]=this.state(e,t);this._currentProcessingHierarchy=s;const a=t=>{const r=i(),n="function"==typeof t?t(r):t;o(n);const s=[e,`__shared.${e}`,`app.${e}`];s.forEach((e=>{this._dirtyDeps.add(e)})),n&&"object"==typeof n&&Object.keys(n).forEach((e=>{s.forEach((t=>{this._dirtyDeps.add(`${t}.${e}`)}))})),this.scheduleFlush()};return PPHP._shared.set(e,{getter:i,setter:a}),[i,a]}getShared(e){let t=!1;const r=function(...r){const s=PPHP._shared.get(e);if(s)return s.getter();const i=[`__shared.${e}`,e,`app.${e}`];for(const e of i)if(n.hasNested(n.props,e)){const t=n.getNested(n.props,e);if(void 0!==t)return t}if(!t){t=!0;const r=(t=1)=>{setTimeout((()=>{const s=PPHP._shared.get(e);if(s){n._dirtyDeps.add(e),n._dirtyDeps.add(`__shared.${e}`);const t=s.getter();t&&"object"==typeof t&&Object.keys(t).forEach((t=>{n._dirtyDeps.add(`${e}.${t}`),n._dirtyDeps.add(`__shared.${e}.${t}`)})),n.scheduleFlush()}else t<10&&r(t+1)}),1===t?10:50)};r()}},n=this;r.set=t=>{let s=PPHP._shared.get(e);if(s)return s.setter(t);const i=r(),o="function"==typeof t?t(i):t;n.hasNested(n.props,"__shared")||n.setNested(n.props,"__shared",{});const a=`__shared.${e}`;n.setNested(n.props,a,o),n._dirtyDeps.add(e),n._dirtyDeps.add(a),n._sharedStateMap.add(e),o&&"object"==typeof o&&n.markNestedPropertiesDirty(e,o),n.scheduleFlush()},Object.defineProperties(r,{__isReactiveProxy:{value:!0,writable:!1,enumerable:!1},__pphp_key:{value:`__shared.${e}`,writable:!1,enumerable:!1},valueOf:{value:()=>r(),enumerable:!1},toString:{value:()=>String(r()),enumerable:!1}});return new Proxy(r,{apply:(e,t,r)=>e.apply(t,r),get(t,r,s){if("set"===r||"__isReactiveProxy"===r||"__pphp_key"===r||"valueOf"===r||"toString"===r)return Reflect.get(t,r,s);if("value"===r)return t();if("string"!=typeof r)return Reflect.get(t,r,s);{const s=t();if(s&&"object"==typeof s){let t=s[r];return t&&"object"==typeof t&&!t.__isReactiveProxy&&(t=n.makeReactive(t,["__shared",e,r])),t}}},set(t,r,s){if("set"===r||"__isReactiveProxy"===r||"__pphp_key"===r)return Reflect.set(t,r,s);if("value"===r)return t.set(s),!0;if("string"==typeof r){const i=t();if(i&&"object"==typeof i)i[r]=s,n._dirtyDeps.add(`${e}.${String(r)}`),n._dirtyDeps.add(`__shared.${e}.${String(r)}`),n.scheduleFlush();else{const e={[r]:s};t.set(e)}return!0}return Reflect.set(t,r,s)},has(e,t){if("set"===t||"__isReactiveProxy"===t||"value"===t)return!0;const r=e();return r&&"object"==typeof r&&t in r}})}clearShare=e=>{e?PPHP._shared.delete(e):PPHP._shared.clear()};state(e,t){if("string"!=typeof e||""===e.trim())throw new Error("PPHP.state: missing or invalid key—make sure the build-time injector rewrote your declaration to pphp.state('foo', 0).");if(arguments.length<2&&(t=void 0),this._reservedWords.has(e))throw new Error(`'${e}' is reserved – choose another state key.`);if(PPHP._shared.has(e)){const r=this._currentProcessingHierarchy||["app"],n=this.generateScopedKey(r,e);console.warn(`⚠️ PPHP State Conflict Warning:\n • Shared state "${e}" already exists\n • Creating local state at "${n}"\n • Setter "set${e.charAt(0).toUpperCase()}${e.slice(1)}" will prioritize SHARED state\n • Consider using different variable names to avoid confusion\n • Current shared value:`,PPHP._shared.get(e)?.getter(),"\n • New local value:",t)}const r=this._currentProcessingHierarchy||["app"],n=this.generateScopedKey(r,e);this._stateHierarchy.set(n,{originalKey:e,hierarchy:[...r],level:r.length}),this.hasNested(this.props,n)||this.setNested(this.props,n,t);const s=()=>this.getNested(this.props,n),i=e=>{const t=s(),r="function"==typeof e?e(t):e;this.setNested(this.props,n,r),this._dirtyDeps.add(n),r&&"object"==typeof r&&this.markNestedPropertiesDirty(n,r),this.scheduleFlush()},o=()=>s();Object.defineProperty(o,"value",{get:()=>s(),set:e=>i(e)}),Object.defineProperties(o,{valueOf:{value:()=>s()},toString:{value:()=>String(s())},__isReactiveProxy:{value:!0,writable:!1}}),Object.defineProperty(o,"__pphp_key",{value:n,writable:!1,enumerable:!1,configurable:!1});const a=s();if(null===a||"object"!=typeof a)return[o,i];const c=this;return[new Proxy(o,{apply:(e,t,r)=>Reflect.apply(e,t,r),get(e,t,r){if("value"===t)return s();if("__pphp_key"===t)return n;if("__isReactiveProxy"===t)return!0;if("valueOf"===t||"toString"===t)return Reflect.get(e,t,r);if("string"==typeof t){const r=s();if(r&&"object"==typeof r){const s=Object.prototype.hasOwnProperty.call(r,t),i=t in e&&void 0!==e[t];if(s||!i){let e=r[t];return e&&"object"==typeof e&&!e.__isReactiveProxy&&(e=c.makeReactive(e,[...n.split("."),t])),e}}}if(t in e)return Reflect.get(e,t,r);const i=s();return i&&"object"==typeof i?i[t]:void 0},set(e,t,r){if("value"===t)return i(r),!0;if("__isReactiveProxy"===t)return!0;const o=s();return o&&"object"==typeof o&&(o[t]=r,c._dirtyDeps.add(`${n}.${String(t)}`),c.scheduleFlush()),!0},has(e,t){if("value"===t||"__isReactiveProxy"===t||t in o)return!0;const r=s();return r&&"object"==typeof r&&t in r}}),i]}getState(e){let t=!1;const r=function(...r){const s=n.determineCurrentComponentHierarchy(),i=s.join(".")+"."+e;if(n.hasNested(n.props,i)){const e=n.getNested(n.props,i);if(void 0!==e)return e}for(let t=s.length-1;t>=0;t--){const r=s.slice(0,t),i=r.length>0?r.join(".")+"."+e:e;if(n.hasNested(n.props,i)){const e=n.getNested(n.props,i);if(void 0!==e)return e}}if(PPHP._shared.has(e)){const t=PPHP._shared.get(e);if(t)return t.getter()}if(!t){t=!0;const r=(t=1)=>{setTimeout((()=>{const s=n.determineCurrentComponentHierarchy().join(".")+"."+e;n.hasNested(n.props,s)?(n._dirtyDeps.add(s),n.scheduleFlush()):t<10&&r(t+1)}),1===t?10:50)};r()}},n=this;r.set=t=>{const s=n.determineCurrentComponentHierarchy();let i=null;const o=s.join(".")+"."+e;if(n.hasNested(n.props,o)&&(i=o),!i)for(let t=s.length-1;t>=0;t--){const r=s.slice(0,t),o=r.length>0?r.join(".")+"."+e:e;if(n.hasNested(n.props,o)){i=o;break}}i||(i=o);const a=r(),c="function"==typeof t?t(a):t;n.setNested(n.props,i,c),n._dirtyDeps.add(i),c&&"object"==typeof c&&n.markNestedPropertiesDirty(i,c),n.scheduleFlush()},Object.defineProperties(r,{__isReactiveProxy:{value:!0,writable:!1,enumerable:!1},__pphp_key:{value:e,writable:!1,enumerable:!1},valueOf:{value:()=>r(),enumerable:!1},toString:{value:()=>String(r()),enumerable:!1}});return new Proxy(r,{apply:(e,t,r)=>e.apply(t,r),get(t,r,s){if("set"===r||"__isReactiveProxy"===r||"__pphp_key"===r||"valueOf"===r||"toString"===r)return Reflect.get(t,r,s);if("value"===r)return t();if("string"!=typeof r)return Reflect.get(t,r,s);{const s=t();if(s&&"object"==typeof s){let t=s[r];return t&&"object"==typeof t&&!t.__isReactiveProxy&&(t=n.makeReactive(t,[e,r])),t}}},set(t,r,s){if("set"===r||"__isReactiveProxy"===r||"__pphp_key"===r)return Reflect.set(t,r,s);if("value"===r)return t.set(s),!0;if("string"==typeof r){const i=t();if(i&&"object"==typeof i){i[r]=s;const t=n.determineCurrentComponentHierarchy().join(".")+"."+e;n._dirtyDeps.add(`${t}.${String(r)}`),n.scheduleFlush()}else{const e={[r]:s};t.set(e)}return!0}return Reflect.set(t,r,s)},has(e,t){if("set"===t||"__isReactiveProxy"===t||"value"===t)return!0;const r=e();return r&&"object"==typeof r&&t in r}})}markNestedPropertiesDirty(e,t,r=new WeakSet){t&&"object"==typeof t&&!r.has(t)&&(r.add(t),Object.keys(t).forEach((n=>{const s=`${e}.${n}`;this._dirtyDeps.add(s),this._sharedStateMap.has(e.split(".")[0])&&this._dirtyDeps.add(`__shared.${s}`);const i=t[n];i&&"object"==typeof i&&!r.has(i)&&this.markNestedPropertiesDirty(s,i,r)})))}static _isBuiltIn=(()=>{const e=new Map,t=[Object.prototype,Function.prototype,Array.prototype,String.prototype,Number.prototype,Boolean.prototype,Date.prototype,RegExp.prototype,Map.prototype,Set.prototype,WeakMap.prototype,WeakSet.prototype,Error.prototype,Promise.prototype];return r=>{const n=e.get(r);if(void 0!==n)return n;const s=r in globalThis||t.some((e=>r in e));return e.set(r,s),s}})();extractDependencies(e){const t=e.trim();if(this.isPlainText(t))return new Set;let r=e.replace(/\?\./g,".");const n=new Set,s=/(?:^|[^\w$])(?:\(\s*([^)]*?)\s*\)|([A-Za-z_$][\w$]*))\s*=>/g;for(let e;e=s.exec(r);)(e[1]??e[2]??"").split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>n.add(e)));const i=/function\s*(?:[A-Za-z_$][\w$]*\s*)?\(\s*([^)]*?)\s*\)/g;for(let e;e=i.exec(r);)e[1].split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>n.add(e)));const o=e=>{let t="",r=0;for(;r<e.length;)if("`"===e[r])for(r++;r<e.length;)if("\\"===e[r])r+=2;else if("$"===e[r]&&"{"===e[r+1]){r+=2;let n=1,s=r;for(;r<e.length&&n;)"{"===e[r]?n++:"}"===e[r]&&n--,r++;t+=o(e.slice(s,r-1))+" "}else{if("`"===e[r]){r++;break}r++}else t+=e[r++];return t};r=o(r),r=r.replace(/(['"])(?:\\.|[^\\])*?\1/g,""),r=r.replace(/\/(?:\\.|[^\/\\])+\/[gimsuy]*/g,"");const a=new Set,c=/\b[A-Za-z_$]\w*(?:\.[A-Za-z_$]\w*)*\b/g;for(const t of r.match(c)??[]){const[r,...s]=t.split(".");if(!n.has(r)&&(0!==s.length||!PPHP._isBuiltIn(r)||!new RegExp(`\\.${r}\\b`).test(e))){if(0===s.length&&new RegExp(`\\b${t}\\s*\\(`).test(e)){if(r in globalThis&&"function"==typeof globalThis[r])continue;if(this.isInlineModuleFunction(r))continue;if(this.looksLikeFunctionName(r))continue}a.add(t)}}return a}isInlineModuleFunction(e){for(const[t,r]of this._inlineModuleFns.entries())if(r.has(e))return!0;if(this._currentProcessingHierarchy){const t=this._currentProcessingHierarchy.join("."),r=this._inlineModuleFns.get(t);if(r&&r.has(e))return!0}return!1}looksLikeFunctionName(e){return[/^[a-z][a-zA-Z0-9]*$/,/^[A-Z][a-zA-Z0-9]*$/,/^[a-z_][a-zA-Z0-9_]*$/,/^handle[A-Z]/,/^on[A-Z]/,/^get[A-Z]/,/^set[A-Z]/,/^is[A-Z]/,/^has[A-Z]/,/^can[A-Z]/,/^should[A-Z]/,/^will[A-Z]/].some((t=>t.test(e)))}isPlainText(e){const t=e.trim();if(/^['"`]/.test(t))return!1;return![/[+\-*/%=<>!&|?:]/,/\.\w+/,/\[\s*\w+\s*\]/,/\(\s*[^)]*\s*\)/,/=>/,/\b(true|false|null|undefined|typeof|new|delete|void|in|of|instanceof)\b/,/\?\./,/\?\?/,/\.\.\./,/\{[^}]*\}/,/\[[^\]]*\]/].some((e=>e.test(t)))&&(!!t.includes(" ")&&(!/\w+\.\w+/.test(t)&&!/\w+\[\w+\]/.test(t)))}async initializeAllReferencedProps(e=document.body){const t=PPHP._mustachePattern,r=PPHP._mustacheTest,n=this.props,s=new Set;this.qsa(e,"*").forEach((e=>{const n=this.detectElementHierarchy(e);for(const{name:i,value:o}of Array.from(e.attributes))if(o){if(r.test(o))for(const e of o.matchAll(t))this.extractScopedDependencies(e[1],n).forEach((e=>s.add(e)));("pp-if"===i||"pp-elseif"===i||i.startsWith("pp-bind"))&&this.extractScopedDependencies(o,n).forEach((e=>s.add(e)))}}));const i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>r.test(e.nodeValue??"")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT});for(;;){const e=i.nextNode();if(!e)break;const r=e.parentElement;if(!r)continue;const n=this.detectElementHierarchy(r);for(const r of e.nodeValue.matchAll(t))this.extractScopedDependencies(r[1],n).forEach((e=>s.add(e)))}const o=Array.from(s).sort(((e,t)=>t.split(".").length-e.split(".").length));for(const e of o){const t=e.split("."),r=t[t.length-1];if(this._sharedStateMap.has(r)&&!e.startsWith("__shared."))continue;let s=n;for(let e=0;e<t.length;e++){const r=t[e],n=e===t.length-1,i=t.slice(0,e+1).join(".");if(!(r in s)||!n&&(null==s[r]||"object"!=typeof s[r])){const e=this._stateHierarchy.has(i);n&&e||(s[r]=n?void 0:{})}s=s[r]}}}async dispatchEvent(e,t,r={}){try{if(!e||"string"!=typeof e)return!1;const n=e.split(".")[0];if(e.includes(".")&&PPHP._shared.has(n)){const r=PPHP._shared.get(n);if(r){const s=r.getter();let i=JSON.parse(JSON.stringify(s||{}));const o=e.substring(n.length+1).split(".");let a=i;for(let e=0;e<o.length-1;e++)null==a[o[e]]&&(a[o[e]]={}),a=a[o[e]];const c=o[o.length-1],l=a[c],h="function"==typeof t?t(l):t;a[c]=h,r.setter(i);const d=`__shared.${e}`,p=`__shared.${n}`;return this._dirtyDeps.add(d),this._dirtyDeps.add(e),this._dirtyDeps.add(p),this._dirtyDeps.add(n),this._hydrated&&this.scheduleFlush(),d}}if(PPHP._shared.has(e)){const r=PPHP._shared.get(e);if(r){r.setter(t);const n=`__shared.${e}`;return this._dirtyDeps.add(n),this._dirtyDeps.add(e),this._hydrated&&this.scheduleFlush(),n}}let s=null;this._currentEffectContext&&(s=this._currentEffectContext.split(".")),!s&&r.from instanceof Element&&(s=this.detectElementHierarchy(r.from)),!s&&this._currentEventTarget instanceof Element&&(s=this.detectElementHierarchy(this._currentEventTarget)),s||(s=["app"]);const i=r.scope??"current";let o=s;Array.isArray(i)?o=i.length?i:["app"]:"parent"===i?o=s.slice(0,-1).length?s.slice(0,-1):["app"]:"root"===i||"app"===i?o=["app"]:"current"!==i&&(o=i.split("."));const a=this.resolveStatePath(e,o),c=a?.startsWith("app.")?a:e.startsWith("app.")?e:`${o.join(".")}.${e}`,l=this.hasNested(this.props,c)?this.getNested(this.props,c):void 0,h="function"==typeof t?t(l):t;if(this.setNested(this.props,c,h),this._dirtyDeps.add(c),this._dirtyDeps.add(`${c}.*`),c.startsWith("app.")){const e=c.slice(4),t=e.split(".")[0];PPHP._shared?.has(t)&&(this._dirtyDeps.add(e),this._dirtyDeps.add(`${e}.*`))}return this._hydrated&&this.scheduleFlush(),c}catch(e){return console.error("PPHP.dispatchEvent error:",e),!1}}determineCurrentComponentHierarchy(){const e=this.getEventSourceHierarchy();if(e.length>0)return e;if(this._currentEffectContext)return this._currentEffectContext.split(".");if(this._currentProcessingHierarchy)return[...this._currentProcessingHierarchy];if(this._currentExecutionScope){return this._currentExecutionScope.split(".")}const t=this.getCurrentScriptHierarchy();if(t.length>0)return t;const r=this.getActiveElementHierarchy();return r.length>0?r:["app"]}trackEventContext(e){e.currentTarget instanceof Element&&(this._currentEventTarget=e.currentTarget,this._eventContextStack.push(e.currentTarget),e.currentTarget.setAttribute("data-pphp-recent",Date.now().toString()),setTimeout((()=>{e.currentTarget?.removeAttribute?.("data-pphp-recent")}),1e3),setTimeout((()=>{this._eventContextStack.pop(),0===this._eventContextStack.length?this._currentEventTarget=null:this._currentEventTarget=this._eventContextStack[this._eventContextStack.length-1]}),0))}getEventSourceHierarchy(){try{let e=null;if(this._currentEventTarget&&(e=this._currentEventTarget),!e){const t=document.currentScript;t&&(e=t.closest("[pp-component]"))}if(!e){const t=document.activeElement;if(t instanceof Element){const r=t.closest("[pp-component]");r&&(e=r)}}if(!e){const t=document.querySelectorAll("[data-pphp-recent]");if(t.length>0){const r=Array.from(t).pop();r&&(e=r.closest("[pp-component]"))}}if(e)return this.buildComponentHierarchy(e)}catch(e){console.warn("Error in getEventSourceHierarchy:",e)}return[]}getCurrentScriptHierarchy(){try{const e=document.currentScript;if(e){const t=e.closest("[pp-component]");if(t)return this.buildComponentHierarchy(t)}}catch(e){}return[]}getActiveElementHierarchy(){try{const e=document.activeElement;if(e&&e!==document.body){const t=e.closest("[pp-component]");if(t)return this.buildComponentHierarchy(t)}}catch(e){}return[]}buildComponentHierarchy(e){const t=[];let r=e;for(;r;){const e=r.getAttribute("pp-component");e&&t.unshift(e),r=r.parentElement}return["app",...t]}resolveStatePath(e,t){if(PPHP._shared.has(e))return`__shared.${e}`;if(e.includes(".")&&this.hasNested(this.props,e))return e;const r=e.split(".")[0];if(PPHP._shared.has(r)){const t=`__shared.${e}`;if(this.hasNested(this.props,t))return t}for(let r=t.length-1;r>=0;r--){const n=t.slice(0,r+1).join(".")+"."+e;if(this.hasNested(this.props,n))return n}for(const[t,r]of this._stateHierarchy.entries())if(r.originalKey===e||t.endsWith("."+e))return t;return t.length>1?t.join(".")+"."+e:e}getCurrentComponent(e){let t=null;if(e){if(t=document.querySelector(e),!t)return console.warn(`PPHP: Element with selector "${e}" not found`),null}else{if(this._currentEffectContext){const e=this._currentEffectContext.split(".");return e[e.length-1]}if(this._currentProcessingHierarchy&&this._currentProcessingHierarchy.length>0)return this._currentProcessingHierarchy[this._currentProcessingHierarchy.length-1];if(this._currentExecutionScope){const e=this._currentExecutionScope.split(".");return e[e.length-1]}const e=document.currentScript;if(e&&(t=e),!t){const e=this.determineCurrentComponentHierarchy();if(e.length>1)return e[e.length-1]}}if(t)return this.findComponentFromElement(t);const r=this.getFallbackComponent();return r||null}findComponentFromElement(e){const t=e.getAttribute("pp-component");if(t)return t;let r=e.parentElement;for(;r&&r!==document.documentElement;){const e=r.getAttribute("pp-component");if(e)return e;r=r.parentElement}return console.warn("PPHP: No pp-component attribute found for element or its ancestors",e),null}getFallbackComponent(){if(this._currentEventTarget){const e=this.findComponentFromElement(this._currentEventTarget);if(e)return e}const e=document.querySelector("[data-pphp-recent-interaction]");if(e){const t=this.findComponentFromElement(e);if(t)return t}const t=document.activeElement;if(t instanceof Element){const e=this.findComponentFromElement(t);if(e)return e}return null}getCurrentComponentHierarchy(){return this.determineCurrentComponentHierarchy()}async updateDocumentContent(e){const t=this.saveScrollPositions(),r=(new DOMParser).parseFromString(this.sanitizePassiveHandlers(e),"text/html");this.scrubTemplateValueAttributes(r),this.reconcileHead(r),this.resetProps(),await this.removeAllEventListenersOnNavigation(),this.ensurePageTransitionStyles();const n=async()=>{morphdom(document.body,r.body,{childrenOnly:!0}),await this.initReactiveOn(),this.restoreScrollPositions(t)};"startViewTransition"in document?await document.startViewTransition(n).finished:(await this.fadeOutBody(),await n(),await this.fadeInBody()),document.body.removeAttribute("hidden")}ensurePageTransitionStyles(){if(this._transitionStyleInjected)return;const e=document.createElement("style");e.id="pphp-page-transition-style",e.textContent="\n body.pphp-fade-out { opacity: 0; }\n body.pphp-fade-in { opacity: 1; }\n body.pphp-fade-in,\n body.pphp-fade-out { transition: opacity 0.25s ease; }\n ",document.head.appendChild(e),this._transitionStyleInjected=!0}async fadeOutBody(e=document.body){e.classList.add("pphp-fade-out");const t=e.getAnimations()[0];return t&&t.finished?t.finished.then((()=>{})):new Promise((e=>setTimeout(e,250)))}async fadeInBody(e=document.body){e.classList.remove("pphp-fade-out"),e.classList.add("pphp-fade-in");const t=e.getAnimations()[0];t&&t.finished?await t.finished:await new Promise((e=>setTimeout(e,250))),e.classList.remove("pphp-fade-in")}reconcileHead(e){const t="pp-dynamic-script",r="pp-dynamic-link";document.head.querySelectorAll("[pp-dynamic-meta]").forEach((e=>e.remove())),document.head.querySelectorAll(`[${r}]`).forEach((e=>e.remove())),document.head.querySelectorAll(`[${t}]`).forEach((e=>e.remove())),Array.from(e.head.children).forEach((e=>{switch(e.tagName){case"SCRIPT":if(e.hasAttribute(t)){const t=document.createElement("script");Array.from(e.attributes).forEach((e=>t.setAttribute(e.name,e.value))),t.textContent=e.textContent,document.head.appendChild(t)}break;case"META":{const t=e;if(t.getAttribute("charset")||"viewport"===t.name)break;const r=t.name?`meta[name="${t.name}"]`:`meta[property="${t.getAttribute("property")}"]`,n=t.cloneNode(!0),s=document.head.querySelector(r);s?document.head.replaceChild(n,s):document.head.insertBefore(n,document.head.querySelector("title")?.nextSibling||null);break}case"TITLE":{const t=e.cloneNode(!0),r=document.head.querySelector("title");r?document.head.replaceChild(t,r):document.head.appendChild(t);break}case"LINK":{const t=e;if("icon"===t.rel){const e=t.cloneNode(!0),r=document.head.querySelector('link[rel="icon"]');r?document.head.replaceChild(e,r):document.head.appendChild(e)}else t.hasAttribute(r)&&document.head.appendChild(t.cloneNode(!0));break}}}))}scrubTemplateValueAttributes(e){e.querySelectorAll('input[value*="{{"], textarea[value*="{{"], select[value*="{{"],[checked*="{{"], [selected*="{{"]').forEach((e=>{e.hasAttribute("value")&&e.removeAttribute("value"),e.hasAttribute("checked")&&e.removeAttribute("checked"),e.hasAttribute("selected")&&e.removeAttribute("selected")}))}restoreScrollPositions(e){requestAnimationFrame((()=>{const t=e.window;t&&window.scrollTo(t.scrollLeft,t.scrollTop),document.querySelectorAll("*").forEach((t=>{const r=this.getElementKey(t);e[r]&&(t.scrollTop=e[r].scrollTop,t.scrollLeft=e[r].scrollLeft)}))}))}PRESERVE_HANDLERS={DETAILS:(e,t)=>(t.open=e.open,!0),INPUT(e,t){const r=e,n=t;return r.value!==n.value&&(n.value=r.value),n.checked=r.checked,document.activeElement!==r||(null!=r.selectionStart&&(n.selectionStart=r.selectionStart,n.selectionEnd=r.selectionEnd),!1)},TEXTAREA(e,t){const r=e,n=t;return r.value!==n.value&&(n.value=r.value),document.activeElement!==r||(n.selectionStart=r.selectionStart,n.selectionEnd=r.selectionEnd,!1)},SELECT(e,t){const r=e;return t.selectedIndex=r.selectedIndex,document.activeElement!==r},VIDEO(e,t){const r=e,n=t;return n.currentTime=r.currentTime,r.paused?n.pause():n.play(),!0},AUDIO:(e,t)=>this.PRESERVE_HANDLERS.VIDEO(e,t),CANVAS:()=>!1};async populateDocumentBody(e){try{const t=document.body,r=e instanceof Document?e.body:e;this._wheelHandlersStashed||(document.querySelectorAll("[onwheel]").forEach((e=>{const t=e.getAttribute("onwheel").trim();if(e.removeAttribute("onwheel"),t){const r=new Function("event",t);e.addEventListener("wheel",r,{passive:!0})}})),this._wheelHandlersStashed=!0);const n=this.PRESERVE_HANDLERS;morphdom(t,r,{getNodeKey(e){if(e.nodeType!==Node.ELEMENT_NODE)return;const t=e;return t.hasAttribute("pp-sync-script")?`pp-sync-script:${t.getAttribute("pp-sync-script")}`:t.getAttribute("key")||void 0},onBeforeElUpdated(e,t){const r=e.tagName;if("SCRIPT"===r||e.hasAttribute("data-nomorph"))return!1;const s=n[r];return!s||s(e,t)},onBeforeNodeDiscarded:e=>(e instanceof HTMLElement&&e.dataset.timerId&&clearTimeout(Number(e.dataset.timerId)),!0)})}catch(e){console.error("Error populating document body:",e)}}saveScrollPositions(){const e={window:{scrollTop:window.scrollY||document.documentElement.scrollTop,scrollLeft:window.scrollX||document.documentElement.scrollLeft}};return document.querySelectorAll("*").forEach((t=>{(t.scrollTop||t.scrollLeft)&&(e[this.getElementKey(t)]={scrollTop:t.scrollTop,scrollLeft:t.scrollLeft})})),e}getElementKey(e){return e.id||e.className||e.tagName}async attachWireFunctionEvents(e=document.body){this.handleHiddenAttribute(),this.handleAnchorTag();const t=Array.from(this._eventHandlers).map((e=>`[${e}]`)).join(",");if(!t)return;const r=this.qsa(e,t);for(const e of r)for(const t of this._eventHandlers){const r=e.getAttribute(t);if(!r)continue;const n=this.decodeEntities(r).trim();if(!n){e.removeAttribute(t);continue}const s=`(event) => { ${this.unwrapArrowBody(this.buildHandlerFromRawBody(n))} }`;e.removeAttribute(t);const i=t.slice(2);e instanceof HTMLInputElement&&this.handleInputAppendParams(e,i),this.handleDebounce(e,i,s)}this.handlePassiveWheelStashes(e instanceof Document?e:document)}decodeEntities=e=>{const t=document.createElement("textarea");t.innerHTML=e;let r=t.value;for(;r.includes("&");){t.innerHTML=r;const e=t.value;if(e===r)break;r=e}return r};unwrapArrowBody=e=>{if(!e.trim())return"";const t=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>\s*\{([\s\S]*)\}\s*$/);if(t){let e=t[1].trim();return e&&!e.endsWith(";")&&(e+=";"),e}const r=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>\s*/);if(r){let t=e.substring(r[0].length).trim();return t&&!t.endsWith(";")&&(t+=";"),t}let n=e.trim();return n&&!n.endsWith(";")&&(n+=";"),n};buildHandlerFromRawBody(e){let t=e.trim();t=t.replace(/([A-Za-z_$][\w$]*)->([A-Za-z_$][\w$]*)\s*\(\s*([^)]*?)\s*\)/g,((e,t,r,n)=>{const s=`${t}->${r}(${n.trim()})`;return`await pphp.handleParsedCallback(this, ${JSON.stringify(s)}, event);`})),t=t.replace(/([A-Za-z_$][\w$]*)::([A-Za-z_$][\w$]*)\s*\(\s*([^)]*?)\s*\)/g,((e,t,r,n)=>{const s=`${t}::${r}(${n.trim()})`;return`await pphp.handleParsedCallback(this, ${JSON.stringify(s)}, event);`}));const{normalized:r,originalParam:n}=this.normalizeToArrow(t),s=this.renameEventParam(r,n);return this.replaceThisReferences(s)}replaceThisReferences(e){return e.replace(/\bthis\./g,"event.target.")}normalizeToArrow(e){const t=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>/);if(!t)return{normalized:`() => { ${e} }`,originalParam:null};const r=t[0].replace(/\s*=>\s*$/,"").trim().replace(/^\(|\)$/g,"").trim();return{normalized:e,originalParam:/^[A-Za-z_$]\w*$/.test(r)?r:null}}renameEventParam(e,t){if(!t||"event"===t)return e;const r=new RegExp(`\\b${this.escapeRegex(t)}\\b`,"g");return e.replace(r,((e,t,r)=>{const n=r[t-1],s=r[t+e.length];return n&&/[\w$]/.test(n)||s&&/[\w$]/.test(s)?e:"event"}))}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async handleDebounce(e,t,r){const n=e.getAttribute("pp-debounce"),s=n?this.parseTime(n):0,i=e.getAttribute("pp-before-request")??"",o=e.getAttribute("pp-after-request")??"",a=PPHP._cancelableEvents,c=async n=>{a.has(t)&&n.cancelable&&n.preventDefault();try{i&&await this.invokeHandler(e,i,n),await this.invokeHandler(e,r,n),o&&!o.startsWith("@close")&&await this.invokeHandler(e,o,n)}catch(e){console.error("Error in debounced handler:",e)}},l={passive:PPHP._passiveEvents.has(t)&&!a.has(t)},h=`${t}::${e.__pphpId||e.tagName}`,d=e=>{if(s>0){const t=PPHP._debounceTimers.get(h);t&&clearTimeout(t);const r=setTimeout((()=>{PPHP._debounceTimers.delete(h),c(e)}),s);PPHP._debounceTimers.set(h,r)}else c(e)};e instanceof HTMLFormElement&&"submit"===t?e.addEventListener("submit",(e=>{e.cancelable&&e.preventDefault(),d(e)}),l):e.addEventListener(t,d,l)}debounce(e,t=300,r=!1){let n;return function(...s){const i=this;n&&clearTimeout(n),n=setTimeout((()=>{n=null,r||e.apply(i,s)}),t),r&&!n&&e.apply(i,s)}}async invokeHandler(e,t,r){const n=this._currentProcessingElement;this._currentProcessingElement=e;try{const n=t.trim();let s=this._handlerCache.get(n);s||(s=this.parseHandler(n),this._handlerCache.set(n,s)),await this.executeHandler(s,e,r,n)}catch(r){this.handleInvokeError(r,t,e)}finally{this._currentProcessingElement=n,this.scheduleFlush()}}parseHandler(e){const t=e.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").trim();if(this.isArrowFunction(t))return this.parseArrowFunction(t);const r=t.match(/^(\w+(?:\.\w+)*)\s*\(\s*(.*?)\s*\)$/s);if(r)return{type:"call",name:r[1],args:r[2],isAsync:this.isAsyncFunction(r[1])};const n=t.match(/^(\w+)$/);return n?{type:"simple",name:n[1],isAsync:this.isAsyncFunction(n[1])}:{type:"complex",body:t,isAsync:!1}}isArrowFunction(e){let t=!1,r="",n=0;for(let s=0;s<e.length-1;s++){const i=e[s],o=e[s+1];if(t||'"'!==i&&"'"!==i&&"`"!==i){if(t&&i===r&&"\\"!==e[s-1])t=!1,r="";else if(!t&&("("===i&&n++,")"===i&&n--,"="===i&&">"===o&&n>=0))return!0}else t=!0,r=i}return!1}parseArrowFunction(e){const t=this.findArrowIndex(e);let r=e.substring(t+2).trim();return r.startsWith("{")&&r.endsWith("}")&&(r=r.slice(1,-1).trim()),{type:"arrow",body:r,isAsync:e.includes("async")||this.containsAwait(r)}}findArrowIndex(e){let t=!1,r="";for(let n=0;n<e.length-1;n++){const s=e[n],i=e[n+1];if(t||'"'!==s&&"'"!==s&&"`"!==s){if(t&&s===r&&"\\"!==e[n-1])t=!1;else if(!t&&"="===s&&">"===i)return n}else t=!0,r=s}return-1}async executeArrowHandler(e,t,r){const n=this.parseStatements(e.body);let s=!1;for(const e of n)await this.executeSingleStatement(e,t,r)&&(s=!0);s||await this.executeDynamic(e.body,t,r)}async executeComplexHandler(e,t,r){await this.executeDynamic(e.body,t,r)}parseStatements(e){const t=[];let r="",n=0,s=!1,i="";for(let o=0;o<e.length;o++){const a=e[o];s||'"'!==a&&"'"!==a&&"`"!==a?s&&a===i&&"\\"!==e[o-1]&&(s=!1,i=""):(s=!0,i=a),s||("("!==a&&"{"!==a&&"["!==a||n++,")"!==a&&"}"!==a&&"]"!==a||n--,";"!==a||0!==n)?r+=a:r.trim()&&(t.push(r.trim()),r="")}return r.trim()&&t.push(r.trim()),t}async executeInlineModule(e,t,r,n,s){if(t&&t.trim())if(this.isJsonLike(t)){const r=this.parseJson(t);null!==r&&"object"==typeof r?await this.callInlineModule(e,{...r}):await this.callInlineModule(e,r)}else try{const n=this.detectElementHierarchy(r),s=this._createScopedPropsContext(n),i=this.makeScopedEvaluator(t,n)(s);await this.callInlineModule(e,i)}catch{await this.callInlineModule(e,{element:r,event:n})}else await this.handleParsedCallback(r,s,n)}async executeSingleStatement(e,t,r){const n=e.trim();if(!n)return!1;const s=n.match(/^\(\s*\)\s*=>\s*(.+)$/);if(s)return this.executeSingleStatement(s[1],t,r);if(/^\s*(if|for|while|switch|try|return|throw|var|let|const|function|class)\b/.test(n))return await this.executeDynamic(n,t,r),!0;const i=n.match(/^(\w+)\s*\(\s*(.*?)\s*\)$/s);if(i){const[,e,s]=i,o=this.detectElementHierarchy(t),a=this.resolveFunctionName(e,o);let c=[];if(""!==s.trim())try{c=JSON5.parse(`[${s}]`)}catch{try{const e=this._createScopedPropsContext(o),t=this.getOrCreateProxy(e),n=/\bevent\b/.test(s)?s.replace(/\bevent\b/g,"_evt"):s;c=new Function("_evt","proxy","props",`with (proxy) { return [ ${n} ]; }`)(r,t,e)}catch(e){c=[]}}if(a){const e=this.getScopedFunction(a,o);if(e)return c.length>0?await e(...c):await this.executeInlineModule(a,s,t,r,n),!0}if(a){const e=globalThis[a];if("function"==typeof e)return e.apply(globalThis,c),!0}return await this.handleParsedCallback(t,n,r),!0}const o=n.match(/^(\w+)$/);if(o){const e=o[1],n=this.detectElementHierarchy(t),s=this.resolveFunctionName(e,n);if(s){if(this.getScopedFunction(s,n))return await this.handleParsedCallback(t,`${s}()`,r),!0}if(s){const e=globalThis[s];if("function"==typeof e)return e.call(globalThis,r),!0}return await this.handleParsedCallback(t,`${e}()`,r),!0}return await this.executeDynamic(n,t,r),!0}async executeCallHandler(e,t,r,n){const{name:s,args:i}=e,o=this.detectElementHierarchy(t),a=this.resolveFunctionName(s,o);if(a){if(this.getScopedFunction(a,o))return void await this.executeInlineModule(a,i||"",t,r,n);const e=globalThis[a];if("function"==typeof e)return void await this.executeGlobalFunction(e,i||"",t,r)}await this.handleParsedCallback(t,n,r)}resolveFunctionName(e,t){if(e.startsWith("set")){const t=e.charAt(3).toLowerCase()+e.slice(4);if(PPHP._shared.has(t))return e}if(t)for(let r=t.length;r>=0;r--){const n=t.slice(0,r).join("."),s=this._inlineModuleFns.get(n);if(s&&s.has(e))return e}return"function"==typeof globalThis[e]?e:null}async executeSimpleHandler(e,t,r){const{name:n}=e,s=this.detectElementHierarchy(t),i=this.resolveFunctionName(n,s);if(i){if(this.getScopedFunction(i,s))return void await this.handleParsedCallback(t,`${i}()`,r);const e=globalThis[i];if("function"==typeof e)return void e.call(globalThis,r)}await this.handleParsedCallback(t,`${n}()`,r)}async executeHandler(e,t,r,n){switch(e.type){case"arrow":await this.executeArrowHandler(e,t,r);break;case"call":await this.executeCallHandler(e,t,r,n);break;case"simple":await this.executeSimpleHandler(e,t,r);break;case"complex":await this.executeComplexHandler(e,t,r);break;default:await this.handleParsedCallback(t,n,r)}}async executeGlobalFunction(e,t,r,n){if(t.trim())if(this.isJsonLike(t)){const r=this.parseJson(t)??{};e.call(globalThis,{...r})}else{const s=this.detectElementHierarchy(r),i=this._createScopedPropsContext(s),o=this.getOrCreateProxy(i);new Function("event","proxy","props","fn",`with (proxy) { return fn(${t}); }`).call(r,n,o,i,e)}else e.call(globalThis,n)}async executeDynamic(e,t,r){const n=this.detectElementHierarchy(t),s=this._createScopedPropsContext(n),i=this.getOrCreateProxy(s),o=new PPHP.AsyncFunction("event","proxy","props",`\n with (proxy) {\n ${e}\n }`);try{await o.call(t,r,i,s)}finally{this.scheduleFlush()}}static AsyncFunction=Object.getPrototypeOf((async()=>{})).constructor;getOrCreateEvaluator(e){let t=this._evaluatorCache.get(e);return t||(t=this.makeSafeEvaluator(e),this._evaluatorCache.set(e,t)),t}getOrCreateProxy(e){let t=this._handlerProxyCache.get(e);return t||(t=this.createHandlerProxy(e),this._handlerProxyCache.set(e,t)),t}createHandlerProxy(e){const t=this._currentProcessingHierarchy||["app"],r={alert:window.alert.bind(window),confirm:window.confirm.bind(window),prompt:window.prompt.bind(window),console:window.console,setTimeout:window.setTimeout.bind(window),setInterval:window.setInterval.bind(window),clearTimeout:window.clearTimeout.bind(window),clearInterval:window.clearInterval.bind(window),fetch:window.fetch.bind(window)};return new Proxy(e,{get:(e,n,s)=>{if("string"==typeof n){if(r.hasOwnProperty(n))return r[n];const i=this.getScopedFunction(n,t);if(i)return i;if(n in e){const t=Reflect.get(e,n,s),r=globalThis[n];if(!(null==t||"object"==typeof t&&0===Object.keys(t).length||PPHP._isBuiltIn(n)&&typeof t!=typeof r))return t}if(n in globalThis&&!r.hasOwnProperty(n)){const e=globalThis[n];return"function"==typeof e&&/^[a-z]/.test(n)?e.bind(globalThis):e}}return Reflect.get(e,n,s)},set:(e,t,r,n)=>Reflect.set(e,t,r,n),has:(e,t)=>{if("string"==typeof t){const n=this._currentProcessingHierarchy||["app"];return r.hasOwnProperty(t)||!!this.getScopedFunction(t,n)||t in e||t in globalThis}return t in e||t in globalThis}})}isAsyncFunction(e){const t=this._inlineModuleFns.get(e)||globalThis[e];return t&&("AsyncFunction"===t.constructor.name||t.toString().includes("async "))}containsAwait(e){return/\bawait\s+/.test(e)}handleInvokeError(e,t,r){const n=e instanceof Error?e.message:String(e),s=r.tagName+(r.id?`#${r.id}`:"");console.error(`Handler execution failed on ${s}:\nHandler: "${t}"\nError: ${n}`,e),r.dispatchEvent(new CustomEvent("pphp:handler-error",{detail:{handler:t,error:e,element:r},bubbles:!0}))}async handleParsedCallback(e,t,r){const{funcName:n,data:s}=this.parseCallback(e,t);if(!n)return;const i=Array.isArray(n)?n:[n],o=this.detectElementHierarchy(e);let a;for(const e of i){const t=this.resolveLocalFunction(e,o);if(t){a=t;break}}if(a){const t=e.hasAttribute("pp-after-request"),n="@close"===e.getAttribute("pp-after-request");let o={args:Array.isArray(s.args)?s.args:[],element:e,data:s,event:r};if(t&&!n){const e=this._responseData?this.parseJson(this._responseData):{response:this._responseData};o={...o,...e}}try{return void await a.call(this,o)}catch(e){return void console.error(`❌ Error executing function ${i[0]}:`,e)}}this.shouldCallServer(i[0],o)?(this._responseData=null,this._responseData=await this.handleUndefinedFunction(e,Array.isArray(n)?n[0]:n,s)):console.warn(`⚠️ Function ${i[0]} not found and not calling server`)}shouldCallServer(e,t){return!!!this.resolveLocalFunction(e,t)}resolveLocalFunction(e,t){const r=this.getScopedFunction(e,t);if(r)return r;for(const[,t]of this._inlineModuleFns.entries())if(t.has(e))return t.get(e);return"function"==typeof this[e]?this[e]:"function"==typeof window[e]?window[e]:void 0}async handleUndefinedFunction(e,t,r){if(this.isCircuitOpen(t))return console.warn(`PPHP: Circuit breaker open for function ${t}, skipping server call`),this.restoreSuspenseElement(e),null;if(this.shouldThrottleRequest(t))return console.warn(`PPHP: Request to ${t} throttled, too many recent calls`),this.restoreSuspenseElement(e),null;const n=new AbortController,s=setTimeout((()=>{console.warn(`PPHP: Request to ${t} timed out`),n.abort()}),1e4);try{const i={callback:await this.encryptCallbackName(t),...r},o={...this.createFetchOptions(i),signal:n.signal},a={...this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()}),signal:n.signal};try{this.saveElementOriginalState(e),this.handleSuspenseElement(e);const n=new URL(window.location.href);let i="",c="",l={success:!1};const h=e.querySelector("input[type='file']");if(h)try{if(i=await this.fetchFileWithData(n.href,t,h,r),c=this.extractJson(i)||"",c)try{l=this.parseJson(c),l||(l={success:!1})}catch(e){console.error(`PPHP: Error parsing JSON response for ${t}:`,e),l={success:!1}}}catch(r){return console.error(`PPHP: File upload failed for ${t}:`,r),this.recordError(t),this.restoreSuspenseElement(e),null}else try{const e=await this.fetch(n.href,o);if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);i=await e.text();const r=this.getRedirectUrl(i);if(r)return clearTimeout(s),await this.redirect(r),i;if(c=this.extractJson(i)||"",c)try{l=this.parseJson(c),l&&"object"==typeof l||(l={success:!1})}catch(e){console.error(`PPHP: Error parsing JSON response for ${t}:`,e),console.log("Raw JSON string:",c.substring(0,200)),l={success:!1}}}catch(r){return r instanceof Error&&"AbortError"===r.name?console.warn(`PPHP: Request for ${t} was aborted (timeout)`):console.error(`PPHP: Network error calling ${t}:`,r),this.recordError(t),this.restoreSuspenseElement(e),clearTimeout(s),null}clearTimeout(s);const d=e.getAttribute("pp-before-request")||"",p=e.getAttribute("pp-after-request")||"";if((d||p&&l.success)&&this.restoreSuspenseElement(e),d||p)try{let e="";if(l.success){e=i.replace(c,"")}else e=i;if(this.appendAfterbegin(e),!p&&!l.success)return i}catch(e){console.error(`PPHP: Error appending content for ${t}:`,e)}if(p&&l.success)try{this.handleAfterRequest(p,c);const e=i.replace(c,"");return this.appendAfterbegin(e),c}catch(e){return console.error(`PPHP: Error handling after-request for ${t}:`,e),c}if("@close"===p)return l.success?c:null;try{const e=await this.fetch(n.href,a);if(!e.ok)throw new Error(`Second request failed: HTTP ${e.status}`);const t=await e.text(),r=this.getRedirectUrl(t);return r?(await this.redirect(r),t):(await this.handleResponseRedirectOrUpdate(i,t,c,l),i)}catch(e){if(console.error(`PPHP: Second request failed for ${t}:`,e),this.recordError(t),i)try{return await this.updateBodyContent(i),i}catch(e){console.error("PPHP: Failed to update with first response:",e)}return null}}catch(r){return console.error(`PPHP: Encryption/setup error for ${t}:`,r),this.recordError(t),this.restoreSuspenseElement(e),clearTimeout(s),null}}catch(r){clearTimeout(s),this.recordError(t),this.restoreSuspenseElement(e),console.error(`PPHP: Unhandled error in ${t}:`,r);try{this.restoreSuspenseElement(e)}catch(e){console.error("PPHP: Failed to restore element state:",e)}return null}}isCircuitOpen(e){return(this._errorCounts.get(e)||0)>=this._maxErrorsPerFunction}recordError(e){const t=this._errorCounts.get(e)||0;this._errorCounts.set(e,t+1),setTimeout((()=>{this._errorCounts.delete(e)}),this._errorResetTimeout)}shouldThrottleRequest(e){const t=Date.now();return t-(this._lastRequestTime.get(e)||0)<this._requestThrottleMs||(this._lastRequestTime.set(e,t),!1)}handleAfterRequest(e,t){if(!this.isJsonLike(e))return;const r=this.parseJson(e),n=t?this.parseJson(t):null,s=r.targets;Array.isArray(s)&&s.forEach((e=>{const{id:t,...r}=e,s=document.querySelector(t);let i={};if(n){for(const t in r)if(r.hasOwnProperty(t))switch(t){case"innerHTML":case"outerHTML":case"textContent":case"innerText":"response"===r[t]&&(i[t]=e.responseKey?n[e.responseKey]:n.response);break;default:i[t]=r[t]}}else i=r;s&&this.updateElementAttributes(s,i)}))}sanitizePassiveHandlers(e){return e.replace(/\s+onwheel\s*=\s*(['"])([\s\S]*?)\1/gi,((e,t,r)=>` data-onwheel-code="${this.decodeEntities(r).replace(/"/g,""")}"`)).replace(/\s+onmousewheel\s*=\s*(['"])[\s\S]*?\1/gi,"")}handlePassiveWheelStashes(e){(e instanceof Document?e.body:e).querySelectorAll("[data-onwheel-code]").forEach((e=>{const t=this.decodeEntities(e.dataset.onwheelCode||"").trim();delete e.dataset.onwheelCode,e.onwheel=null,t&&(e.removeAllEventListeners("wheel"),this.handleDebounce(e,"wheel",t))}))}async handleResponseRedirectOrUpdate(e,t,r,n){const s=this.sanitizePassiveHandlers(t),i=this.getUpdatedHTMLContent(e,r,n),o=(new DOMParser).parseFromString(s,"text/html");i&&o.body.insertAdjacentElement("afterbegin",i),this.updateBodyContent(o.body.outerHTML)}getUpdatedHTMLContent(e,t,r){const n=document.createElement("div");if(n.id="afterbegin-8D95D",r&&t?.success){const t=e.replace(r,"");n.innerHTML=t}else n.innerHTML=e;return n.innerHTML?n:null}async updateBodyContent(e){try{const t=this.saveScrollPositions();this.saveElementState();const r=(new DOMParser).parseFromString(e,"text/html");this.scrubTemplateValueAttributes(r),await this.appendCallbackResponse(r),await this.populateDocumentBody(r),await this.removeAllEventListenersOnNavigation(),await this.initReactiveOn(),this.restoreScrollPositions(t),document.body.removeAttribute("hidden")}catch(e){console.error("updateBodyContent failed:",e)}}restoreElementState(){if(this._elementState.focusId){const e=document.getElementById(this._elementState.focusId)||document.querySelector(`[name="${this._elementState.focusId}"]`);if(e instanceof HTMLInputElement){const t=e.value.length||0;void 0!==this._elementState.focusSelectionStart&&null!==this._elementState.focusSelectionEnd&&e.setSelectionRange(t,t),this._elementState.focusValue&&("checkbox"===e.type||"radio"===e.type?e.checked=!!this._elementState.focusChecked:"number"===e.type||"email"===e.type?(e.type="text",e.setSelectionRange(t,t),e.type="number"===e.type?"number":"email"):"date"===e.type||"month"===e.type||"week"===e.type||"time"===e.type||"datetime-local"===e.type||"color"===e.type||"file"===e.type||""!==e.value&&(e.value=this._elementState.focusValue)),e.focus()}else if(e instanceof HTMLTextAreaElement){const t=e.value.length||0;void 0!==this._elementState.focusSelectionStart&&null!==this._elementState.focusSelectionEnd&&e.setSelectionRange(t,t),this._elementState.focusValue&&""!==e.value&&(e.value=this._elementState.focusValue),e.focus()}else e instanceof HTMLSelectElement&&(this._elementState.focusValue&&""!==e.value&&(e.value=this._elementState.focusValue),e.focus())}this._elementState.checkedElements.forEach((e=>{const t=document.getElementById(e);t&&(t.checked=!0)}))}async appendCallbackResponse(e){const t=e.getElementById("afterbegin-8D95D");if(t){const e=document.getElementById("afterbegin-8D95D");e?e.innerHTML=t.innerHTML:document.body.insertAdjacentHTML("afterbegin",t.outerHTML)}}saveElementState(){const e=document.activeElement;this._elementState.focusId=e?.id||e?.name,this._elementState.focusValue=e?.value,this._elementState.focusChecked=e?.checked,this._elementState.focusType=e?.type,this._elementState.focusSelectionStart=e?.selectionStart,this._elementState.focusSelectionEnd=e?.selectionEnd,this._elementState.isSuspense=e.hasAttribute("pp-suspense"),this._elementState.checkedElements.clear(),document.querySelectorAll('input[type="checkbox"]:checked').forEach((e=>{this._elementState.checkedElements.add(e.id||e.name)})),document.querySelectorAll('input[type="radio"]:checked').forEach((e=>{this._elementState.checkedElements.add(e.id||e.name)}))}updateElementAttributes(e,t){for(const r in t)if(t.hasOwnProperty(r))switch(r){case"innerHTML":case"outerHTML":case"textContent":case"innerText":e[r]=this.decodeHTML(t[r]);break;case"insertAdjacentHTML":e.insertAdjacentHTML(t.position||"beforeend",this.decodeHTML(t[r].html));break;case"insertAdjacentText":e.insertAdjacentText(t.position||"beforeend",this.decodeHTML(t[r].text));break;case"setAttribute":e.setAttribute(t.attrName,this.decodeHTML(t[r]));break;case"removeAttribute":e.removeAttribute(t[r]);break;case"className":e.className=this.decodeHTML(t[r]);break;case"classList.add":e.classList.add(...this.decodeHTML(t[r]).split(","));break;case"classList.remove":e.classList.remove(...this.decodeHTML(t[r]).split(","));break;case"classList.toggle":e.classList.toggle(this.decodeHTML(t[r]));break;case"classList.replace":const[n,s]=this.decodeHTML(t[r]).split(",");e.classList.replace(n,s);break;case"dataset":e.dataset[t.attrName]=this.decodeHTML(t[r]);break;case"style":Object.assign(e.style,t[r]);break;case"value":e.value=this.decodeHTML(t[r]);break;case"checked":e.checked=t[r];break;default:e.setAttribute(r,this.decodeHTML(t[r]))}}decodeHTML(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}appendAfterbegin(e){if(!e)return;const t="afterbegin-8D95D";let r=document.getElementById(t);r?(r.innerHTML=e,document.body.insertAdjacentElement("afterbegin",r)):(r=document.createElement("div"),r.id=t,r.innerHTML=e,document.body.insertAdjacentElement("afterbegin",r))}restoreSuspenseElement(e){const t=e.getAttribute("pp-original-state");if(e.hasAttribute("pp-suspense")&&t){const r=(e,t)=>{for(const r in t)t.hasOwnProperty(r)&&("textContent"===r?e.textContent=t[r]:"innerHTML"===r?e.innerHTML=t[r]:"disabled"===r?!0===t[r]?e.setAttribute("disabled","true"):e.removeAttribute("disabled"):e.setAttribute(r,t[r]));for(const r of Array.from(e.attributes))t.hasOwnProperty(r.name)||e.removeAttribute(r.name)},n=(e,t)=>{for(const n in t)if(t.hasOwnProperty(n))for(const t of Array.from(e.elements))if(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){const e=t.getAttribute("pp-original-state")||"";if(e){if(this.isJsonLike(e)){const n=this.parseJson(e);r(t,n)}else s(t,e);t.removeAttribute("pp-original-state")}}},s=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},i=(e,t)=>{e instanceof HTMLFormElement?n(e,t):r(e,t)};try{const s=this.parseJson(t);if(s)if(e instanceof HTMLFormElement){const t=e.id;if(t){const e=document.querySelector(`[form="${t}"]`);if(e){const t=e.getAttribute("pp-original-state");if(t&&this.isJsonLike(t)){const n=this.parseJson(t);r(e,n)}}}const s=new FormData(e),i={};if(s.forEach(((e,t)=>{i[t]=e})),n(e,i),e.hasAttribute("pp-suspense")){const t=e.getAttribute("pp-suspense")||"";if(this.parseJson(t).disabled)for(const t of Array.from(e.elements))(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&t.removeAttribute("disabled")}}else if(s.targets){s.targets.forEach((e=>{const{id:t,...r}=e,n=document.querySelector(t);n&&i(n,r)}));const{targets:t,...n}=s;r(e,n)}else{const{empty:t,...n}=s;r(e,n)}}catch(e){console.error(`Error parsing JSON: ${e instanceof Error?e.message:"Unknown error"}. Please ensure the JSON string is valid.`,e)}}e.querySelectorAll("[pp-suspense]").forEach((e=>this.restoreSuspenseElement(e))),e.removeAttribute("pp-original-state")}extractJson(e){const t=e?.match(/\{[\s\S]*\}/);return t?t[0]:null}getRedirectUrl(e){const t=e.match(this._redirectRegex);return t?t[1]:null}async fetchFileWithData(e,t,r,n={}){const s=new FormData,i=r.files;if(i)for(let e=0;e<i.length;e++)s.append("file[]",i[e]);s.append("callback",t);for(const e in n)n.hasOwnProperty(e)&&s.append(e,n[e]);const o=await this.fetch(e,{method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:s});return await o.text()}async handleSuspenseElement(e){let t=e.getAttribute("pp-suspense")||"";const r=(e,t)=>{for(const r in t)if(t.hasOwnProperty(r))for(const t of e.elements)if(t instanceof HTMLInputElement||t instanceof HTMLButtonElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){const e=t.getAttribute("pp-suspense")||"";if(e)if(this.isJsonLike(e)){const r=this.parseJson(e);"disabled"!==r.onsubmit&&this.updateElementAttributes(t,r),r.targets&&r.targets.forEach((e=>{const{id:t,...r}=e,n=document.querySelector(t);n&&s(n,r)}))}else n(t,e)}},n=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},s=(e,t)=>{e instanceof HTMLFormElement?r(e,t):this.updateElementAttributes(e,t)};try{if(t&&this.isJsonLike(t)){const n=this.parseJson(t);if(n)if(e instanceof HTMLFormElement){const t=new FormData(e),s={};t.forEach(((e,t)=>{s[t]=e})),n.disabled&&this.toggleFormElements(e,!0);const{disabled:i,...o}=n;this.updateElementAttributes(e,o),r(e,s)}else if(n.targets){n.targets.forEach((e=>{const{id:t,...r}=e,n=document.querySelector(t);n&&s(n,r)}));const{targets:t,...r}=n;this.updateElementAttributes(e,r)}else{if("disabled"===n.empty&&""===e.value)return;const{empty:t,...r}=n;this.updateElementAttributes(e,r)}}else if(t)n(e,t);else if(e instanceof HTMLFormElement){const t=new FormData(e),n={};t.forEach(((e,t)=>{n[t]=e})),r(e,n)}}catch(e){console.error(`Error parsing JSON: ${e instanceof Error?e.message:"Unknown error"}. Please ensure the JSON string is valid.`,e)}}toggleFormElements(e,t){Array.from(e.elements).forEach((e=>{(e instanceof HTMLInputElement||e instanceof HTMLButtonElement||e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(e.disabled=t)}))}saveElementOriginalState(e){if(e.hasAttribute("pp-suspense")&&!e.hasAttribute("pp-original-state")){const t={};e.textContent&&(t.textContent=e.textContent.trim()),e.innerHTML&&(t.innerHTML=e.innerHTML.trim()),(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(t.value=e.value);for(let r=0;r<e.attributes.length;r++){const n=e.attributes[r];t[n.name]=n.value}e.setAttribute("pp-original-state",JSON.stringify(t))}if(e instanceof HTMLFormElement){let t=null;const r=e.id;r&&(t=document.querySelector(`[form="${r}"]`)),r&&t||(t=Array.from(e.elements).find((e=>e instanceof HTMLButtonElement||e instanceof HTMLInputElement))),t?t.hasAttribute("pp-original-state")||this.saveElementOriginalState(t):console.warn("Warning: No invoker detected for the form. Ensure the form has an associated invoker or an ID for proper handling.")}e.querySelectorAll("[pp-suspense]").forEach((e=>this.saveElementOriginalState(e)))}getUrlParams(){const e={};return new URLSearchParams(window.location.search).forEach(((t,r)=>{e[r]=t})),e}createFetchOptions(e){return{method:"POST",headers:{"Content-Type":"application/json",HTTP_PPHP_WIRE_REQUEST:"true"},body:JSON.stringify(e)}}parseCallback(e,t){let r={};const n=e.closest("form");if(n){new FormData(n).forEach(((e,t)=>{const n=this.clean(e);r[t]?r[t]=Array.isArray(r[t])?[...r[t],n]:[r[t],n]:r[t]=n}))}else e instanceof HTMLInputElement?r=this.handleInputElement(e):(e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(r[e.name]=e.value);if("args"in r){const e=r.args,t=Array.isArray(e)&&e.every((e=>null==e||""===e));(null==e||""===e||t)&&delete r.args}const s=t.match(/^([^(]+)\(([\s\S]*)\)$/);if(!s)return{funcName:t.trim(),data:r};const i=s[1].trim(),o=s[2].trim();if(""===o)return{funcName:i,data:r};const a=/,(?=(?:[^'"]*['"][^'"]*['"])*[^'"]*$)/;if(o.startsWith("{")&&o.endsWith("}")||o.startsWith("[")&&o.endsWith("]"))if(this.isJsonLike(o))try{const e=this.parseJson(o);Array.isArray(e)?r.args=e:e&&"object"==typeof e&&(r={...r,...e})}catch(e){console.error("Error parsing JSON args:",e),r.rawArgs=o}else try{const e=this.evaluateJavaScriptObject(o);Array.isArray(e)?r.args=e:e&&"object"==typeof e?r={...r,...e}:r.rawArgs=o}catch(e){console.error("Error evaluating JS object args:",e),r.rawArgs=o}else if(/^[\s\d"'[\{]/.test(o))try{const e=new Function(`return [${o}];`)();r.args=Array.isArray(e)?e:[e]}catch{a.test(o)?r.args=o.split(a).map((e=>e.trim().replace(/^['"]|['"]$/g,""))):r.args=[o.replace(/^['"]|['"]$/g,"")]}else try{const e=this.getOrCreateEvaluator(o)(this.props);r.args=[e]}catch{r.args=o.split(a).map((e=>e.trim().replace(/^['"]|['"]$/g,"")))}return Array.isArray(r.args)&&(r.args=r.args.filter((e=>!(null==e||""===e))),0===r.args.length&&delete r.args),{funcName:i,data:r}}clean(e){if("string"!=typeof e)return e;let t=e.replace(/"/g,'"').trim();/^"(?:[^"\\]|\\.)*"$/.test(t)&&(t=t.slice(1,-1));try{return JSON.parse(t)}catch{}if(/^-?\d+(\.\d+)?$/.test(t)&&!/^0\d/.test(t)){const e=Number(t);if(!Number.isNaN(e))return e}return t}evaluateJavaScriptObject(e){try{const t=this.getOrCreateProxy(this.props);return new Function("proxy","Date","Math","JSON",`\n with (proxy) {\n return ${e};\n }\n `).call(null,t,Date,Math,JSON)}catch(e){throw console.error("Failed to evaluate JavaScript object:",e),e}}handleInputElement(e){let t={};if(e.name)if("checkbox"===e.type)t[e.name]={value:e.value,checked:e.checked};else if("radio"===e.type){const r=document.querySelector(`input[name="${e.name}"]:checked`);t[e.name]=r?r.value:null}else t[e.name]=e.value;else"checkbox"===e.type||"radio"===e.type?t.value=e.checked:t.value=e.value;return t}handleInputAppendParams(e,t){const r=e.getAttribute("pp-append-params"),n=e.getAttribute("pp-append-params-sync");if("true"===r){if("true"===n){const t=e.name||e.id;if(t){const r=new URL(window.location.href),n=new URLSearchParams(r.search);n.has(t)&&(e.value=n.get(t)||"")}}e.addEventListener(t,(e=>{const t=e.currentTarget,r=t.value,n=new URL(window.location.href),s=new URLSearchParams(n.search),i=t.name||t.id;if(i){r?s.set(i,r):s.delete(i);const e=s.toString()?`${n.pathname}?${s.toString()}`:n.pathname;history.replaceState(null,"",e)}}))}}handleHiddenAttribute(){const e=document.querySelectorAll("[pp-visibility]"),t=document.querySelectorAll("[pp-display]"),r=this.handleElementVisibility.bind(this),n=this.handleElementDisplay.bind(this);e.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-visibility",r))),t.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-display",n)))}handleVisibilityElementAttribute(e,t,r){const n=e.getAttribute(t);if(n)if(this.isJsonLike(n)){r(e,this.parseJson(n))}else{const r=this.parseTime(n);if(r>0){const n="pp-visibility"===t?"visibility":"display",s="visibility"===n?"hidden":"none";this.scheduleChange(e,r,n,s)}}}handleElementVisibility(e,t){this.handleElementChange(e,t,"visibility","hidden","visible")}handleElementDisplay(e,t){this.handleElementChange(e,t,"display","none","block")}handleElementChange(e,t,r,n,s){const i=t.start?this.parseTime(t.start):0,o=t.end?this.parseTime(t.end):0;i>0?(e.style[r]=n,this.scheduleChange(e,i,r,s),o>0&&this.scheduleChange(e,i+o,r,n)):o>0&&this.scheduleChange(e,o,r,n)}handleAnchorTag(){document.querySelectorAll("a").forEach((e=>{e.addEventListener("click",(async e=>{const t=e.currentTarget,r=t.getAttribute("href"),n=t.getAttribute("target");if(r&&"_blank"!==n&&!e.metaKey&&!e.ctrlKey&&(e.preventDefault(),!this._isNavigating)){this._isNavigating=!0;try{if(/^(https?:)?\/\//i.test(r)&&!r.startsWith(window.location.origin))window.location.href=r;else{const e=t.getAttribute("pp-append-params");let n="";if(r.startsWith("?")&&"true"===e){const e=new URL(window.location.href),t=new URLSearchParams(e.search);let s="";const[i,o]=r.split("#");o&&(s=`#${o}`);new URLSearchParams(i.split("?")[1]).forEach(((e,r)=>{t.set(r,e)})),n=`${e.pathname}?${t.toString()}${s}`}else{const[e,t]=r.split("#");n=`${e}${t?`#${t}`:""}`}history.pushState(null,"",n);const s=r.indexOf("#");if(-1!==s){const e=r.slice(s+1),t=document.getElementById(e);if(t)t.scrollIntoView({behavior:"smooth"});else{await this.handleNavigation();const t=document.getElementById(e);t&&t.scrollIntoView({behavior:"smooth"})}}else await this.handleNavigation()}}catch(e){console.error("Anchor click error:",e)}finally{this._isNavigating=!1}}}))}))}handlePopState(){window.addEventListener("popstate",(async()=>{await this.handleNavigation()}))}async handleNavigation(){const e=Date.now();if(e-this._lastNavigationTime<this._navigationThrottleMs)console.warn("PPHP: Navigation throttled to prevent infinite loop");else{this._lastNavigationTime=e;try{const e=document.getElementById("loading-file-1B87E");if(e){const t=this.findLoadingElement(e,window.location.pathname);t&&await this.updateContentWithTransition(t)}const t=await this.fetch(window.location.href),r=await t.text();if(!t.ok)return await this.updateDocumentContent(r),void console.error(`Navigation error: ${t.status} ${t.statusText}`);const n=r.match(this._redirectRegex);if(n&&n[1])return void await this.redirect(n[1]);await this.updateDocumentContent(r)}catch(e){console.error("Navigation error:",e)}}}findLoadingElement(e,t){let r=t;for(;;){const t=e.querySelector(`div[pp-loading-url='${r}']`);if(t)return t;if("/"===r)break;const n=r.lastIndexOf("/");r=n<=0?"/":r.substring(0,n)}return e.querySelector("div[pp-loading-url='/' ]")}async updateContentWithTransition(e){const t=document.querySelector("[pp-loading-content='true']")||document.body;if(!t)return;const{fadeIn:r,fadeOut:n}=this.parseTransition(e);await this.fadeOut(t,n),t.innerHTML=e.innerHTML,this.fadeIn(t,r)}parseTransition(e){let t=250,r=250;const n=e.querySelector("[pp-loading-transition]"),s=n?.getAttribute("pp-loading-transition");if(s){const e=this.parseJson(s);e&&"object"==typeof e?(t=this.parseTime(e.fadeIn??t),r=this.parseTime(e.fadeOut??r)):console.warn("pp-loading-transition is not valid JSON → default values (250 ms) will be used. String:",s)}return{fadeIn:t,fadeOut:r}}fadeOut(e,t){return new Promise((r=>{e.style.transition=`opacity ${t}ms ease-out`,e.style.opacity="0",setTimeout((()=>{e.style.transition="",r()}),t)}))}fadeIn(e,t){e.style.transition=`opacity ${t}ms ease-in`,e.style.opacity="1",setTimeout((()=>{e.style.transition=""}),t)}async redirect(e){if(e)try{const t=new URL(e,window.location.origin);t.origin!==window.location.origin?window.location.href=e:(history.pushState(null,"",e),await this.handleNavigation())}catch(e){console.error("Redirect error:",e)}}abortActiveRequest(){this._activeAbortController&&(console.log("Aborting active request..."),this._activeAbortController.abort(),this._activeAbortController=null)}async fetch(e,t,r=!1){let n;return r?(this._activeAbortController&&this._activeAbortController.abort(),this._activeAbortController=new AbortController,n=this._activeAbortController):n=new AbortController,fetch(e,{...t,signal:n.signal,headers:{...t?.headers,"X-PPHP-Navigation":"partial","X-Requested-With":"XMLHttpRequest"}})}isJsonLike(e){try{if("string"!=typeof e)return!1;const t=e.trim();return!(!/^\{[\s\S]*\}$/.test(t)&&!/^\[[\s\S]*\]$/.test(t))&&!(t.includes("(")||t.includes(")")||t.includes("=>"))}catch{return!1}}parseJson(e){if(!e||"string"!=typeof e)return null;const t=e.trim();if(!t)return null;try{return JSON.parse(t)}catch(e){try{return JSON5.parse(t)}catch(r){return console.error("PPHP: Failed to parse JSON with both JSON and JSON5:",{input:t.substring(0,200),standardError:e instanceof Error?e.message:String(e),json5Error:r instanceof Error?r.message:String(r)}),null}}}parseTime(e){if("number"==typeof e)return e;const t=e.match(/^(\d+)(ms|s|m)?$/);if(t){const e=parseInt(t[1],10);switch(t[2]||"ms"){case"ms":default:return e;case"s":return 1e3*e;case"m":return 60*e*1e3}}return 0}scheduleChange(e,t,r,n){setTimeout((()=>{requestAnimationFrame((()=>{e.style[r]=n}))}),t)}async fetchFunction(e,t={},r=!1){let n=null;try{r&&this._activeAbortController&&(this._activeAbortController.abort(),this._activeAbortController=null),n=new AbortController,r&&(this._activeAbortController=n);const s={callback:await this.encryptCallbackName(e),...t},i=window.location.href;let o;if(Object.keys(s).some((e=>{const t=s[e];return t instanceof File||t instanceof FileList&&t.length>0}))){const e=new FormData;Object.keys(s).forEach((t=>{const r=s[t];r instanceof File?e.append(t,r):r instanceof FileList?Array.from(r).forEach((r=>e.append(t,r))):e.append(t,r)})),o={method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:e,signal:n.signal}}else o={signal:n.signal,...this.createFetchOptions(s)};const a=await fetch(i,o);if(!a.ok)throw new Error(`Fetch failed with status: ${a.status} ${a.statusText}`);const c=await a.text();n&&this._activeAbortController===n&&(this._activeAbortController=null);try{return JSON.parse(c)}catch{return c}}catch(e){if(n&&this._activeAbortController===n&&(this._activeAbortController=null),e instanceof Error&&"AbortError"===e.name)return console.log("Request was cancelled"),{cancelled:!0};throw console.error("Error in fetchFunction:",e),new Error("Failed to fetch data.")}}async sync(...e){try{const t=this.saveScrollPositions();this.saveElementState();const r=e.length?e:["true"],n=await this.fetch(window.location.href,this.createFetchOptions({pphpSync71163:!0,selectors:r,secondRequestC69CD:!0,...this.getUrlParams()}));let s;if(n.headers.get("content-type")?.includes("application/json")){s=(await n.json()).fragments}else s={[r[0]]:await n.text()};const i=`<body>${Object.values(s).join("")}</body>`,o=(new DOMParser).parseFromString(i,"text/html");await this.initReactiveOn(o,{wire:!1});const a=[];r.forEach((e=>{const t=`[pp-sync="${e}"]`,r=document.querySelectorAll(t),n=o.body.querySelector(t);n&&r.forEach((e=>{morphdom(e,n,{childrenOnly:!0,onBeforeElUpdated:(e,t)=>{const r=e.tagName,n=this.PRESERVE_HANDLERS[r];return!n||n(e,t)},onBeforeNodeDiscarded:e=>(e instanceof HTMLElement&&e.dataset.timerId&&clearTimeout(Number(e.dataset.timerId)),!0),getNodeKey:e=>{if(e.nodeType!==Node.ELEMENT_NODE)return;const t=e;return t.getAttribute("key")||t.getAttribute("pp-key")||void 0}}),a.push(e)}))})),this.restoreElementState(),this.restoreScrollPositions(t);for(const e of a)await this.attachWireFunctionEvents(e)}catch(e){console.error("pphp.sync failed:",e)}}async fetchAndUpdateBodyContent(){const e=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});this.abortActiveRequest();const t=await this.fetch(window.location.href,e,!0),r=await t.text();await this.updateBodyContent(r)}copyCode(e,t,r,n,s="img",i=2e3){if(!(e instanceof HTMLElement))return;const o=e.closest(`.${t}`)?.querySelector("pre code"),a=o?.textContent?.trim()||"";a?navigator.clipboard.writeText(a).then((()=>{const t=e.querySelector(s);if(t)for(const[e,r]of Object.entries(n))e in t?t[e]=r:t.setAttribute(e,r);setTimeout((()=>{if(t)for(const[e,n]of Object.entries(r))e in t?t[e]=n:t.setAttribute(e,n)}),i)}),(()=>{alert("Failed to copy command to clipboard")})):alert("Failed to find the code block to copy")}getCookie(e){return document.cookie.split("; ").find((t=>t.startsWith(e+"=")))?.split("=")[1]||null}}class PPHPLocalStore{state;static instance=null;listeners;pphp;STORAGE_KEY;lastSyncedState=null;constructor(e={}){this.state=e,this.listeners=[],this.pphp=PPHP.instance,this.STORAGE_KEY=this.pphp.getCookie("pphp_local_store_key")||"pphp_local_store_59e13",this.lastSyncedState=localStorage.getItem(this.STORAGE_KEY),this.loadState()}static getInstance(e={}){return PPHPLocalStore.instance||(PPHPLocalStore.instance=new PPHPLocalStore(e)),PPHPLocalStore.instance}setState(e,t=!1){const r={...this.state,...e};if(JSON.stringify(r)!==JSON.stringify(this.state)&&(this.state=r,this.listeners.forEach((e=>e(this.state))),this.saveState(),t)){const e=localStorage.getItem(this.STORAGE_KEY);e&&e!==this.lastSyncedState&&(this.pphp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]:e}),this.lastSyncedState=e)}}saveState(){localStorage.setItem(this.STORAGE_KEY,JSON.stringify(this.state))}loadState(){const e=localStorage.getItem(this.STORAGE_KEY);e&&(this.state=this.pphp.parseJson(e),this.listeners.forEach((e=>e(this.state))))}resetState(e,t=!1){if(e?(delete this.state[e],this.saveState()):(this.state={},localStorage.removeItem(this.STORAGE_KEY)),this.listeners.forEach((e=>e(this.state))),t){const t=e?localStorage.getItem(this.STORAGE_KEY):null;this.pphp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]:t}),this.lastSyncedState=t}}}class SearchParamsManager{static instance=null;listeners=[];constructor(){}static getInstance(){return SearchParamsManager.instance||(SearchParamsManager.instance=new SearchParamsManager),SearchParamsManager.instance}get params(){return new URLSearchParams(window.location.search)}get(e){return this.params.get(e)}set(e,t){const r=this.params;r.set(e,t),this.updateURL(r)}delete(e){const t=this.params;t.delete(e),this.updateURL(t)}replace(e){const t=new URLSearchParams;for(const r in e){const n=e[r];null!==n&&t.set(r,n)}this.updateURL(t,!0)}updateURL(e,t=!1){const r=`${window.location.pathname}?${e.toString()}`;t?history.replaceState(null,"",r):history.pushState(null,"",r),this.notifyListeners(e)}listen(e){this.listeners.push(e)}notifyListeners(e){for(const t of this.listeners)t(e)}enablePopStateListener(){window.addEventListener("popstate",(()=>{this.notifyListeners(this.params)}))}}var pphp=PPHP.instance,store=PPHPLocalStore.getInstance(),searchParams=SearchParamsManager.getInstance();
|
|
1
|
+
var Ut=Object.defineProperty,Wt=(e,t,s)=>t in e?Ut(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,d=(e,t,s)=>Wt(e,"symbol"!=typeof t?t+"":t,s),Ht=[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],zt="·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛-࢟࣊-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄ఼ా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ೳഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-໎໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜕ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠏-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿ-ᫎᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯・꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏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"},Le="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",qt={5:Le,"5module":Le+" export import",6:Le+" const class extends export import super"},Xt=/^in(stanceof)?$/,Gt=new RegExp("["+st+"]"),Kt=new RegExp("["+st+zt+"]");function Oe(e,t){for(var s=65536,n=0;n<t.length;n+=2){if((s+=t[n])>e)return!1;if((s+=t[n+1])>=e)return!0}return!1}function H(e,t){return e<65?36===e:e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&Gt.test(String.fromCharCode(e)):!1!==t&&Oe(e,tt)))}function ee(e,t){return e<48?36===e:e<58||!(e<65)&&(e<91||(e<97?95===e:e<123||(e<=65535?e>=170&&Kt.test(String.fromCharCode(e)):!1!==t&&(Oe(e,tt)||Oe(e,Ht)))))}var T=function(e,t){void 0===t&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function D(e,t){return new T(e,{beforeExpr:!0,binop:t})}var B={beforeExpr:!0},O={startsExpr:!0},$e={};function w(e,t){return void 0===t&&(t={}),t.keyword=e,$e[e]=new T(e,t)}var u={num:new T("num",O),regexp:new T("regexp",O),string:new T("string",O),name:new T("name",O),privateId:new T("privateId",O),eof:new T("eof"),bracketL:new T("[",{beforeExpr:!0,startsExpr:!0}),bracketR:new T("]"),braceL:new T("{",{beforeExpr:!0,startsExpr:!0}),braceR:new T("}"),parenL:new T("(",{beforeExpr:!0,startsExpr:!0}),parenR:new T(")"),comma:new T(",",B),semi:new T(";",B),colon:new T(":",B),dot:new T("."),question:new T("?",B),questionDot:new T("?."),arrow:new T("=>",B),template:new T("template"),invalidTemplate:new T("invalidTemplate"),ellipsis:new T("...",B),backQuote:new T("`",O),dollarBraceL:new T("${",{beforeExpr:!0,startsExpr:!0}),eq:new T("=",{beforeExpr:!0,isAssign:!0}),assign:new T("_=",{beforeExpr:!0,isAssign:!0}),incDec:new T("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new T("!/~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:D("||",1),logicalAND:D("&&",2),bitwiseOR:D("|",3),bitwiseXOR:D("^",4),bitwiseAND:D("&",5),equality:D("==/!=/===/!==",6),relational:D("</>/<=/>=",7),bitShift:D("<</>>/>>>",8),plusMin:new T("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:D("%",10),star:D("*",10),slash:D("/",10),starstar:new T("**",{beforeExpr:!0}),coalesce:D("??",1),_break:w("break"),_case:w("case",B),_catch:w("catch"),_continue:w("continue"),_debugger:w("debugger"),_default:w("default",B),_do:w("do",{isLoop:!0,beforeExpr:!0}),_else:w("else",B),_finally:w("finally"),_for:w("for",{isLoop:!0}),_function:w("function",O),_if:w("if"),_return:w("return",B),_switch:w("switch"),_throw:w("throw",B),_try:w("try"),_var:w("var"),_const:w("const"),_while:w("while",{isLoop:!0}),_with:w("with"),_new:w("new",{beforeExpr:!0,startsExpr:!0}),_this:w("this",O),_super:w("super",O),_class:w("class",O),_extends:w("extends",B),_export:w("export"),_import:w("import",O),_null:w("null",O),_true:w("true",O),_false:w("false",O),_in:w("in",{beforeExpr:!0,binop:7}),_instanceof:w("instanceof",{beforeExpr:!0,binop:7}),_typeof:w("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:w("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:w("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},V=/\r\n?|\n|\u2028|\u2029/,Qt=new RegExp(V.source,"g");function ce(e){return 10===e||13===e||8232===e||8233===e}function it(e,t,s){void 0===s&&(s=e.length);for(var n=t;n<s;n++){var i=e.charCodeAt(n);if(ce(i))return n<s-1&&13===i&&10===e.charCodeAt(n+1)?n+2:n+1}return-1}var nt=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/,L=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,rt=Object.prototype,Zt=rt.hasOwnProperty,Jt=rt.toString,ue=Object.hasOwn||function(e,t){return Zt.call(e,t)},Ke=Array.isArray||function(e){return"[object Array]"===Jt.call(e)},Qe=Object.create(null);function Y(e){return Qe[e]||(Qe[e]=new RegExp("^(?:"+e.replace(/ /g,"|")+")$"))}function G(e){return e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode(55296+(e>>10),56320+(1023&e)))}var Yt=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,de=function(e,t){this.line=e,this.column=t};de.prototype.offset=function(e){return new de(this.line,this.column+e)};var Te=function(e,t,s){this.start=t,this.end=s,null!==e.sourceFile&&(this.source=e.sourceFile)};function at(e,t){for(var s=1,n=0;;){var i=it(e,n,t);if(i<0)return new de(s,t-n);++s,n=i}}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},Ze=!1;function es(e){var t={};for(var s in Ve)t[s]=e&&ue(e,s)?e[s]:Ve[s];if("latest"===t.ecmaVersion?t.ecmaVersion=1e8:null==t.ecmaVersion?(!Ze&&"object"==typeof console&&console.warn&&(Ze=!0,console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.")),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),null==t.allowReserved&&(t.allowReserved=t.ecmaVersion<5),(!e||null==e.allowHashBang)&&(t.allowHashBang=t.ecmaVersion>=14),Ke(t.onToken)){var n=t.onToken;t.onToken=function(e){return n.push(e)}}return Ke(t.onComment)&&(t.onComment=ts(t,t.onComment)),t}function ts(e,t){return function(s,n,i,r,a,o){var c={type:s?"Block":"Line",value:n,start:i,end:r};e.locations&&(c.loc=new Te(this,a,o)),e.ranges&&(c.range=[i,r]),t.push(c)}}var me=1,le=2,je=4,ot=8,Ue=16,ct=32,_e=64,ut=128,re=256,ge=512,Ae=me|le|re;function We(e,t){return le|(e?je:0)|(t?ot:0)}var Ee=0,He=1,Q=2,lt=3,pt=4,ht=5,P=function(e,t,s){this.options=e=es(e),this.sourceFile=e.sourceFile,this.keywords=Y(qt[e.ecmaVersion>=6?6:"module"===e.sourceType?"5module":5]);var n="";!0!==e.allowReserved&&(n=Me[e.ecmaVersion>=6?6:5===e.ecmaVersion?5:3],"module"===e.sourceType&&(n+=" await")),this.reservedWords=Y(n);var i=(n?n+" ":"")+Me.strict;this.reservedWordsStrict=Y(i),this.reservedWordsStrictBind=Y(i+" "+Me.strictBind),this.input=String(t),this.containsEsc=!1,s?(this.pos=s,this.lineStart=this.input.lastIndexOf("\n",s-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="module"===e.sourceType,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),0===this.pos&&e.allowHashBang&&"#!"===this.input.slice(0,2)&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(me),this.regexpState=null,this.privateNameStack=[]},z={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}};P.prototype.parse=function(){var e=this.options.program||this.startNode();return this.nextToken(),this.parseTopLevel(e)},z.inFunction.get=function(){return(this.currentVarScope().flags&le)>0},z.inGenerator.get=function(){return(this.currentVarScope().flags&ot)>0},z.inAsync.get=function(){return(this.currentVarScope().flags&je)>0},z.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e].flags;if(t&(re|ge))return!1;if(t&le)return(t&je)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},z.allowSuper.get=function(){return(this.currentThisScope().flags&_e)>0||this.options.allowSuperOutsideMethod},z.allowDirectSuper.get=function(){return(this.currentThisScope().flags&ut)>0},z.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},z.allowNewDotTarget.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e].flags;if(t&(re|ge)||t&le&&!(t&Ue))return!0}return!1},z.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&re)>0},P.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var s=this,n=0;n<e.length;n++)s=e[n](s);return s},P.parse=function(e,t){return new this(t,e).parse()},P.parseExpressionAt=function(e,t,s){var n=new this(s,e,t);return n.nextToken(),n.parseExpression()},P.tokenizer=function(e,t){return new this(t,e)},Object.defineProperties(P.prototype,z);var R=P.prototype,ss=/^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/;R.strictDirective=function(e){if(this.options.ecmaVersion<5)return!1;for(;;){L.lastIndex=e,e+=L.exec(this.input)[0].length;var t=ss.exec(this.input.slice(e));if(!t)return!1;if("use strict"===(t[1]||t[2])){L.lastIndex=e+t[0].length;var s=L.exec(this.input),n=s.index+s[0].length,i=this.input.charAt(n);return";"===i||"}"===i||V.test(s[0])&&!(/[(`.[+\-/*%<>=,?^&]/.test(i)||"!"===i&&"="===this.input.charAt(n+1))}e+=t[0].length,L.lastIndex=e,e+=L.exec(this.input)[0].length,";"===this.input[e]&&e++}},R.eat=function(e){return this.type===e&&(this.next(),!0)},R.isContextual=function(e){return this.type===u.name&&this.value===e&&!this.containsEsc},R.eatContextual=function(e){return!!this.isContextual(e)&&(this.next(),!0)},R.expectContextual=function(e){this.eatContextual(e)||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(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},R.expect=function(e){this.eat(e)||this.unexpected()},R.unexpected=function(e){this.raise(e??this.start,"Unexpected token")};var Ie=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};R.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,"Comma is not permitted after the rest element");var s=t?e.parenthesizedAssign:e.parenthesizedBind;s>-1&&this.raiseRecoverable(s,t?"Assigning to rvalue":"Parenthesized pattern")}},R.checkExpressionErrors=function(e,t){if(!e)return!1;var s=e.shorthandAssign,n=e.doubleProto;if(!t)return s>=0||n>=0;s>=0&&this.raise(s,"Shorthand property assignments are valid only in destructuring patterns"),n>=0&&this.raiseRecoverable(n,"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(e){return"ParenthesizedExpression"===e.type?this.isSimpleAssignTarget(e.expression):"Identifier"===e.type||"MemberExpression"===e.type};var b=P.prototype;b.parseTopLevel=function(e){var t=Object.create(null);for(e.body||(e.body=[]);this.type!==u.eof;){var s=this.parseStatement(null,!0,t);e.body.push(s)}if(this.inModule)for(var n=0,i=Object.keys(this.undefinedExports);n<i.length;n+=1){var r=i[n];this.raiseRecoverable(this.undefinedExports[r].start,"Export '"+r+"' is not defined")}return this.adaptDirectivePrologue(e.body),this.next(),e.sourceType=this.options.sourceType,this.finishNode(e,"Program")};var ze={kind:"loop"},is={kind:"switch"};b.isLet=function(e){if(this.options.ecmaVersion<6||!this.isContextual("let"))return!1;L.lastIndex=this.pos;var t=L.exec(this.input),s=this.pos+t[0].length,n=this.input.charCodeAt(s);if(91===n||92===n)return!0;if(e)return!1;if(123===n||n>55295&&n<56320)return!0;if(H(n,!0)){for(var i=s+1;ee(n=this.input.charCodeAt(i),!0);)++i;if(92===n||n>55295&&n<56320)return!0;var r=this.input.slice(s,i);if(!Xt.test(r))return!0}return!1},b.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async"))return!1;L.lastIndex=this.pos;var e,t=L.exec(this.input),s=this.pos+t[0].length;return!(V.test(this.input.slice(this.pos,s))||"function"!==this.input.slice(s,s+8)||s+8!==this.input.length&&(ee(e=this.input.charCodeAt(s+8))||e>55295&&e<56320))},b.isUsingKeyword=function(e,t){if(this.options.ecmaVersion<17||!this.isContextual(e?"await":"using"))return!1;L.lastIndex=this.pos;var s=L.exec(this.input),n=this.pos+s[0].length;if(V.test(this.input.slice(this.pos,n)))return!1;if(e){var i,r=n+5;if("using"!==this.input.slice(n,r)||r===this.input.length||ee(i=this.input.charCodeAt(r))||i>55295&&i<56320)return!1;L.lastIndex=r;var a=L.exec(this.input);if(a&&V.test(this.input.slice(r,r+a[0].length)))return!1}if(t){var o,c=n+2;if(!("of"!==this.input.slice(n,c)||c!==this.input.length&&(ee(o=this.input.charCodeAt(c))||o>55295&&o<56320)))return!1}var p=this.input.charCodeAt(n);return H(p,!0)||92===p},b.isAwaitUsing=function(e){return this.isUsingKeyword(!0,e)},b.isUsing=function(e){return this.isUsingKeyword(!1,e)},b.parseStatement=function(e,t,s){var n,i=this.type,r=this.startNode();switch(this.isLet(e)&&(i=u._var,n="let"),i){case u._break:case u._continue:return this.parseBreakContinueStatement(r,i.keyword);case u._debugger:return this.parseDebuggerStatement(r);case u._do:return this.parseDoStatement(r);case u._for:return this.parseForStatement(r);case u._function:return e&&(this.strict||"if"!==e&&"label"!==e)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(r,!1,!e);case u._class:return e&&this.unexpected(),this.parseClass(r,!0);case u._if:return this.parseIfStatement(r);case u._return:return this.parseReturnStatement(r);case u._switch:return this.parseSwitchStatement(r);case u._throw:return this.parseThrowStatement(r);case u._try:return this.parseTryStatement(r);case u._const:case u._var:return n=n||this.value,e&&"var"!==n&&this.unexpected(),this.parseVarStatement(r,n);case u._while:return this.parseWhileStatement(r);case u._with:return this.parseWithStatement(r);case u.braceL:return this.parseBlock(!0,r);case u.semi:return this.parseEmptyStatement(r);case u._export:case u._import:if(this.options.ecmaVersion>10&&i===u._import){L.lastIndex=this.pos;var a=L.exec(this.input),o=this.pos+a[0].length,c=this.input.charCodeAt(o);if(40===c||46===c)return this.parseExpressionStatement(r,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||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(r):this.parseExport(r,s);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(r,!0,!e);var p=this.isAwaitUsing(!1)?"await using":this.isUsing(!1)?"using":null;if(p)return t&&"script"===this.options.sourceType&&this.raise(this.start,"Using declaration cannot appear in the top level when source type is `script`"),"await using"===p&&(this.canAwait||this.raise(this.start,"Await using cannot appear outside of async function"),this.next()),this.next(),this.parseVar(r,!1,p),this.semicolon(),this.finishNode(r,"VariableDeclaration");var h=this.value,l=this.parseExpression();return i===u.name&&"Identifier"===l.type&&this.eat(u.colon)?this.parseLabeledStatement(r,h,l,e):this.parseExpressionStatement(r,l)}},b.parseBreakContinueStatement=function(e,t){var s="break"===t;this.next(),this.eat(u.semi)||this.insertSemicolon()?e.label=null:this.type!==u.name?this.unexpected():(e.label=this.parseIdent(),this.semicolon());for(var n=0;n<this.labels.length;++n){var i=this.labels[n];if((null==e.label||i.name===e.label.name)&&(null!=i.kind&&(s||"loop"===i.kind)||e.label&&s))break}return n===this.labels.length&&this.raise(e.start,"Unsyntactic "+t),this.finishNode(e,s?"BreakStatement":"ContinueStatement")},b.parseDebuggerStatement=function(e){return this.next(),this.semicolon(),this.finishNode(e,"DebuggerStatement")},b.parseDoStatement=function(e){return this.next(),this.labels.push(ze),e.body=this.parseStatement("do"),this.labels.pop(),this.expect(u._while),e.test=this.parseParenExpression(),this.options.ecmaVersion>=6?this.eat(u.semi):this.semicolon(),this.finishNode(e,"DoWhileStatement")},b.parseForStatement=function(e){this.next();var t=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 t>-1&&this.unexpected(t),this.parseFor(e,null);var s=this.isLet();if(this.type===u._var||this.type===u._const||s){var n=this.startNode(),i=s?"let":this.value;return this.next(),this.parseVar(n,!0,i),this.finishNode(n,"VariableDeclaration"),this.parseForAfterInit(e,n,t)}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(),"await using"===o&&this.next(),this.parseVar(c,!0,o),this.finishNode(c,"VariableDeclaration"),this.parseForAfterInit(e,c,t)}var p=this.containsEsc,h=new Ie,l=this.start,d=t>-1?this.parseExprSubscripts(h,"await"):this.parseExpression(!0,h);return this.type===u._in||(a=this.options.ecmaVersion>=6&&this.isContextual("of"))?(t>-1?(this.type===u._in&&this.unexpected(t),e.await=!0):a&&this.options.ecmaVersion>=8&&(d.start!==l||p||"Identifier"!==d.type||"async"!==d.name?this.options.ecmaVersion>=9&&(e.await=!1):this.unexpected()),r&&a&&this.raise(d.start,"The left-hand side of a for-of loop may not start with 'let'."),this.toAssignable(d,!1,h),this.checkLValPattern(d),this.parseForIn(e,d)):(this.checkExpressionErrors(h,!0),t>-1&&this.unexpected(t),this.parseFor(e,d))},b.parseForAfterInit=function(e,t,s){return(this.type===u._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&1===t.declarations.length?(this.options.ecmaVersion>=9&&(this.type===u._in?s>-1&&this.unexpected(s):e.await=s>-1),this.parseForIn(e,t)):(s>-1&&this.unexpected(s),this.parseFor(e,t))},b.parseFunctionStatement=function(e,t,s){return this.next(),this.parseFunction(e,fe|(s?0:Fe),!1,t)},b.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement("if"),e.alternate=this.eat(u._else)?this.parseStatement("if"):null,this.finishNode(e,"IfStatement")},b.parseReturnStatement=function(e){return!this.inFunction&&!this.options.allowReturnOutsideFunction&&this.raise(this.start,"'return' outside of function"),this.next(),this.eat(u.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,"ReturnStatement")},b.parseSwitchStatement=function(e){this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(u.braceL),this.labels.push(is),this.enterScope(0);for(var t,s=!1;this.type!==u.braceR;)if(this.type===u._case||this.type===u._default){var n=this.type===u._case;t&&this.finishNode(t,"SwitchCase"),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),n?t.test=this.parseExpression():(s&&this.raiseRecoverable(this.lastTokStart,"Multiple default clauses"),s=!0,t.test=null),this.expect(u.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,"SwitchCase"),this.next(),this.labels.pop(),this.finishNode(e,"SwitchStatement")},b.parseThrowStatement=function(e){return this.next(),V.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,"Illegal newline after throw"),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,"ThrowStatement")};var ns=[];b.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t="Identifier"===e.type;return this.enterScope(t?ct:0),this.checkLValPattern(e,t?pt:Q),this.expect(u.parenR),e},b.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===u._catch){var t=this.startNode();this.next(),this.eat(u.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,"CatchClause")}return e.finalizer=this.eat(u._finally)?this.parseBlock():null,!e.handler&&!e.finalizer&&this.raise(e.start,"Missing catch or finally clause"),this.finishNode(e,"TryStatement")},b.parseVarStatement=function(e,t,s){return this.next(),this.parseVar(e,!1,t,s),this.semicolon(),this.finishNode(e,"VariableDeclaration")},b.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(ze),e.body=this.parseStatement("while"),this.labels.pop(),this.finishNode(e,"WhileStatement")},b.parseWithStatement=function(e){return this.strict&&this.raise(this.start,"'with' in strict mode"),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement("with"),this.finishNode(e,"WithStatement")},b.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,"EmptyStatement")},b.parseLabeledStatement=function(e,t,s,n){for(var i=0,r=this.labels;i<r.length;i+=1){r[i].name===t&&this.raise(s.start,"Label '"+t+"' is already declared")}for(var a=this.type.isLoop?"loop":this.type===u._switch?"switch":null,o=this.labels.length-1;o>=0;o--){var c=this.labels[o];if(c.statementStart!==e.start)break;c.statementStart=this.start,c.kind=a}return this.labels.push({name:t,kind:a,statementStart:this.start}),e.body=this.parseStatement(n?-1===n.indexOf("label")?n+"label":n:"label"),this.labels.pop(),e.label=s,this.finishNode(e,"LabeledStatement")},b.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,"ExpressionStatement")},b.parseBlock=function(e,t,s){for(void 0===e&&(e=!0),void 0===t&&(t=this.startNode()),t.body=[],this.expect(u.braceL),e&&this.enterScope(0);this.type!==u.braceR;){var n=this.parseStatement(null);t.body.push(n)}return s&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,"BlockStatement")},b.parseFor=function(e,t){return e.init=t,this.expect(u.semi),e.test=this.type===u.semi?null:this.parseExpression(),this.expect(u.semi),e.update=this.type===u.parenR?null:this.parseExpression(),this.expect(u.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,"ForStatement")},b.parseForIn=function(e,t){var s=this.type===u._in;return this.next(),"VariableDeclaration"===t.type&&null!=t.declarations[0].init&&(!s||this.options.ecmaVersion<8||this.strict||"var"!==t.kind||"Identifier"!==t.declarations[0].id.type)&&this.raise(t.start,(s?"for-in":"for-of")+" loop variable declaration may not have an initializer"),e.left=t,e.right=s?this.parseExpression():this.parseMaybeAssign(),this.expect(u.parenR),e.body=this.parseStatement("for"),this.exitScope(),this.labels.pop(),this.finishNode(e,s?"ForInStatement":"ForOfStatement")},b.parseVar=function(e,t,s,n){for(e.declarations=[],e.kind=s;;){var i=this.startNode();if(this.parseVarId(i,s),this.eat(u.eq)?i.init=this.parseMaybeAssign(t):n||"const"!==s||this.type===u._in||this.options.ecmaVersion>=6&&this.isContextual("of")?n||"using"!==s&&"await using"!==s||!(this.options.ecmaVersion>=17)||this.type===u._in||this.isContextual("of")?n||"Identifier"===i.id.type||t&&(this.type===u._in||this.isContextual("of"))?i.init=null:this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value"):this.raise(this.lastTokEnd,"Missing initializer in "+s+" declaration"):this.unexpected(),e.declarations.push(this.finishNode(i,"VariableDeclarator")),!this.eat(u.comma))break}return e},b.parseVarId=function(e,t){e.id="using"===t||"await using"===t?this.parseIdent():this.parseBindingAtom(),this.checkLValPattern(e.id,"var"===t?He:Q,!1)};var fe=1,Fe=2,ft=4;function rs(e,t){var s=t.key.name,n=e[s],i="true";return"MethodDefinition"===t.type&&("get"===t.kind||"set"===t.kind)&&(i=(t.static?"s":"i")+t.kind),"iget"===n&&"iset"===i||"iset"===n&&"iget"===i||"sget"===n&&"sset"===i||"sset"===n&&"sget"===i?(e[s]="true",!1):!!n||(e[s]=i,!1)}function ve(e,t){var s=e.computed,n=e.key;return!s&&("Identifier"===n.type&&n.name===t||"Literal"===n.type&&n.value===t)}b.parseFunction=function(e,t,s,n,i){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!n)&&(this.type===u.star&&t&Fe&&this.unexpected(),e.generator=this.eat(u.star)),this.options.ecmaVersion>=8&&(e.async=!!n),t&fe&&(e.id=t&ft&&this.type!==u.name?null:this.parseIdent(),e.id&&!(t&Fe)&&this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?He:Q:lt));var r=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(We(e.async,e.generator)),t&fe||(e.id=this.type===u.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,s,!1,i),this.yieldPos=r,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,t&fe?"FunctionDeclaration":"FunctionExpression")},b.parseFunctionParams=function(e){this.expect(u.parenL),e.params=this.parseBindingList(u.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},b.parseClass=function(e,t){this.next();var s=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var n=this.enterClassBody(),i=this.startNode(),r=!1;for(i.body=[],this.expect(u.braceL);this.type!==u.braceR;){var a=this.parseClassElement(null!==e.superClass);a&&(i.body.push(a),"MethodDefinition"===a.type&&"constructor"===a.kind?(r&&this.raiseRecoverable(a.start,"Duplicate constructor in the same class"),r=!0):a.key&&"PrivateIdentifier"===a.key.type&&rs(n,a)&&this.raiseRecoverable(a.key.start,"Identifier '#"+a.key.name+"' has already been declared"))}return this.strict=s,this.next(),e.body=this.finishNode(i,"ClassBody"),this.exitClassBody(),this.finishNode(e,t?"ClassDeclaration":"ClassExpression")},b.parseClassElement=function(e){if(this.eat(u.semi))return null;var t=this.options.ecmaVersion,s=this.startNode(),n="",i=!1,r=!1,a="method",o=!1;if(this.eatContextual("static")){if(t>=13&&this.eat(u.braceL))return this.parseClassStaticBlock(s),s;this.isClassElementNameStart()||this.type===u.star?o=!0:n="static"}if(s.static=o,!n&&t>=8&&this.eatContextual("async")&&(!this.isClassElementNameStart()&&this.type!==u.star||this.canInsertSemicolon()?n="async":r=!0),!n&&(t>=9||!r)&&this.eat(u.star)&&(i=!0),!n&&!r&&!i){var c=this.value;(this.eatContextual("get")||this.eatContextual("set"))&&(this.isClassElementNameStart()?a=c:n=c)}if(n?(s.computed=!1,s.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),s.key.name=n,this.finishNode(s.key,"Identifier")):this.parseClassElementName(s),t<13||this.type===u.parenL||"method"!==a||i||r){var p=!s.static&&ve(s,"constructor"),h=p&&e;p&&"method"!==a&&this.raise(s.key.start,"Constructor can't have get/set modifier"),s.kind=p?"constructor":a,this.parseClassMethod(s,i,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(e){this.type===u.privateId?("constructor"===this.value&&this.raise(this.start,"Classes can't have an element named '#constructor'"),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},b.parseClassMethod=function(e,t,s,n){var i=e.key;"constructor"===e.kind?(t&&this.raise(i.start,"Constructor can't be a generator"),s&&this.raise(i.start,"Constructor can't be an async method")):e.static&&ve(e,"prototype")&&this.raise(i.start,"Classes may not have a static property named prototype");var r=e.value=this.parseMethod(t,s,n);return"get"===e.kind&&0!==r.params.length&&this.raiseRecoverable(r.start,"getter should have no params"),"set"===e.kind&&1!==r.params.length&&this.raiseRecoverable(r.start,"setter should have exactly one param"),"set"===e.kind&&"RestElement"===r.params[0].type&&this.raiseRecoverable(r.params[0].start,"Setter cannot use rest params"),this.finishNode(e,"MethodDefinition")},b.parseClassField=function(e){return ve(e,"constructor")?this.raise(e.key.start,"Classes can't have a field named 'constructor'"):e.static&&ve(e,"prototype")&&this.raise(e.key.start,"Classes can't have a static field named 'prototype'"),this.eat(u.eq)?(this.enterScope(ge|_e),e.value=this.parseMaybeAssign(),this.exitScope()):e.value=null,this.semicolon(),this.finishNode(e,"PropertyDefinition")},b.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(re|_e);this.type!==u.braceR;){var s=this.parseStatement(null);e.body.push(s)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,"StaticBlock")},b.parseClassId=function(e,t){this.type===u.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,Q,!1)):(!0===t&&this.unexpected(),e.id=null)},b.parseClassSuper=function(e){e.superClass=this.eat(u._extends)?this.parseExprSubscripts(null,!1):null},b.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},b.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,s=e.used;if(this.options.checkPrivateFields)for(var n=this.privateNameStack.length,i=0===n?null:this.privateNameStack[n-1],r=0;r<s.length;++r){var a=s[r];ue(t,a.name)||(i?i.used.push(a):this.raiseRecoverable(a.start,"Private field '#"+a.name+"' must be declared in an enclosing class"))}},b.parseExportAllDeclaration=function(e,t){return this.options.ecmaVersion>=11&&(this.eatContextual("as")?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual("from"),this.type!==u.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ExportAllDeclaration")},b.parseExport=function(e,t){if(this.next(),this.eat(u.star))return this.parseExportAllDeclaration(e,t);if(this.eat(u._default))return this.checkExport(t,"default",this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,"ExportDefaultDeclaration");if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),"VariableDeclaration"===e.declaration.type?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null,this.options.ecmaVersion>=16&&(e.attributes=[]);else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual("from"))this.type!==u.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var s=0,n=e.specifiers;s<n.length;s+=1){var i=n[s];this.checkUnreserved(i.local),this.checkLocalExport(i.local),"Literal"===i.local.type&&this.raise(i.local.start,"A string literal cannot be used as an exported binding without `from`.")}e.source=null,this.options.ecmaVersion>=16&&(e.attributes=[])}this.semicolon()}return this.finishNode(e,"ExportNamedDeclaration")},b.parseExportDeclaration=function(e){return this.parseStatement(null)},b.parseExportDefaultDeclaration=function(){var e;if(this.type===u._function||(e=this.isAsyncFunction())){var t=this.startNode();return this.next(),e&&this.next(),this.parseFunction(t,fe|ft,!1,e)}if(this.type===u._class){var s=this.startNode();return this.parseClass(s,"nullableID")}var n=this.parseMaybeAssign();return this.semicolon(),n},b.checkExport=function(e,t,s){e&&("string"!=typeof t&&(t="Identifier"===t.type?t.name:t.value),ue(e,t)&&this.raiseRecoverable(s,"Duplicate export '"+t+"'"),e[t]=!0)},b.checkPatternExport=function(e,t){var s=t.type;if("Identifier"===s)this.checkExport(e,t,t.start);else if("ObjectPattern"===s)for(var n=0,i=t.properties;n<i.length;n+=1){var r=i[n];this.checkPatternExport(e,r)}else if("ArrayPattern"===s)for(var a=0,o=t.elements;a<o.length;a+=1){var c=o[a];c&&this.checkPatternExport(e,c)}else"Property"===s?this.checkPatternExport(e,t.value):"AssignmentPattern"===s?this.checkPatternExport(e,t.left):"RestElement"===s&&this.checkPatternExport(e,t.argument)},b.checkVariableExport=function(e,t){if(e)for(var s=0,n=t;s<n.length;s+=1){var i=n[s];this.checkPatternExport(e,i.id)}},b.shouldParseExportStatement=function(){return"var"===this.type.keyword||"const"===this.type.keyword||"class"===this.type.keyword||"function"===this.type.keyword||this.isLet()||this.isAsyncFunction()},b.parseExportSpecifier=function(e){var t=this.startNode();return t.local=this.parseModuleExportName(),t.exported=this.eatContextual("as")?this.parseModuleExportName():t.local,this.checkExport(e,t.exported,t.exported.start),this.finishNode(t,"ExportSpecifier")},b.parseExportSpecifiers=function(e){var t=[],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;t.push(this.parseExportSpecifier(e))}return t},b.parseImport=function(e){return this.next(),this.type===u.string?(e.specifiers=ns,e.source=this.parseExprAtom()):(e.specifiers=this.parseImportSpecifiers(),this.expectContextual("from"),e.source=this.type===u.string?this.parseExprAtom():this.unexpected()),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,"ImportDeclaration")},b.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual("as")?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,Q),this.finishNode(e,"ImportSpecifier")},b.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,Q),this.finishNode(e,"ImportDefaultSpecifier")},b.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual("as"),e.local=this.parseIdent(),this.checkLValSimple(e.local,Q),this.finishNode(e,"ImportNamespaceSpecifier")},b.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===u.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(u.comma)))return e;if(this.type===u.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(u.braceL);!this.eat(u.braceR);){if(t)t=!1;else if(this.expect(u.comma),this.afterTrailingComma(u.braceR))break;e.push(this.parseImportSpecifier())}return e},b.parseWithClause=function(){var e=[];if(!this.eat(u._with))return e;this.expect(u.braceL);for(var t={},s=!0;!this.eat(u.braceR);){if(s)s=!1;else if(this.expect(u.comma),this.afterTrailingComma(u.braceR))break;var n=this.parseImportAttribute(),i="Identifier"===n.key.type?n.key.name:n.key.value;ue(t,i)&&this.raiseRecoverable(n.key.start,"Duplicate attribute key '"+i+"'"),t[i]=!0,e.push(n)}return e},b.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===u.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved),this.expect(u.colon),this.type!==u.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,"ImportAttribute")},b.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===u.string){var e=this.parseLiteral(this.value);return Yt.test(e.value)&&this.raise(e.start,"An export name cannot include a lone surrogate."),e}return this.parseIdent(!0)},b.adaptDirectivePrologue=function(e){for(var t=0;t<e.length&&this.isDirectiveCandidate(e[t]);++t)e[t].directive=e[t].expression.raw.slice(1,-1)},b.isDirectiveCandidate=function(e){return this.options.ecmaVersion>=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"string"==typeof e.expression.value&&('"'===this.input[e.start]||"'"===this.input[e.start])};var j=P.prototype;j.toAssignable=function(e,t,s){if(this.options.ecmaVersion>=6&&e)switch(e.type){case"Identifier":this.inAsync&&"await"===e.name&&this.raise(e.start,"Cannot use 'await' as identifier inside an async function");break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":e.type="ObjectPattern",s&&this.checkPatternErrors(s,!0);for(var n=0,i=e.properties;n<i.length;n+=1){var r=i[n];this.toAssignable(r,t),"RestElement"===r.type&&("ArrayPattern"===r.argument.type||"ObjectPattern"===r.argument.type)&&this.raise(r.argument.start,"Unexpected token")}break;case"Property":"init"!==e.kind&&this.raise(e.key.start,"Object pattern can't contain getter or setter"),this.toAssignable(e.value,t);break;case"ArrayExpression":e.type="ArrayPattern",s&&this.checkPatternErrors(s,!0),this.toAssignableList(e.elements,t);break;case"SpreadElement":e.type="RestElement",this.toAssignable(e.argument,t),"AssignmentPattern"===e.argument.type&&this.raise(e.argument.start,"Rest elements cannot have a default value");break;case"AssignmentExpression":"="!==e.operator&&this.raise(e.left.end,"Only '=' operator can be used for specifying default value."),e.type="AssignmentPattern",delete e.operator,this.toAssignable(e.left,t);break;case"ParenthesizedExpression":this.toAssignable(e.expression,t,s);break;case"ChainExpression":this.raiseRecoverable(e.start,"Optional chaining cannot appear in left-hand side");break;case"MemberExpression":if(!t)break;default:this.raise(e.start,"Assigning to rvalue")}else s&&this.checkPatternErrors(s,!0);return e},j.toAssignableList=function(e,t){for(var s=e.length,n=0;n<s;n++){var i=e[n];i&&this.toAssignable(i,t)}if(s){var r=e[s-1];6===this.options.ecmaVersion&&t&&r&&"RestElement"===r.type&&"Identifier"!==r.argument.type&&this.unexpected(r.argument.start)}return e},j.parseSpread=function(e){var t=this.startNode();return this.next(),t.argument=this.parseMaybeAssign(!1,e),this.finishNode(t,"SpreadElement")},j.parseRestBinding=function(){var e=this.startNode();return this.next(),6===this.options.ecmaVersion&&this.type!==u.name&&this.unexpected(),e.argument=this.parseBindingAtom(),this.finishNode(e,"RestElement")},j.parseBindingAtom=function(){if(this.options.ecmaVersion>=6)switch(this.type){case u.bracketL:var e=this.startNode();return this.next(),e.elements=this.parseBindingList(u.bracketR,!0,!0),this.finishNode(e,"ArrayPattern");case u.braceL:return this.parseObj(!0)}return this.parseIdent()},j.parseBindingList=function(e,t,s,n){for(var i=[],r=!0;!this.eat(e);)if(r?r=!1:this.expect(u.comma),t&&this.type===u.comma)i.push(null);else{if(s&&this.afterTrailingComma(e))break;if(this.type===u.ellipsis){var a=this.parseRestBinding();this.parseBindingListItem(a),i.push(a),this.type===u.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.expect(e);break}i.push(this.parseAssignableListItem(n))}return i},j.parseAssignableListItem=function(e){var t=this.parseMaybeDefault(this.start,this.startLoc);return this.parseBindingListItem(t),t},j.parseBindingListItem=function(e){return e},j.parseMaybeDefault=function(e,t,s){if(s=s||this.parseBindingAtom(),this.options.ecmaVersion<6||!this.eat(u.eq))return s;var n=this.startNodeAt(e,t);return n.left=s,n.right=this.parseMaybeAssign(),this.finishNode(n,"AssignmentPattern")},j.checkLValSimple=function(e,t,s){void 0===t&&(t=Ee);var n=t!==Ee;switch(e.type){case"Identifier":this.strict&&this.reservedWordsStrictBind.test(e.name)&&this.raiseRecoverable(e.start,(n?"Binding ":"Assigning to ")+e.name+" in strict mode"),n&&(t===Q&&"let"===e.name&&this.raiseRecoverable(e.start,"let is disallowed as a lexically bound name"),s&&(ue(s,e.name)&&this.raiseRecoverable(e.start,"Argument name clash"),s[e.name]=!0),t!==ht&&this.declareName(e.name,t,e.start));break;case"ChainExpression":this.raiseRecoverable(e.start,"Optional chaining cannot appear in left-hand side");break;case"MemberExpression":n&&this.raiseRecoverable(e.start,"Binding member expression");break;case"ParenthesizedExpression":return n&&this.raiseRecoverable(e.start,"Binding parenthesized expression"),this.checkLValSimple(e.expression,t,s);default:this.raise(e.start,(n?"Binding":"Assigning to")+" rvalue")}},j.checkLValPattern=function(e,t,s){switch(void 0===t&&(t=Ee),e.type){case"ObjectPattern":for(var n=0,i=e.properties;n<i.length;n+=1){var r=i[n];this.checkLValInnerPattern(r,t,s)}break;case"ArrayPattern":for(var a=0,o=e.elements;a<o.length;a+=1){var c=o[a];c&&this.checkLValInnerPattern(c,t,s)}break;default:this.checkLValSimple(e,t,s)}},j.checkLValInnerPattern=function(e,t,s){switch(void 0===t&&(t=Ee),e.type){case"Property":this.checkLValInnerPattern(e.value,t,s);break;case"AssignmentPattern":this.checkLValPattern(e.left,t,s);break;case"RestElement":this.checkLValPattern(e.argument,t,s);break;default:this.checkLValPattern(e,t,s)}};var U=function(e,t,s,n,i){this.token=e,this.isExpr=!!t,this.preserveSpace=!!s,this.override=n,this.generator=!!i},I={b_stat:new U("{",!1),b_expr:new U("{",!0),b_tmpl:new U("${",!1),p_stat:new U("(",!1),p_expr:new U("(",!0),q_tmpl:new U("`",!0,!0,(function(e){return e.tryReadTemplateToken()})),f_stat:new U("function",!1),f_expr:new U("function",!0),f_expr_gen:new U("function",!0,!1,null,!0),f_gen:new U("function",!1,!1,null,!0)},pe=P.prototype;pe.initialContext=function(){return[I.b_stat]},pe.curContext=function(){return this.context[this.context.length-1]},pe.braceIsBlock=function(e){var t=this.curContext();return t===I.f_expr||t===I.f_stat||(e!==u.colon||t!==I.b_stat&&t!==I.b_expr?e===u._return||e===u.name&&this.exprAllowed?V.test(this.input.slice(this.lastTokEnd,this.start)):e===u._else||e===u.semi||e===u.eof||e===u.parenR||e===u.arrow||(e===u.braceL?t===I.b_stat:e!==u._var&&e!==u._const&&e!==u.name&&!this.exprAllowed):!t.isExpr)},pe.inGeneratorContext=function(){for(var e=this.context.length-1;e>=1;e--){var t=this.context[e];if("function"===t.token)return t.generator}return!1},pe.updateContext=function(e){var t,s=this.type;s.keyword&&e===u.dot?this.exprAllowed=!1:(t=s.updateContext)?t.call(this,e):this.exprAllowed=s.beforeExpr},pe.overrideContext=function(e){this.curContext()!==e&&(this.context[this.context.length-1]=e)},u.parenR.updateContext=u.braceR.updateContext=function(){if(1!==this.context.length){var e=this.context.pop();e===I.b_stat&&"function"===this.curContext().token&&(e=this.context.pop()),this.exprAllowed=!e.isExpr}else this.exprAllowed=!0},u.braceL.updateContext=function(e){this.context.push(this.braceIsBlock(e)?I.b_stat:I.b_expr),this.exprAllowed=!0},u.dollarBraceL.updateContext=function(){this.context.push(I.b_tmpl),this.exprAllowed=!0},u.parenL.updateContext=function(e){var t=e===u._if||e===u._for||e===u._with||e===u._while;this.context.push(t?I.p_stat:I.p_expr),this.exprAllowed=!0},u.incDec.updateContext=function(){},u._function.updateContext=u._class.updateContext=function(e){!e.beforeExpr||e===u._else||e===u.semi&&this.curContext()!==I.p_stat||e===u._return&&V.test(this.input.slice(this.lastTokEnd,this.start))||(e===u.colon||e===u.braceL)&&this.curContext()===I.b_stat?this.context.push(I.f_stat):this.context.push(I.f_expr),this.exprAllowed=!1},u.colon.updateContext=function(){"function"===this.curContext().token&&this.context.pop(),this.exprAllowed=!0},u.backQuote.updateContext=function(){this.curContext()===I.q_tmpl?this.context.pop():this.context.push(I.q_tmpl),this.exprAllowed=!1},u.star.updateContext=function(e){if(e===u._function){var t=this.context.length-1;this.context[t]===I.f_expr?this.context[t]=I.f_expr_gen:this.context[t]=I.f_gen}this.exprAllowed=!0},u.name.updateContext=function(e){var t=!1;this.options.ecmaVersion>=6&&e!==u.dot&&("of"===this.value&&!this.exprAllowed||"yield"===this.value&&this.inGeneratorContext())&&(t=!0),this.exprAllowed=t};var y=P.prototype;function dt(e){return"Identifier"===e.type||"ParenthesizedExpression"===e.type&&dt(e.expression)}function De(e){return"MemberExpression"===e.type&&"PrivateIdentifier"===e.property.type||"ChainExpression"===e.type&&De(e.expression)||"ParenthesizedExpression"===e.type&&De(e.expression)}y.checkPropClash=function(e,t,s){if(!(this.options.ecmaVersion>=9&&"SpreadElement"===e.type||this.options.ecmaVersion>=6&&(e.computed||e.method||e.shorthand))){var n,i=e.key;switch(i.type){case"Identifier":n=i.name;break;case"Literal":n=String(i.value);break;default:return}var r=e.kind;if(this.options.ecmaVersion>=6)return void("__proto__"===n&&"init"===r&&(t.proto&&(s?s.doubleProto<0&&(s.doubleProto=i.start):this.raiseRecoverable(i.start,"Redefinition of __proto__ property")),t.proto=!0));var a=t[n="$"+n];if(a)("init"===r?this.strict&&a.init||a.get||a.set:a.init||a[r])&&this.raiseRecoverable(i.start,"Redefinition of property");else a=t[n]={init:!1,get:!1,set:!1};a[r]=!0}},y.parseExpression=function(e,t){var s=this.start,n=this.startLoc,i=this.parseMaybeAssign(e,t);if(this.type===u.comma){var r=this.startNodeAt(s,n);for(r.expressions=[i];this.eat(u.comma);)r.expressions.push(this.parseMaybeAssign(e,t));return this.finishNode(r,"SequenceExpression")}return i},y.parseMaybeAssign=function(e,t,s){if(this.isContextual("yield")){if(this.inGenerator)return this.parseYield(e);this.exprAllowed=!1}var n=!1,i=-1,r=-1,a=-1;t?(i=t.parenthesizedAssign,r=t.trailingComma,a=t.doubleProto,t.parenthesizedAssign=t.trailingComma=-1):(t=new Ie,n=!0);var o=this.start,c=this.startLoc;(this.type===u.parenL||this.type===u.name)&&(this.potentialArrowAt=this.start,this.potentialArrowInForAwait="await"===e);var p=this.parseMaybeConditional(e,t);if(s&&(p=s.call(this,p,o,c)),this.type.isAssign){var h=this.startNodeAt(o,c);return h.operator=this.value,this.type===u.eq&&(p=this.toAssignable(p,!1,t)),n||(t.parenthesizedAssign=t.trailingComma=t.doubleProto=-1),t.shorthandAssign>=p.start&&(t.shorthandAssign=-1),this.type===u.eq?this.checkLValPattern(p):this.checkLValSimple(p),h.left=p,this.next(),h.right=this.parseMaybeAssign(e),a>-1&&(t.doubleProto=a),this.finishNode(h,"AssignmentExpression")}return n&&this.checkExpressionErrors(t,!0),i>-1&&(t.parenthesizedAssign=i),r>-1&&(t.trailingComma=r),p},y.parseMaybeConditional=function(e,t){var s=this.start,n=this.startLoc,i=this.parseExprOps(e,t);if(this.checkExpressionErrors(t))return i;if(this.eat(u.question)){var r=this.startNodeAt(s,n);return r.test=i,r.consequent=this.parseMaybeAssign(),this.expect(u.colon),r.alternate=this.parseMaybeAssign(e),this.finishNode(r,"ConditionalExpression")}return i},y.parseExprOps=function(e,t){var s=this.start,n=this.startLoc,i=this.parseMaybeUnary(t,!1,!1,e);return this.checkExpressionErrors(t)||i.start===s&&"ArrowFunctionExpression"===i.type?i:this.parseExprOp(i,s,n,-1,e)},y.parseExprOp=function(e,t,s,n,i){var r=this.type.binop;if(null!=r&&(!i||this.type!==u._in)&&r>n){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 p=this.start,h=this.startLoc,l=this.parseExprOp(this.parseMaybeUnary(null,!1,!1,i),p,h,r,i),d=this.buildBinary(t,s,e,l,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(d,t,s,n,i)}return e},y.buildBinary=function(e,t,s,n,i,r){"PrivateIdentifier"===n.type&&this.raise(n.start,"Private identifier can only be left side of binary expression");var a=this.startNodeAt(e,t);return a.left=s,a.operator=i,a.right=n,this.finishNode(a,r?"LogicalExpression":"BinaryExpression")},y.parseMaybeUnary=function(e,t,s,n){var i,r=this.start,a=this.startLoc;if(this.isContextual("await")&&this.canAwait)i=this.parseAwait(n),t=!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,n),this.checkExpressionErrors(e,!0),c?this.checkLValSimple(o.argument):this.strict&&"delete"===o.operator&&dt(o.argument)?this.raiseRecoverable(o.start,"Deleting local variable in strict mode"):"delete"===o.operator&&De(o.argument)?this.raiseRecoverable(o.start,"Private fields can not be deleted"):t=!0,i=this.finishNode(o,c?"UpdateExpression":"UnaryExpression")}else if(t||this.type!==u.privateId){if(i=this.parseExprSubscripts(e,n),this.checkExpressionErrors(e))return i;for(;this.type.postfix&&!this.canInsertSemicolon();){var p=this.startNodeAt(r,a);p.operator=this.value,p.prefix=!1,p.argument=i,this.checkLValSimple(i),this.next(),i=this.finishNode(p,"UpdateExpression")}}else(n||0===this.privateNameStack.length)&&this.options.checkPrivateFields&&this.unexpected(),i=this.parsePrivateIdent(),this.type!==u._in&&this.unexpected();return s||!this.eat(u.starstar)?i:t?void this.unexpected(this.lastTokStart):this.buildBinary(r,a,i,this.parseMaybeUnary(null,!1,!1,n),"**",!1)},y.parseExprSubscripts=function(e,t){var s=this.start,n=this.startLoc,i=this.parseExprAtom(e,t);if("ArrowFunctionExpression"===i.type&&")"!==this.input.slice(this.lastTokStart,this.lastTokEnd))return i;var r=this.parseSubscripts(i,s,n,!1,t);return e&&"MemberExpression"===r.type&&(e.parenthesizedAssign>=r.start&&(e.parenthesizedAssign=-1),e.parenthesizedBind>=r.start&&(e.parenthesizedBind=-1),e.trailingComma>=r.start&&(e.trailingComma=-1)),r},y.parseSubscripts=function(e,t,s,n,i){for(var r=this.options.ecmaVersion>=8&&"Identifier"===e.type&&"async"===e.name&&this.lastTokEnd===e.end&&!this.canInsertSemicolon()&&e.end-e.start==5&&this.potentialArrowAt===e.start,a=!1;;){var o=this.parseSubscript(e,t,s,n,r,a,i);if(o.optional&&(a=!0),o===e||"ArrowFunctionExpression"===o.type){if(a){var c=this.startNodeAt(t,s);c.expression=o,o=this.finishNode(c,"ChainExpression")}return o}e=o}},y.shouldParseAsyncArrow=function(){return!this.canInsertSemicolon()&&this.eat(u.arrow)},y.parseSubscriptAsyncArrow=function(e,t,s,n){return this.parseArrowExpression(this.startNodeAt(e,t),s,!0,n)},y.parseSubscript=function(e,t,s,n,i,r,a){var o=this.options.ecmaVersion>=11,c=o&&this.eat(u.questionDot);n&&c&&this.raise(this.lastTokStart,"Optional chaining cannot appear in the callee of new expressions");var p=this.eat(u.bracketL);if(p||c&&this.type!==u.parenL&&this.type!==u.backQuote||this.eat(u.dot)){var h=this.startNodeAt(t,s);h.object=e,p?(h.property=this.parseExpression(),this.expect(u.bracketR)):this.type===u.privateId&&"Super"!==e.type?h.property=this.parsePrivateIdent():h.property=this.parseIdent("never"!==this.options.allowReserved),h.computed=!!p,o&&(h.optional=c),e=this.finishNode(h,"MemberExpression")}else if(!n&&this.eat(u.parenL)){var l=new Ie,d=this.yieldPos,m=this.awaitPos,f=this.awaitIdentPos;this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0;var g=this.parseExprList(u.parenR,this.options.ecmaVersion>=8,!1,l);if(i&&!c&&this.shouldParseAsyncArrow())return this.checkPatternErrors(l,!1),this.checkYieldAwaitInDefaultParams(),this.awaitIdentPos>0&&this.raise(this.awaitIdentPos,"Cannot use 'await' as identifier inside an async function"),this.yieldPos=d,this.awaitPos=m,this.awaitIdentPos=f,this.parseSubscriptAsyncArrow(t,s,g,a);this.checkExpressionErrors(l,!0),this.yieldPos=d||this.yieldPos,this.awaitPos=m||this.awaitPos,this.awaitIdentPos=f||this.awaitIdentPos;var x=this.startNodeAt(t,s);x.callee=e,x.arguments=g,o&&(x.optional=c),e=this.finishNode(x,"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 E=this.startNodeAt(t,s);E.tag=e,E.quasi=this.parseTemplate({isTagged:!0}),e=this.finishNode(E,"TaggedTemplateExpression")}return e},y.parseExprAtom=function(e,t,s){this.type===u.slash&&this.readRegexp();var n,i=this.potentialArrowAt===this.start;switch(this.type){case u._super:return this.allowSuper||this.raise(this.start,"'super' keyword outside a method"),n=this.startNode(),this.next(),this.type===u.parenL&&!this.allowDirectSuper&&this.raise(n.start,"super() call outside constructor of a subclass"),this.type!==u.dot&&this.type!==u.bracketL&&this.type!==u.parenL&&this.unexpected(),this.finishNode(n,"Super");case u._this:return n=this.startNode(),this.next(),this.finishNode(n,"ThisExpression");case u.name:var r=this.start,a=this.startLoc,o=this.containsEsc,c=this.parseIdent(!1);if(this.options.ecmaVersion>=8&&!o&&"async"===c.name&&!this.canInsertSemicolon()&&this.eat(u._function))return this.overrideContext(I.f_expr),this.parseFunction(this.startNodeAt(r,a),0,!1,!0,t);if(i&&!this.canInsertSemicolon()){if(this.eat(u.arrow))return this.parseArrowExpression(this.startNodeAt(r,a),[c],!1,t);if(this.options.ecmaVersion>=8&&"async"===c.name&&this.type===u.name&&!o&&(!this.potentialArrowInForAwait||"of"!==this.value||this.containsEsc))return c=this.parseIdent(!1),(this.canInsertSemicolon()||!this.eat(u.arrow))&&this.unexpected(),this.parseArrowExpression(this.startNodeAt(r,a),[c],!0,t)}return c;case u.regexp:var p=this.value;return(n=this.parseLiteral(p.value)).regex={pattern:p.pattern,flags:p.flags},n;case u.num:case u.string:return this.parseLiteral(this.value);case u._null:case u._true:case u._false:return(n=this.startNode()).value=this.type===u._null?null:this.type===u._true,n.raw=this.type.keyword,this.next(),this.finishNode(n,"Literal");case u.parenL:var h=this.start,l=this.parseParenAndDistinguishExpression(i,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(l)&&(e.parenthesizedAssign=h),e.parenthesizedBind<0&&(e.parenthesizedBind=h)),l;case u.bracketL:return n=this.startNode(),this.next(),n.elements=this.parseExprList(u.bracketR,!0,!0,e),this.finishNode(n,"ArrayExpression");case u.braceL:return this.overrideContext(I.b_expr),this.parseObj(!1,e);case u._function:return n=this.startNode(),this.next(),this.parseFunction(n,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()}},y.parseExprAtomDefault=function(){this.unexpected()},y.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword import"),this.next(),this.type===u.parenL&&!e)return this.parseDynamicImport(t);if(this.type===u.dot){var s=this.startNodeAt(t.start,t.loc&&t.loc.start);return s.name="import",t.meta=this.finishNode(s,"Identifier"),this.parseImportMeta(t)}this.unexpected()},y.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(u.parenR)?e.options=null:(this.expect(u.comma),this.afterTrailingComma(u.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(u.parenR)||(this.expect(u.comma),this.afterTrailingComma(u.parenR)||this.unexpected())));else if(!this.eat(u.parenR)){var t=this.start;this.eat(u.comma)&&this.eat(u.parenR)?this.raiseRecoverable(t,"Trailing comma is not allowed in import()"):this.unexpected(t)}return this.finishNode(e,"ImportExpression")},y.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),"meta"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for import is 'import.meta'"),t&&this.raiseRecoverable(e.start,"'import.meta' must not contain escaped characters"),"module"!==this.options.sourceType&&!this.options.allowImportExportEverywhere&&this.raiseRecoverable(e.start,"Cannot use 'import.meta' outside a module"),this.finishNode(e,"MetaProperty")},y.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),110===t.raw.charCodeAt(t.raw.length-1)&&(t.bigint=null!=t.value?t.value.toString():t.raw.slice(0,-1).replace(/_/g,"")),this.next(),this.finishNode(t,"Literal")},y.parseParenExpression=function(){this.expect(u.parenL);var e=this.parseExpression();return this.expect(u.parenR),e},y.shouldParseArrow=function(e){return!this.canInsertSemicolon()},y.parseParenAndDistinguishExpression=function(e,t){var s,n=this.start,i=this.startLoc,r=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var a,o=this.start,c=this.startLoc,p=[],h=!0,l=!1,d=new Ie,m=this.yieldPos,f=this.awaitPos;for(this.yieldPos=0,this.awaitPos=0;this.type!==u.parenR;){if(h?h=!1:this.expect(u.comma),r&&this.afterTrailingComma(u.parenR,!0)){l=!0;break}if(this.type===u.ellipsis){a=this.start,p.push(this.parseParenItem(this.parseRestBinding())),this.type===u.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element");break}p.push(this.parseMaybeAssign(!1,d,this.parseParenItem))}var g=this.lastTokEnd,x=this.lastTokEndLoc;if(this.expect(u.parenR),e&&this.shouldParseArrow(p)&&this.eat(u.arrow))return this.checkPatternErrors(d,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=m,this.awaitPos=f,this.parseParenArrowList(n,i,p,t);(!p.length||l)&&this.unexpected(this.lastTokStart),a&&this.unexpected(a),this.checkExpressionErrors(d,!0),this.yieldPos=m||this.yieldPos,this.awaitPos=f||this.awaitPos,p.length>1?((s=this.startNodeAt(o,c)).expressions=p,this.finishNodeAt(s,"SequenceExpression",g,x)):s=p[0]}else s=this.parseParenExpression();if(this.options.preserveParens){var E=this.startNodeAt(n,i);return E.expression=s,this.finishNode(E,"ParenthesizedExpression")}return s},y.parseParenItem=function(e){return e},y.parseParenArrowList=function(e,t,s,n){return this.parseArrowExpression(this.startNodeAt(e,t),s,!1,n)};var as=[];y.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,"Escape sequence in keyword new");var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===u.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name="new",e.meta=this.finishNode(t,"Identifier"),this.next();var s=this.containsEsc;return e.property=this.parseIdent(!0),"target"!==e.property.name&&this.raiseRecoverable(e.property.start,"The only valid meta property for new is 'new.target'"),s&&this.raiseRecoverable(e.start,"'new.target' must not contain escaped characters"),this.allowNewDotTarget||this.raiseRecoverable(e.start,"'new.target' can only be used in functions and class static block"),this.finishNode(e,"MetaProperty")}var n=this.start,i=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),n,i,!0,!1),this.eat(u.parenL)?e.arguments=this.parseExprList(u.parenR,this.options.ecmaVersion>=8,!1):e.arguments=as,this.finishNode(e,"NewExpression")},y.parseTemplateElement=function(e){var t=e.isTagged,s=this.startNode();return this.type===u.invalidTemplate?(t||this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal"),s.value={raw:this.value.replace(/\r\n?/g,"\n"),cooked:null}):s.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value},this.next(),s.tail=this.type===u.backQuote,this.finishNode(s,"TemplateElement")},y.parseTemplate=function(e){void 0===e&&(e={});var t=e.isTagged;void 0===t&&(t=!1);var s=this.startNode();this.next(),s.expressions=[];var n=this.parseTemplateElement({isTagged:t});for(s.quasis=[n];!n.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(n=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(s,"TemplateLiteral")},y.isAsyncProp=function(e){return!e.computed&&"Identifier"===e.key.type&&"async"===e.key.name&&(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))},y.parseObj=function(e,t){var s=this.startNode(),n=!0,i={};for(s.properties=[],this.next();!this.eat(u.braceR);){if(n)n=!1;else if(this.expect(u.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(u.braceR))break;var r=this.parseProperty(e,t);e||this.checkPropClash(r,i,t),s.properties.push(r)}return this.finishNode(s,e?"ObjectPattern":"ObjectExpression")},y.parseProperty=function(e,t){var s,n,i,r,a=this.startNode();if(this.options.ecmaVersion>=9&&this.eat(u.ellipsis))return e?(a.argument=this.parseIdent(!1),this.type===u.comma&&this.raiseRecoverable(this.start,"Comma is not permitted after the rest element"),this.finishNode(a,"RestElement")):(a.argument=this.parseMaybeAssign(!1,t),this.type===u.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(a,"SpreadElement"));this.options.ecmaVersion>=6&&(a.method=!1,a.shorthand=!1,(e||t)&&(i=this.start,r=this.startLoc),e||(s=this.eat(u.star)));var o=this.containsEsc;return this.parsePropertyName(a),!e&&!o&&this.options.ecmaVersion>=8&&!s&&this.isAsyncProp(a)?(n=!0,s=this.options.ecmaVersion>=9&&this.eat(u.star),this.parsePropertyName(a)):n=!1,this.parsePropertyValue(a,e,s,n,i,r,t,o),this.finishNode(a,"Property")},y.parseGetterSetter=function(e){var t=e.key.name;this.parsePropertyName(e),e.value=this.parseMethod(!1),e.kind=t;var s="get"===e.kind?0:1;if(e.value.params.length!==s){var n=e.value.start;"get"===e.kind?this.raiseRecoverable(n,"getter should have no params"):this.raiseRecoverable(n,"setter should have exactly one param")}else"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raiseRecoverable(e.value.params[0].start,"Setter cannot use rest params")},y.parsePropertyValue=function(e,t,s,n,i,r,a,o){(s||n)&&this.type===u.colon&&this.unexpected(),this.eat(u.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,a),e.kind="init"):this.options.ecmaVersion>=6&&this.type===u.parenL?(t&&this.unexpected(),e.method=!0,e.value=this.parseMethod(s,n),e.kind="init"):t||o||!(this.options.ecmaVersion>=5)||e.computed||"Identifier"!==e.key.type||"get"!==e.key.name&&"set"!==e.key.name||this.type===u.comma||this.type===u.braceR||this.type===u.eq?this.options.ecmaVersion>=6&&!e.computed&&"Identifier"===e.key.type?((s||n)&&this.unexpected(),this.checkUnreserved(e.key),"await"===e.key.name&&!this.awaitIdentPos&&(this.awaitIdentPos=i),t?e.value=this.parseMaybeDefault(i,r,this.copyNode(e.key)):this.type===u.eq&&a?(a.shorthandAssign<0&&(a.shorthandAssign=this.start),e.value=this.parseMaybeDefault(i,r,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.kind="init",e.shorthand=!0):this.unexpected():((s||n)&&this.unexpected(),this.parseGetterSetter(e))},y.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(u.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(u.bracketR),e.key;e.computed=!1}return e.key=this.type===u.num||this.type===u.string?this.parseExprAtom():this.parseIdent("never"!==this.options.allowReserved)},y.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},y.parseMethod=function(e,t,s){var n=this.startNode(),i=this.yieldPos,r=this.awaitPos,a=this.awaitIdentPos;return this.initFunction(n),this.options.ecmaVersion>=6&&(n.generator=e),this.options.ecmaVersion>=8&&(n.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(We(t,n.generator)|_e|(s?ut:0)),this.expect(u.parenL),n.params=this.parseBindingList(u.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(n,!1,!0,!1),this.yieldPos=i,this.awaitPos=r,this.awaitIdentPos=a,this.finishNode(n,"FunctionExpression")},y.parseArrowExpression=function(e,t,s,n){var i=this.yieldPos,r=this.awaitPos,a=this.awaitIdentPos;return this.enterScope(We(s,!1)|Ue),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!s),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,n),this.yieldPos=i,this.awaitPos=r,this.awaitIdentPos=a,this.finishNode(e,"ArrowFunctionExpression")},y.parseFunctionBody=function(e,t,s,n){var i=t&&this.type!==u.braceL,r=this.strict,a=!1;if(i)e.body=this.parseMaybeAssign(n),e.expression=!0,this.checkParams(e,!1);else{var o=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);(!r||o)&&((a=this.strictDirective(this.end))&&o&&this.raiseRecoverable(e.start,"Illegal 'use strict' directive in function with non-simple parameter list"));var c=this.labels;this.labels=[],a&&(this.strict=!0),this.checkParams(e,!r&&!a&&!t&&!s&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,ht),e.body=this.parseBlock(!1,void 0,a&&!r),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=c}this.exitScope()},y.isSimpleParamList=function(e){for(var t=0,s=e;t<s.length;t+=1){if("Identifier"!==s[t].type)return!1}return!0},y.checkParams=function(e,t){for(var s=Object.create(null),n=0,i=e.params;n<i.length;n+=1){var r=i[n];this.checkLValInnerPattern(r,He,t?null:s)}},y.parseExprList=function(e,t,s,n){for(var i=[],r=!0;!this.eat(e);){if(r)r=!1;else if(this.expect(u.comma),t&&this.afterTrailingComma(e))break;var a=void 0;s&&this.type===u.comma?a=null:this.type===u.ellipsis?(a=this.parseSpread(n),n&&this.type===u.comma&&n.trailingComma<0&&(n.trailingComma=this.start)):a=this.parseMaybeAssign(!1,n),i.push(a)}return i},y.checkUnreserved=function(e){var t=e.start,s=e.end,n=e.name;(this.inGenerator&&"yield"===n&&this.raiseRecoverable(t,"Cannot use 'yield' as identifier inside a generator"),this.inAsync&&"await"===n&&this.raiseRecoverable(t,"Cannot use 'await' as identifier inside an async function"),!(this.currentThisScope().flags&Ae)&&"arguments"===n&&this.raiseRecoverable(t,"Cannot use 'arguments' in class field initializer"),this.inClassStaticBlock&&("arguments"===n||"await"===n)&&this.raise(t,"Cannot use "+n+" in class static initialization block"),this.keywords.test(n)&&this.raise(t,"Unexpected keyword '"+n+"'"),this.options.ecmaVersion<6&&-1!==this.input.slice(t,s).indexOf("\\"))||(this.strict?this.reservedWordsStrict:this.reservedWords).test(n)&&(!this.inAsync&&"await"===n&&this.raiseRecoverable(t,"Cannot use keyword 'await' outside an async function"),this.raiseRecoverable(t,"The keyword '"+n+"' is reserved"))},y.parseIdent=function(e){var t=this.parseIdentNode();return this.next(!!e),this.finishNode(t,"Identifier"),e||(this.checkUnreserved(t),"await"===t.name&&!this.awaitIdentPos&&(this.awaitIdentPos=t.start)),t},y.parseIdentNode=function(){var e=this.startNode();return this.type===u.name?e.name=this.value:this.type.keyword?(e.name=this.type.keyword,("class"===e.name||"function"===e.name)&&(this.lastTokEnd!==this.lastTokStart+1||46!==this.input.charCodeAt(this.lastTokStart))&&this.context.pop(),this.type=u.name):this.unexpected(),e},y.parsePrivateIdent=function(){var e=this.startNode();return this.type===u.privateId?e.name=this.value:this.unexpected(),this.next(),this.finishNode(e,"PrivateIdentifier"),this.options.checkPrivateFields&&(0===this.privateNameStack.length?this.raise(e.start,"Private field '#"+e.name+"' must be declared in an enclosing class"):this.privateNameStack[this.privateNameStack.length-1].used.push(e)),e},y.parseYield=function(e){this.yieldPos||(this.yieldPos=this.start);var t=this.startNode();return this.next(),this.type===u.semi||this.canInsertSemicolon()||this.type!==u.star&&!this.type.startsExpr?(t.delegate=!1,t.argument=null):(t.delegate=this.eat(u.star),t.argument=this.parseMaybeAssign(e)),this.finishNode(t,"YieldExpression")},y.parseAwait=function(e){this.awaitPos||(this.awaitPos=this.start);var t=this.startNode();return this.next(),t.argument=this.parseMaybeUnary(null,!0,!1,e),this.finishNode(t,"AwaitExpression")};var ye=P.prototype;ye.raise=function(e,t){var s=at(this.input,e);t+=" ("+s.line+":"+s.column+")",this.sourceFile&&(t+=" in "+this.sourceFile);var n=new SyntaxError(t);throw n.pos=e,n.loc=s,n.raisedAt=this.pos,n},ye.raiseRecoverable=ye.raise,ye.curPosition=function(){if(this.options.locations)return new de(this.curLine,this.pos-this.lineStart)};var te=P.prototype,os=function(e){this.flags=e,this.var=[],this.lexical=[],this.functions=[]};te.enterScope=function(e){this.scopeStack.push(new os(e))},te.exitScope=function(){this.scopeStack.pop()},te.treatFunctionsAsVarInScope=function(e){return e.flags&le||!this.inModule&&e.flags&me},te.declareName=function(e,t,s){var n=!1;if(t===Q){var i=this.currentScope();n=i.lexical.indexOf(e)>-1||i.functions.indexOf(e)>-1||i.var.indexOf(e)>-1,i.lexical.push(e),this.inModule&&i.flags&me&&delete this.undefinedExports[e]}else if(t===pt){this.currentScope().lexical.push(e)}else if(t===lt){var r=this.currentScope();n=this.treatFunctionsAsVar?r.lexical.indexOf(e)>-1:r.lexical.indexOf(e)>-1||r.var.indexOf(e)>-1,r.functions.push(e)}else for(var a=this.scopeStack.length-1;a>=0;--a){var o=this.scopeStack[a];if(o.lexical.indexOf(e)>-1&&!(o.flags&ct&&o.lexical[0]===e)||!this.treatFunctionsAsVarInScope(o)&&o.functions.indexOf(e)>-1){n=!0;break}if(o.var.push(e),this.inModule&&o.flags&me&&delete this.undefinedExports[e],o.flags&Ae)break}n&&this.raiseRecoverable(s,"Identifier '"+e+"' has already been declared")},te.checkLocalExport=function(e){-1===this.scopeStack[0].lexical.indexOf(e.name)&&-1===this.scopeStack[0].var.indexOf(e.name)&&(this.undefinedExports[e.name]=e)},te.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},te.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&(Ae|ge|re))return t}},te.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&(Ae|ge|re)&&!(t.flags&Ue))return t}};var Pe=function(e,t,s){this.type="",this.start=t,this.end=0,e.options.locations&&(this.loc=new Te(e,s)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},xe=P.prototype;function mt(e,t,s,n){return e.type=t,e.end=s,this.options.locations&&(e.loc.end=n),this.options.ranges&&(e.range[1]=s),e}xe.startNode=function(){return new Pe(this,this.start,this.startLoc)},xe.startNodeAt=function(e,t){return new Pe(this,e,t)},xe.finishNode=function(e,t){return mt.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},xe.finishNodeAt=function(e,t,s,n){return mt.call(this,e,t,s,n)},xe.copyNode=function(e){var t=new Pe(this,e.start,this.startLoc);for(var s in e)t[s]=e[s];return t};var cs="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",bt=xt,Et=xt+" EBase EComp EMod EPres ExtPict",vt=Et,us=Et,ls={9:gt,10:xt,11:xt,12:Et,13:Et,14:us},ps="Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji",hs={9:"",10:"",11:"",12:"",13:"",14:ps},Je="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",Ct=yt+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd",St=Ct+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho",wt=St+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi",Tt=wt+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith",fs=Tt+" "+cs,ds={9:yt,10:Ct,11:St,12:wt,13:Tt,14:fs},_t={};function ms(e){var t=_t[e]={binary:Y(ls[e]+" "+Je),binaryOfStrings:Y(hs[e]),nonBinary:{General_Category:Y(Je),Script:Y(ds[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var Re=0,Ye=[9,10,11,12,13,14];Re<Ye.length;Re+=1){var gs=Ye[Re];ms(gs)}var x=P.prototype,Ce=function(e,t){this.parent=e,this.base=t||this};Ce.prototype.separatedFrom=function(e){for(var t=this;t;t=t.parent)for(var s=e;s;s=s.parent)if(t.base===s.base&&t!==s)return!0;return!1},Ce.prototype.sibling=function(){return new Ce(this.parent,this.base)};var q=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=_t[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};function xs(e){for(var t in e)return!0;return!1}function bs(e){return 105===e||109===e||115===e}function At(e){return 36===e||e>=40&&e<=43||46===e||63===e||e>=91&&e<=94||e>=123&&e<=125}function Es(e){return H(e,!0)||36===e||95===e}function vs(e){return ee(e,!0)||36===e||95===e||8204===e||8205===e}function It(e){return e>=65&&e<=90||e>=97&&e<=122}function ys(e){return e>=0&&e<=1114111}q.prototype.reset=function(e,t,s){var n=-1!==s.indexOf("v"),i=-1!==s.indexOf("u");this.start=0|e,this.source=t+"",this.flags=s,n&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=i&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=i&&this.parser.options.ecmaVersion>=9)},q.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+e)},q.prototype.at=function(e,t){void 0===t&&(t=!1);var s=this.source,n=s.length;if(e>=n)return-1;var i=s.charCodeAt(e);if(!t&&!this.switchU||i<=55295||i>=57344||e+1>=n)return i;var r=s.charCodeAt(e+1);return r>=56320&&r<=57343?(i<<10)+r-56613888:i},q.prototype.nextIndex=function(e,t){void 0===t&&(t=!1);var s=this.source,n=s.length;if(e>=n)return n;var i,r=s.charCodeAt(e);return!t&&!this.switchU||r<=55295||r>=57344||e+1>=n||(i=s.charCodeAt(e+1))<56320||i>57343?e+1:e+2},q.prototype.current=function(e){return void 0===e&&(e=!1),this.at(this.pos,e)},q.prototype.lookahead=function(e){return void 0===e&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},q.prototype.advance=function(e){void 0===e&&(e=!1),this.pos=this.nextIndex(this.pos,e)},q.prototype.eat=function(e,t){return void 0===t&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},q.prototype.eatChars=function(e,t){void 0===t&&(t=!1);for(var s=this.pos,n=0,i=e;n<i.length;n+=1){var r=i[n],a=this.at(s,t);if(-1===a||a!==r)return!1;s=this.nextIndex(s,t)}return this.pos=s,!0},x.validateRegExpFlags=function(e){for(var t=e.validFlags,s=e.flags,n=!1,i=!1,r=0;r<s.length;r++){var a=s.charAt(r);-1===t.indexOf(a)&&this.raise(e.start,"Invalid regular expression flag"),s.indexOf(a,r+1)>-1&&this.raise(e.start,"Duplicate regular expression flag"),"u"===a&&(n=!0),"v"===a&&(i=!0)}this.options.ecmaVersion>=15&&n&&i&&this.raise(e.start,"Invalid regular expression flag")},x.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&xs(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},x.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue="",e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise("Unmatched ')'"),(e.eat(93)||e.eat(125))&&e.raise("Lone quantifier brackets")),e.maxBackReference>e.numCapturingParens&&e.raise("Invalid escape");for(var t=0,s=e.backReferenceNames;t<s.length;t+=1){var n=s[t];e.groupNames[n]||e.raise("Invalid named capture referenced")}},x.regexp_disjunction=function(e){var t=this.options.ecmaVersion>=16;for(t&&(e.branchID=new Ce(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise("Nothing to repeat"),e.eat(123)&&e.raise("Lone quantifier brackets")},x.regexp_alternative=function(e){for(;e.pos<e.source.length&&this.regexp_eatTerm(e););},x.regexp_eatTerm=function(e){return this.regexp_eatAssertion(e)?(e.lastAssertionIsQuantifiable&&this.regexp_eatQuantifier(e)&&e.switchU&&e.raise("Invalid quantifier"),!0):!!(e.switchU?this.regexp_eatAtom(e):this.regexp_eatExtendedAtom(e))&&(this.regexp_eatQuantifier(e),!0)},x.regexp_eatAssertion=function(e){var t=e.pos;if(e.lastAssertionIsQuantifiable=!1,e.eat(94)||e.eat(36))return!0;if(e.eat(92)){if(e.eat(66)||e.eat(98))return!0;e.pos=t}if(e.eat(40)&&e.eat(63)){var s=!1;if(this.options.ecmaVersion>=9&&(s=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise("Unterminated group"),e.lastAssertionIsQuantifiable=!s,!0}return e.pos=t,!1},x.regexp_eatQuantifier=function(e,t){return void 0===t&&(t=!1),!!this.regexp_eatQuantifierPrefix(e,t)&&(e.eat(63),!0)},x.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},x.regexp_eatBracedQuantifier=function(e,t){var s=e.pos;if(e.eat(123)){var n=0,i=-1;if(this.regexp_eatDecimalDigits(e)&&(n=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(i=e.lastIntValue),e.eat(125)))return-1!==i&&i<n&&!t&&e.raise("numbers out of order in {} quantifier"),!0;e.switchU&&!t&&e.raise("Incomplete quantifier"),e.pos=s}return!1},x.regexp_eatAtom=function(e){return this.regexp_eatPatternCharacters(e)||e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)},x.regexp_eatReverseSolidusAtomEscape=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatAtomEscape(e))return!0;e.pos=t}return!1},x.regexp_eatUncapturingGroup=function(e){var t=e.pos;if(e.eat(40)){if(e.eat(63)){if(this.options.ecmaVersion>=16){var s=this.regexp_eatModifiers(e),n=e.eat(45);if(s||n){for(var i=0;i<s.length;i++){var r=s.charAt(i);s.indexOf(r,i+1)>-1&&e.raise("Duplicate regular expression modifiers")}if(n){var a=this.regexp_eatModifiers(e);!s&&!a&&58===e.current()&&e.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)&&e.raise("Duplicate regular expression modifiers")}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise("Unterminated group")}}e.pos=t}return!1},x.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):63===e.current()&&e.raise("Invalid group"),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise("Unterminated group")}return!1},x.regexp_eatModifiers=function(e){for(var t="",s=0;-1!==(s=e.current())&&bs(s);)t+=G(s),e.advance();return t},x.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},x.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise("Nothing to repeat"),!1},x.regexp_eatSyntaxCharacter=function(e){var t=e.current();return!!At(t)&&(e.lastIntValue=t,e.advance(),!0)},x.regexp_eatPatternCharacters=function(e){for(var t=e.pos,s=0;-1!==(s=e.current())&&!At(s);)e.advance();return e.pos!==t},x.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return!(-1===t||36===t||t>=40&&t<=43||46===t||63===t||91===t||94===t||124===t)&&(e.advance(),!0)},x.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise("Invalid group");var t=this.options.ecmaVersion>=16,s=e.groupNames[e.lastStringValue];if(s)if(t)for(var n=0,i=s;n<i.length;n+=1){i[n].separatedFrom(e.branchID)||e.raise("Duplicate capture group name")}else e.raise("Duplicate capture group name");t?(s||(e.groupNames[e.lastStringValue]=[])).push(e.branchID):e.groupNames[e.lastStringValue]=!0}},x.regexp_eatGroupName=function(e){if(e.lastStringValue="",e.eat(60)){if(this.regexp_eatRegExpIdentifierName(e)&&e.eat(62))return!0;e.raise("Invalid capture group name")}return!1},x.regexp_eatRegExpIdentifierName=function(e){if(e.lastStringValue="",this.regexp_eatRegExpIdentifierStart(e)){for(e.lastStringValue+=G(e.lastIntValue);this.regexp_eatRegExpIdentifierPart(e);)e.lastStringValue+=G(e.lastIntValue);return!0}return!1},x.regexp_eatRegExpIdentifierStart=function(e){var t=e.pos,s=this.options.ecmaVersion>=11,n=e.current(s);return e.advance(s),92===n&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(n=e.lastIntValue),Es(n)?(e.lastIntValue=n,!0):(e.pos=t,!1)},x.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,s=this.options.ecmaVersion>=11,n=e.current(s);return e.advance(s),92===n&&this.regexp_eatRegExpUnicodeEscapeSequence(e,s)&&(n=e.lastIntValue),vs(n)?(e.lastIntValue=n,!0):(e.pos=t,!1)},x.regexp_eatAtomEscape=function(e){return!!(this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e))||(e.switchU&&(99===e.current()&&e.raise("Invalid unicode escape"),e.raise("Invalid escape")),!1)},x.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var s=e.lastIntValue;if(e.switchU)return s>e.maxBackReference&&(e.maxBackReference=s),!0;if(s<=e.numCapturingParens)return!0;e.pos=t}return!1},x.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise("Invalid named reference")}return!1},x.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},x.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},x.regexp_eatZero=function(e){return 48===e.current()&&!ke(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},x.regexp_eatControlEscape=function(e){var t=e.current();return 116===t?(e.lastIntValue=9,e.advance(),!0):110===t?(e.lastIntValue=10,e.advance(),!0):118===t?(e.lastIntValue=11,e.advance(),!0):102===t?(e.lastIntValue=12,e.advance(),!0):114===t&&(e.lastIntValue=13,e.advance(),!0)},x.regexp_eatControlLetter=function(e){var t=e.current();return!!It(t)&&(e.lastIntValue=t%32,e.advance(),!0)},x.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){void 0===t&&(t=!1);var s=e.pos,n=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(n&&i>=55296&&i<=56319){var r=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var a=e.lastIntValue;if(a>=56320&&a<=57343)return e.lastIntValue=1024*(i-55296)+(a-56320)+65536,!0}e.pos=r,e.lastIntValue=i}return!0}if(n&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&ys(e.lastIntValue))return!0;n&&e.raise("Invalid unicode escape"),e.pos=s}return!1},x.regexp_eatIdentityEscape=function(e){if(e.switchU)return!!this.regexp_eatSyntaxCharacter(e)||!!e.eat(47)&&(e.lastIntValue=47,!0);var t=e.current();return!(99===t||e.switchN&&107===t)&&(e.lastIntValue=t,e.advance(),!0)},x.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do{e.lastIntValue=10*e.lastIntValue+(t-48),e.advance()}while((t=e.current())>=48&&t<=57);return!0}return!1};var Pt=0,K=1,$=2;function Cs(e){return 100===e||68===e||115===e||83===e||119===e||87===e}function kt(e){return It(e)||95===e}function Ss(e){return kt(e)||ke(e)}function ws(e){return 33===e||e>=35&&e<=38||e>=42&&e<=44||46===e||e>=58&&e<=64||94===e||96===e||126===e}function Ts(e){return 40===e||41===e||45===e||47===e||e>=91&&e<=93||e>=123&&e<=125}function _s(e){return 33===e||35===e||37===e||38===e||44===e||45===e||e>=58&&e<=62||64===e||96===e||126===e}function ke(e){return e>=48&&e<=57}function Nt(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function Mt(e){return e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:e-48}function Lt(e){return e>=48&&e<=55}x.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(Cs(t))return e.lastIntValue=-1,e.advance(),K;var s=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((s=80===t)||112===t)){var n;if(e.lastIntValue=-1,e.advance(),e.eat(123)&&(n=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return s&&n===$&&e.raise("Invalid property name"),n;e.raise("Invalid property name")}return Pt},x.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var s=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var n=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,s,n),K}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var i=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,i)}return Pt},x.regexp_validateUnicodePropertyNameAndValue=function(e,t,s){ue(e.unicodeProperties.nonBinary,t)||e.raise("Invalid property name"),e.unicodeProperties.nonBinary[t].test(s)||e.raise("Invalid property value")},x.regexp_validateUnicodePropertyNameOrValue=function(e,t){return e.unicodeProperties.binary.test(t)?K:e.switchV&&e.unicodeProperties.binaryOfStrings.test(t)?$:void e.raise("Invalid property name")},x.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue="";kt(t=e.current());)e.lastStringValue+=G(t),e.advance();return""!==e.lastStringValue},x.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue="";Ss(t=e.current());)e.lastStringValue+=G(t),e.advance();return""!==e.lastStringValue},x.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},x.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),s=this.regexp_classContents(e);return e.eat(93)||e.raise("Unterminated character class"),t&&s===$&&e.raise("Negated character class may contain strings"),!0}return!1},x.regexp_classContents=function(e){return 93===e.current()?K:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),K)},x.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var s=e.lastIntValue;e.switchU&&(-1===t||-1===s)&&e.raise("Invalid character class"),-1!==t&&-1!==s&&t>s&&e.raise("Range out of order in character class")}}},x.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var s=e.current();(99===s||Lt(s))&&e.raise("Invalid class escape"),e.raise("Invalid escape")}e.pos=t}var n=e.current();return 93!==n&&(e.lastIntValue=n,e.advance(),!0)},x.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},x.regexp_classSetExpression=function(e){var t,s=K;if(!this.regexp_eatClassSetRange(e))if(t=this.regexp_eatClassSetOperand(e)){t===$&&(s=$);for(var n=e.pos;e.eatChars([38,38]);)38!==e.current()&&(t=this.regexp_eatClassSetOperand(e))?t!==$&&(s=K):e.raise("Invalid character in character class");if(n!==e.pos)return s;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise("Invalid character in character class");if(n!==e.pos)return s}else e.raise("Invalid character in character class");for(;;)if(!this.regexp_eatClassSetRange(e)){if(!(t=this.regexp_eatClassSetOperand(e)))return s;t===$&&(s=$)}},x.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var s=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var n=e.lastIntValue;return-1!==s&&-1!==n&&s>n&&e.raise("Range out of order in character class"),!0}e.pos=t}return!1},x.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?K:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},x.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var s=e.eat(94),n=this.regexp_classContents(e);if(e.eat(93))return s&&n===$&&e.raise("Negated character class may contain strings"),n;e.pos=t}if(e.eat(92)){var i=this.regexp_eatCharacterClassEscape(e);if(i)return i;e.pos=t}return null},x.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var s=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return s}else e.raise("Invalid escape");e.pos=t}return null},x.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)this.regexp_classString(e)===$&&(t=$);return t},x.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return 1===t?K:$},x.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return!(!this.regexp_eatCharacterEscape(e)&&!this.regexp_eatClassSetReservedPunctuator(e))||(e.eat(98)?(e.lastIntValue=8,!0):(e.pos=t,!1));var s=e.current();return!(s<0||s===e.lookahead()&&ws(s)||Ts(s))&&(e.advance(),e.lastIntValue=s,!0)},x.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return!!_s(t)&&(e.lastIntValue=t,e.advance(),!0)},x.regexp_eatClassControlLetter=function(e){var t=e.current();return!(!ke(t)&&95!==t)&&(e.lastIntValue=t%32,e.advance(),!0)},x.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise("Invalid escape"),e.pos=t}return!1},x.regexp_eatDecimalDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;ke(s=e.current());)e.lastIntValue=10*e.lastIntValue+(s-48),e.advance();return e.pos!==t},x.regexp_eatHexDigits=function(e){var t=e.pos,s=0;for(e.lastIntValue=0;Nt(s=e.current());)e.lastIntValue=16*e.lastIntValue+Mt(s),e.advance();return e.pos!==t},x.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var s=e.lastIntValue;t<=3&&this.regexp_eatOctalDigit(e)?e.lastIntValue=64*t+8*s+e.lastIntValue:e.lastIntValue=8*t+s}else e.lastIntValue=t;return!0}return!1},x.regexp_eatOctalDigit=function(e){var t=e.current();return Lt(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)},x.regexp_eatFixedHexDigits=function(e,t){var s=e.pos;e.lastIntValue=0;for(var n=0;n<t;++n){var i=e.current();if(!Nt(i))return e.pos=s,!1;e.lastIntValue=16*e.lastIntValue+Mt(i),e.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])},S=P.prototype;function As(e,t){return t?parseInt(e,8):parseFloat(e.replace(/_/g,""))}function Rt(e){return"function"!=typeof BigInt?null:BigInt(e.replace(/_/g,""))}S.next=function(e){!e&&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()},S.getToken=function(){return this.next(),new qe(this)},typeof Symbol<"u"&&(S[Symbol.iterator]=function(){var e=this;return{next:function(){var t=e.getToken();return{done:t.type===u.eof,value:t}}}}),S.nextToken=function(){var e=this.curContext();return(!e||!e.preserveSpace)&&this.skipSpace(),this.start=this.pos,this.options.locations&&(this.startLoc=this.curPosition()),this.pos>=this.input.length?this.finishToken(u.eof):e.override?e.override(this):void this.readToken(this.fullCharCodeAtPos())},S.readToken=function(e){return H(e,this.options.ecmaVersion>=6)||92===e?this.readWord():this.getTokenFromCode(e)},S.fullCharCodeAtPos=function(){var e=this.input.charCodeAt(this.pos);if(e<=55295||e>=56320)return e;var t=this.input.charCodeAt(this.pos+1);return t<=56319||t>=57344?e:(e<<10)+t-56613888},S.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,s=this.input.indexOf("*/",this.pos+=2);if(-1===s&&this.raise(this.pos-2,"Unterminated comment"),this.pos=s+2,this.options.locations)for(var n=void 0,i=t;(n=it(this.input,i,this.pos))>-1;)++this.curLine,i=this.lineStart=n;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,s),t,this.pos,e,this.curPosition())},S.skipLineComment=function(e){for(var t=this.pos,s=this.options.onComment&&this.curPosition(),n=this.input.charCodeAt(this.pos+=e);this.pos<this.input.length&&!ce(n);)n=this.input.charCodeAt(++this.pos);this.options.onComment&&this.options.onComment(!1,this.input.slice(t+e,this.pos),t,this.pos,s,this.curPosition())},S.skipSpace=function(){e:for(;this.pos<this.input.length;){var e=this.input.charCodeAt(this.pos);switch(e){case 32:case 160:++this.pos;break;case 13:10===this.input.charCodeAt(this.pos+1)&&++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(!(e>8&&e<14||e>=5760&&nt.test(String.fromCharCode(e))))break e;++this.pos}}},S.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var s=this.type;this.type=e,this.value=t,this.updateContext(s)},S.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&46===e&&46===t?(this.pos+=3,this.finishToken(u.ellipsis)):(++this.pos,this.finishToken(u.dot))},S.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):61===e?this.finishOp(u.assign,2):this.finishOp(u.slash,1)},S.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),s=1,n=42===e?u.star:u.modulo;return this.options.ecmaVersion>=7&&42===e&&42===t&&(++s,n=u.starstar,t=this.input.charCodeAt(this.pos+2)),61===t?this.finishOp(u.assign,s+1):this.finishOp(n,s)},S.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);if(t===e){if(this.options.ecmaVersion>=12)if(61===this.input.charCodeAt(this.pos+2))return this.finishOp(u.assign,3);return this.finishOp(124===e?u.logicalOR:u.logicalAND,2)}return 61===t?this.finishOp(u.assign,2):this.finishOp(124===e?u.bitwiseOR:u.bitwiseAND,1)},S.readToken_caret=function(){return 61===this.input.charCodeAt(this.pos+1)?this.finishOp(u.assign,2):this.finishOp(u.bitwiseXOR,1)},S.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?45!==t||this.inModule||62!==this.input.charCodeAt(this.pos+2)||0!==this.lastTokEnd&&!V.test(this.input.slice(this.lastTokEnd,this.pos))?this.finishOp(u.incDec,2):(this.skipLineComment(3),this.skipSpace(),this.nextToken()):61===t?this.finishOp(u.assign,2):this.finishOp(u.plusMin,1)},S.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),s=1;return t===e?(s=62===e&&62===this.input.charCodeAt(this.pos+2)?3:2,61===this.input.charCodeAt(this.pos+s)?this.finishOp(u.assign,s+1):this.finishOp(u.bitShift,s)):33!==t||60!==e||this.inModule||45!==this.input.charCodeAt(this.pos+2)||45!==this.input.charCodeAt(this.pos+3)?(61===t&&(s=2),this.finishOp(u.relational,s)):(this.skipLineComment(4),this.skipSpace(),this.nextToken())},S.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return 61===t?this.finishOp(u.equality,61===this.input.charCodeAt(this.pos+2)?3:2):61===e&&62===t&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(u.arrow)):this.finishOp(61===e?u.eq:u.prefix,1)},S.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(46===t){var s=this.input.charCodeAt(this.pos+2);if(s<48||s>57)return this.finishOp(u.questionDot,2)}if(63===t){if(e>=12)if(61===this.input.charCodeAt(this.pos+2))return this.finishOp(u.assign,3);return this.finishOp(u.coalesce,2)}}return this.finishOp(u.question,1)},S.readToken_numberSign=function(){var e=35;if(this.options.ecmaVersion>=13&&(++this.pos,H(e=this.fullCharCodeAtPos(),!0)||92===e))return this.finishToken(u.privateId,this.readWord1());this.raise(this.pos,"Unexpected character '"+G(e)+"'")},S.getTokenFromCode=function(e){switch(e){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 t=this.input.charCodeAt(this.pos+1);if(120===t||88===t)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(111===t||79===t)return this.readRadixNumber(8);if(98===t||66===t)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(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);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(e)+"'")},S.finishOp=function(e,t){var s=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,s)},S.readRegexp=function(){for(var e,t,s=this.pos;;){this.pos>=this.input.length&&this.raise(s,"Unterminated regular expression");var n=this.input.charAt(this.pos);if(V.test(n)&&this.raise(s,"Unterminated regular expression"),e)e=!1;else{if("["===n)t=!0;else if("]"===n&&t)t=!1;else if("/"===n&&!t)break;e="\\"===n}++this.pos}var i=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 q(this));o.reset(s,i,a),this.validateRegExpFlags(o),this.validateRegExpPattern(o);var c=null;try{c=new RegExp(i,a)}catch{}return this.finishToken(u.regexp,{pattern:i,flags:a,value:c})},S.readInt=function(e,t,s){for(var n=this.options.ecmaVersion>=12&&void 0===t,i=s&&48===this.input.charCodeAt(this.pos),r=this.pos,a=0,o=0,c=0,p=t??1/0;c<p;++c,++this.pos){var h=this.input.charCodeAt(this.pos),l=void 0;if(n&&95===h)i&&this.raiseRecoverable(this.pos,"Numeric separator is not allowed in legacy octal numeric literals"),95===o&&this.raiseRecoverable(this.pos,"Numeric separator must be exactly one underscore"),0===c&&this.raiseRecoverable(this.pos,"Numeric separator is not allowed at the first of digits"),o=h;else{if((l=h>=97?h-97+10:h>=65?h-65+10:h>=48&&h<=57?h-48:1/0)>=e)break;o=h,a=a*e+l}}return n&&95===o&&this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits"),this.pos===r||null!=t&&this.pos-r!==t?null:a},S.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var s=this.readInt(e);return null==s&&this.raise(this.start+2,"Expected number in radix "+e),this.options.ecmaVersion>=11&&110===this.input.charCodeAt(this.pos)?(s=Rt(this.input.slice(t,this.pos)),++this.pos):H(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(u.num,s)},S.readNumber=function(e){var t=this.pos;!e&&null===this.readInt(10,void 0,!0)&&this.raise(t,"Invalid number");var s=this.pos-t>=2&&48===this.input.charCodeAt(t);s&&this.strict&&this.raise(t,"Invalid number");var n=this.input.charCodeAt(this.pos);if(!s&&!e&&this.options.ecmaVersion>=11&&110===n){var i=Rt(this.input.slice(t,this.pos));return++this.pos,H(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number"),this.finishToken(u.num,i)}s&&/[89]/.test(this.input.slice(t,this.pos))&&(s=!1),46===n&&!s&&(++this.pos,this.readInt(10),n=this.input.charCodeAt(this.pos)),(69===n||101===n)&&!s&&((43===(n=this.input.charCodeAt(++this.pos))||45===n)&&++this.pos,null===this.readInt(10)&&this.raise(t,"Invalid number")),H(this.fullCharCodeAtPos())&&this.raise(this.pos,"Identifier directly after number");var r=As(this.input.slice(t,this.pos),s);return this.finishToken(u.num,r)},S.readCodePoint=function(){var e;if(123===this.input.charCodeAt(this.pos)){this.options.ecmaVersion<6&&this.unexpected();var t=++this.pos;e=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos),++this.pos,e>1114111&&this.invalidStringToken(t,"Code point out of bounds")}else e=this.readHexChar(4);return e},S.readString=function(e){for(var t="",s=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated string constant");var n=this.input.charCodeAt(this.pos);if(n===e)break;92===n?(t+=this.input.slice(s,this.pos),t+=this.readEscapedChar(!1),s=this.pos):8232===n||8233===n?(this.options.ecmaVersion<10&&this.raise(this.start,"Unterminated string constant"),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(ce(n)&&this.raise(this.start,"Unterminated string constant"),++this.pos)}return t+=this.input.slice(s,this.pos++),this.finishToken(u.string,t)};var Ot={};S.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e!==Ot)throw e;this.readInvalidTemplateToken()}this.inTemplateElement=!1},S.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw Ot;this.raise(e,t)},S.readTmplToken=function(){for(var e="",t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,"Unterminated template");var s=this.input.charCodeAt(this.pos);if(96===s||36===s&&123===this.input.charCodeAt(this.pos+1))return this.pos!==this.start||this.type!==u.template&&this.type!==u.invalidTemplate?(e+=this.input.slice(t,this.pos),this.finishToken(u.template,e)):36===s?(this.pos+=2,this.finishToken(u.dollarBraceL)):(++this.pos,this.finishToken(u.backQuote));if(92===s)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(ce(s)){switch(e+=this.input.slice(t,this.pos),++this.pos,s){case 13:10===this.input.charCodeAt(this.pos)&&++this.pos;case 10:e+="\n";break;default:e+=String.fromCharCode(s)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},S.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":"\n"===this.input[this.pos+1]&&++this.pos;case"\n":case"\u2028":case"\u2029":++this.curLine,this.lineStart=this.pos+1}this.raise(this.start,"Unterminated template")},S.readEscapedChar=function(e){var t=this.input.charCodeAt(++this.pos);switch(++this.pos,t){case 110:return"\n";case 114:return"\r";case 120:return String.fromCharCode(this.readHexChar(2));case 117:return G(this.readCodePoint());case 116:return"\t";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 13:10===this.input.charCodeAt(this.pos)&&++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"),e){var s=this.pos-1;this.invalidStringToken(s,"Invalid escape sequence in template string")}default:if(t>=48&&t<=55){var n=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],i=parseInt(n,8);return i>255&&(n=n.slice(0,-1),i=parseInt(n,8)),this.pos+=n.length-1,t=this.input.charCodeAt(this.pos),("0"!==n||56===t||57===t)&&(this.strict||e)&&this.invalidStringToken(this.pos-1-n.length,e?"Octal literal in template string":"Octal literal in strict mode"),String.fromCharCode(i)}return ce(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),""):String.fromCharCode(t)}},S.readHexChar=function(e){var t=this.pos,s=this.readInt(16,e);return null===s&&this.invalidStringToken(t,"Bad character escape sequence"),s},S.readWord1=function(){this.containsEsc=!1;for(var e="",t=!0,s=this.pos,n=this.options.ecmaVersion>=6;this.pos<this.input.length;){var i=this.fullCharCodeAtPos();if(ee(i,n))this.pos+=i<=65535?1:2;else{if(92!==i)break;this.containsEsc=!0,e+=this.input.slice(s,this.pos);var r=this.pos;117!==this.input.charCodeAt(++this.pos)&&this.invalidStringToken(this.pos,"Expecting Unicode escape sequence \\uXXXX"),++this.pos;var a=this.readCodePoint();(t?H:ee)(a,n)||this.invalidStringToken(r,"Invalid Unicode escape"),e+=G(a),s=this.pos}t=!1}return e+this.input.slice(s,this.pos)},S.readWord=function(){var e=this.readWord1(),t=u.name;return this.keywords.test(e)&&(t=$e[e]),this.finishToken(t,e)};var Is="8.15.0";function ne(e,t){return P.parse(e,t)}function J(e,t,s,n,i){s||(s=m),function e(n,i,r){var a=r||n.type;s[a](n,i,e),t[a]&&t[a](n,i)}(e,n,i)}function Ps(e,t,s,n,i){var r=[];s||(s=m),function e(n,i,a){var o=a||n.type,c=n!==r[r.length-1];c&&r.push(n),s[o](n,i,e),t[o]&&t[o](n,i||r,r),c&&r.pop()}(e,n,i)}function Xe(e,t,s){s(e,t)}function ae(e,t,s){}P.acorn={Parser:P,version:Is,defaultOptions:Ve,Position:de,SourceLocation:Te,getLineInfo:at,Node:Pe,TokenType:T,tokTypes:u,keywordTypes:$e,TokContext:U,tokContexts:I,isIdentifierChar:ee,isIdentifierStart:H,Token:qe,isNewLine:ce,lineBreak:V,lineBreakG:Qt,nonASCIIwhitespace:nt};var m={};m.Program=m.BlockStatement=m.StaticBlock=function(e,t,s){for(var n=0,i=e.body;n<i.length;n+=1){s(i[n],t,"Statement")}},m.Statement=Xe,m.EmptyStatement=ae,m.ExpressionStatement=m.ParenthesizedExpression=m.ChainExpression=function(e,t,s){return s(e.expression,t,"Expression")},m.IfStatement=function(e,t,s){s(e.test,t,"Expression"),s(e.consequent,t,"Statement"),e.alternate&&s(e.alternate,t,"Statement")},m.LabeledStatement=function(e,t,s){return s(e.body,t,"Statement")},m.BreakStatement=m.ContinueStatement=ae,m.WithStatement=function(e,t,s){s(e.object,t,"Expression"),s(e.body,t,"Statement")},m.SwitchStatement=function(e,t,s){s(e.discriminant,t,"Expression");for(var n=0,i=e.cases;n<i.length;n+=1){s(i[n],t)}},m.SwitchCase=function(e,t,s){e.test&&s(e.test,t,"Expression");for(var n=0,i=e.consequent;n<i.length;n+=1){s(i[n],t,"Statement")}},m.ReturnStatement=m.YieldExpression=m.AwaitExpression=function(e,t,s){e.argument&&s(e.argument,t,"Expression")},m.ThrowStatement=m.SpreadElement=function(e,t,s){return s(e.argument,t,"Expression")},m.TryStatement=function(e,t,s){s(e.block,t,"Statement"),e.handler&&s(e.handler,t),e.finalizer&&s(e.finalizer,t,"Statement")},m.CatchClause=function(e,t,s){e.param&&s(e.param,t,"Pattern"),s(e.body,t,"Statement")},m.WhileStatement=m.DoWhileStatement=function(e,t,s){s(e.test,t,"Expression"),s(e.body,t,"Statement")},m.ForStatement=function(e,t,s){e.init&&s(e.init,t,"ForInit"),e.test&&s(e.test,t,"Expression"),e.update&&s(e.update,t,"Expression"),s(e.body,t,"Statement")},m.ForInStatement=m.ForOfStatement=function(e,t,s){s(e.left,t,"ForInit"),s(e.right,t,"Expression"),s(e.body,t,"Statement")},m.ForInit=function(e,t,s){"VariableDeclaration"===e.type?s(e,t):s(e,t,"Expression")},m.DebuggerStatement=ae,m.FunctionDeclaration=function(e,t,s){return s(e,t,"Function")},m.VariableDeclaration=function(e,t,s){for(var n=0,i=e.declarations;n<i.length;n+=1){s(i[n],t)}},m.VariableDeclarator=function(e,t,s){s(e.id,t,"Pattern"),e.init&&s(e.init,t,"Expression")},m.Function=function(e,t,s){e.id&&s(e.id,t,"Pattern");for(var n=0,i=e.params;n<i.length;n+=1){s(i[n],t,"Pattern")}s(e.body,t,e.expression?"Expression":"Statement")},m.Pattern=function(e,t,s){"Identifier"===e.type?s(e,t,"VariablePattern"):"MemberExpression"===e.type?s(e,t,"MemberPattern"):s(e,t)},m.VariablePattern=ae,m.MemberPattern=Xe,m.RestElement=function(e,t,s){return s(e.argument,t,"Pattern")},m.ArrayPattern=function(e,t,s){for(var n=0,i=e.elements;n<i.length;n+=1){var r=i[n];r&&s(r,t,"Pattern")}},m.ObjectPattern=function(e,t,s){for(var n=0,i=e.properties;n<i.length;n+=1){var r=i[n];"Property"===r.type?(r.computed&&s(r.key,t,"Expression"),s(r.value,t,"Pattern")):"RestElement"===r.type&&s(r.argument,t,"Pattern")}},m.Expression=Xe,m.ThisExpression=m.Super=m.MetaProperty=ae,m.ArrayExpression=function(e,t,s){for(var n=0,i=e.elements;n<i.length;n+=1){var r=i[n];r&&s(r,t,"Expression")}},m.ObjectExpression=function(e,t,s){for(var n=0,i=e.properties;n<i.length;n+=1){s(i[n],t)}},m.FunctionExpression=m.ArrowFunctionExpression=m.FunctionDeclaration,m.SequenceExpression=function(e,t,s){for(var n=0,i=e.expressions;n<i.length;n+=1){s(i[n],t,"Expression")}},m.TemplateLiteral=function(e,t,s){for(var n=0,i=e.quasis;n<i.length;n+=1){s(i[n],t)}for(var r=0,a=e.expressions;r<a.length;r+=1){s(a[r],t,"Expression")}},m.TemplateElement=ae,m.UnaryExpression=m.UpdateExpression=function(e,t,s){s(e.argument,t,"Expression")},m.BinaryExpression=m.LogicalExpression=function(e,t,s){s(e.left,t,"Expression"),s(e.right,t,"Expression")},m.AssignmentExpression=m.AssignmentPattern=function(e,t,s){s(e.left,t,"Pattern"),s(e.right,t,"Expression")},m.ConditionalExpression=function(e,t,s){s(e.test,t,"Expression"),s(e.consequent,t,"Expression"),s(e.alternate,t,"Expression")},m.NewExpression=m.CallExpression=function(e,t,s){if(s(e.callee,t,"Expression"),e.arguments)for(var n=0,i=e.arguments;n<i.length;n+=1){s(i[n],t,"Expression")}},m.MemberExpression=function(e,t,s){s(e.object,t,"Expression"),e.computed&&s(e.property,t,"Expression")},m.ExportNamedDeclaration=m.ExportDefaultDeclaration=function(e,t,s){e.declaration&&s(e.declaration,t,"ExportNamedDeclaration"===e.type||e.declaration.id?"Statement":"Expression"),e.source&&s(e.source,t,"Expression")},m.ExportAllDeclaration=function(e,t,s){e.exported&&s(e.exported,t),s(e.source,t,"Expression")},m.ImportDeclaration=function(e,t,s){for(var n=0,i=e.specifiers;n<i.length;n+=1){s(i[n],t)}s(e.source,t,"Expression")},m.ImportExpression=function(e,t,s){s(e.source,t,"Expression")},m.ImportSpecifier=m.ImportDefaultSpecifier=m.ImportNamespaceSpecifier=m.Identifier=m.PrivateIdentifier=m.Literal=ae,m.TaggedTemplateExpression=function(e,t,s){s(e.tag,t,"Expression"),s(e.quasi,t,"Expression")},m.ClassDeclaration=m.ClassExpression=function(e,t,s){return s(e,t,"Class")},m.Class=function(e,t,s){e.id&&s(e.id,t,"Pattern"),e.superClass&&s(e.superClass,t,"Expression"),s(e.body,t)},m.ClassBody=function(e,t,s){for(var n=0,i=e.body;n<i.length;n+=1){s(i[n],t)}},m.MethodDefinition=m.PropertyDefinition=m.Property=function(e,t,s){e.computed&&s(e.key,t,"Expression"),e.value&&s(e.value,t,"Expression")};const g={ATTR_PREFIXES:{COMPONENT:"pp-component",CONTEXT:"pp-context",LOOP:"pp-for",SPREAD:"pp-spread"},SCRIPT_TYPE:"text/pp",MAX_CACHE_SIZE:500,DEBOUNCE_MS:16,POOL_SIZE:10,MUSTACHE_PATTERN:/\{((?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*)\}/,MUSTACHE_SINGLE_PATTERN:/^\{((?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*)\}$/},Vt=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"]);function ks(e,t){let s;return(...n)=>{clearTimeout(s),s=window.setTimeout((()=>e(...n)),t)}}function Ft(e){return e.charAt(0).toUpperCase()+e.slice(1)}function k(e){if(null==e||"boolean"==typeof e||"function"==typeof e||Array.isArray(e)&&0===e.length||"object"==typeof e&&0===Object.keys(e).length)return"";if("number"==typeof e)return String(e);if("string"==typeof e)return e;if(Array.isArray(e))return e.map((e=>k(e))).filter((e=>""!==e)).join("");if("object"==typeof e)try{return JSON.stringify(e)}catch{return"[object Object]"}return String(e)}const W=class e{constructor(){d(this,"stateVariables",new Set)}static getInstance(){return e.instance||(e.instance=new e),e.instance}transformEffectDeclarations(e){try{const t=ne(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0});let s=e;const n=[];return J(t,{CallExpression:t=>{const s=this.transformEffectCall(t,e);s&&n.push(s)}}),n.sort(((e,t)=>t.start-e.start)).forEach((e=>{s=s.slice(0,e.start)+e.replacement+s.slice(e.end)})),s}catch(t){return console.error("Effect transformation error:",t),e}}transformEffectCall(e,t){if(!this.isPPEffectCall(e))return null;const s=e.arguments;if(s.length<2)return null;const n=s[1];if("ArrayExpression"!==n.type||!n.elements.some((e=>!!e&&("Identifier"===e.type||"MemberExpression"===e.type))))return null;const i=n.elements.map((e=>e?"Identifier"===e.type?`"${e.name}"`:"MemberExpression"===e.type?`"${this.extractMemberExpression(e,t)}"`:t.slice(e.start,e.end):"null")),r=t.slice(s[0].start,s[0].end),a=s.slice(2).map((e=>t.slice(e.start,e.end))).join(", "),o=`[${i.join(", ")}]`,c=a?`pp.effect(${r}, ${o}, ${a})`:`pp.effect(${r}, ${o})`;return{start:e.start,end:e.end,replacement:c}}extractMemberExpression(e,t){if("MemberExpression"!==e.type)return"Identifier"===e.type?e.name:t.slice(e.start,e.end);const s=this.extractMemberExpression(e.object,t);if(e.computed){return`${s}[${t.slice(e.property.start,e.property.end)}]`}return`${s}.${e.property.name||t.slice(e.property.start,e.property.end)}`}isPPEffectCall(e){var t,s,n;return"MemberExpression"===(null==(t=e.callee)?void 0:t.type)&&"Identifier"===(null==(s=e.callee.object)?void 0:s.type)&&"pp"===e.callee.object.name&&"Identifier"===(null==(n=e.callee.property)?void 0:n.type)&&"effect"===e.callee.property.name}transformStateDeclarations(e){this.stateVariables.clear();let t=this.transformStateDeclarationsOnly(e);return t=this.transformEffectDeclarations(t),t=this.transformUnsupportedStateUsages(t),t}transformStateDeclarationsOnlyOriginal(e){try{const t=ne(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0});let s=e;const n=[];return J(t,{VariableDeclarator:t=>{const s=this.transformStateDeclarator(t,e);s&&n.push(s)}}),n.sort(((e,t)=>t.start-e.start)).forEach((e=>{s=s.slice(0,e.start)+e.replacement+s.slice(e.end)})),s}catch(t){return console.error("AST transformation error:",t),e}}transformStateDeclarationsOnly(e){let t=this.transformStateDeclarationsOnlyOriginal(e);return t=this.transformDestructuringAssignments(t),t}transformUnsupportedStateUsages(e){try{const t=ne(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0});this.collectStateVariables(t);let s=e;const n=[];return J(t,{SpreadElement:e=>{const t=this.transformSpreadElement(e,s);t&&n.push(t)},UnaryExpression:e=>{const t=this.transformUnaryExpression(e,s);t&&n.push(t)},BinaryExpression:e=>{const t=this.transformBinaryExpression(e,s);t&&n.push(t)},LogicalExpression:e=>{const t=this.transformLogicalExpression(e,s);t&&n.push(t)},ConditionalExpression:e=>{const t=this.transformConditionalExpression(e,s);t&&n.push(t)},IfStatement:e=>{const t=this.transformIfStatement(e,s);t&&n.push(t)},WhileStatement:e=>{const t=this.transformWhileStatement(e,s);t&&n.push(t)},ForStatement:e=>{const t=this.transformForStatement(e,s);t&&n.push(t)},ReturnStatement:e=>{const t=this.transformReturnStatement(e,s);t&&n.push(t)},VariableDeclarator:e=>{const t=this.transformVariableDeclarator(e,s);t&&n.push(t)},AssignmentExpression:e=>{const t=this.transformAssignmentExpression(e,s);t&&n.push(t)},CallExpression:e=>{const t=this.transformGeneralCallExpression(e,s);t&&n.push(t)}}),Ps(t,{Identifier:(e,t)=>{n.some((t=>e.start>=t.start&&e.end<=t.end))||this.stateVariables.has(e.name)&&(this.alreadyHasValue(e,s)||this.isPartOfStateDeclaration(e,t)||this.isPropertyName(e,t)||this.isMethodCallObject(e,t)||this.isPartOfPPCall(e,t)||this.isPartOfDestructuring(e,t)||n.push({start:e.start,end:e.end,replacement:`${e.name}.value`}))}}),n.sort(((e,t)=>t.start-e.start)).forEach((e=>{s=s.slice(0,e.start)+e.replacement+s.slice(e.end)})),s=this.transformMultipleCallArguments(s),s}catch(t){return console.error("State usage transformation error:",t),e}}transformLogicalExpression(e,t){var s,n;return"Identifier"===(null==(s=e.left)?void 0:s.type)&&this.stateVariables.has(e.left.name)&&!this.alreadyHasValue(e.left,t)?{start:e.left.start,end:e.left.end,replacement:`${e.left.name}.value`}:"Identifier"===(null==(n=e.right)?void 0:n.type)&&this.stateVariables.has(e.right.name)&&!this.alreadyHasValue(e.right,t)?{start:e.right.start,end:e.right.end,replacement:`${e.right.name}.value`}:null}transformConditionalExpression(e,t){var s,n,i;return"Identifier"===(null==(s=e.test)?void 0:s.type)&&this.stateVariables.has(e.test.name)&&!this.alreadyHasValue(e.test,t)?{start:e.test.start,end:e.test.end,replacement:`${e.test.name}.value`}:"Identifier"===(null==(n=e.consequent)?void 0:n.type)&&this.stateVariables.has(e.consequent.name)&&!this.alreadyHasValue(e.consequent,t)?{start:e.consequent.start,end:e.consequent.end,replacement:`${e.consequent.name}.value`}:"Identifier"===(null==(i=e.alternate)?void 0:i.type)&&this.stateVariables.has(e.alternate.name)&&!this.alreadyHasValue(e.alternate,t)?{start:e.alternate.start,end:e.alternate.end,replacement:`${e.alternate.name}.value`}:null}transformIfStatement(e,t){return this.transformExpressionNode(e.test,t)}transformWhileStatement(e,t){return this.transformExpressionNode(e.test,t)}transformForStatement(e,t){return e.test?this.transformExpressionNode(e.test,t):null}transformReturnStatement(e,t){return e.argument?this.transformExpressionNode(e.argument,t):null}transformVariableDeclarator(e,t){var s,n,i;return this.isStateDeclaration(e)||"ArrayPattern"===(null==(s=e.id)?void 0:s.type)||"ObjectPattern"===(null==(n=e.id)?void 0:n.type)?null:"Identifier"===(null==(i=e.init)?void 0:i.type)&&this.stateVariables.has(e.init.name)&&!this.alreadyHasValue(e.init,t)?{start:e.init.start,end:e.init.end,replacement:`${e.init.name}.value`}:null}transformAssignmentExpression(e,t){var s,n,i;return"ArrayPattern"===(null==(s=e.left)?void 0:s.type)||"ObjectPattern"===(null==(n=e.left)?void 0:n.type)?null:"Identifier"===(null==(i=e.right)?void 0:i.type)&&this.stateVariables.has(e.right.name)&&!this.alreadyHasValue(e.right,t)?{start:e.right.start,end:e.right.end,replacement:`${e.right.name}.value`}:null}transformGeneralCallExpression(t,s){var n,i;const r=s.slice(t.callee.start,t.callee.end);if("MemberExpression"===(null==(n=t.callee)?void 0:n.type)&&"Identifier"===(null==(i=t.callee.object)?void 0:i.type)&&this.stateVariables.has(t.callee.object.name)||this.isPPCall(t))return null;if(!e.isFunctionNeedingValueTransform(r)&&t.arguments.length>0)for(const e of t.arguments)if("Identifier"===e.type&&this.stateVariables.has(e.name)&&!this.alreadyHasValue(e,s))return{start:e.start,end:e.end,replacement:`${e.name}.value`};return null}static isFunctionNeedingValueTransform(e){return this.FUNCTIONS_NEEDING_VALUE_TRANSFORM.some((t=>t.includes(".")?e===t:e===t||e.endsWith("."+t)))}transformExpressionNode(e,t){return"Identifier"===(null==e?void 0:e.type)&&this.stateVariables.has(e.name)&&!this.alreadyHasValue(e,t)?{start:e.start,end:e.end,replacement:`${e.name}.value`}:null}isPPCall(e){var t,s,n;return"MemberExpression"===(null==(t=e.callee)?void 0:t.type)&&"Identifier"===(null==(s=e.callee.object)?void 0:s.type)&&"pp"===e.callee.object.name&&"Identifier"===(null==(n=e.callee.property)?void 0:n.type)&&("state"===e.callee.property.name||"effect"===e.callee.property.name)}isPartOfStateDeclaration(e,t){var s,n;if(!t||!Array.isArray(t))return!1;for(const e of t)if("VariableDeclarator"===e.type&&"ArrayPattern"===(null==(s=e.id)?void 0:s.type)&&"CallExpression"===(null==(n=e.init)?void 0:n.type)&&this.isPPStateCall(e.init))return!0;return!1}isPropertyName(e,t){if(!t||0===t.length)return!1;const s=t[t.length-1];return"Property"===(null==s?void 0:s.type)&&s.key===e||"MemberExpression"===(null==s?void 0:s.type)&&s.property===e&&!s.computed}isMethodCallObject(e,t){if(!t||0===t.length)return!1;const s=t[t.length-1];if("MemberExpression"===(null==s?void 0:s.type)&&s.object===e&&t.length>=2){const e=t[t.length-2];if("CallExpression"===(null==e?void 0:e.type)&&e.callee===s)return!0}return!1}isPartOfPPCall(e,t){var s,n,i;if(!t||!Array.isArray(t))return!1;for(const e of t)if("CallExpression"===e.type&&"MemberExpression"===(null==(s=e.callee)?void 0:s.type)&&"Identifier"===(null==(n=e.callee.object)?void 0:n.type)&&"pp"===e.callee.object.name&&"Identifier"===(null==(i=e.callee.property)?void 0:i.type)&&("state"===e.callee.property.name||"effect"===e.callee.property.name))return!0;return!1}isPartOfDestructuring(e,t){if(!t||!Array.isArray(t))return!1;for(let s=0;s<t.length;s++){const n=t[s];if("ArrayPattern"===n.type||"ObjectPattern"===n.type){if(s+1<t.length){const i=t[s+1];if("VariableDeclarator"===(null==i?void 0:i.type)&&i.id===n&&i.init===e)return!1}return!0}}return!1}collectStateVariables(e){J(e,{VariableDeclarator:e=>{if(this.isStateDeclaration(e)){const t=e.id.elements[0];"Identifier"===(null==t?void 0:t.type)&&this.stateVariables.add(t.name)}}})}isStateDeclaration(e){var t,s;return"ArrayPattern"===(null==(t=e.id)?void 0:t.type)&&"CallExpression"===(null==(s=e.init)?void 0:s.type)&&this.isPPStateCall(e.init)}transformSpreadElement(e,t){var s;return"Identifier"===(null==(s=e.argument)?void 0:s.type)&&this.stateVariables.has(e.argument.name)?this.alreadyHasValue(e.argument,t)?null:{start:e.argument.start,end:e.argument.end,replacement:`${e.argument.name}.value`}:null}transformUnaryExpression(e,t){var s;return"Identifier"===(null==(s=e.argument)?void 0:s.type)&&this.stateVariables.has(e.argument.name)&&["typeof","!","+","-","~","void","delete"].includes(e.operator)&&!this.alreadyHasValue(e.argument,t)?{start:e.argument.start,end:e.argument.end,replacement:`${e.argument.name}.value`}:null}transformBinaryExpression(e,t){var s,n;if(["===","!==","==","!=",">","<",">=","<=","+","-","*","/","%","**","&","|","^","<<",">>",">>>","in","instanceof"].includes(e.operator)){if("Identifier"===(null==(s=e.left)?void 0:s.type)&&this.stateVariables.has(e.left.name)&&!this.alreadyHasValue(e.left,t))return{start:e.left.start,end:e.left.end,replacement:`${e.left.name}.value`};if("Identifier"===(null==(n=e.right)?void 0:n.type)&&this.stateVariables.has(e.right.name)&&!this.alreadyHasValue(e.right,t))return{start:e.right.start,end:e.right.end,replacement:`${e.right.name}.value`}}return null}transformMultipleCallArguments(t){try{const s=ne(t,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0});let n=t;const i=[];return J(s,{CallExpression:t=>{const s=n.slice(t.callee.start,t.callee.end);if(e.isFunctionNeedingValueTransform(s)&&t.arguments.length>0)for(const e of t.arguments)"Identifier"===e.type&&this.stateVariables.has(e.name)&&(this.alreadyHasValue(e,n)||i.push({start:e.start,end:e.end,replacement:`${e.name}.value`}))}}),i.sort(((e,t)=>t.start-e.start)).forEach((e=>{n=n.slice(0,e.start)+e.replacement+n.slice(e.end)})),n}catch(e){return console.error("Multiple call arguments transformation error:",e),t}}transformDestructuringAssignments(e){try{const t=ne(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0});let s=e;const n=[];return J(t,{VariableDeclarator:t=>{var s,i,r;this.isStateDeclaration(t)||("ArrayPattern"===(null==(s=t.id)?void 0:s.type)||"ObjectPattern"===(null==(i=t.id)?void 0:i.type))&&"Identifier"===(null==(r=t.init)?void 0:r.type)&&this.stateVariables.has(t.init.name)&&(this.alreadyHasValue(t.init,e)||n.push({start:t.init.start,end:t.init.end,replacement:`${t.init.name}.value`}))},AssignmentExpression:t=>{var s,i,r;("ArrayPattern"===(null==(s=t.left)?void 0:s.type)||"ObjectPattern"===(null==(i=t.left)?void 0:i.type))&&"Identifier"===(null==(r=t.right)?void 0:r.type)&&this.stateVariables.has(t.right.name)&&(this.alreadyHasValue(t.right,e)||n.push({start:t.right.start,end:t.right.end,replacement:`${t.right.name}.value`}))}}),n.sort(((e,t)=>t.start-e.start)).forEach((e=>{s=s.slice(0,e.start)+e.replacement+s.slice(e.end)})),s}catch(t){return console.error("Destructuring transformation error:",t),e}}alreadyHasValue(e,t){const s=e.end;return t.slice(s,s+6).startsWith(".value")}transformStateDeclarator(e,t){var s,n;if("ArrayPattern"!==(null==(s=e.id)?void 0:s.type)||"CallExpression"!==(null==(n=e.init)?void 0:n.type))return null;const i=e.init;if(!this.isPPStateCall(i))return null;const r=e.id.elements[0];if(!r||"Identifier"!==r.type)return null;const a=r.name,o=`set${this.capitalize(a)}`,c=e.id.elements[1];return"Identifier"===(null==c?void 0:c.type)&&c.name!==o&&console.warn(`Setter name mismatch: expected ${o}, got ${c.name}`),this.createTransformation(i,a,t)}isPPStateCall(e){var t,s,n;return"MemberExpression"===(null==(t=e.callee)?void 0:t.type)&&"Identifier"===(null==(s=e.callee.object)?void 0:s.type)&&"pp"===e.callee.object.name&&"Identifier"===(null==(n=e.callee.property)?void 0:n.type)&&"state"===e.callee.property.name}createTransformation(e,t,s){const n=e.arguments;if(0===n.length){const s=`pp.state("${t}")`;return{start:e.start,end:e.end,replacement:s}}const i=n[0];if("Literal"===i.type&&"string"==typeof i.value&&i.value===t)return null;if(1===n.length){const n=`pp.state("${t}", ${s.slice(i.start,i.end)})`;return{start:e.start,end:e.end,replacement:n}}const r=`pp.state("${t}", ${s.slice(e.arguments[0].start,e.arguments[e.arguments.length-1].end)})`;return{start:e.start,end:e.end,replacement:r}}looksLikeVariableName(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)&&e.length<=50&&!e.includes(" ")}extractStateDeclarations(e){const t=[];try{J(ne(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0,locations:!0}),{VariableDeclarator:s=>{const n=this.extractStateFromDeclarator(s,e);n&&t.push(n)}})}catch(e){console.error("State extraction error:",e)}return t}extractStateFromDeclarator(e,t){var s,n,i,r;if("ArrayPattern"!==(null==(s=e.id)?void 0:s.type)||"CallExpression"!==(null==(n=e.init)?void 0:n.type)||!this.isPPStateCall(e.init))return null;const a=e.id.elements[0],o=e.id.elements[1];if("Identifier"!==(null==a?void 0:a.type)||"Identifier"!==(null==o?void 0:o.type))return null;const c=e.init.arguments;let p,h=a.name;return c.length>=1&&("Literal"===c[0].type&&"string"==typeof c[0].value?this.looksLikeVariableName(c[0].value)?(h=c[0].value,c.length>=2&&(p=this.extractLiteralValue(c[1]))):(h=a.name,p=this.extractLiteralValue(c[0])):p=this.extractLiteralValue(c[0])),{variableName:a.name,setterName:o.name,stateKey:h,initialValue:p,line:(null==(i=e.loc)?void 0:i.start.line)||0,column:(null==(r=e.loc)?void 0:r.start.column)||0}}extractFunctionDeclarations(e){const t=[];try{J(ne(e,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0,locations:!0}),{FunctionDeclaration:e=>{var s,n;"Identifier"===(null==(s=e.id)?void 0:s.type)&&t.push({name:e.id.name,type:"function",params:e.params.map((e=>"Identifier"===e.type?e.name:"")),line:(null==(n=e.loc)?void 0:n.start.line)||0})},VariableDeclarator:e=>{var s,n,i,r;if("Identifier"===(null==(s=e.id)?void 0:s.type)&&("ArrowFunctionExpression"===(null==(n=e.init)?void 0:n.type)||"FunctionExpression"===(null==(i=e.init)?void 0:i.type))){const s=e.init;t.push({name:e.id.name,type:"ArrowFunctionExpression"===s.type?"arrow":"function",params:s.params.map((e=>"Identifier"===e.type?e.name:"")),line:(null==(r=e.loc)?void 0:r.start.line)||0})}}})}catch(e){console.error("Function extraction error:",e)}return t}extractLiteralValue(e){if("Literal"===e.type)return e.value;"Identifier"===e.type&&e.name}capitalize(e){return e.charAt(0).toUpperCase()+e.slice(1)}};d(W,"instance"),d(W,"FUNCTIONS_NEEDING_VALUE_TRANSFORM",["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"]);let Se=W;class Ge{constructor(e){this.evaluator=e}render(e,t,s){const n=N.isSingleExpression(e);if(n)return this.evaluator.evaluateExpression(n,t,s);let i="";for(const n of N.parse(e))if("static"===n.type)i+=n.content;else if(n.expression)try{i+=k(this.evaluator.evaluateExpression(n.expression,t,s))}catch{}return i}dependencies(e,t,s){const n=N.extractExpressions(e),i=new Set;for(const e of n)for(const n of this.evaluator.extractDependencies(e,t,s))i.add(n);return[...i]}}class Dt{static containsMustacheExpression(e){if(g.MUSTACHE_PATTERN.test(e))return!0;const t=N.decodeEntities(e);return g.MUSTACHE_PATTERN.test(t)}}class C{static getContextComponent(e){const t=e.getAttribute(g.ATTR_PREFIXES.CONTEXT);if(t){if("parent"===t){const t=C.getElementComponent(e);return C.getParentOfComponent(t,e)}return"app"===t?"app":t}return C.getElementComponent(e)}static getParentOfComponent(e,t){if("app"===e)return"app";let s=t;for(;s&&s.getAttribute(g.ATTR_PREFIXES.COMPONENT)!==e;)s=s.parentElement;if(!s)return"app";let n=s.parentElement;for(;n;){const e=n.getAttribute(g.ATTR_PREFIXES.COMPONENT);if(e)return e;n=n.parentElement}return"app"}static findElementForComponent(e,t){return"app"===t?document.body:document.querySelectorAll(`[${g.ATTR_PREFIXES.COMPONENT}="${t}"]`)[0]||null}static getElementDepth(e){let t=0,s=e.parentElement;for(;s&&s!==document.body;)t++,s=s.parentElement;return t}static getParentComponentForElement(e){let t=e.parentElement;for(;t;){const e=t.getAttribute(g.ATTR_PREFIXES.COMPONENT);if(e)return e;t=t.parentElement}return"app"}static isTextNodeInsideScript(e){let t=e.parentElement;for(;t&&t!==document.body;){const e=t.tagName.toLowerCase();if("script"===e||"style"===e)return!0;t=t.parentElement}return!1}static getComponentForNode(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;for(;t;){const e=t.getAttribute(g.ATTR_PREFIXES.COMPONENT);if(e)return e;t=t.parentElement}return"app"}static getElementComponent(e){const t=e.getAttribute(g.ATTR_PREFIXES.COMPONENT);if(t)return t;let s=e.parentElement;for(;s;){const e=s.getAttribute(g.ATTR_PREFIXES.COMPONENT);if(e)return e;s=s.parentElement}return"app"}}class he{static isEventAttribute(e){return e.startsWith("on")&&e.length>2&&!e.includes("-")}}class we{static findExistingStateKey(e,t,s){return[`${t}.${e}`,`app.${e}`,e].find((e=>e in s))||null}}class Ns{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)}}class et{constructor(){d(this,"pendingUpdates",new Map),d(this,"batchTimeout",null),d(this,"componentManager"),d(this,"domBindingManager")}setManagers(e,t){this.componentManager=e,this.domBindingManager=t}scheduleUpdate(e,t){this.pendingUpdates.has(e)||this.pendingUpdates.set(e,new Set),this.pendingUpdates.get(e).add(t),null===this.batchTimeout&&(this.batchTimeout=window.setTimeout((()=>{this.processBatchedUpdates()}),0))}processBatchedUpdates(){const e=new Map(this.pendingUpdates);this.pendingUpdates.clear(),this.batchTimeout=null;const t=this.sortUpdatesByDependency(e);for(const[e,s]of t)this.processComponentUpdate(e,s)}sortUpdatesByDependency(e){return Array.from(e.entries()).sort((([,e],[,t])=>Math.min(...Array.from(e).map((e=>C.getElementDepth(e))))-Math.min(...Array.from(t).map((e=>C.getElementDepth(e))))))}processComponentUpdate(e,t){if(!this.componentManager||!this.domBindingManager)return;this.componentManager.invalidateComponent(e);const s=[],n=[],i=[];for(const r of t){if(!document.contains(r))continue;const t=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null);let a;for(;a=t.nextNode();)s.push(a);const o=this.domBindingManager.loopManager;if(o){const t=o.getAllLoops();for(const[s,i]of t)i.component===e&&r.contains(s)&&n.push([s,i])}i.push(r)}this.updateTextNodesBatch(s,e),this.updateLoopsBatch(n),this.updateElementsBatch(i,e)}updateTextNodesBatch(e,t){const s=this.domBindingManager.textNodeManager;s&&e.forEach((e=>{document.contains(e)&&C.getComponentForNode(e)===t&&s.updateTextNode(e)}))}updateLoopsBatch(e){const t=this.domBindingManager.loopManager;if(!t)return;const s=new Map;e.forEach((([e,t])=>{const n=C.getElementDepth(e);s.has(n)||s.set(n,[]),s.get(n).push([e,t])}));const n=Array.from(s.keys()).sort(((e,t)=>e-t));for(const e of n)s.get(e).forEach((([e,s])=>{document.contains(e)&&t.renderLoop(s,s.iterableExpr)}))}updateElementsBatch(e,t){e.forEach((e=>{document.contains(e)&&this.domBindingManager.processElementBindings(e,!0)}))}}class Bt{constructor(e,t){d(this,"loopBindings",new Map),d(this,"stateManager"),d(this,"expressionEvaluator"),d(this,"componentManager"),d(this,"domBindingManager"),d(this,"cleanupObserver"),d(this,"loopCounter",0),d(this,"pendingTemplates",[]),d(this,"loopItemElements",new WeakSet),d(this,"loopItemContexts",new WeakMap),d(this,"templateRenderer"),d(this,"contextCache",new Map),d(this,"contextCacheTimestamps",new Map),this.stateManager=e,this.expressionEvaluator=t,this.cleanupObserver=new MutationObserver((e=>{this.cleanupDetachedTemplates(e)})),this.cleanupObserver.observe(document.body,{childList:!0,subtree:!0}),this.templateRenderer=new Ge(t)}getLoopContextForElement(e){if(!this.domBindingManager)return null;const t=this.domBindingManager.loopManager;if(!t)return null;let s=e.parentElement;for(;s;){if(t.isLoopItem&&t.isLoopItem(s))return t.getLoopItemContext(s);s=s.parentElement}const n=t.getAllLoops();for(const[t,s]of n)for(const t of s.renderedItems)if(t.element.contains(e))return t.context;return null}setDependencies(e,t){this.componentManager=e,this.domBindingManager=t}queueTemplate(e,t){this.loopBindings.has(e)||this.pendingTemplates.push({template:e,component:t})}processPendingTemplates(){const e=[...this.pendingTemplates];this.pendingTemplates=[];for(const{template:t,component:s}of e)document.contains(t)&&this.processTemplate(t,s)}processTemplate(e,t){const s=e.getAttribute("pp-for");if(!s||this.loopBindings.has(e))return;const n=this.parseLoopExpression(s);if(!n)return void console.error(`Invalid pp-for syntax: "${s}"`);const i=e.parentElement,r=document.createComment(`pp-for: ${s}`);i.insertBefore(r,e);const a={template:e,expression:s,itemVar:n.itemVar,indexVar:n.indexVar,component:t,subscriptionIds:[],renderedItems:[],keyExpression:void 0,parentElement:i,placeholder:r,iterableExpr:n.iterableExpr};this.loopBindings.set(e,a),this.setupLoopReactivity(a,n.iterableExpr),this.renderLoop(a,n.iterableExpr)}parseLoopExpression(e){const t=e.match(/^\s*([a-zA-Z_$][\w$]*)\s+in\s+(.+)$/);if(t)return{itemVar:t[1],iterableExpr:t[2].trim()};const s=e.match(/^\s*\(\s*([a-zA-Z_$][\w$]*)\s*,\s*([a-zA-Z_$][\w$]*)\s*\)\s+in\s+(.+)$/);return s?{itemVar:s[1],indexVar:s[2],iterableExpr:s[3].trim()}:null}setupLoopReactivity(e,t){const s=`loop_${Date.now()}_${++this.loopCounter}`,n=this.expressionEvaluator.extractDependencies(t,e.component,this.stateManager),i=this.findComponentElementForLoop(e);if(i&&this.componentManager){const t=this.componentManager.getComponentPropDependencies(i,e.component);n.push(...t)}const r={id:s,selector:"",dependencies:new Set(n),callback:()=>{this.renderLoop(e,e.iterableExpr)},element:e.parentElement,component:e.component};this.stateManager.addSubscription(r),e.subscriptionIds.push(s)}renderLoop(e,t){if(this.componentManager&&this.domBindingManager)try{const s=this.findComponentElementForLoop(e);let n;const i=this.findParentLoopContext(e.template);n=i?{...this.componentManager.buildComponentContextWithProps(e.component,s),...i}:this.componentManager.buildComponentContextWithProps(e.component,s);const r=this.expressionEvaluator.evaluateExpression(t,n,e.component);if(!Array.isArray(r))return console.warn(`Loop expression "${t}" did not return an array:`,r,`Available context keys: [${Object.keys(n).join(", ")}]`,"Parent loop context:",i),void this.clearRenderedItems(e);this.updateRenderedItems(e,r)}catch(s){console.error(`Error evaluating loop expression "${t}":`,s),this.clearRenderedItems(e)}}findParentLoopContext(e){const t=[];let s=e.parentElement;for(;s&&s!==document.body;){if(this.loopItemElements.has(s)){const e=this.loopItemContexts.get(s);e&&t.unshift(e)}for(const[n,i]of this.loopBindings)if(i.template!==e)for(const n of i.renderedItems)if(n.element===s||n.element.contains(e)){t.unshift(n.context);break}s=s.parentElement}return t.length>0?t.reduce(((e,t)=>({...e,...t})),{}):null}findComponentElementForLoop(e){let t=e.parentElement;for(;t;){if(t.getAttribute(g.ATTR_PREFIXES.COMPONENT)===e.component)return t;t=t.parentElement}return document.querySelectorAll(`[${g.ATTR_PREFIXES.COMPONENT}="${e.component}"]`)[0]||void 0}updateRenderedItems(e,t){const s=e.renderedItems,n=[],i=new Set,r=new Map;s.forEach((e=>{r.set(e.key,e)})),t.forEach(((t,s)=>{const a=this.generateItemKey(e,t,s),o=r.get(a);if(o&&!i.has(o.element))i.add(o.element),this.updateItemContext(e,o,t,s),n.push(o);else{const i=this.createLoopItem(e,t,s,a);i&&(n.push(i),this.processNestedLoopsInItem(i,e.component))}})),s.forEach((e=>{i.has(e.element)||this.cleanupLoopItem(e)})),this.updateDOMOrder(e,n),e.renderedItems=n}processNestedLoopsInItem(e,t){e.element.querySelectorAll("template[pp-for]").forEach((s=>{const n=s;this.loopBindings.has(n)||this.processNestedTemplate(n,t,e.context)}))}generateItemKey(e,t,s){const n=e.template.content.firstElementChild;if(n&&n.hasAttribute("key")){const i=n.getAttribute("key");try{const n=this.createItemContextWithParentContext(e,t,s),r=N.isSingleExpression(i);if(r){const t=this.expressionEvaluator.evaluateExpression(r,n,e.component);return String(t)}{const t=N.parse(i);let s="";for(const i of t)if("static"===i.type)s+=i.content;else if(i.expression){s+=k(this.expressionEvaluator.evaluateExpression(i.expression,n,e.component))}return s}}catch(n){console.warn(`Error evaluating key expression "${i}":`,n,"Available context keys:",Object.keys(this.createItemContextWithParentContext(e,t,s)))}}return t&&"object"==typeof t&&"id"in t?String(t.id):`${e.expression}_${s}`}createItemContextWithParentContext(e,t,s){if(!this.componentManager)return{};e.component,e.expression;const n={...this.componentManager.buildComponentContext(e.component),...this.getAllParentLoopContexts(e.template),[e.itemVar]:t};return e.indexVar&&(n[e.indexVar]=s),n}getAllParentLoopContexts(e){const t=[];let s=e.parentElement;for(;s&&s!==document.body;){if(this.loopItemElements.has(s)){const e=this.loopItemContexts.get(s);e&&t.unshift(e)}for(const[n,i]of this.loopBindings)if(n!==e)for(const n of i.renderedItems)if(n.element===s||n.element.contains(e)){t.unshift(n.context);break}s=s.parentElement}return t.reduce(((e,t)=>({...e,...t})),{})}createItemContext(e,t,s){if(!this.componentManager)return{};const n={...this.componentManager.buildComponentContext(e.component),...this.findAllParentLoopContexts(e.template),[e.itemVar]:t};return e.indexVar&&(n[e.indexVar]=s),n}findAllParentLoopContexts(e){const t={};let s=e.parentElement;for(;s&&s!==document.body;){if(this.loopItemElements.has(s)){const e=this.loopItemContexts.get(s);if(e)for(const[s,n]of Object.entries(e))s in t||(t[s]=n)}for(const[n,i]of this.loopBindings)if(n!==e)for(const e of i.renderedItems)if(e.element===s){for(const[s,n]of Object.entries(e.context))s in t||(t[s]=n);break}s=s.parentElement}return t}createLoopItem(e,t,s,n){if(!this.domBindingManager)return null;try{const i=this.createItemContextWithParentContext(e,t,s),r=document.importNode(e.template.content,!0),a=document.createElement("div");a.appendChild(r);const o=a.firstElementChild;if(!o)return console.warn("Template content must contain exactly one root element"),null;a.removeChild(o),this.loopItemElements.add(o),this.loopItemContexts.set(o,i),o.getAttribute("key")&&o.removeAttribute("key");const c={key:n,element:o,context:i,subscriptionIds:[],textNodeTemplates:new Map,attributeTemplates:new Map};return this.executeComponentScriptsInLoopItem(o),this.processElementWithContext(o,i,e.component,c),this.cleanupRawMustacheAttributes(o),c}catch(e){return console.error("Error creating loop item:",e),null}}executeComponentScriptsInLoopItem(e){if(!this.componentManager)return;const t=[e],s=e.querySelectorAll(`[${g.ATTR_PREFIXES.COMPONENT}]`);t.push(...Array.from(s)),t.forEach((e=>{if(e.hasAttribute(g.ATTR_PREFIXES.COMPONENT)){const t=e.getAttribute(g.ATTR_PREFIXES.COMPONENT);if(t){const s=this.getLoopItemContextForElement(e),n=`${t}_${this.generateInstanceId(s)}`;e.setAttribute(g.ATTR_PREFIXES.COMPONENT,n),e.__originalComponentName=t,e.__uniqueComponentName=n,this.componentManager.pushComponent(n),this.getComponentScripts(e).forEach((e=>{this.componentManager.executeScript(e)})),this.componentManager.popComponent()}}}))}getLoopItemContextForElement(e){let t=e;for(;t;){if(this.loopItemElements.has(t)){const e=this.loopItemContexts.get(t);if(e)return e}t=t.parentElement}for(const[t,s]of this.loopBindings)for(const t of s.renderedItems)if(t.element===e||t.element.contains(e))return t.context;return console.warn("⚠️ No loop item context found, using empty context"),{}}generateInstanceId(e){const t={};for(const[s,n]of Object.entries(e))"function"==typeof n||s.startsWith("set")||s.endsWith("Getter")||"getContext"===s||"withContext"===s||"__getProp"===s||(n&&"object"==typeof n&&"id"in n||"object"!=typeof n||Array.isArray(n))&&(t[s]=n);return 0===Object.keys(t).length?`${Date.now()}_${Math.random().toString(36).substring(2,7)}`:Object.keys(t).sort().map((e=>{const s=t[e];return s&&"object"==typeof s&&"id"in s?`${e}_${s.id}`:"string"==typeof s||"number"==typeof s?`${e}_${s}`:`${e}_${JSON.stringify(s)}`})).join("_").replace(/[^a-zA-Z0-9_]/g,"").substring(0,20)||`fallback_${Date.now()}`}getComponentScripts(e){const t=[];return e.querySelectorAll(`script[type="${g.SCRIPT_TYPE}"]`).forEach((s=>{const n=s;let i=n.parentElement,r=!1;for(;i&&i!==e.parentElement;){if(i===e){r=!0;break}if(i.hasAttribute(g.ATTR_PREFIXES.COMPONENT)&&i!==e)break;i=i.parentElement}r&&t.push(n)})),t}cleanupRawMustacheAttributes(e){this.cleanupElementMustacheAttributes(e);const t=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,null);let s;for(;s=t.nextNode();)this.cleanupElementMustacheAttributes(s)}cleanupElementMustacheAttributes(e){const t=Array.from(e.attributes);for(const s of t)s.value&&g.MUSTACHE_PATTERN.test(s.value)&&(Ns.isBooleanAttribute(s.name),e.removeAttribute(s.name))}processElementWithContext(e,t,s,n){if(!this.domBindingManager||!this.componentManager)return;const i=(e,s)=>{const n=this.componentManager.buildComponentContext(s),i=e.getAttribute(g.ATTR_PREFIXES.COMPONENT);if(i&&i!==s){const e=this.componentManager.buildComponentContext(i);return{...t,...n,...e}}return{...t,...n}},r=this.componentManager.buildComponentContextWithProps.bind(this.componentManager);this.componentManager.buildComponentContextWithProps=(t,s)=>s&&(s===e||e.contains(s))?i(s,t):r(t,s);try{this.bindLoopItemElement(e,t,s,n),this.setupEventBindingsForLoopItem(e,s);const r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,{acceptNode:t=>{if(t===e)return NodeFilter.FILTER_SKIP;if(t.nodeType===Node.TEXT_NODE){const e=t;if(C.isTextNodeInsideScript(e))return NodeFilter.FILTER_REJECT;if(e.textContent&&g.MUSTACHE_PATTERN.test(e.textContent))return NodeFilter.FILTER_ACCEPT}else if(t.nodeType===Node.ELEMENT_NODE)return"script"===t.tagName.toLowerCase()?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT;return NodeFilter.FILTER_SKIP}});let a;for(;a=r.nextNode();)if(a.nodeType===Node.TEXT_NODE){const e=a;if(e.textContent&&g.MUSTACHE_PATTERN.test(e.textContent)){const t=this.getComponentForTextNode(e),s=i(e.parentElement,t);this.processTextNodeWithLoopContext(e,s,t,n)}}else if(a.nodeType===Node.ELEMENT_NODE){const e=a,t=C.getElementComponent(e),s=i(e,t);this.bindLoopItemElement(e,s,t,n),this.setupEventBindingsForLoopItem(e,t)}e.querySelectorAll("template[pp-for]").forEach((e=>{this.processNestedTemplate(e,s,t)}))}finally{this.componentManager.buildComponentContextWithProps=r}}getComponentForTextNode(e){let t=e.parentElement;for(;t;){const e=t.getAttribute(g.ATTR_PREFIXES.COMPONENT);if(e)return e;t=t.parentElement}return"app"}processNestedTemplate(e,t,s){const n=e.getAttribute("pp-for");if(!n||this.loopBindings.has(e))return;const i=this.parseLoopExpression(n);if(!i)return void console.error(`Invalid pp-for syntax: "${n}"`);const r=e.parentElement,a=document.createComment(`pp-for: ${n}`);r.insertBefore(a,e);const o=this.findComponentElementForTemplate(e);let c={...s};const p=this.findParentLoopContextForNestedTemplate(e);if(p&&(c={...c,...p}),o&&this.componentManager){const e=o.getAttribute(g.ATTR_PREFIXES.COMPONENT);if(e){const t=C.getParentComponentForElement(o);this.componentManager.hasStoredProps(o)||this.componentManager.setupProps(o,t);const s=this.evaluateComponentPropsWithContext(o,c);c={...this.componentManager.buildComponentContext(e),...s,...c}}}const h={template:e,expression:n,itemVar:i.itemVar,indexVar:i.indexVar,iterableExpr:i.iterableExpr,component:t,subscriptionIds:[],renderedItems:[],keyExpression:void 0,parentElement:r,placeholder:a};this.loopBindings.set(e,h),this.setupNestedLoopReactivity(h,i.iterableExpr,c),this.renderNestedLoop(h,i.iterableExpr,c)}findParentLoopContextForNestedTemplate(e){let t=e.parentElement;const s={};let n=0;for(;t&&t!==document.body&&n<10;){if(n++,this.loopItemElements.has(t)){const e=this.loopItemContexts.get(t);if(e)for(const[t,n]of Object.entries(e))t in s||(s[t]=n)}for(const[n,i]of this.loopBindings)for(const n of i.renderedItems)(n.element.contains(e)||n.element===t)&&(i.itemVar in s||(s[i.itemVar]=n.context[i.itemVar]),i.indexVar&&!(i.indexVar in s)&&(s[i.indexVar]=n.context[i.indexVar]));t=t.parentElement}return Object.keys(s).length>0?s:null}evaluateComponentPropsWithContext(e,t){const s={};if(!this.componentManager||!this.expressionEvaluator)return s;const n=this.componentManager.extractProps(e,"app");for(const[e,i]of n)try{const n=this.templateRenderer.render(i.expression,t,i.component);s[e]=n}catch(t){console.error(`Failed to evaluate prop "${e}":`,t),s[e]=void 0}return s}findComponentElementForTemplate(e){let t=e.parentElement;for(;t;){if(t.hasAttribute(g.ATTR_PREFIXES.COMPONENT))return t;t=t.parentElement}return null}setupNestedLoopReactivity(e,t,s){const n=`nested_loop_${Date.now()}_${++this.loopCounter}`;let i=this.expressionEvaluator.extractDependencies(t,e.component,this.stateManager);const r={id:n,selector:"",dependencies:new Set(i),callback:()=>{const n=e.template,i=this.findComponentElementForTemplate(n);let r=s;if(n.parentElement){const e=this.getParentLoopContextForElement(n);e&&(r={...r,...e})}if(i&&this.componentManager){const t=i.getAttribute(g.ATTR_PREFIXES.COMPONENT);if(t){const n=this.extractParentLoopContextFromBinding(e,s),a=this.evaluateComponentPropsWithContext(i,n),o=this.componentManager.buildComponentContext(t);r={...n,...o,...a}}}this.renderNestedLoop(e,t,r)},element:e.parentElement,component:e.component};this.stateManager.addSubscription(r),e.subscriptionIds.push(n)}getParentLoopContextForElement(e){let t=e.parentElement;for(;t;){if(this.loopItemElements.has(t)){const e=this.loopItemContexts.get(t);if(e)return e}t=t.parentElement}return null}extractParentLoopContextFromBinding(e,t){const s=new Set;for(const[t,n]of this.loopBindings)if(n!==e)for(const t of n.renderedItems)if(t.element.contains(e.template)){s.add(n.itemVar),n.indexVar&&s.add(n.indexVar);break}const n={};for(const[e,i]of Object.entries(t))(s.has(e)||e.startsWith("users")||e.startsWith("set")||e.includes("Getter")||"function"==typeof i)&&(n[e]=i);return n}renderNestedLoop(e,t,s){if(this.componentManager&&this.domBindingManager)try{const n=this.expressionEvaluator.evaluateExpression(t,s,e.component);if(!Array.isArray(n))return console.warn(`Nested loop expression "${t}" did not return an array:`,n,`Available context keys: [${Object.keys(s).join(", ")}]`),void this.clearRenderedItems(e);this.updateNestedRenderedItems(e,n,s)}catch(n){console.error(`Error evaluating nested loop expression "${t}":`,n,`Available context keys: [${Object.keys(s).join(", ")}]`),this.clearRenderedItems(e)}}updateNestedRenderedItems(e,t,s){const n=e.renderedItems,i=[],r=new Set,a=new Map;n.forEach((e=>{a.set(e.key,e)})),t.forEach(((t,n)=>{const o=this.generateNestedItemKey(e,t,n,s),c=a.get(o);if(c&&!r.has(c.element))r.add(c.element),this.updateNestedItemContext(e,c,t,n,s),i.push(c);else{const r=this.createNestedLoopItem(e,t,n,o,s);r&&i.push(r)}})),n.forEach((e=>{r.has(e.element)||this.cleanupLoopItem(e)})),this.updateDOMOrder(e,i),e.renderedItems=i}generateNestedItemKey(e,t,s,n){return t&&"object"==typeof t&&"id"in t?String(t.id):`${e.expression}_${s}_${JSON.stringify(n[e.itemVar]||{})}`}createNestedLoopItem(e,t,s,n,i){if(!this.domBindingManager)return null;try{const r={...i,[e.itemVar]:t};e.indexVar&&(r[e.indexVar]=s);const 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 p={key:n,element:c,context:r,subscriptionIds:[],textNodeTemplates:new Map,attributeTemplates:new Map};return this.processElementWithContext(c,r,e.component,p),this.cleanupRawMustacheAttributes(c),p}catch(e){return console.error("Error creating nested loop item:",e),null}}updateNestedItemContext(e,t,s,n,i){const r={...i};r[e.itemVar]=s,e.indexVar&&(r[e.indexVar]=n);const a=this.gatherAllComponentContextsInLoopItem(t.element),o={...r,...a};if(t.context=o,this.loopItemContexts.set(t.element,o),t.textNodeTemplates)for(const[e,s]of t.textNodeTemplates)document.contains(e)&&this.updateTextNodeWithContext(e,s,o,this.getTextNodeComponent(e));if(t.attributeTemplates)for(const[e,s]of t.attributeTemplates)document.contains(e)&&s.forEach(((t,s)=>{var n;try{const i=C.getElementComponent(e),r=this.buildElementSpecificContext(e,o),a=this.templateRenderer.render(t,r,i);null==(n=this.domBindingManager)||n.updateElementProperty(e,s,a)}catch(e){console.error(`Nested binding update error for "${t}":`,e)}}))}bindLoopItemElement(e,t,s,n){const i=this.extractMustacheBindings(e);n&&i.size>0&&(n.attributeTemplates||(n.attributeTemplates=new Map),n.attributeTemplates.set(e,new Map(i))),i.forEach(((i,r)=>{this.createLoopItemBinding(e,r,i,t,s,n)}))}setupEventBindingsForLoopItem(e,t){const s=this.domBindingManager.eventDelegation;if(!s)return void console.warn("No event delegation manager available");const n=Array.from(e.attributes);for(const i of n)if(he.isEventAttribute(i.name)){const n=i.name.substring(2);s.registerEventHandler(e,n,i.value,t),e.removeAttribute(i.name)}}processTextNodeWithLoopContext(e,t,s,n){if(C.isTextNodeInsideScript(e))return;const i=e.textContent||"";if(!N.parse(i).some((e=>"expression"===e.type)))return;n&&(n.textNodeTemplates||(n.textNodeTemplates=new Map),n.textNodeTemplates.set(e,i));const r=this.findActualComponentForTextNode(e);this.updateTextNodeWithContext(e,i,t,r);const a=`loop_text_${Date.now()}_${Math.random()}`,o=this.templateRenderer.dependencies(i,r,this.stateManager),c=new Set(o),p={id:a,selector:"",dependencies:c,callback:()=>{if(!document.contains(e))return void this.stateManager.removeSubscription(a);let t={};if(this.componentManager&&(t=this.componentManager.buildComponentContext(r)),n){const e={};let s=null;for(const[e,t]of this.loopBindings)if(t.renderedItems.includes(n)){s=t;break}if(s){e[s.itemVar]=n.context[s.itemVar],s.indexVar&&(e[s.indexVar]=n.context[s.indexVar]);const t=this.findParentLoopContext(s.template);t&&Object.assign(e,t)}t={...t,...e}}this.updateTextNodeWithContext(e,i,t,r)},component:r};this.stateManager.addSubscription(p),n&&n.subscriptionIds.push(a)}findActualComponentForTextNode(e){let t=e.parentElement;for(;t;){const e=t.getAttribute(g.ATTR_PREFIXES.COMPONENT);if(e){return t.__uniqueComponentName||e}t=t.parentElement}return"app"}updateTextNodeWithContext(e,t,s,n){const i=N.parse(t);let r="";for(const e of i)if("static"===e.type)r+=e.content;else if(e.expression)try{r+=k(this.expressionEvaluator.evaluateExpression(e.expression,s,n))}catch(t){console.warn(`Loop text evaluation error for "${e.expression}":`,t,"Available context keys:",Object.keys(s)),r+=""}e.textContent!==r&&(e.textContent=r)}extractMustacheBindings(e){const t=new Map,s=e.attributes;for(let e=0;e<s.length;e++){const n=s[e];if(n.name!==g.ATTR_PREFIXES.COMPONENT&&"key"!==n.name&&!n.name.startsWith("on")&&n.value){const e=g.MUSTACHE_PATTERN.test(n.value),s=N.decodeEntities(n.value),i=g.MUSTACHE_PATTERN.test(s);(e||i)&&t.set(n.name,s)}}return t}createLoopItemBinding(e,t,s,n,i,r){const a=`loop_item_${Date.now()}_${Math.random()}`,o=this.templateRenderer.dependencies(s,i,this.stateManager),c=new Set(o);let p=!1,h=0;const l=()=>{var o;if(!p)if(document.contains(e)){h=0;try{const a=this.componentManager.buildComponentContext(i);let c;if(r){c={...a};let e=null;for(const[t,s]of this.loopBindings)if(s.renderedItems.includes(r)){e=s;break}e&&(c[e.itemVar]=r.context[e.itemVar],e.indexVar&&(c[e.indexVar]=r.context[e.indexVar]));for(const[e,t]of Object.entries(r.context))e in c||(c[e]=t)}else c=n;const p=this.templateRenderer.render(s,c,i);null==(o=this.domBindingManager)||o.updateElementProperty(e,t,p)}catch(e){console.error(`Loop item binding evaluation error for "${s}":`,e),console.error("Available context keys:",Object.keys(n))}}else if(h++,h<5){const e=10*Math.pow(2,h-1);setTimeout((()=>{p||l()}),e)}else p=!0,this.stateManager.removeSubscription(a)},u={id:a,selector:"",dependencies:c,callback:()=>{p||l()},element:e,component:i};if(this.stateManager.addSubscription(u),r){r.subscriptionIds.push(a);const e=this.cleanupLoopItem.bind(this);this.cleanupLoopItem=t=>{t===r&&(p=!0),e(t)}}(()=>{document.contains(e)?l():Promise.resolve().then((()=>{if(!p&&document.contains(e))l();else if(!p&&h<5){h++;const e=10*Math.pow(2,h-1);setTimeout((()=>{p||l()}),e)}else!p&&h>=5&&(p=!0,this.stateManager.removeSubscription(a))}))})()}updateItemContext(e,t,s,n){const i={...this.createItemContext(e,s,n),...this.gatherAllComponentContextsInLoopItem(t.element)};if(t.context=i,this.loopItemContexts.set(t.element,i),t.textNodeTemplates)for(const[e,s]of t.textNodeTemplates)document.contains(e)&&this.updateTextNodeWithContext(e,s,i,this.getTextNodeComponent(e));if(t.attributeTemplates)for(const[e,s]of t.attributeTemplates)document.contains(e)&&s.forEach(((t,s)=>{var n;try{const r=C.getElementComponent(e),a=this.buildElementSpecificContext(e,i),o=this.templateRenderer.render(t,a,r);null==(n=this.domBindingManager)||n.updateElementProperty(e,s,o)}catch(e){console.error(`Attribute binding update error for "${t}":`,e)}}))}gatherAllComponentContextsInLoopItem(e){if(!this.componentManager)return{};const t={};if(e.hasAttribute(g.ATTR_PREFIXES.COMPONENT)){const s=e.getAttribute(g.ATTR_PREFIXES.COMPONENT),n=this.componentManager.buildComponentContext(s);Object.assign(t,n)}return e.querySelectorAll(`[${g.ATTR_PREFIXES.COMPONENT}]`).forEach((e=>{var s;const n=e.getAttribute(g.ATTR_PREFIXES.COMPONENT),i=null==(s=this.componentManager)?void 0:s.buildComponentContext(n);Object.assign(t,i)})),t}buildElementSpecificContext(e,t){if(!this.componentManager)return t;const s=C.getElementComponent(e),n=this.componentManager.buildComponentContext(s);return{...t,...n}}getTextNodeComponent(e){let t=e.parentElement;for(;t;){const e=t.getAttribute(g.ATTR_PREFIXES.COMPONENT);if(e)return e;t=t.parentElement}return"app"}updateDOMOrder(e,t){let s=e.placeholder;t.forEach((t=>{(t.element.parentElement!==e.parentElement||t.element!==s.nextSibling)&&e.parentElement.insertBefore(t.element,s.nextSibling),s=t.element}))}clearRenderedItems(e){e.renderedItems.forEach((e=>{this.cleanupLoopItem(e)})),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((e=>{this.stateManager.removeSubscription(e)}))}isLoopItem(e){return this.loopItemElements.has(e)}getLoopItemContext(e){return this.loopItemContexts.get(e)}cleanupDetachedTemplates(e){for(const t of e)"childList"===t.type&&t.removedNodes.forEach((e=>{if(e.nodeType===Node.ELEMENT_NODE){const t=e;"TEMPLATE"===t.tagName&&t.hasAttribute("pp-for")&&this.cleanupTemplate(t),t.querySelectorAll("template[pp-for]").forEach((e=>{this.cleanupTemplate(e)}))}}))}cleanupTemplate(e){const t=this.loopBindings.get(e);t&&(this.clearRenderedItems(t),t.subscriptionIds.forEach((e=>{this.stateManager.removeSubscription(e)})),t.placeholder.parentElement&&t.placeholder.parentElement.removeChild(t.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 oe{constructor(e){d(this,"cache",new Map),d(this,"maxSize"),this.maxSize=e}get(e){const t=this.cache.get(e);return void 0!==t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;void 0!==e&&this.cache.delete(e)}this.cache.set(e,t)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}}const F=class e{static parseSpreadDirective(e){const t=e.replace(/^\s*\{\s*|\s*\}\s*$/g,""),s=this.parseSpreadParts(t),n=[],i=[];for(const e of s){const t=e.trim();if(t.startsWith("..."))n.push(t.substring(3).trim());else if(t.startsWith("{")&&t.endsWith("}")){const e=t.slice(1,-1).trim();if(e){const t=this.parseObjectProperties(e);i.push(t)}}else console.warn(`Invalid spread directive part: "${t}". Expected ...spread or {object}`)}return{spreads:n,objects:i}}static parseSpreadParts(e){const t=[];let s="",n=0,i=!1,r="",a=0;for(;a<e.length;){const o=e[a],c=a>0?e[a-1]:"";if(i||'"'!==o&&"'"!==o?i&&o===r&&"\\"!==c&&(i=!1,r=""):(i=!0,r=o),!i)if("{"===o)n++;else if("}"===o)n--;else if(","===o&&0===n){t.push(s.trim()),s="",a++;continue}s+=o,a++}return s.trim()&&t.push(s.trim()),t}static parseObjectProperties(e){const t=[],s=this.parseObjectParts(e);for(const e of s){const s=e.trim(),n=this.findPropertySeparator(s);if(-1!==n){const e=s.substring(0,n).trim().replace(/['"]/g,""),i=s.substring(n+1).trim();t.push({key:e,value:i})}else console.warn(`Invalid object property: "${s}". Expected key: value format.`)}return t}static parseObjectParts(e){const t=[];let s="",n=0,i=!1,r="";for(let a=0;a<e.length;a++){const o=e[a],c=a>0?e[a-1]:"";if(i||'"'!==o&&"'"!==o?i&&o===r&&"\\"!==c&&(i=!1,r=""):(i=!0,r=o),!i)if("{"===o||"["===o||"("===o)n++;else if("}"===o||"]"===o||")"===o)n--;else if(","===o&&0===n){t.push(s.trim()),s="";continue}s+=o}return s.trim()&&t.push(s.trim()),t}static findPropertySeparator(e){let t=0,s=!1,n="";for(let i=0;i<e.length;i++){const r=e[i],a=i>0?e[i-1]:"";if(s||'"'!==r&&"'"!==r?s&&r===n&&"\\"!==a&&(s=!1,n=""):(s=!0,n=r),!s)if("{"===r||"["===r||"("===r)t++;else if("}"===r||"]"===r||")"===r)t--;else if(":"===r&&0===t)return i}return-1}static splitMixedExpression(e){const t=[];let s="",n=0,i=!1,r="";for(let a=0;a<e.length;a++){const o=e[a],c=a>0?e[a-1]:"";if(i||'"'!==o&&"'"!==o?i&&o===r&&"\\"!==c&&(i=!1,r=""):(i=!0,r=o),!i)if("{"===o||"["===o||"("===o)n++;else if("}"===o||"]"===o||")"===o)n--;else if(","===o&&0===n){t.push(s.trim()),s="";continue}s+=o}return s.trim()&&t.push(s.trim()),t}static parse(t){const s=e.decodeEntities(t);if(e.EXPRESSION_CACHE.has(s))return e.EXPRESSION_CACHE.get(s);const n=e.parseContentWithNesting(s);return e.EXPRESSION_CACHE.set(s,n),n}static parseContentWithNesting(e){const t=[],s=e.length;let n=0,i=0;for(;n<s;)if("{"===e[n]){n>i&&t.push({type:"static",content:e.substring(i,n),expression:null});const s=this.extractNestedExpression(e,n);-1!==s.endIndex?(t.push({type:"expression",content:e.substring(n,s.endIndex+1),expression:s.expression.trim()}),n=s.endIndex+1,i=n):n++}else n++;return i<s&&t.push({type:"static",content:e.substring(i),expression:null}),t}static extractNestedExpression(e,t){let s=1,n=t+1,i=!1,r="",a=!1;for(;n<e.length&&s>0;){const t=e[n],o=n>0?e[n-1]:"";i||'"'!==t&&"'"!==t?i&&t===r&&"\\"!==o&&(i=!1,r=""):(i=!0,r=t),!i&&"`"===t&&"\\"!==o&&(a=!a),!i&&!a&&("{"===t?s++:"}"===t&&s--),n++}if(0===s){return{endIndex:n-1,expression:e.slice(t+1,n-1)}}return{endIndex:-1,expression:""}}static isSingleExpression(t){const s=e.decodeEntities(t),n=e.parseContentWithNesting(s);return 1===n.length&&"expression"===n[0].type?n[0].expression:null}static extractExpressions(t){const s=e.decodeEntities(t);return e.parseContentWithNesting(s).filter((e=>"expression"===e.type)).map((e=>e.expression)).filter((e=>e))}};d(F,"EXPRESSION_CACHE",new oe(1e3)),d(F,"decodeEntities",(e=>{const t=document.createElement("textarea");t.innerHTML=e;let s=t.value;for(;s.includes("&");){t.innerHTML=s;const e=t.value;if(e===s)break;s=e}return s}));let N=F;class Ms{constructor(e,t){d(this,"textNodeBindings",new Map),d(this,"expressionEvaluator"),d(this,"stateManager"),d(this,"componentManager"),d(this,"cleanupObserver"),d(this,"bindingCount",0),this.expressionEvaluator=e,this.stateManager=t,this.cleanupObserver=new MutationObserver((e=>{this.cleanupDetachedNodes(e)})),this.cleanupObserver.observe(document.body,{childList:!0,subtree:!0})}cleanupDetachedNodes(e){for(const t of e)"childList"===t.type&&t.removedNodes.forEach((e=>{if(e.nodeType===Node.TEXT_NODE)this.cleanupTextNode(e);else if(e.nodeType===Node.ELEMENT_NODE){const t=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,null);let s;for(;s=t.nextNode();)this.cleanupTextNode(s)}}));const t=[];for(const[e]of this.textNodeBindings)document.contains(e)||t.push(e);t.forEach((e=>this.cleanupTextNode(e)))}processTextNode(e,t){if(this.textNodeBindings.has(e)||C.isTextNodeInsideScript(e)||this.isInsideLoopItem(e))return;const s=e.textContent||"",n=N.parse(s);if(!n.some((e=>"expression"===e.type)))return;const i={originalContent:s,expressions:n,subscriptionIds:[]};n.filter((e=>"expression"===e.type)).forEach((s=>{if(!s.expression)return;const n=`text_${Date.now()}_${Math.random()}`,r=this.expressionEvaluator.extractDependencies(s.expression,t,this.stateManager),a={id:n,selector:"",dependencies:new Set(r),callback:()=>{this.updateTextNode(e)},element:e.parentElement??void 0,component:t};this.stateManager.addSubscription(a),i.subscriptionIds.push(n)})),this.textNodeBindings.set(e,i),this.bindingCount++,this.updateTextNode(e)}isInsideLoopItem(e){var t,s,n;let i=e.parentElement;for(;i&&i!==document.body;){const e=i.previousSibling;if(e&&e.nodeType===Node.COMMENT_NODE&&null!=(t=e.textContent)&&t.startsWith("pp-for:"))return!0;let r=(null==(s=i.parentElement)?void 0:s.firstChild)||null;for(;r;){if(r.nodeType===Node.COMMENT_NODE&&null!=(n=r.textContent)&&n.startsWith("pp-for:")&&r!==i)return!0;r=r.nextSibling}i=i.parentElement}return!1}updateTextNode(e){const t=this.textNodeBindings.get(e);if(!t||!e.parentElement)return;const s=C.getComponentForNode(e),n=this.resolveComponentRootForElement(e,s),i=this.getContextForComponent(s,n);let r="";for(const e of t.expressions)if("static"===e.type)r+=e.content;else if(e.expression)try{r+=k(this.expressionEvaluator.evaluateExpression(e.expression,i,s))}catch(t){const s="object"==typeof t&&null!==t&&"message"in t?t.message:String(t);console.warn(`Text binding evaluation warning for "${e.expression}": ${s}`),r+=""}e.textContent!==r&&(e.textContent=r)}resolveComponentRootForElement(e,t){let s=e.parentElement;for(;s&&s.nodeType===Node.ELEMENT_NODE;){const e=s;if(e.getAttribute(g.ATTR_PREFIXES.COMPONENT)===t)return e;s=s.parentElement}}getContextForComponent(e,t){return this.componentManager?this.componentManager.buildComponentContextWithProps(e,t):{}}cleanupTextNode(e){const t=this.textNodeBindings.get(e);t&&(t.subscriptionIds.forEach((e=>{this.stateManager.removeSubscription(e)})),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 Ls{constructor(){d(this,"listeners",new Map)}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){var s;null==(s=this.listeners.get(e))||s.delete(t)}emit(e,...t){const s=this.listeners.get(e);s&&s.forEach((s=>{try{s(...t)}catch(t){console.error(`Event listener error for ${e}:`,t)}}))}}class Rs{constructor(){d(this,"stateStore",{}),d(this,"subscriptions",new Map),d(this,"keyIndex",new Map),d(this,"updateQueue",new Set),d(this,"isUpdating",!1),d(this,"eventBus",new Ls),d(this,"contextCache",new Map),d(this,"previousValues",new Map),d(this,"scheduleFlush",ks((()=>{this.flushUpdates()}),g.DEBOUNCE_MS)),this.setupGlobalStateProxy()}batchStateUpdates(e){const t=this.isUpdating;this.isUpdating=!0;try{return e()}finally{this.isUpdating=t,!this.isUpdating&&this.updateQueue.size>0&&this.scheduleFlush()}}invalidateContextCache(){this.contextCache.clear()}setupGlobalStateProxy(){this.stateStore=new Proxy(this.stateStore,{set:(e,t,s,n)=>{const i=e[t],r=Reflect.set(e,t,s,n);return i!==s&&this.notifySubscribers(t),r},get:(e,t)=>Reflect.get(e,t)})}notifySubscribers(e){if(this.eventBus.emit("stateChanged",e),this.updateQueue.add(e),e.includes(".")){const t=e.split(".")[0];this.updateQueue.add(t)}this.notifyPathBasedSubscribers(e),this.isUpdating||this.scheduleFlush()}notifyPathBasedSubscribers(e){var t;const s=this.stateStore[e],n=null==(t=this.previousValues)?void 0:t.get(e);for(const[t,i]of this.subscriptions)for(const t of i.dependencies)if(this.isPathDependency(t)&&t.startsWith(e+".")){const i=t.substring(e.length+1),r=this.getPathValue(n,i),a=this.getPathValue(s,i);this.deepEqual(r,a)||this.updateQueue.add(t)}}isPathDependency(e){return e.includes(".")&&e.split(".").length>1}getPathValue(e,t){if(!e||"object"!=typeof e)return;const s=t.split(".");let n=e;for(const e of s){if(null==n)return;if(Array.isArray(n))return"length"===e?n.length:n.map((t=>null==t?void 0:t[e])).filter((e=>void 0!==e));n=n[e]}return n}deepEqual(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every(((e,s)=>this.deepEqual(e,t[s])));if("object"==typeof e&&"object"==typeof t){const s=Object.keys(e),n=Object.keys(t);return s.length===n.length&&s.every((s=>this.deepEqual(e[s],t[s])))}return!1}flushUpdates(){if(!this.isUpdating){this.isUpdating=!0;try{const e=new Set,t=this.keyIndex.get("*");if(t&&t.size>0&&this.updateQueue.size>0)for(const e of Array.from(t)){const t=this.subscriptions.get(e);if(!t)continue;if(t.element&&!document.contains(t.element)){this.removeSubscription(e);continue}const s=t.element??document.body;try{const e=Array.from(this.updateQueue)[0];t.callback(s,{key:e})}catch(e){console.error("Wildcard subscription callback failed:",e)}}for(const t of this.updateQueue){if(e.has(t))continue;e.add(t);const s=this.keyIndex.get(t);if(s)for(const e of Array.from(s)){const s=this.subscriptions.get(e);if(!s)continue;if(s.element&&!document.contains(s.element)){this.removeSubscription(e);continue}const n=s.element??document.body;try{s.callback(n,{key:t})}catch(e){console.error("Subscription callback failed:",e)}}}}finally{this.updateQueue.clear(),this.isUpdating=!1}}}getState(){return this.stateStore}setState(e,t){if(this.previousValues.set(e,this.stateStore[e]),this.stateStore[e]=t,this.previousValues.size>100){const e=this.previousValues.keys().next().value;"string"==typeof e&&this.previousValues.delete(e)}}hasState(e){return e in this.stateStore}addSubscription(e){this.subscriptions.set(e.id,e);for(const t of e.dependencies)this.keyIndex.has(t)||this.keyIndex.set(t,new Set),this.keyIndex.get(t).add(e.id)}removeSubscription(e){var t,s;const n=this.subscriptions.get(e);if(n){for(const i of n.dependencies)null==(t=this.keyIndex.get(i))||t.delete(e),0===(null==(s=this.keyIndex.get(i))?void 0:s.size)&&this.keyIndex.delete(i);this.subscriptions.delete(e)}}onStateChange(e){return this.eventBus.on("stateChanged",e)}batch(e){const t=this.isUpdating;this.isUpdating=!0;try{return e()}finally{this.isUpdating=t,!this.isUpdating&&this.updateQueue.size&&this.flushUpdates()}}getSubscriptions(){return this.subscriptions}getKeyIndex(){return this.keyIndex}}class Os{constructor(){d(this,"expressionCache",new oe(g.MAX_CACHE_SIZE)),d(this,"dependencyCache",new oe(g.MAX_CACHE_SIZE)),d(this,"dependencyParser",new Vs),d(this,"commonExpressions",new Map),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((e=>{const t={fn:new Function("return "+e),contextMap:new Map,dependencies:[e],timestamp:Date.now(),hitCount:0};this.commonExpressions.set(e,t)}))}extractDependencies(e,t,s){const n=this.normalizeExpression(e),i=`${t}:${n}`;if(this.dependencyCache.has(i))return this.dependencyCache.get(i);const r=this.dependencyParser.extract(n,t,s);return this.dependencyCache.set(i,r),r}evaluateExpression(e,t,s){const n=this.normalizeExpression(e);if(this.commonExpressions.has(n)){const e=this.commonExpressions.get(n);e.hitCount++;try{return e.fn()}catch(e){return void console.error(`Common expression evaluation failed: "${n}"`,e)}}const i=`${s}:${n}`;let r=this.expressionCache.get(i);(!r||this.isStale(r))&&(r=this.compileExpression(n,t,s),this.expressionCache.set(i,r)),r.hitCount++;try{const e=this.buildArguments(r.contextMap,t);return r.fn(...e)}catch(e){return console.error(`Expression evaluation failed: "${n}"`,e),void console.error("Available context:",Object.keys(t))}}compileExpression(e,t,s){const n=this.prepareSafeContext(t),i=new Map,r=[];Object.keys(n).forEach(((e,t)=>{i.set(e,t),r.push(e)}));const a=this.dependencyParser.extract(e,s);return{fn:new Function(...r,`return (${e})`),contextMap:i,dependencies:a,timestamp:Date.now(),hitCount:0}}buildArguments(e,t){const s=new Array(e.size);for(const[n,i]of e)s[i]=t[n];return s}isStale(e){return Date.now()-e.timestamp>3e5}prepareSafeContext(e){const t={};for(const[s,n]of Object.entries(e))"this"===s||"arguments"===s||"eval"===s||"function"===s||(t[s]=n);return t}invalidateCache(e){if(!e)return this.expressionCache.clear(),this.dependencyCache.clear(),void this.dependencyParser.clearCache();const t=`${e}:`;for(const[e]of this.expressionCache.cache)"string"==typeof e&&e.startsWith(t)&&(this.expressionCache.delete(e),this.dependencyCache.delete(e))}}class Vs{constructor(){d(this,"parseCache",new oe(500))}extract(e,t,s){const n=this.normalizeExpression(e),i=`${t}:${n}`;if(this.parseCache.has(i))return this.parseCache.get(i);const r=this.parseExpression(n,t,s);return this.parseCache.set(i,r),r}normalizeExpression(e){return e.replace(/\r\n/g," ").replace(/\r/g," ").replace(/\n/g," ").replace(/\s+/g," ").trim()}parseExpression(e,t,s){const n=this.extractIdentifiers(e),i=[],r=(null==s?void 0:s.getState())||{};for(const e of n){if(Vt.has(e))continue;const s=e.indexOf("."),n=-1===s?e:e.substring(0,s),a=we.findExistingStateKey(n,t,r);if(a)i.push(a);else{const e="app"===t?[`app.${n}`]:[`${t}.${n}`,`app.${n}`];i.push(...e)}if(-1!==s){const e="app"===t?[`app.${n}`]:[`${t}.${n}`,`app.${n}`];i.push(...e)}}return Array.from(new Set(i))}extractIdentifiers(e){const t=[];let s=0;for(;s<e.length;){const n=e[s];if("'"!==n)if('"'!==n)if("`"!==n)if(this.isIdentifierStart(n)){const n=this.extractIdentifier(e,s);t.push(n.value),s=n.endIndex}else s++;else s=this.skipTemplateLiteral(e,s,t);else s=this.skipString(e,s,'"');else s=this.skipString(e,s,"'")}return t}skipString(e,t,s){let n=t+1;for(;n<e.length&&e[n]!==s;)"\\"===e[n]&&n++,n++;return n+1}skipTemplateLiteral(e,t,s){let n=t+1;for(;n<e.length&&"`"!==e[n];)if("$"===e[n]&&n+1<e.length&&"{"===e[n+1]){n+=2;let t=1;for(;n<e.length&&t>0;){const i=e[n];if('"'!==i&&"'"!==i){if("{"===i?t++:"}"===i&&t--,t>0&&this.isIdentifierStart(i)){const t=this.extractIdentifier(e,n);s.push(t.value),n=t.endIndex-1}n++}else n=this.skipString(e,n,i)}}else"\\"===e[n]&&n++,n++;return n+1}extractIdentifier(e,t){let s=t;for(;s<e.length&&(this.isIdentifierPart(e[s])||"."===e[s]);)s++;return{value:e.substring(t,s),endIndex:s}}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 Fs{constructor(e){d(this,"componentStack",["app"]),d(this,"contextCache",new oe(100)),d(this,"contextIndex",new Map),d(this,"contextInvalidated",new Set),d(this,"stateManager"),d(this,"processedScripts",new WeakSet),d(this,"componentFunctions",new Map),d(this,"elementProps",new WeakMap),d(this,"expressionEvaluator"),d(this,"domBindingManager"),d(this,"loopManager"),d(this,"templateRenderer"),d(this,"updateTimeouts"),d(this,"updateBatcher",new et),d(this,"propDependencyCache",new Map),this.stateManager=e,this.updateBatcher=new et,this.stateManager.onStateChange((e=>this.invalidateContextCache(e)))}getPropDependencies(e,t){var s;const n=this.findElementWithProps(t);if(!n)return[];const i=this.elementProps.get(n);if(!i||!i.has(e))return[];const r=i.get(e);return(null==(s=this.templateRenderer)?void 0:s.dependencies(r.expression,r.component,this.stateManager))||[]}buildRestrictedComponentContext(e,t=!1){const s={};window[e]&&Object.assign(s,window[e]);const n=this.componentFunctions.get(e);if(n)for(const[e,t]of n)s[e]=t;const i=this.stateManager.getState();for(const t of Object.keys(i))if(t.startsWith(e+".")){const n=t.substring(e.length+1);n in s||(s[n]=i[t])}if(t){if(window.app)for(const[e,t]of Object.entries(window.app))e in s||(s[e]=t);const e=this.componentFunctions.get("app");if(e)for(const[t,n]of e)t in s||(s[t]=n);for(const e of Object.keys(i))if(e.startsWith("app.")){const t=e.substring(4);t in s||(s[t]=i[e])}}return s}getComponentPropDependencies(e,t){if(this.propDependencyCache.has(e))return this.propDependencyCache.get(e);const s=[],n=this.elementProps.get(e);n&&this.templateRenderer&&n.forEach((e=>{var t;const n=null==(t=this.templateRenderer)?void 0:t.dependencies(e.expression,e.component,this.stateManager);s.push(...n??[])}));const i=Array.from(new Set(s));return this.propDependencyCache.set(e,i),i}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 Ge(e),this.loopManager=new Bt(this.stateManager,e)}extractProps(e,t){const s=new Map,n=e.attributes;for(let e=0;e<n.length;e++){const i=n[e];if(i.name!==g.ATTR_PREFIXES.COMPONENT&&i.value&&Dt.containsMustacheExpression(i.value)){const e=this.attributeToPropName(i.name),n={name:e,expression:i.value,component:t,subscriptionIds:[]};s.set(e,n)}}return s}attributeToPropName(e){return e.replace(/-([a-z])/g,((e,t)=>t.toUpperCase()))}setupProps(e,t){const s=this.extractProps(e,t);0!==s.size&&(this.elementProps.set(e,s),this.expressionEvaluator&&s.forEach(((t,s)=>{this.setupPropBinding(e,t)})))}setupPropBinding(e,t){var s;if(!this.expressionEvaluator)return;const n=`prop_${Date.now()}_${Math.random()}`,i=(null==(s=this.templateRenderer)?void 0:s.dependencies(t.expression,t.component,this.stateManager))||[],r={id:n,selector:"",dependencies:new Set(i),callback:()=>{const t=e.getAttribute(g.ATTR_PREFIXES.COMPONENT);t&&(this.updateBatcher.scheduleUpdate(t,e),this.refreshComponentBindings(e,t))},element:e,component:t.component};this.stateManager.addSubscription(r),t.subscriptionIds.push(n)}refreshComponentBindings(e,t){this.contextInvalidated.add(t),this.contextCache.delete(t),this.domBindingManager&&this.domBindingManager.refreshComponentElement(e,t)}evaluateProps(e){const t={},s=this.elementProps.get(e);if(!s||!this.expressionEvaluator)return t;const n=s.values().next().value;if(!n)return t;const i=this.buildComponentContext(n.component);return s.forEach(((e,s)=>{var n;try{const r=null==(n=this.templateRenderer)?void 0:n.render(e.expression,i,e.component);t[s]="function"==typeof r?(...e)=>r.apply(this,e):r}catch(e){console.error(`❌ Failed to evaluate prop "${s}":`,e),t[s]=void 0}})),t}cleanupProps(e){const t=this.elementProps.get(e);t&&(t.forEach((e=>{e.subscriptionIds.forEach((e=>{this.stateManager.removeSubscription(e)}))})),this.elementProps.delete(e))}buildComponentContextWithProps(e,t){const s=this.buildComponentContext(e);let n=this.findElementWithProps(e);if(t&&this.elementProps.has(t)&&(n=t),n)try{const i=this.evaluatePropsWithContext(n,e,t);Object.keys(i).length>0&&Object.keys(i).forEach((e=>{s[e]=i[e]}))}catch(t){console.error(`❌ Error evaluating props for ${e}:`,t)}return s}evaluatePropsWithContext(e,t,s){var n;const i={},r=this.elementProps.get(e);if(!r||!this.expressionEvaluator)return i;const a=r.values().next().value;if(!a)return i;let o=this.buildComponentContext(a.component);const c=null==(n=this.loopManager)?void 0:n.getLoopContextForElement(e);return c&&(o={...o,...c}),r.forEach(((e,t)=>{var s;try{const n=null==(s=this.templateRenderer)?void 0:s.render(e.expression,o,e.component);"function"==typeof n?this.isFunctionExplicitlyPassed(e.expression)?i[t]=(...e)=>n.apply(this,e):(console.warn(`⚠️ Function "${t}" not passed - not from shared namespace or explicitly passed`),i[t]=void 0):i[t]=n}catch(e){console.error(`❌ Failed to evaluate prop "${t}":`,e),i[t]=void 0}})),i}isFunctionExplicitlyPassed(e){const t=N.isSingleExpression(e);return!!t&&/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(t.trim())}findElementWithProps(e){const t=document.querySelectorAll(`[${g.ATTR_PREFIXES.COMPONENT}="${e}"]`);for(const e of t){const t=this.elementProps.get(e);if(t&&t.size>0)return e}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 t=this.computeComponentContext(e);return this.contextCache.set(e,t),this.contextInvalidated.delete(e),t}computeComponentContext(e){const t={};"app"!==e&&window[e]&&Object.assign(t,window[e]),"app"===e&&window.app&&Object.assign(t,window.app);const s=this.componentFunctions.get(e);if(s)for(const[e,n]of s)t[e]=n;if("app"===e){const e=this.componentFunctions.get("app");if(e)for(const[s,n]of e)s in t||(t[s]=n)}const n=this.stateManager.getState();for(const s of Object.keys(n))if(s.startsWith(e+".")){const i=s.substring(e.length+1);i in t||(t[i]=n[s])}return t}invalidateContextCache(e){if(e.startsWith("app.")){for(const e of this.contextCache.cache.keys())this.invalidateComponent(e);return}const t=e.indexOf(".");if(-1!==t){const s=e.slice(0,t);this.invalidateComponent(s)}}invalidateComponent(e){this.contextInvalidated.add(e),this.contextIndex.delete(e)}executePhpScripts(e){const t=this.componentStack.length,s=e.getAttribute(g.ATTR_PREFIXES.COMPONENT),n=e===document.body;if(s||n){if(s){this.pushComponent(s);const t=this.getParentComponent(e);this.setupProps(e,t)}this.getRelevantScripts(e,n).forEach((e=>{const t=e.getAttribute(g.ATTR_PREFIXES.COMPONENT);t&&t!==s?(this.pushComponent(t),this.executeScript(e),this.popComponent()):this.executeScript(e)}))}for(Array.from(e.children).forEach((e=>this.executePhpScripts(e)));this.componentStack.length>t;)this.popComponent();document.body.hidden=!1}getParentComponent(e){let t=e.parentElement;for(;t;){const e=t.getAttribute(g.ATTR_PREFIXES.COMPONENT);if(e)return e;t=t.parentElement}return"app"}getRelevantScripts(e,t){return Array.from(e.querySelectorAll(`script[type="${g.SCRIPT_TYPE}"]`)).filter((s=>{if(this.processedScripts.has(s))return!1;if(t)return!!s.hasAttribute(g.ATTR_PREFIXES.COMPONENT)||!s.closest(`[${g.ATTR_PREFIXES.COMPONENT}]`);let n=s.parentElement;for(;n&&n!==e;){if(n.hasAttribute(g.ATTR_PREFIXES.COMPONENT))return!1;n=n.parentElement}return n===e||e.contains(s)}))}executeScript(e){if(this.processedScripts.has(e))return;this.processedScripts.add(e);const t=this.getCurrentComponent(),s=e.textContent||"",n=N.decodeEntities(s);try{const s=this.findComponentElementForScript(e,t);if(s===e){const t=this.getParentComponent(e);this.setupProps(e,t)}const i=this.buildComponentContextWithProps(t,s);window[t]||(window[t]={}),this.executeScriptFunctions(n,t,i)}catch(e){console.error(`Script execution failed in component ${t}:`,e),console.error("Script content:",n)}}findComponentElementForScript(e,t){if(e.getAttribute(g.ATTR_PREFIXES.COMPONENT)===t)return e;let s=e.parentElement;for(;s;){if(s.getAttribute(g.ATTR_PREFIXES.COMPONENT)===t)return s;s=s.parentElement}const n=document.querySelectorAll(`[${g.ATTR_PREFIXES.COMPONENT}="${t}"]`);for(const e of n)if(this.elementProps.has(e))return e;return n[0]||void 0}executeScriptFunctions(e,t,s){const n=this.extractFunctionNames(e),i=this.findElementWithProps(t),r=this.extractVariableDeclarations(e);let a={...s};if(r.forEach((e=>{delete a[e];const t=`set${Ft(e)}`,s=`${e}Getter`;delete a[t],delete a[s]})),i){const e=this.evaluateProps(i);Object.assign(a,e)}a.getContext=()=>this.buildComponentContextWithProps(t),a.withContext=e=>{const s=this.buildComponentContextWithProps(t);return e.call(s,s)},a.__getProp=e=>{if(i)return this.evaluateProps(i)[e]};let o=Se.getInstance().transformStateDeclarations(e);o=this.modifyScriptForReactiveProps(o,t,i||void 0);const c=`\n ${o}\n\n ${n.map((e=>`\n if (typeof ${e} === 'function') {\n this['${e}'] = ${e};\n }\n `)).join("\n")}\n `,p=Object.keys(a),h=p.map((e=>a[e]));if(this.checkIfInLoopItem()){const e=this.extractLoopItemContext();this.domBindingManager.stateManager.currentLoopContext=e}try{new Function(...p,c).call(window[t],...h),window[t].getContext=a.getContext,window[t].withContext=a.withContext,window[t].__getProp=a.__getProp;for(const e of n){const s=window[t][e];"function"==typeof s&&this.storeFunctionForComponent(t,e,s)}this.invalidateComponent(t)}catch(s){console.error("Script execution failed:",s),console.error("Component:",t),console.error("Original script:",e),console.error("Processed script:",o),console.error("Execution context keys:",Object.keys(a))}finally{this.domBindingManager.stateManager.currentLoopContext=null}}checkIfInLoopItem(){return!1}extractLoopItemContext(){return{}}extractVariableDeclarations(e){const t=Se.getInstance().extractStateDeclarations(e).map((e=>e.variableName)),s=[],n=/(?:const|let|var)\s*\[\s*([^,\]]+)(?:\s*,\s*([^,\]]+))?\s*\]/g;let i;for(;null!==(i=n.exec(e));)i[1]&&!t.includes(i[1].trim())&&s.push(i[1].trim()),i[2]&&!t.includes(i[2].trim())&&s.push(i[2].trim());const r=/(?:const|let|var)\s+([a-zA-Z_$][\w$]*)/g;for(;null!==(i=r.exec(e));)t.includes(i[1])||s.push(i[1]);return[...t,...s]}modifyScriptForReactiveProps(e,t,s){if(!s||!this.elementProps.has(s))return e;const n=this.elementProps.get(s),i=Array.from(n.keys());let r=e;return i.forEach((e=>{r=this.replacePropOutsideStrings(r,e)})),r}replacePropOutsideStrings(e,t){let s="",n=0;const i=e.length;for(;n<i;){const r=e[n];if("'"!==r)if('"'!==r)if("`"!==r){if("/"===r&&n+1<i){if("/"===e[n+1]){const t=e.indexOf("\n",n),r=-1===t?i:t;s+=e.slice(n,r),n=r;continue}if("*"===e[n+1]){const t=e.indexOf("*/",n+2),r=-1===t?i:t+2;s+=e.slice(n,r),n=r;continue}}this.matchesPropName(e,n,t)?(s+=`__getProp('${t}')`,n+=t.length):(s+=r,n++)}else{const t=this.findTemplateEnd(e,n);s+=e.slice(n,t+1),n=t+1}else{const t=this.findStringEnd(e,n,'"');s+=e.slice(n,t+1),n=t+1}else{const t=this.findStringEnd(e,n,"'");s+=e.slice(n,t+1),n=t+1}}return s}findStringEnd(e,t,s){let n=t+1;for(;n<e.length;){if(e[n]===s&&"\\"!==e[n-1])return n;"\\"===e[n]&&n++,n++}return e.length-1}findTemplateEnd(e,t){let s=t+1,n=0;for(;s<e.length;){const t=e[s];if("`"===t&&0===n)return s;"$"===t&&s+1<e.length&&"{"===e[s+1]?(n++,s++):"}"===t&&n>0?n--:"\\"===t&&s++,s++}return e.length-1}matchesPropName(e,t,s){if(t+s.length>e.length||e.substr(t,s.length)!==s)return!1;const n=t>0?e[t-1]:"",i=t+s.length<e.length?e[t+s.length]:"",r=0===t||!/[a-zA-Z0-9_$]/.test(n),a=t+s.length===e.length||!/[a-zA-Z0-9_$]/.test(i);if(!r||!a)return!1;const o=e.slice(t+s.length);return!/^\s*[=:]/.test(o)}extractFunctionNames(e){const t=[],s=/function\s+([a-zA-Z_$][\w$]*)\s*\(/g;let n;for(;null!==(n=s.exec(e));)t.push(n[1]);const i=/(?:const|let|var)\s+([a-zA-Z_$][\w$]*)\s*=\s*(?:\([^)]*\)|[^)]*)\s*=>/g;for(;null!==(n=i.exec(e));)t.push(n[1]);return t}storeFunctionForComponent(e,t,s){this.componentFunctions.has(e)||this.componentFunctions.set(e,new Map),this.componentFunctions.get(e).set(t,s),window[e]||(window[e]={}),window[e][t]=s}getComponentFunctions(e){return this.componentFunctions.get(e)}destroy(){if(this.updateTimeouts){for(const e of this.updateTimeouts.values())clearTimeout(e);this.updateTimeouts.clear()}}}class Ds{constructor(e,t,s){d(this,"stateManager"),d(this,"componentManager"),d(this,"expressionEvaluator"),d(this,"textNodeManager"),d(this,"observer"),d(this,"listeners",new WeakMap),d(this,"pendingBindings",[]),d(this,"pendingTextNodes",[]),d(this,"applyingUpdates",!1),d(this,"elementCache",new WeakMap),d(this,"batchedUpdates",new Set),d(this,"processingRAF",null),d(this,"updateQueue",new Map),d(this,"eventDelegation",new Be),d(this,"processedElements",new WeakSet),d(this,"loopManager"),d(this,"templateRenderer"),d(this,"isRelevantMutation",(e=>{if(this.applyingUpdates&&"attributes"===e.type)return!1;if("childList"===e.type||"characterData"===e.type)return!0;if("attributes"===e.type){const t=e.attributeName;return t===g.ATTR_PREFIXES.COMPONENT||null!==t&&he.isEventAttribute(t)}return!1})),this.stateManager=e,this.componentManager=t,this.expressionEvaluator=s,this.textNodeManager=new Ms(s,e),this.textNodeManager.componentManager=this.componentManager,this.componentManager.setDOMBindingManager(this),this.setupMutationObserver(),this.eventDelegation.setupEventDelegation(),this.loopManager=new Bt(e,s),this.loopManager.setDependencies(t,this),this.loopManager.eventDelegation=this.eventDelegation,this.eventDelegation.setDependencies(this.componentManager,this.expressionEvaluator,this.loopManager),this.templateRenderer=new Ge(s)}refreshComponentElement(e,t){this.elementCache.delete(e),this.processedElements.delete(e);const s=[...this.componentManager.componentStack];this.componentManager.componentStack=["app"],"app"!==t&&this.componentManager.componentStack.push(t);try{const s=this.componentManager.buildComponentContextWithProps(t,e);this.processElementInContext(e,s,t,!0),this.walkComponentChildren(e,t),this.refreshComponentTextNodes(e,t)}finally{this.componentManager.componentStack=s}}refreshComponentTextNodes(e,t){const s=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>{const s=e;return!s.textContent||!g.MUSTACHE_PATTERN.test(s.textContent)||C.isTextNodeInsideScript(s)||this.isTextNodeInsideLoopItem(s)||C.getComponentForNode(s)!==t?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}});let n;const i=[];for(;n=s.nextNode();)i.push(n);i.forEach((e=>{this.textNodeManager.cleanupTextNode(e),this.textNodeManager.cleanupTextNode(e),this.textNodeManager.processTextNode(e,t)}))}walkComponentChildren(e,t){const s=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:s=>{const n=s;return C.getElementComponent(n)!==t?NodeFilter.FILTER_REJECT:n===e?NodeFilter.FILTER_SKIP:NodeFilter.FILTER_ACCEPT}});let n;const i=[];for(;n=s.nextNode();){const e=n;i.push(e)}i.forEach((s=>{this.elementCache.delete(s),this.processedElements.delete(s);const n=this.componentManager.buildComponentContextWithProps(t,e);this.processElementInContext(s,n,t,!0)}))}createSpreadDirectiveBinding(e,t,s){const n=`spread_${Date.now()}_${Math.random()}`,i=N.parseSpreadDirective(t);if(0===i.spreads.length&&0===i.objects.length)return void console.warn(`Invalid pp-spread directive: ${t}`);const r=new Set,a=()=>{if(document.contains(e))try{const t=this.componentManager.buildComponentContextWithProps(s,e);this.clearSpreadAttributes(e,r);for(const n of i.spreads){const i=this.expressionEvaluator.evaluateExpression(n,t,s);i&&"object"==typeof i&&this.applySpreadObject(e,i,r)}for(const n of i.objects)this.applyObjectProperties(e,n,t,s,r)}catch(e){console.error(`Spread directive evaluation error for "${t}":`,e)}else this.stateManager.removeSubscription(n)},o=new Set;for(const e of i.spreads)this.templateRenderer.dependencies(e,s,this.stateManager).forEach((e=>o.add(e)));for(const e of i.objects)for(const t of e)this.templateRenderer.dependencies(t.value,s,this.stateManager).forEach((e=>o.add(e)));const c={id:n,selector:"",dependencies:o,callback:a,element:e,component:s};this.stateManager.addSubscription(c),this.storeSpreadSubscription(e,n),a()}applyObjectProperties(e,t,s,n,i){for(const r of t)try{const t=this.expressionEvaluator.evaluateExpression(r.value,s,n);if(this.isEventProperty(r.key)){this.handleSpreadEventProperty(e,r.key,t);continue}const a=this.normalizeAttributeName(r.key);this.updateElementProperty(e,a,t),i.add(a)}catch(e){console.error(`Error evaluating object property "${r.key}: ${r.value}":`,e)}}applySpreadObject(e,t,s){for(const[n,i]of Object.entries(t))if(null!=i){if(this.isEventProperty(n)){this.handleSpreadEventProperty(e,n,i);continue}const t=this.normalizeAttributeName(n);(!e.hasAttribute(t)||s.has(t))&&(this.updateElementProperty(e,t,i),s.add(t))}}isEventProperty(e){return e.startsWith("on")&&e.length>2}handleSpreadEventProperty(e,t,s){const n=t.substring(2).toLowerCase();if("function"==typeof s){const t=t=>{var n;try{const i=C.getContextComponent(e),r=(null==(n=this.componentManager)?void 0:n.buildComponentContextWithProps(i,e))||{};s.call(r,t)}catch(e){console.error("Spread event handler error:",e)}};return e.addEventListener(n,t),void this.storeDirectEventListener(e,n,t)}if("string"==typeof s){const t=C.getContextComponent(e);this.eventDelegation.registerEventHandler(e,n,s,t)}}storeDirectEventListener(e,t,s){e.__directEventListeners||(e.__directEventListeners=[]),e.__directEventListeners.push({eventType:t,listener:s})}clearSpreadAttributes(e,t){for(const s of t)e.hasAttribute(s)&&e.removeAttribute(s);t.clear()}normalizeAttributeName(e){return e.replace(/([A-Z])/g,"-$1").toLowerCase()}storeSpreadSubscription(e,t){e.__spreadSubscriptions||(e.__spreadSubscriptions=[]),e.__spreadSubscriptions.push(t)}setupMutationObserver(){this.observer=new MutationObserver((e=>{const t=e.filter(this.isRelevantMutation);0!==t.length&&this.processMutationsBatch(t)})),this.observer.observe(document.body,{childList:!0,subtree:!0,attributes:!0,characterData:!0,attributeFilter:[g.ATTR_PREFIXES.COMPONENT]})}processElement(e,t=!0){if(e===document.body){const s=Array.from(document.querySelectorAll(`[${g.ATTR_PREFIXES.COMPONENT}]`)).sort(((e,t)=>C.getElementDepth(e)-C.getElementDepth(t)));this.processElementsBatch([e],t),s.forEach((e=>{this.processElementsBatch([e],t)})),t&&this.loopManager.processPendingTemplates()}else this.processElementsBatch([e],t)}processElementsBatch(e,t=!0){for(const s of e)this.processSingleElement(s,t);t&&(e.forEach((e=>{this.componentManager.executePhpScripts(e)})),this.processPendingBindings())}processSingleElement(e,t){const s=C.getElementComponent(e),n=C.getParentComponentForElement(e),i=this.componentManager.componentStack.length;"app"!==s&&(this.componentManager.pushComponent(s),this.componentManager.setupProps(e,n)),t&&this.componentManager.executePhpScripts(e),this.processLoopTemplates(e,s);const r=t?this.componentManager.buildComponentContextWithProps(s,e):{};for(this.processElementInContext(e,r,s,t),this.walkDOM(e,r,s,t);this.componentManager.componentStack.length>i;)this.componentManager.popComponent()}processLoopTemplates(e,t){this.getDirectComponentTemplates(e,t).forEach((e=>{this.loopManager.queueTemplate(e,t)}))}getDirectComponentTemplates(e,t){const s=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:t=>{const s=t;return s!==e&&s.hasAttribute(g.ATTR_PREFIXES.COMPONENT)?NodeFilter.FILTER_REJECT:"TEMPLATE"===s.tagName&&s.hasAttribute("pp-for")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});let i;for(;i=n.nextNode();)s.push(i);return s}walkDOM(e,t,s,n){const i=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,{acceptNode:t=>{if(t.nodeType===Node.ELEMENT_NODE){const n=t;if("script"===n.tagName.toLowerCase()||this.loopManager.isLoopItem(n))return NodeFilter.FILTER_REJECT;let i=n.parentElement;for(;i&&i!==e;){if(this.loopManager.isLoopItem(i))return NodeFilter.FILTER_REJECT;i=i.parentElement}const r=C.getElementComponent(n);if(n===e)return NodeFilter.FILTER_ACCEPT;if(r!==s)return NodeFilter.FILTER_REJECT}else if(t.nodeType===Node.TEXT_NODE){const e=t;if(C.isTextNodeInsideScript(e)||this.isTextNodeInsideLoopItem(e)||C.getComponentForNode(e)!==s)return NodeFilter.FILTER_REJECT}return NodeFilter.FILTER_ACCEPT}});let r;const a=[],o=[];for(;r=i.nextNode();)if(r.nodeType===Node.TEXT_NODE){const e=r;e.textContent&&g.MUSTACHE_PATTERN.test(e.textContent)&&C.getComponentForNode(e)===s&&a.push(e)}else if(r.nodeType===Node.ELEMENT_NODE){const e=r;this.loopManager.isLoopItem(e)||C.getElementComponent(e)===s&&!this.processedElements.has(e)&&(o.push(e),this.processedElements.add(e))}a.forEach((e=>{n?this.textNodeManager.processTextNode(e,s):this.pendingTextNodes.push({textNode:e,component:s})})),o.forEach((e=>{this.processElementInContext(e,t,s,n)}))}isTextNodeInsideLoopItem(e){let t=e.parentElement;for(;t&&t!==document.body;){if(this.loopManager.isLoopItem(t))return!0;t=t.parentElement}return!1}processElementInContext(e,t,s,n){if(e.hasAttribute(g.ATTR_PREFIXES.SPREAD)){const t=e.getAttribute(g.ATTR_PREFIXES.SPREAD);n&&this.createSpreadDirectiveBinding(e,t,s),e.removeAttribute(g.ATTR_PREFIXES.SPREAD)}if(this.loopManager.isLoopItem(e)||this.isElementInLoopItem(e))return;const i=this.extractDomMustacheBindings(e),r=this.elementCache.get(e),a=this.getElementHash(e);if(r&&r.hash===a&&this.isCacheValid(r)&&n)return void this.applyBindingsFromCache(e,r,t);const o={bindings:i,component:s,listeners:[],lastProcessed:Date.now(),hash:a};n?this.applyBindings(e,i,t,s):i.forEach(((t,n)=>{this.pendingBindings.push({element:e,property:n,expression:t,component:s})})),this.setupEventBindings(e,s),this.elementCache.set(e,o)}isElementInLoopItem(e){let t=e;for(;t;){if(this.loopManager.isLoopItem(t))return!0;t=t.parentElement}return!1}extractDomMustacheBindings(e){const t=new Map,s=e.attributes;for(let n=0;n<s.length;n++){const i=s[n];if(i.name===g.ATTR_PREFIXES.COMPONENT||he.isEventAttribute(i.name))continue;const r=e.hasAttribute(g.ATTR_PREFIXES.COMPONENT);if(!(r&&i.value&&Dt.containsMustacheExpression(i.value))&&!r&&i.value){const e=g.MUSTACHE_PATTERN.test(i.value),s=N.decodeEntities(i.value),n=g.MUSTACHE_PATTERN.test(s);(e||n)&&t.set(i.name,i.value)}}return t}applyBindings(e,t,s,n){t.forEach(((t,s)=>{this.createMustacheBinding(e,s,t)})),this.setupEventBindings(e,n)}applyBindingsFromCache(e,t,s){t.bindings.forEach(((s,n)=>{try{const i=this.componentManager.buildComponentContextWithProps(t.component,e),r=this.templateRenderer.render(s,i,t.component);this.updateElementProperty(e,n,r)}catch(e){console.error(`Cached binding evaluation error for "${s}":`,e)}}))}createMustacheBinding(e,t,s){const n=`mustache_${Date.now()}_${Math.random()}`,i=this.componentManager.getCurrentComponent(),r=new Set;this.templateRenderer.dependencies(s,i,this.stateManager).forEach((e=>r.add(e)));const a=()=>{if(document.contains(e))try{const n=this.componentManager.buildComponentContextWithProps(i,e),r=this.templateRenderer.render(s,n,i);this.scheduleElementUpdate(e,t,r)}catch(e){console.error(`Mustache binding evaluation error for "${s}":`,e)}else this.stateManager.removeSubscription(n)},o={id:n,selector:"",dependencies:r,callback:a,element:e,component:i};this.stateManager.addSubscription(o),this.setupTwoWayBindingIfNeeded(e,t,s,i),a()}setupEventBindings(e,t){for(let t=0;t<e.attributes.length;t++){const s=e.attributes[t];if(he.isEventAttribute(s.name)){const t=s.name.substring(2),n=C.getContextComponent(e);this.eventDelegation.registerEventHandler(e,t,s.value,n),e.removeAttribute(s.name)}}}setupTwoWayBindingIfNeeded(e,t,s,n){const i=N.isSingleExpression(s);i&&("value"===t&&(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)?this.setupTwoWayBinding(e,i,n):"checked"===t&&e instanceof HTMLInputElement&&("checkbox"===e.type||"radio"===e.type)&&this.setupTwoWayBinding(e,i,n,!0))}setupTwoWayBinding(e,t,s,n=!1){const i=this.findStateTarget(t,s);if(!i)return;const r=()=>{try{const t=n?e.checked:e.value,s=n?!!t:t;if(!i.tailPath)return void this.stateManager.setState(i.fullRoot,s);const r=this.stateManager.getState()[i.fullRoot],a=r&&"object"==typeof r?{...r}:{};this.setPath(a,i.tailPath,s),this.stateManager.setState(i.fullRoot,a)}catch(e){console.error("Two-way binding error:",e)}},a=n?"change":"input";e.addEventListener(a,r);const o=this.listeners.get(e)||[];o.push({type:a,fn:r}),this.listeners.set(e,o)}findStateTarget(e,t){const s=e.match(/^([a-zA-Z_$][\w$]*(?:\.[\w$]+)*)$/);if(!s)return null;const[n,...i]=s[1].split("."),r=we.findExistingStateKey(n,t,this.stateManager.getState());return r?{fullRoot:r,tailPath:i.join(".")}:null}setPath(e,t,s){if(!t)return;const n=t.split("."),i=n.pop();let r=e;for(const e of n)r=r[e]=r[e]||{};r[i]=s}scheduleElementUpdate(e,t,s){this.updateQueue.has(e)||(this.updateQueue.set(e,new Set),this.batchedUpdates.add(e)),this.updateQueue.get(e).add(t),this.processingRAF||(this.processingRAF=requestAnimationFrame((()=>{this.processBatchedElementUpdates()}))),e[`__pending_${t}`]=s}processBatchedElementUpdates(){this.applyingUpdates=!0;try{for(const e of this.batchedUpdates){const t=this.updateQueue.get(e);if(t)for(const s of t){const t=e[`__pending_${s}`];this.updateElementProperty(e,s,t),delete e[`__pending_${s}`]}}}finally{this.batchedUpdates.clear(),this.updateQueue.clear(),this.processingRAF=null,this.applyingUpdates=!1}}updateElementProperty(e,t,s){try{switch(t){case"textContent":const n=k(s);e.textContent!==n&&(e.textContent=n);break;case"innerHTML":const i=k(s);e.innerHTML!==i&&(e.innerHTML=i);break;case"value":if(e instanceof HTMLOptionElement){const t=k(s);e.value!==t&&(e.value=t,e.setAttribute("value",t));break}if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement){const t=k(s);e.value!==t&&(e.value=t)}break;case"selectedIndex":if(e instanceof HTMLSelectElement){const t=Number(s);e.selectedIndex!==t&&(e.selectedIndex=t)}break;case"checked":case"disabled":case"hidden":case"readonly":case"required":case"multiple":case"selected":case"autofocus":case"autoplay":case"controls":case"defer":case"loop":case"muted":case"open":case"reversed":case"async":case"default":case"formnovalidate":case"novalidate":case"allowfullscreen":case"capture":case"itemscope":if(e instanceof HTMLElement){const n=!!s;e[t]!==n&&(e[t]=n)}break;case"indeterminate":if(e instanceof HTMLInputElement&&"checkbox"===e.type){const t=!!s;e.indeterminate!==t&&(e.indeterminate=t)}break;case"class":const r=k(s);e.className!==r&&(e.className=r);break;case"htmlFor":case"for":if(e instanceof HTMLLabelElement){const t=k(s);e.htmlFor!==t&&(e.htmlFor=t)}break;case"style":if(e instanceof HTMLElement)if("object"==typeof s&&s&&!Array.isArray(s))Object.assign(e.style,s);else{const t=k(s);e.style.cssText!==t&&(e.style.cssText=t)}break;case"tabIndex":if(e instanceof HTMLElement){const t=null==s?-1:Number(s);e.tabIndex!==t&&(e.tabIndex=t)}break;case"contentEditable":if(e instanceof HTMLElement){const t=!0===s?"true":!1===s?"false":String(s);e.contentEditable!==t&&(e.contentEditable=t)}break;case"draggable":if(e instanceof HTMLElement){const t=!0===s?"true":"false";e.draggable.toString()!==t&&(e.draggable=!0===s),e.getAttribute("draggable")!==t&&e.setAttribute("draggable",t)}break;case"spellcheck":if(e instanceof HTMLElement){const t=!0===s?"true":"false";e.spellcheck!==!!s&&(e.spellcheck=!!s),e.getAttribute("spellcheck")!==t&&e.setAttribute("spellcheck",t)}break;case"src":case"href":case"action":case"alt":case"title":case"placeholder":case"id":case"name":case"type":case"method":case"target":case"rel":case"pattern":case"accept":case"autocomplete":case"enctype":case"wrap":case"download":case"ping":case"referrerpolicy":case"crossorigin":case"integrity":case"loading":case"decoding":case"srcset":case"sizes":case"dir":case"lang":case"translate":case"role":const a=k(s);e.getAttribute(t)!==a&&(null==s?e.removeAttribute(t):e.setAttribute(t,a));break;case"min":case"max":case"step":case"maxLength":case"minLength":case"size":case"rows":case"cols":case"rowSpan":case"colSpan":if(e instanceof HTMLElement){const n=String(s);e.getAttribute(t)!==n&&(null==s?e.removeAttribute(t):e.setAttribute(t,n))}break;default:if(t.startsWith("aria-")){const n=k(s);e.getAttribute(t)!==n&&(null==s||!1===s?e.removeAttribute(t):e.setAttribute(t,n));break}if(t.startsWith("data-")){const n=k(s);e.getAttribute(t)!==n&&(null==s?e.removeAttribute(t):e.setAttribute(t,n));break}const o=k(s);e.getAttribute(t)!==o&&(null==s||!1===s?e.removeAttribute(t):e.setAttribute(t,o))}}catch(s){console.error(`Failed to update property "${t}" on element:`,e,s)}}processPendingBindings(){const e=[...this.pendingBindings];this.pendingBindings=[];const t=new Map;for(const s of e)t.has(s.component)||t.set(s.component,[]),t.get(s.component).push(s);for(const[e,s]of t){const t=[...this.componentManager.componentStack];this.componentManager.componentStack="app"!==e?["app",e]:["app"];for(const t of s)try{if(!document.contains(t.element))continue;this.createMustacheBinding(t.element,t.property,t.expression)}catch(t){console.error(`❌ Failed to create binding for ${e}:`,t)}this.componentManager.componentStack=t}this.processTextNodesPending()}processTextNodesPending(){const e=new Map;for(const t of this.pendingTextNodes)e.has(t.component)||e.set(t.component,[]),e.get(t.component).push(t);this.pendingTextNodes=[];for(const[t,s]of e){const e=[...this.componentManager.componentStack];this.componentManager.componentStack="app"!==t?["app",t]:["app"];for(const{textNode:e,component:t}of s)if(document.contains(e))try{this.textNodeManager.processTextNode(e,t)}catch(e){console.error(`❌ Failed to process text node for ${t}:`,e)}this.componentManager.componentStack=e}}processMutationsBatch(e){const t=new Set,s=new Set,n=new Set,i=new Set;for(const r of e)if("childList"===r.type&&(r.addedNodes.forEach((e=>{if(e.nodeType===Node.ELEMENT_NODE)t.add(e);else if(e.nodeType===Node.TEXT_NODE){const t=e;t.textContent&&g.MUSTACHE_PATTERN.test(t.textContent)&&i.add(t)}})),r.removedNodes.forEach((e=>{e.nodeType===Node.ELEMENT_NODE?s.add(e):e.nodeType===Node.TEXT_NODE&&this.textNodeManager.cleanupTextNode(e)}))),"attributes"===r.type&&r.target&&n.add(r.target),"characterData"===r.type&&r.target){const e=r.target;e.textContent&&g.MUSTACHE_PATTERN.test(e.textContent)&&i.add(e)}s.size>0&&this.cleanupElementsBatch(Array.from(s)),t.size>0&&this.processElementsBatch(Array.from(t)),i.size>0&&this.processTextNodesBatch(Array.from(i)),n.size>0&&this.rebindChangedElements(Array.from(n))}processTextNodesBatch(e){const t=new Map;for(const s of e){const e=C.getComponentForNode(s);t.has(e)||t.set(e,[]),t.get(e).push(s)}for(const[e,s]of t)s.forEach((t=>{this.textNodeManager.processTextNode(t,e)}))}rebindChangedElements(e){e.forEach((e=>{this.processElementBindings(e,!0)}))}processElementBindings(e,t=!0){const s=this.extractDomMustacheBindings(e),n=C.getElementComponent(e);s.forEach(((s,i)=>{t?this.createMustacheBinding(e,i,s):this.pendingBindings.push({element:e,property:i,expression:s,component:n})})),t&&this.setupEventBindings(e,n)}cleanupElementsBatch(e){e.forEach((e=>this.cleanupElement(e)))}cleanupElement(e){const t=this.listeners.get(e)||[];for(const{type:s,fn:n}of t)e.removeEventListener(s,n);this.listeners.delete(e),this.elementCache.delete(e),this.processedElements.delete(e),this.componentManager.cleanupProps(e),this.cleanupSubscriptions(e);const s=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,null);let n;for(;n=s.nextNode();)this.textNodeManager.cleanupTextNode(n);"TEMPLATE"===e.tagName&&e.hasAttribute("pp-for")&&this.loopManager.cleanupTemplate(e),e.querySelectorAll("template[pp-for]").forEach((e=>{this.loopManager.cleanupTemplate(e)}));const i=e.__directEventListeners;i&&(i.forEach((({eventType:t,listener:s})=>{e.removeEventListener(t,s)})),delete e.__directEventListeners);const r=e.__spreadEventHandlers;r&&(r.forEach((e=>{window.__spreadHandlers&&window.__spreadHandlers.delete(e)})),delete e.__spreadEventHandlers)}cleanupSubscriptions(e){const t=[];for(const[s,n]of this.stateManager.getSubscriptions())(n.element===e||n.element&&e.contains(n.element)||n.element&&!document.contains(n.element))&&t.push(s);t.forEach((e=>this.stateManager.removeSubscription(e)))}getElementHash(e){const t=[];for(let s=0;s<e.attributes.length;s++){const n=e.attributes[s];(n.name===g.ATTR_PREFIXES.COMPONENT||he.isEventAttribute(n.name)||n.value&&g.MUSTACHE_PATTERN.test(n.value))&&t.push(`${n.name}=${n.value}`)}return t.sort().join("|")}isCacheValid(e){return Date.now()-e.lastProcessed<3e4}refreshAllBindings(){this.elementCache=new WeakMap,this.processedElements=new WeakSet,this.processElement(document.body,!0)}destroy(){this.observer&&this.observer.disconnect(),this.eventDelegation.cleanup(),this.batchedUpdates.clear(),this.updateQueue.clear(),this.processingRAF&&cancelAnimationFrame(this.processingRAF),this.elementCache=new WeakMap,this.listeners=new WeakMap,this.processedElements=new WeakSet,this.loopManager.destroy()}}const X=class e{constructor(){d(this,"delegatedEvents",new Map),d(this,"elementHandlers",new WeakMap),d(this,"handlerCache",new oe(200)),d(this,"componentManager"),d(this,"expressionEvaluator"),d(this,"loopManager")}static getAllAvailableEvents(){if(e.eventCache)return e.eventCache;const t=new Set;try{Object.getOwnPropertyNames(HTMLElement.prototype).filter((e=>e.startsWith("on")&&e.length>2)).map((e=>e.substring(2).toLowerCase())).forEach((e=>t.add(e)))}catch(e){console.warn("Could not get HTMLElement events:",e)}try{Object.getOwnPropertyNames(Document.prototype).filter((e=>e.startsWith("on")&&e.length>2)).map((e=>e.substring(2).toLowerCase())).forEach((e=>t.add(e)))}catch(e){console.warn("Could not get Document events:",e)}try{Object.getOwnPropertyNames(Window.prototype).filter((e=>e.startsWith("on")&&e.length>2)).map((e=>e.substring(2).toLowerCase())).forEach((e=>t.add(e)))}catch(e){console.warn("Could not get Window events:",e)}try{Object.getOwnPropertyNames(Element.prototype).filter((e=>e.startsWith("on")&&e.length>2)).map((e=>e.substring(2).toLowerCase())).forEach((e=>t.add(e)))}catch(e){console.warn("Could not get Element events:",e)}return new Set(["beforeunload","unload","pagehide","pageshow","popstate","hashchange","storage","message","messageerror","offline","online","languagechange","rejectionhandled","unhandledrejection","afterprint","beforeprint","devicemotion","deviceorientation","deviceorientationabsolute"]).forEach((e=>t.delete(e))),e.eventCache=t,t}setupEventDelegation(){const t=e.getAllAvailableEvents();for(const e of t){const t=this.createDelegatedListener(e),s=this.getEventOptions(e);document.addEventListener(e,t,s),this.delegatedEvents.set(e,{listener:t,elements:new WeakSet})}}getEventOptions(e){const t={capture:!0,passive:!1};return["wheel","touchstart","touchmove","touchend","scroll","mousewheel"].includes(e)&&(t.passive=!0),("focusin"===e||"focusout"===e)&&(t.capture=!1),t}isEventSupported(t){return e.getAllAvailableEvents().has(t.toLowerCase())}getAllSupportedEvents(){return Array.from(e.getAllAvailableEvents()).sort()}getDelegatedEvents(){return Array.from(this.delegatedEvents.keys()).sort()}setDependencies(e,t,s){this.componentManager=e,this.expressionEvaluator=t,this.loopManager=s}createDelegatedListener(e){return t=>{const s=t.target;if(!s)return;const n=this.findHandler(s,e);n&&this.executeHandler(n.handler,n.element,t)}}registerEventHandler(e,t,s,n){const i=t.toLowerCase();if(!this.isEventSupported(i))return void console.warn(`⚠️ Event type "${t}" is not supported`);const r=C.getContextComponent(e);this.elementHandlers.has(e)||this.elementHandlers.set(e,new Map);const a={code:s,component:r};this.elementHandlers.get(e).set(i,a);const o=this.delegatedEvents.get(i);o?o.elements.add(e):(console.warn(`⚠️ No delegated listener for ${i}, attaching directly`),this.attachDirectListener(e,i,a))}findHandler(e,t){let s=e;for(;s;){const e=this.elementHandlers.get(s);if(null!=e&&e.has(t))return{handler:e.get(t),element:s};s=s.parentElement}return null}compileHandler(e,t){const s=`${t}:${e}`;if(this.handlerCache.has(s))return this.handlerCache.get(s);let n=e;n.includes("this")&&(n=n.replace(/\bthis\b/g,"thisElement")),n.includes("event")&&(n=n.replace(/\bevent\b/g,"eventObject"));const i=new Function("eventObject","thisElement","context",`\n try {\n with(context) {\n ${n}\n }\n } catch(error) {\n console.error('Event handler execution error:', error);\n console.error('Handler code:', ${JSON.stringify(e)});\n console.error('Component:', '${t}');\n console.error('Available context keys:', Object.keys(context));\n }\n `);return this.handlerCache.set(s,i),i}executeHandler(e,t,s){var n;if(this.componentManager&&this.expressionEvaluator)try{let i=e.component,r=t;for(;r;){const e=r.__uniqueComponentName;if(e){i=e;break}r=r.parentElement}const a=t.getAttribute(g.ATTR_PREFIXES.CONTEXT),o="app"===a||"parent"===a,c="app"===C.getElementComponent(t),p=C.findElementForComponent(t,i);let h;if(o||c)h=this.componentManager.buildComponentContextWithProps("app"===i||"app"===a?"app":i,p||void 0);else if(h=this.componentManager.buildRestrictedComponentContext(i,!1),p){const e=this.componentManager.evaluateProps(p);Object.assign(h,e)}const l=null==(n=this.loopManager)?void 0:n.getLoopContextForElement(t);if(l){const e={};for(const[t,s]of Object.entries(l))"function"!=typeof s&&(e[t]=s);h={...e,...h}}e.compiledFn||(e.compiledFn=this.compileHandler(e.code,i)),e.compiledFn&&e.compiledFn(s,t,h)}catch(t){console.error("💥 Event handler execution failed:",t),console.error("Handler code:",e.code),console.error("Handler component:",e.component)}else console.warn("EventDelegationManager dependencies not set")}extractComponentFunctions(e){const t={};for(const[s,n]of Object.entries(e))"function"==typeof n&&(t[s]=n);return t}attachDirectListener(e,t,s){const n=t=>{this.executeHandler(s,e,t)};e.addEventListener(t,n),e[`__${t}_listener`]=n}removeEventHandler(e,t){var s,n;const i=this.elementHandlers.get(e);i&&(i.delete(t),0===i.size&&this.elementHandlers.delete(e));const r=this.delegatedEvents.get(t);r&&(null==(n=(s=r.elements).delete)||n.call(s,e));const a=e[`__${t}_listener`];a&&(e.removeEventListener(t,a),delete e[`__${t}_listener`])}cleanup(){for(const[e,t]of this.delegatedEvents)document.removeEventListener(e,t.listener,!0);this.delegatedEvents.clear(),this.handlerCache.clear()}};d(X,"eventCache",null);let Be=X;class Bs{constructor(){d(this,"stateManager",new Rs),d(this,"expressionEvaluator",new Os),d(this,"componentManager",new Fs(this.stateManager)),d(this,"domBindingManager",new Ds(this.stateManager,this.componentManager,this.expressionEvaluator)),d(this,"initialized",!1),d(this,"currentLoopContext",null),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",(()=>this.initialize())):setTimeout((()=>this.initialize()),0)}initialize(){this.initialized||(this.initialized=!0,this.componentManager.setExpressionEvaluator(this.expressionEvaluator),this.domBindingManager.processElement(document.body,!0),this.componentManager.executePhpScripts(document.body),this.domBindingManager.processPendingBindings())}state(e,t){const s=this.componentManager.getCurrentComponent();let n,i,r;"string"==typeof e&&2===arguments.length?(n=e,i=t):"string"==typeof e&&1===arguments.length?this.looksLikeVariableName(e)?(n=e,i=void 0):(console.warn("pp.state() called with string that doesn't look like variable name:",e),n="unknownState",i=e):(console.warn("pp.state() called without explicit key - this should be handled by AST transformation"),n="unknownState",i=e);const a=this.getLoopExecutionContext();if(a){const e=this.generateLoopInstanceId(a);r=`${s}.${e}.${n}`}else r=`${s}.${n}`;this.stateManager.hasState(r)||this.stateManager.setState(r,i);const o=()=>this.stateManager.getState()[r],c=new Proxy(o,{get(e,t,s){if("__pphp_key"===t||"__pphp_fullKey"===t||"__pphp_component"===t||"value"===t||"valueOf"===t||"toString"===t)return Reflect.get(e,t,s);const n=e();if(null!=n){if(t in Object(n)){const e=n[t];return"function"==typeof e?e.bind(n):e}return Reflect.get(e,t,s)}},has(e,t){if("__pphp_key"===t||"__pphp_fullKey"===t||"__pphp_component"===t||"value"===t||"valueOf"===t||"toString"===t)return Reflect.has(e,t);const s=e();return null!=s&&t in Object(s)||Reflect.has(e,t)},apply:(e,t,s)=>Reflect.apply(e,t,s)});Object.defineProperty(c,"__pphp_key",{value:n,enumerable:!1,writable:!1}),Object.defineProperty(c,"__pphp_fullKey",{value:r,enumerable:!1,writable:!1}),Object.defineProperty(c,"__pphp_component",{value:s,enumerable:!1,writable:!1}),Object.defineProperty(c,"value",{get:()=>this.stateManager.getState()[r],enumerable:!0,configurable:!0}),o.valueOf=()=>this.stateManager.getState()[r],o.toString=()=>k(this.stateManager.getState()[r]);const p=e=>{const t=this.stateManager.getState()[r],s="function"==typeof e?e(t):e;this.stateManager.setState(r,s)};return this.createComponentScopedGlobals(s,n,c,p),[c,p]}getLoopExecutionContext(){return this.currentLoopContext}generateLoopInstanceId(e){const t=Object.keys(e).sort().map((t=>{const s=e[t];return s&&"object"==typeof s&&"id"in s?`${t}:${s.id}`:`${t}:${JSON.stringify(s)}`}));return`loop_${btoa(t.join("|")).replace(/[^a-zA-Z0-9]/g,"").substring(0,8)}`}looksLikeVariableName(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)&&e.length<=50&&!e.includes(" ")&&!Vt.has(e)}effect(e,t){const s=`effect_${Date.now()}_${Math.random()}`,n=this.componentManager.getCurrentComponent();let i,r,a,o=!1;if(1===arguments.length)r="always",a={immediate:!0,detectDeps:!0};else if(Array.isArray(t)){const e=this.extractDependencyNames(t,n);0===e.length?(r="once",a={deps:e,immediate:!0}):(r="deps",a={deps:e,immediate:!0})}else{const e={immediate:!0,...t||{}};if(e.deps&&0!==e.deps.length){r="deps",a={deps:this.extractDependencyNames(e.deps,n),immediate:e.immediate,detectDeps:e.detectDeps}}else r="always",a={immediate:e.immediate,detectDeps:!0}}const c=()=>{if(!o){if(i&&"function"==typeof i)try{i()}catch(e){console.error("Effect cleanup error:",e)}try{i=e()}catch(e){console.error("Effect callback error:",e)}}};switch(r){case"always":const e={id:s,selector:"",dependencies:new Set(["*"]),callback:c,component:n};this.stateManager.addSubscription(e);break;case"once":break;case"deps":const t=this.resolveDependencies(a.deps,n);if(t.length){const e={id:s,selector:"",dependencies:new Set(t),callback:c,component:n};this.stateManager.addSubscription(e)}}return!1!==a.immediate&&c(),()=>{if(o=!0,i&&"function"==typeof i)try{i()}catch(e){console.error("Effect cleanup error:",e)}this.stateManager.removeSubscription(s)}}extractDependencyNames(e,t){const s=[];for(const t of e)"string"==typeof t?s.push(t):"function"==typeof t&&t.__pphp_key?s.push(t.__pphp_key):console.warn("Invalid dependency in effect:",t);return s.filter(Boolean)}resolveDependencies(e,t){const s=[],n=this.stateManager.getState();for(const i of e)if(i.includes(".")){const e=i.split("."),r=e[0],a=e.slice(1).join("."),o=this.componentManager.getPropDependencies(r,t);if(o.length>0)s.push(...o);else{const e=we.findExistingStateKey(r,t,n);e?s.push(`${e}.${a}`):s.push(`${t}.${i}`)}}else{const e=this.componentManager.getPropDependencies(i,t);if(e.length>0)s.push(...e);else{const e=we.findExistingStateKey(i,t,n);e?s.push(e):s.push(`${t}.${i}`)}}return Array.from(new Set(s))}createComponentScopedGlobals(e,t,s,n){window[e]||(window[e]={});const i=`set${Ft(t)}`;Object.defineProperty(window[e],t,{get:()=>s.valueOf(),configurable:!0,enumerable:!0}),window[e][i]=n,window[e][`${t}Getter`]=s}}const $t=new Bs;window.pp=$t,globalThis.pp=$t;
|
package/dist/src/app/layout.php
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
<?php
|
|
2
2
|
|
|
3
|
-
use
|
|
4
|
-
use
|
|
3
|
+
use PP\MainLayout;
|
|
4
|
+
use PP\Request;
|
|
5
5
|
|
|
6
6
|
MainLayout::$title = !empty(MainLayout::$title) ? MainLayout::$title : 'Create Prisma PHP App';
|
|
7
7
|
MainLayout::$description = !empty(MainLayout::$description) ? MainLayout::$description : 'Generated by create Prisma PHP App';
|
|
@@ -16,7 +16,7 @@ MainLayout::$description = !empty(MainLayout::$description) ? MainLayout::$descr
|
|
|
16
16
|
<!-- Dynamic Header Scripts -->
|
|
17
17
|
</head>
|
|
18
18
|
|
|
19
|
-
<body
|
|
19
|
+
<body>
|
|
20
20
|
<?= MainLayout::$children; ?>
|
|
21
21
|
<!-- Dynamic Footer Scripts -->
|
|
22
22
|
</body>
|