create-prisma-php-app 3.0.0-beta.0 → 3.0.0-beta.10
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.
|
@@ -17,10 +17,10 @@ class IncludeTracker
|
|
|
17
17
|
/**
|
|
18
18
|
* Includes and echoes a file wrapped in a unique pp-section-id container.
|
|
19
19
|
* Supported $mode values: 'include', 'include_once', 'require', 'require_once'
|
|
20
|
-
*
|
|
20
|
+
*
|
|
21
21
|
* @param string $filePath The path to the file to be included.
|
|
22
|
-
* @param string $mode
|
|
23
|
-
* @throws RuntimeException
|
|
22
|
+
* @param string $mode The mode of inclusion.
|
|
23
|
+
* @throws RuntimeException If the file does not exist.
|
|
24
24
|
* @throws InvalidArgumentException If an invalid mode is provided.
|
|
25
25
|
* @return void
|
|
26
26
|
*/
|
|
@@ -36,20 +36,16 @@ class IncludeTracker
|
|
|
36
36
|
'include_once' => include_once $filePath,
|
|
37
37
|
'require' => require $filePath,
|
|
38
38
|
'require_once' => require_once $filePath,
|
|
39
|
-
default => throw new InvalidArgumentException("Invalid include mode: $mode")
|
|
39
|
+
default => throw new InvalidArgumentException("Invalid include mode: $mode"),
|
|
40
40
|
};
|
|
41
41
|
$html = ob_get_clean();
|
|
42
42
|
|
|
43
|
-
$wrapped
|
|
44
|
-
|
|
45
|
-
$fragDom = TemplateCompiler::convertToXml($wrapped, false);
|
|
43
|
+
$wrapped = self::wrapWithId($filePath, $html);
|
|
44
|
+
$fragDom = TemplateCompiler::convertToXml($wrapped);
|
|
46
45
|
|
|
47
46
|
self::prefixInlineHandlers($fragDom);
|
|
48
47
|
|
|
49
|
-
$newHtml =
|
|
50
|
-
foreach ($fragDom->documentElement->childNodes as $c) {
|
|
51
|
-
$newHtml .= $fragDom->saveXML($c);
|
|
52
|
-
}
|
|
48
|
+
$newHtml = TemplateCompiler::innerXml($fragDom);
|
|
53
49
|
|
|
54
50
|
self::$sections[$filePath] = [
|
|
55
51
|
'path' => $filePath,
|
|
@@ -62,7 +58,6 @@ class IncludeTracker
|
|
|
62
58
|
private static function wrapWithId(string $filePath, string $html): string
|
|
63
59
|
{
|
|
64
60
|
$id = 's' . base_convert(sprintf('%u', crc32($filePath)), 10, 36);
|
|
65
|
-
|
|
66
61
|
return "<div pp-section-id=\"$id\">\n$html\n</div>";
|
|
67
62
|
}
|
|
68
63
|
|
|
@@ -121,21 +121,6 @@ class PHPX implements IPHPX
|
|
|
121
121
|
array_flip(array_merge($reserved, $exclude))
|
|
122
122
|
);
|
|
123
123
|
|
|
124
|
-
$props = array_combine(
|
|
125
|
-
array_map('strtolower', array_keys($props)),
|
|
126
|
-
$props
|
|
127
|
-
);
|
|
128
|
-
|
|
129
|
-
foreach ($props as $key => $val) {
|
|
130
|
-
if (str_starts_with($key, 'on')) {
|
|
131
|
-
$event = substr($key, 2);
|
|
132
|
-
if (in_array($event, PrismaPHPSettings::$htmlEvents, true) && trim((string)$val) !== '') {
|
|
133
|
-
$props["pp-original-on{$event}"] = (string)$val;
|
|
134
|
-
}
|
|
135
|
-
unset($props[$key]);
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
|
|
139
124
|
foreach ($params as $k => $v) {
|
|
140
125
|
$props[$k] = $v;
|
|
141
126
|
}
|
|
@@ -15,6 +15,7 @@ use RuntimeException;
|
|
|
15
15
|
use Bootstrap;
|
|
16
16
|
use LibXMLError;
|
|
17
17
|
use DOMXPath;
|
|
18
|
+
use ReflectionClass;
|
|
18
19
|
|
|
19
20
|
class TemplateCompiler
|
|
20
21
|
{
|
|
@@ -118,11 +119,9 @@ class TemplateCompiler
|
|
|
118
119
|
|
|
119
120
|
private static function escapeAmpersands(string $content): string
|
|
120
121
|
{
|
|
121
|
-
return
|
|
122
|
-
'/&(
|
|
123
|
-
|
|
124
|
-
? $m[0]
|
|
125
|
-
: '&' . substr($m[0], 1),
|
|
122
|
+
return preg_replace(
|
|
123
|
+
'/&(?![a-zA-Z][A-Za-z0-9]*;|#[0-9]+;|#x[0-9A-Fa-f]+;)/',
|
|
124
|
+
'&',
|
|
126
125
|
$content
|
|
127
126
|
);
|
|
128
127
|
}
|
|
@@ -145,16 +144,13 @@ class TemplateCompiler
|
|
|
145
144
|
);
|
|
146
145
|
}
|
|
147
146
|
|
|
148
|
-
public static function convertToXml(string $templateContent
|
|
147
|
+
public static function convertToXml(string $templateContent): DOMDocument
|
|
149
148
|
{
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
)
|
|
156
|
-
);
|
|
157
|
-
}
|
|
149
|
+
$templateContent = self::escapeMustacheAngles(
|
|
150
|
+
self::escapeAttributeAngles(
|
|
151
|
+
self::escapeAmpersands($templateContent)
|
|
152
|
+
)
|
|
153
|
+
);
|
|
158
154
|
|
|
159
155
|
$dom = new DOMDocument();
|
|
160
156
|
libxml_use_internal_errors(true);
|
|
@@ -169,6 +165,28 @@ class TemplateCompiler
|
|
|
169
165
|
return $dom;
|
|
170
166
|
}
|
|
171
167
|
|
|
168
|
+
/**
|
|
169
|
+
* Extracts the inner XML of a DOMNode, including all child nodes.
|
|
170
|
+
*
|
|
171
|
+
* @param DOMNode $node The node from which to extract the inner XML.
|
|
172
|
+
* @return string The inner XML as a string.
|
|
173
|
+
*/
|
|
174
|
+
public static function innerXml(DOMNode $node): string
|
|
175
|
+
{
|
|
176
|
+
if ($node instanceof DOMDocument) {
|
|
177
|
+
$node = $node->documentElement;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** @var DOMDocument $doc */
|
|
181
|
+
$doc = $node->ownerDocument;
|
|
182
|
+
|
|
183
|
+
$html = '';
|
|
184
|
+
foreach ($node->childNodes as $child) {
|
|
185
|
+
$html .= $doc->saveXML($child);
|
|
186
|
+
}
|
|
187
|
+
return $html;
|
|
188
|
+
}
|
|
189
|
+
|
|
172
190
|
protected static function getXmlErrors(): array
|
|
173
191
|
{
|
|
174
192
|
$errors = libxml_get_errors();
|
|
@@ -283,23 +301,25 @@ class TemplateCompiler
|
|
|
283
301
|
string $componentName,
|
|
284
302
|
array $incomingProps
|
|
285
303
|
): string {
|
|
286
|
-
$
|
|
287
|
-
$
|
|
304
|
+
$incomingProps = self::sanitizeIncomingProps($incomingProps);
|
|
305
|
+
$mapping = self::selectComponentMapping($componentName);
|
|
306
|
+
$instance = self::initializeComponentInstance($mapping, $incomingProps);
|
|
288
307
|
|
|
289
308
|
$childHtml = '';
|
|
290
309
|
foreach ($node->childNodes as $c) {
|
|
291
310
|
$childHtml .= self::processNode($c);
|
|
292
311
|
}
|
|
293
|
-
$instance->children = $childHtml;
|
|
294
312
|
|
|
295
|
-
$
|
|
296
|
-
|
|
313
|
+
$instance->children = self::sanitizeEventAttributes($childHtml);
|
|
314
|
+
|
|
315
|
+
$baseId = 's' . base_convert(sprintf('%u', crc32($mapping['className'])), 10, 36);
|
|
316
|
+
$idx = self::$componentInstanceCounts[$baseId] ?? 0;
|
|
297
317
|
self::$componentInstanceCounts[$baseId] = $idx + 1;
|
|
298
318
|
$sectionId = $idx === 0 ? $baseId : "{$baseId}{$idx}";
|
|
299
319
|
|
|
300
|
-
$html
|
|
301
|
-
$fragDom
|
|
302
|
-
$xpath
|
|
320
|
+
$html = $instance->render();
|
|
321
|
+
$fragDom = self::convertToXml($html);
|
|
322
|
+
$xpath = new DOMXPath($fragDom);
|
|
303
323
|
|
|
304
324
|
/** @var DOMElement $el */
|
|
305
325
|
foreach ($xpath->query('//*') as $el) {
|
|
@@ -317,14 +337,11 @@ class TemplateCompiler
|
|
|
317
337
|
$value = $attr->value;
|
|
318
338
|
|
|
319
339
|
if (str_starts_with($name, 'pp-original-')) {
|
|
320
|
-
$origName
|
|
321
|
-
$originalEvents[$origName]
|
|
340
|
+
$origName = substr($name, strlen('pp-original-'));
|
|
341
|
+
$originalEvents[$origName] = $value;
|
|
322
342
|
} elseif (str_starts_with($name, 'on')) {
|
|
323
343
|
$event = substr($name, 2);
|
|
324
|
-
if (
|
|
325
|
-
in_array($event, PrismaPHPSettings::$htmlEvents, true)
|
|
326
|
-
&& trim((string)$value) !== ''
|
|
327
|
-
) {
|
|
344
|
+
if ($value !== '' && in_array($event, PrismaPHPSettings::$htmlEvents, true)) {
|
|
328
345
|
$componentEvents[$name] = $value;
|
|
329
346
|
}
|
|
330
347
|
}
|
|
@@ -334,18 +351,10 @@ class TemplateCompiler
|
|
|
334
351
|
foreach (array_keys($componentEvents) as $k) $el->removeAttribute($k);
|
|
335
352
|
|
|
336
353
|
foreach ($componentEvents as $evAttr => $compValue) {
|
|
337
|
-
|
|
338
|
-
$el->setAttribute(
|
|
339
|
-
"data-pp-child-{$evAttr}",
|
|
340
|
-
$compValue
|
|
341
|
-
);
|
|
354
|
+
$el->setAttribute("data-pp-child-{$evAttr}", $compValue);
|
|
342
355
|
|
|
343
356
|
if (isset($originalEvents[$evAttr])) {
|
|
344
|
-
$
|
|
345
|
-
$el->setAttribute(
|
|
346
|
-
"data-pp-parent-{$evAttr}",
|
|
347
|
-
$parentValue
|
|
348
|
-
);
|
|
357
|
+
$el->setAttribute("data-pp-parent-{$evAttr}", $originalEvents[$evAttr]);
|
|
349
358
|
unset($originalEvents[$evAttr]);
|
|
350
359
|
}
|
|
351
360
|
}
|
|
@@ -363,11 +372,7 @@ class TemplateCompiler
|
|
|
363
372
|
}
|
|
364
373
|
}
|
|
365
374
|
|
|
366
|
-
$htmlOut =
|
|
367
|
-
foreach ($root->childNodes as $child) {
|
|
368
|
-
$htmlOut .= $fragDom->saveXML($child);
|
|
369
|
-
}
|
|
370
|
-
|
|
375
|
+
$htmlOut = self::innerXml($fragDom);
|
|
371
376
|
if (
|
|
372
377
|
str_contains($htmlOut, '{{') ||
|
|
373
378
|
self::hasComponentTag($htmlOut) ||
|
|
@@ -379,6 +384,53 @@ class TemplateCompiler
|
|
|
379
384
|
return $htmlOut;
|
|
380
385
|
}
|
|
381
386
|
|
|
387
|
+
protected static function sanitizeIncomingProps(array $props): array
|
|
388
|
+
{
|
|
389
|
+
foreach ($props as $key => $val) {
|
|
390
|
+
if (str_starts_with($key, 'on')) {
|
|
391
|
+
$event = substr($key, 2);
|
|
392
|
+
if (in_array($event, PrismaPHPSettings::$htmlEvents, true) && trim((string)$val) !== '') {
|
|
393
|
+
$props["pp-original-on{$event}"] = (string)$val;
|
|
394
|
+
unset($props[$key]);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
return $props;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
protected static function sanitizeEventAttributes(string $html): string
|
|
403
|
+
{
|
|
404
|
+
$fragDom = self::convertToXml($html, false);
|
|
405
|
+
$xpath = new DOMXPath($fragDom);
|
|
406
|
+
|
|
407
|
+
/** @var DOMElement $el */
|
|
408
|
+
foreach ($xpath->query('//*') as $el) {
|
|
409
|
+
foreach (iterator_to_array($el->attributes) as $attr) {
|
|
410
|
+
$name = strtolower($attr->name);
|
|
411
|
+
|
|
412
|
+
if (!str_starts_with($name, 'on')) {
|
|
413
|
+
continue;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
$event = substr($name, 2);
|
|
417
|
+
$value = trim($attr->value);
|
|
418
|
+
|
|
419
|
+
if ($value !== '' && in_array($event, PrismaPHPSettings::$htmlEvents, true)) {
|
|
420
|
+
$el->setAttribute("pp-original-on{$event}", $value);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
$el->removeAttribute($name);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
$body = $fragDom->getElementsByTagName('body')[0] ?? null;
|
|
428
|
+
|
|
429
|
+
return $body instanceof DOMElement
|
|
430
|
+
? self::innerXml($body)
|
|
431
|
+
: self::innerXml($fragDom);
|
|
432
|
+
}
|
|
433
|
+
|
|
382
434
|
private static function selectComponentMapping(string $componentName): array
|
|
383
435
|
{
|
|
384
436
|
if (!isset(self::$classMappings[$componentName])) {
|
|
@@ -416,7 +468,16 @@ class TemplateCompiler
|
|
|
416
468
|
throw new RuntimeException("Class {$className} not found");
|
|
417
469
|
}
|
|
418
470
|
|
|
419
|
-
|
|
471
|
+
$instance = new $className($attributes);
|
|
472
|
+
$ref = new ReflectionClass($instance);
|
|
473
|
+
|
|
474
|
+
foreach ($attributes as $key => $value) {
|
|
475
|
+
if ($ref->hasProperty($key) && $ref->getProperty($key)->isPublic()) {
|
|
476
|
+
$instance->$key = $value;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
return $instance;
|
|
420
481
|
}
|
|
421
482
|
|
|
422
483
|
protected static function initializeClassMappings(): void
|
package/dist/src/app/js/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{const e=EventTarget.prototype.addEventListener,t=EventTarget.prototype.removeEventListener,s=new Map,n=new Set(["wheel","mousewheel","touchstart","touchmove","touchend","touchcancel","scroll"]);EventTarget.prototype.addEventListener=function(t,r,i){let a=i;n.has(t)&&(void 0===a?a={passive:!0}:"boolean"==typeof a?a={capture:a,passive:!0}:a&&void 0===a.passive&&(a={...a,passive:!0})),s.has(this)||s.set(this,new Map);const o=s.get(this),c=o.get(t)||new Set;c.add(r),o.set(t,c),e.call(this,t,r,a)},EventTarget.prototype.removeEventListener=function(e,n,r){if(s.has(this)&&s.get(this).has(e)){const t=s.get(this).get(e);t.delete(n),0===t.size&&s.get(this).delete(e)}t.call(this,e,n,r)},EventTarget.prototype.removeAllEventListeners=function(e){if(!s.has(this))return;const n=s.get(this).get(e);n&&(n.forEach((s=>{t.call(this,e,s)})),s.get(this).delete(e))}})();class PPHP{props={};_isNavigating=!1;_responseData=null;_elementState={checkedElements:new Set};_activeAbortController=null;_reservedWords;_declaredStateRoots=new Set;_arrayMethodCache=new WeakMap;_scopedKeys=new Map;_updateScheduled=!1;_pendingBindings=new Set;_effects=new Set;_pendingEffects=new Set;_processedPhpSections=new Set;_processedPhpScripts=new WeakSet;_bindings=[];_templateStore=new WeakMap;_inlineDepth=0;_activeSection=null;_inlineModuleFns=new Map;_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 Map;_sectionParentMap=new Map;_eventHandlers;_redirectRegex=/redirect_7F834\s*=\s*(\/[^\s]*)/;_assignmentRe=/^\s*[\w.]+\s*=(?!=)/;_mustacheRe=/\{\{\s*([\s\S]+?)\s*\}\}/gu;_mutators;_boolAttrs=new Set(["checked","selected","disabled","readonly","multiple","hidden"]);_bareIdRe=/^\s*([A-Za-z_$][\w$]*)\s*$/;_bareCallReEvent=/^\s*([A-Za-z_$][\w$]*)\(\s*\)\s*;?\s*$/;_arrowSigRe=/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>/;_callRe=/^\s*([A-Za-z_$]\w*)\s*\(([\s\S]*)\)\s*;?\s*$/;static _instance;static _effectCleanups;static debounceTimers=new Map;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"]);static _bareCallRe=/^[A-Za-z_$]\w*\s*\(.*\)$/;constructor(){const e=Object.getOwnPropertyNames(HTMLElement.prototype).filter((e=>e.startsWith("on"))),t=Object.getOwnPropertyNames(Document.prototype).filter((e=>e.startsWith("on"))),s=Object.getOwnPropertyNames(Window.prototype).filter((e=>e.startsWith("on")));this._eventHandlers=new Set([...e,...t,...s].map((e=>e.toLowerCase()))),this._reservedWords=new Set(["null","undefined","true","false","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","finally","for","function","if","import","in","instanceof","let","new","return","super","switch","this","throw","try","typeof","var","void","while","with","yield","async","await","implements","interface","event","NaN","Infinity","Number","String","Boolean","Object","Array","Function","Date","RegExp","Error","JSON","Math","Map","Set"]),this._mutators=new Set(["push","pop","shift","unshift","splice","sort","reverse","copyWithin","fill"]),this.handlePopState(),this._proxyCache=new WeakMap,this._evaluatorCache.clear(),this._depsCache.clear(),this.props=this.makeReactive(this._rawProps),this.scheduleInitialHydration()}static get instance(){return PPHP._instance||(PPHP._instance=new PPHP),PPHP._instance}scheduleInitialHydration(){const e=async()=>{await this.initRefs(),await this.processInlineModuleScripts(),await this.initializeAllReferencedProps(),await this.initBindings(),await this.initLoopBindings(),this.attachWireFunctionEvents(),this._bindings.forEach((e=>e.update())),document.body.removeAttribute("hidden")};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e,{once:!0}):e()}getScopeId(e){for(;e;){const t=e.getAttribute("pp-phpx-id");if(t)return t;const s=e.getAttribute("pp-section-id");if(s)return s;e=e.parentElement}return null}getSectionId(e){for(;e;){const t=e.getAttribute("pp-section-id");if(t)return t;e=e.parentElement}return null}getPhpxId(e){for(;e;){const t=e.getAttribute("pp-phpx-id");if(t)return t;e=e.parentElement}return null}getPhpxParentId(e){if(!e)return null;let t=e,s=null;for(;t&&!s;)s=t.getAttribute("pp-phpx-id"),s||(t=t.parentElement);let n=t?.parentElement;for(;n;){const e=n.getAttribute("pp-phpx-id");if(e&&e!==s)return e;n=n.parentElement}return null}ref(e,t){const s=this._activeSection;let n=[];if(s&&(n=this._sectionRefs.get(s)?.get(e)??[]),0===n.length&&(n=this._refs.get(e)??[]),null!=t){const s=n[t];if(!s)throw new Error(`pphp.ref('${e}', ${t}) — no element at that index`);return s}if(0===n.length)throw new Error(`pphp.ref('${e}') failed — no element was found`);return 1===n.length?n[0]:n}effect(e,t){const s=this._currentScopeId(),n=Array.isArray(t),r=n?t:[],i=n&&0===r.length,a=r.map((e=>{if("function"==typeof e&&e.__pphp_key)return e.__pphp_key;if("string"!=typeof e)return"";if(e.includes("_"))return e;for(const[t,s]of this._scopedKeys)if(s.has(e))return`${t}_${e}`;if(s){const t=this._sharedStateMap.get(s);if(t?.has(e)){const t=this._sectionParentMap.get(s);return t?`${t}_${e}`:e}}return e})).filter(Boolean),o=new Set(a),c=new Map;for(const e of a){const t=this.getNested(this.props,e);c.set(e,t)}let l=0;PPHP._effectCleanups||(PPHP._effectCleanups=new WeakMap);const h=PPHP._effectCleanups,p=()=>{const t=h.get(p);if(t){try{t()}catch(e){console.error("cleanup error:",e)}h.delete(p)}if(++l>50)throw new Error("PPHP: effect ran >50 times — possible loop");if(!i&&a.length>0){let e=!1;for(const t of a){if(this.getNested(this.props,t)!==c.get(t)){e=!0;break}}if(!e)return;for(const e of a)c.set(e,this.getNested(this.props,e))}try{const t=e();"function"==typeof t&&h.set(p,t)}catch(e){console.error("effect error:",e)}};Object.assign(p,{__deps:o,__sectionId:s??null,__static:i});try{const t=e();"function"==typeof t&&h.set(p,t)}catch(e){console.error("effect error (initial):",e)}for(const e of a)c.set(e,this.getNested(this.props,e));const u=n&&this._inlineDepth>0?this._pendingEffects:this._effects;return i?this._effects.add(p):u.add(p),()=>{const e=h.get(p);if(e){try{e()}catch(e){console.error("cleanup error:",e)}h.delete(p)}this._effects.delete(p),this._pendingEffects.delete(p)}}resetProps(){Object.keys(this._rawProps).forEach((e=>{if(window.hasOwnProperty(e)){const t=Object.getOwnPropertyDescriptor(window,e);t&&t.configurable&&delete window[e]}})),this._rawProps={},this._proxyCache=new WeakMap,this._templateStore=new WeakMap,this._arrayMethodCache=new WeakMap,this._depsCache.clear(),this._evaluatorCache.clear(),this._processedPhpSections.clear(),this._processedPhpScripts=new WeakSet,this._scopedKeys=new Map,this._declaredStateRoots.clear(),this._inlineModuleFns.clear(),this._bindings=[],this._pendingBindings.clear(),this._effects.clear(),this._pendingEffects.clear(),this._refs.clear(),this._sectionRefs.clear(),this.clearHandlerCaches(),this.props=this.makeReactive(this._rawProps)}async initMakeReactive(){await this.initRefs(),await this.initializeAllReferencedProps(),await this.initBindings(),await this.initLoopBindings(),this.attachWireFunctionEvents(),this._bindings.forEach((e=>e.update())),document.body.removeAttribute("hidden")}async initLoopBindings(){document.querySelectorAll("[pp-for]").forEach((e=>this.registerLoop(e)))}registerLoop(e){const t=this.getScopeId(e),s=e.getAttribute("pp-for").trim(),[n,r]=s.split(/\s+in\s+/),[i,a]=n.replace(/^\(|\)$/g,"").split(",").map((e=>e.trim())),o=t?`${t}_${i}`:i,c=a?t?`${t}_${a}`:a:null,l=t?r.replace(/\b([A-Za-z_$]\w*)\b/g,((e,s,n,r)=>"."===r[n-1]||this._reservedWords.has(s)||s.startsWith(t+"_")?e:`${t}_${s}`)):r,h=e.parentNode,p=document.createComment("pp-for");h.insertBefore(p,e),h.removeChild(e);const u=this.makeSafeEvaluator(l),d=e=>t?e.replace(new RegExp(`\\b${i}\\b`,"g"),o).replace(a?new RegExp(`\\b${a}\\b`,"g"):/$^/,c??""):e,f=this.extractDependencies(l);this._bindings.push({dependencies:f,update:()=>{const t=document.activeElement;let s=null,n=null;if((t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&h.contains(t)){const e=t.closest("[key]");s=e?.getAttribute("key")??null,n=t.selectionStart}for(let e=p.nextSibling;e&&e.nodeType!==Node.COMMENT_NODE;){const t=e.nextSibling;h.removeChild(e),e=t}const r=u(this.props);Array.isArray(r)||console.warn("[pp-for] expected an Array but got:",r);if((Array.isArray(r)?r:[]).forEach(((t,s)=>{this.props[o]=t,c&&(this.props[c]=s);const n=e.content.cloneNode(!0),r=document.createTreeWalker(n,NodeFilter.SHOW_TEXT);for(let e;e=r.nextNode();)e.nodeValue=(e.nodeValue||"").replace(PPHP._mustachePattern,((e,t)=>{try{const e=d(t);return this.formatValue(this.makeSafeEvaluator(e)(this.props))}catch{return""}}));n.querySelectorAll("*").forEach((e=>{for(const{name:t,value:s}of Array.from(e.attributes)){if("pp-bind"===t){const t=d(s),n=this.makeSafeEvaluator(t)(this.props);e.textContent=this.formatValue(n);continue}if("pp-bind-expr"===t){const t=this.decodeEntities?this.decodeEntities(s):s,n=d(t),r=this.makeSafeEvaluator(n)(this.props);e.textContent=this.formatValue(r);continue}const n=t.match(/^pp-bind-(.+)$/);if(!n)continue;const r=n[1],i=d(s),a=this.makeSafeEvaluator(i)(this.props);if(this._boolAttrs.has(r)){const t=!!a;e[r]=t,t?e.setAttribute(r,""):e.removeAttribute(r)}else r in e?e[r]=a:e.setAttribute(r,String(a))}})),n.querySelectorAll("*").forEach((e=>{for(const{name:t,value:s}of Array.from(e.attributes)){const n=t.match(/^pp-bind-(.+)$/);if(!n)continue;const r=n[1],i=d(s),a=this.makeSafeEvaluator(i)(this.props);if(this._boolAttrs.has(r)){const t=!!a;e[r]=t,t?e.setAttribute(r,""):e.removeAttribute(r)}else r in e?e[r]=a:e.setAttribute(r,String(a))}})),n.querySelectorAll("*").forEach((e=>{Array.from(e.attributes).forEach((n=>{const r=n.name.startsWith("on"),o=n.name.startsWith("pp-inc-on"),c=n.name.startsWith("pp-comp-on");if(!r&&!o&&!c)return;let l=n.value;/\b(?:i|idx)\b/.test(l)&&(l=((e,t)=>e.replace(/\[\s*(?:i|idx)\s*\]/g,`[${t}]`).replace(/(^|[^\w$])(?:i|idx)(?!\w)/g,((e,s)=>s+t)))(l,s));const h=new RegExp(`\\b${i}\\b`,"g");var p;if(l=l.replace(h,(p=t,JSON.stringify(p))),a){const e=new RegExp(`\\b${a}\\b`,"g");l=l.replace(e,String(s))}e.setAttribute(n.name,l)}))})),h.insertBefore(n,p.nextSibling)})),null!==s){const e=h.querySelector(`[key="${s}"]`),t=e?.querySelector("input,textarea");if((t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&(t.focus({preventScroll:!0}),null!==n)){const e=Math.min(n,t.value.length);t.setSelectionRange(e,e)}}this.attachWireFunctionEvents()}})}_sectionRefs=new Map;async initRefs(){document.querySelectorAll("[pp-ref]").forEach((e=>{const t=e.getAttribute("pp-ref"),s=this.getScopeId(e)??"__global__",n=this._sectionRefs.get(s)??new Map,r=n.get(t)??[];r.push(e),n.set(t,r),this._sectionRefs.set(s,n);const i=this._refs.get(t)??[];i.push(e),this._refs.set(t,i),e.removeAttribute("pp-ref")}))}scheduleBindingUpdate(e){this._pendingBindings.add(e),this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this.flushBindings()})))}makeReactive(e,t=[]){const s=this._proxyCache.get(e);if(s)return s;if(e instanceof Map||e instanceof Set||"object"!=typeof e||null===e)return e;const n=this,r=new Proxy(e,{get(e,s,r){const i=Reflect.get(e,s,r);if(Array.isArray(e)&&"string"==typeof s&&n._mutators.has(s)){let a=n._arrayMethodCache.get(e);if(a||(a=new Map,n._arrayMethodCache.set(e,a)),!a.has(s)){const e=i.bind(r),o=t.join("."),c=function(...t){const s=e(...t);return queueMicrotask((()=>{n._bindings.forEach((e=>{e.dependencies.has(o)&&n.scheduleBindingUpdate(e)}))})),s};a.set(s,c)}return a.get(s)}return null!==i&&"object"==typeof i?n.makeReactive(i,[...t,s]):i},set(e,s,r,i){let a=r;null!==r&&"object"==typeof r&&(a=n.makeReactive(r,[...t,s]));const o=e[s],c=Reflect.set(e,s,a,i);if(o===a)return c;const l=[...t,s].join(".");return n._bindings.forEach((e=>{for(const t of e.dependencies)if(l===t||l.startsWith(t+".")||t.startsWith(l+".")){n.scheduleBindingUpdate(e);break}})),c}});return this._proxyCache.set(e,r),r}makeAttrTemplateUpdater(e,t,s,n){let r=this._templateStore.get(e);r||(r=new Map,this._templateStore.set(e,r)),r.has(t)||r.set(t,e.getAttribute(t)||"");const i=n??r.get(t)??"";return(i.match(this._mustacheRe)||[]).forEach((e=>{this.extractDependencies(e).forEach((e=>s.add(e)))})),()=>{try{const s=i.replace(this._mustacheRe,((e,t)=>{try{const e=this.makeSafeEvaluator(t);return this.formatValue(e(this.props))}catch(e){return console.error("Error token:",t,e),""}}));e.getAttribute(t)!==s&&e.setAttribute(t,s)}catch(e){console.error(`Error evaluating the template for attribute "${t}". Please check the template syntax and dependencies.`,e)}}}makePrimitiveUpdater(e,t,s){const n={};return this._eventHandlers.forEach((e=>{if(e.startsWith("on")){const t=e.slice(2);n[t]=t}})),n.value="input",n.checked="change",()=>{try{const r=s(this.props),i=this.formatValue(r);let a=!1;if("value"===t){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,s="true"===i;"checked"in e&&t.checked!==s?(t.checked=s,a=!0):"checked"in e||(e.setAttribute("checked",i),a=!0)}if(!a||e instanceof HTMLInputElement&&("hidden"===e.type||e.disabled||e.readOnly))return;const o=n[t]||t,c="click"===o?new MouseEvent(o,{bubbles:!0,cancelable:!0}):new Event(o,{bubbles:!0});e.dispatchEvent(c)}catch(e){console.error(`Error evaluating attribute "${t}":`,e)}}}formatValue(e){return null!==e&&"object"==typeof e&&1===Object.keys(e).length&&Object.prototype.hasOwnProperty.call(e,"value")?this.formatValue(e.value):"function"==typeof e?"":"boolean"==typeof e?e?"true":"false":Array.isArray(e)?e.map((e=>"object"==typeof e?JSON.stringify(e):String(e))).join(", "):e&&"object"==typeof e?Object.keys(e).length?JSON.stringify(e,null,2):"":e?.toString()??""}registerBinding(e,t,s="text",n){if(this._assignmentRe.test(t))return;const r=this.getScopeId(e);let i=t;if(r){const e=this._scopedKeys.get(r)||new Set,s=this._sharedStateMap.get(r)||new Set,n=this._sectionParentMap.get(r);i=t.replace(/\b([A-Za-z_$][\w$]*)\b/g,((t,i,a,o)=>{if("."===o[a-1]||this._reservedWords.has(i))return t;if(s.has(i))return n?`${n}_${i}`:i;if(e.has(i)||this.hasNested(this.props,`${r}_${i}`))return`${r}_${i}`;let c=this._sectionParentMap.get(r)||null;for(;c;){if(this._scopedKeys.get(c)?.has(i)||this.hasNested(this.props,`${c}_${i}`))return`${c}_${i}`;c=this._sectionParentMap.get(c)||null}return t}))}const a=new Set([...this.extractDependencies(i)].map((e=>e.split(".")[0])).filter((e=>e in this.props&&!this._reservedWords.has(e)))),o=this.makeSafeEvaluator(i);if("value"===n||"checked"===n){const t=this.makePrimitiveUpdater(e,n,o);return void this._bindings.push({dependencies:a,update:t})}if(n){const s=n.toLowerCase();if(this._boolAttrs.has(s)){e.removeAttribute(s);const r=()=>{try{const t=!!o(this.props);e[n]!==t&&(e[n]=t),t?e.setAttribute(s,""):e.removeAttribute(s)}catch(e){console.error(`PPHP: error evaluating boolean attribute ${n}="${t}"`,e)}};return void this._bindings.push({dependencies:a,update:r})}const c=e.getAttribute(n)??"";if(this._mustacheRe.test(i)||this._mustacheRe.test(c)){const t=this._scopedKeys.get(r??"")??new Set,s=this._sharedStateMap.get(r??"")??new Set,i=this._sectionParentMap.get(r??"")??null,o=c.replace(this._mustacheRe,((e,n)=>`{{ ${n.replace(/\b([A-Za-z_$][\w$]*)\b/g,((e,n,a,o)=>{if("."===o[a-1]||this._reservedWords.has(n))return e;if(s.has(n))return i?`${i}_${n}`:n;if(t.has(n))return`${r}_${n}`;let c=this._sectionParentMap.get(r??"")||null;for(;c;){if(this._scopedKeys.get(c)?.has(n)||this.hasNested(this.props,`${c}_${n}`))return`${c}_${n}`;c=this._sectionParentMap.get(c)||null}return e}))} }}`)),l=this.makeAttrTemplateUpdater(e,n,a,o);return void this._bindings.push({dependencies:a,update:l})}const l=()=>{try{const t=o(this.props),s=this.formatValue(t);n in e&&(e[n]=s),e.setAttribute(n,s)}catch(e){console.error(`Error evaluating attribute ${n}="${t}"`,e)}};return void this._bindings.push({dependencies:a,update:l})}const c={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:a,update:()=>{try{const t=o(this.props),n=this.formatValue(t);c[s](e,n)}catch(e){console.error(`Error evaluating expression "${t}"`,e)}}})}makeSafeEvaluator(e){const t=e.trim(),s=`\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",s)}catch(t){const s=JSON.stringify(e);n=new Function("ctx",`try { return ${s}; } catch { return ""; }`)}return e=>{try{const t=n(e);return null==t?"":t}catch{return""}}}async initBindings(){this._bindings=[];const e=new WeakSet;document.body.querySelectorAll("[pp-if]").forEach((t=>{if(e.has(t))return;const s=[];let n=t;for(;n;){if(n.hasAttribute("pp-if"))s.push({el:n,expr:n.getAttribute("pp-if")});else if(n.hasAttribute("pp-elseif"))s.push({el:n,expr:n.getAttribute("pp-elseif")});else{if(!n.hasAttribute("pp-else"))break;s.push({el:n,expr:null})}e.add(n),n=n.nextElementSibling}s.forEach((e=>{if(null!==e.expr){const t=e.expr.replace(/^{\s*|\s*}$/g,"");e.deps=this.extractDependencies(t);const s=this.makeSafeEvaluator(t);e.evaluate=()=>!!s(this.props)}}));const r=new Set;s.forEach((e=>e.deps?.forEach((e=>r.add(e)))));this._bindings.push({dependencies:r,update:()=>{let e=!1;for(const{el:t,expr:n,evaluate:r}of s)!e&&null!==n&&r()?(t.removeAttribute("hidden"),e=!0):e||null!==n?t.setAttribute("hidden",""):(t.removeAttribute("hidden"),e=!0)}})})),document.body.querySelectorAll("*").forEach((e=>{["pp-bind","pp-bind-expr"].forEach((t=>{const s=e.getAttribute(t);s&&this.registerBinding(e,s,"text")})),Array.from(e.attributes).forEach((t=>{if(!t.name.startsWith("pp-bind-"))return;if("pp-bind"===t.name||"pp-bind-expr"===t.name||"pp-bind-spread"===t.name)return;const s=this.decodeEntities(t.value).replace(/^{{\s*|\s*}}$/g,"");let n=t.name.replace(/^(pp-bind-)+/,"");const r="value"===n?"value":"checked"===n?"checked":"text";this.registerBinding(e,s,r,n)})),Array.from(e.attributes).forEach((t=>{if("pp-bind-spread"!==t.name)return;const s=this.decodeEntities(t.value).split(",").map((e=>e.trim())).filter(Boolean),n=new Set;s.forEach((e=>n.add(e.split(".")[0])));const r=new Set;this._bindings.push({dependencies:n,update:()=>{try{const t={};s.forEach((e=>{const s=this.getNested(this.props,e)??{};Object.assign(t,s)})),r.forEach((s=>{s in t||e.hasAttribute(s)||(e.removeAttribute(s),r.delete(s))})),Object.entries(t).forEach((([t,s])=>{if(!r.has(t)&&e.hasAttribute(t))return;if(!1===s||null==s)return void(r.has(t)&&(e.removeAttribute(t),r.delete(t)));const n="object"==typeof s?JSON.stringify(s):String(s);e.getAttribute(t)!==n&&e.setAttribute(t,n),r.add(t)}))}catch(e){console.error("pp-spread error:",e)}}})}))}))}callInlineModule(e,...t){const s=this._inlineModuleFns.get(e);if(!s)throw new Error(`PPHP: no inline module named "${e}"`);return s(...t)}async processInlineModuleScripts(){this._inlineDepth++,this._sharedStateMap.clear(),this._sectionParentMap.clear();try{const e=Array.from(document.body.querySelectorAll('script[type="text/php"]:not([src])')).filter((e=>{const t=this.getScopeId(e);return t?!this._processedPhpSections.has(t):!this._processedPhpScripts.has(e)}));if(!e.length)return;document.querySelectorAll("[pp-section-id]").forEach((e=>{const t=e.getAttribute("pp-section-id"),s=this.findParentSectionId(e);s&&this._sectionParentMap.set(t,s)})),document.querySelectorAll("[pp-phpx-id]").forEach((e=>{const t=e.getAttribute("pp-phpx-id"),s=this.findParentSectionId(e);s&&this._sectionParentMap.set(t,s)}));const t=this.sortScriptsByDependency(e),s={};for(const e of t){const t=this.getScopeId(e);if(!t)continue;const n=e.textContent||"";for(const[,e]of[...n.matchAll(/export\s+const\s+([A-Za-z_$]\w*)/g),...n.matchAll(/export\s+function\s+([A-Za-z_$]\w*)/g)])s[e]=t}for(const[e,t]of Object.entries(s))this._scopedKeys.has(t)||this._scopedKeys.set(t,new Set),this._scopedKeys.get(t).add(e);for(const e of t){const t=this.getScopeId(e);let n=(e.textContent||"").trim();if(n=this.decodeEntities(n),n=this.transformStateDeclarations(n,t),t){const e=this._sectionParentMap.get(t)??null,s=t+"_",r=e?e+"_":"",i=new Set;if(this._declaredStateRoots.forEach((e=>{e.startsWith(s)?i.add(e.slice(s.length)):r&&e.startsWith(r)?i.add(e.slice(r.length)):e.includes("_")||i.add(e)})),i.size){let e="";for(const a of i){const i=this.hasNested(pphp.props,s+a)?s+a:this.hasNested(pphp.props,r+a)?r+a:a,o="set"+a[0].toUpperCase()+a.slice(1),c=t?`${t}_${a}`:a,l=t?`${t}_${o}`:o;new RegExp(`\\b(?:const|let|var)\\s+\\[?\\s*${a}\\b`).test(n)||(e+=`\n const ${a} = (() => {\n const fn = () => pphp.props.${i};\n fn.__pphp_key = '${i}';\n Object.defineProperty(fn, 'value', {\n get(){ return pphp.props.${i}; },\n set(v){ pphp.props.${i} = v; }\n });\n return fn;\n })();\n const ${o} = v => {\n pphp.props.${i} = typeof v === 'function' ? v(pphp.props.${i}) : v;\n };\n pphp._inlineModuleFns.set('${c}', ${a});\n pphp._inlineModuleFns.set('${l}', ${o});\n `)}n=e+"\n"+n}}const r=this.extractSetters(n,t);if(r.length){n+="\n\n";for(const e of r){n+=`pphp._inlineModuleFns.set('${t?`${t}_${e}`:e}', ${e});\n`}}if(t){const e=this._sectionParentMap.get(t)??null,s=e?e+"_":"";n=n.replace(/(\bpphp\.state\(\s*['"])([^'"]+)(['"])/g,((e,n,r,i)=>r.startsWith(t+"_")||s&&r.startsWith(s)||!r.includes("_")?n+r+i:n+`${t}_${r}`+i))}n=n.replace(/\b([A-Za-z_$]\w*)\s*\(/g,((e,t,n,r)=>{const i=r.slice(Math.max(0,n-20),n);if(/\b(?:function|export\s+function)\s*$/.test(i.trim()))return e;const a=s[t];return a?`${a}_${t}(`:e}));const i=new Blob([n],{type:"application/javascript"}),a=URL.createObjectURL(i),o=PPHP.prototype._currentScopeId;t&&(PPHP.prototype._currentScopeId=()=>t);try{const e=await import(a);for(const[s,n]of Object.entries(e))if("function"==typeof n){const e=t?`${t}_${s}`:s;this._inlineModuleFns.set(e,n)}}catch(e){console.error("Inline module import failed:",e)}finally{PPHP.prototype._currentScopeId=o,URL.revokeObjectURL(a),t?this._processedPhpSections.add(t):this._processedPhpScripts.add(e)}}}finally{this._inlineDepth--,0===this._inlineDepth&&requestAnimationFrame((()=>{this._pendingEffects.forEach((e=>this._effects.add(e))),this._pendingEffects.clear()}))}}findParentSectionId(e){const t=e.parentElement?.closest("[pp-section-id]");return t?t.getAttribute("pp-section-id"):null}extractSetters(e,t){const s=[],n=/\[\s*([A-Za-z_$]\w*)\s*,\s*([A-Za-z_$]\w*)\s*\]\s*=\s*pphp\.state\(/g;let r;for(;null!==(r=n.exec(e));){const[,,e]=r,n=r[1];t&&this._sharedStateMap.get(t)?.has(n)||s.push(e)}return s}transformStateDeclarations(e,t){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\s*\(\s*)/g,((e,s,n,r,i)=>t&&this._sharedStateMap.get(t)?.has(n)?e:`${s}${n}, ${r}${i}'${n}', `))).replace(/(\b(?:const|let|var)\s+\[\s*)([A-Za-z_$]\w*)\s*(\]\s*=\s*pphp\.state\s*\(\s*)/g,((e,s,n,r)=>t&&this._sharedStateMap.get(t)?.has(n)?e:`${s}${n}${r}'${n}', `))).replace(/(\b(?:const|let|var)\s+)([A-Za-z_$]\w*)(\s*=\s*pphp\.state\s*\(\s*)/g,((e,s,n,r)=>t&&this._sharedStateMap.get(t)?.has(n)?e:`${s}[${n}] = pphp.state('${n}', `))}sortScriptsByDependency(e){const t=new Map;for(const s of e){const e=this.getScopeId(s);t.has(e)||t.set(e,[]),t.get(e).push(s)}const s=[],n=new Set,r=e=>{if(!e)return[];const t=this._sectionParentMap.get(e);if(t)return[t];const s=this._sharedStateMap.get(e);return s&&s.size>0?[t||null]:[]},i=e=>{if(n.has(e))return;for(const t of r(e))i(t);const a=t.get(e)||[];s.push(...a),n.add(e)};i(null);for(const e of t.keys())null!==e&&i(e);return s}flushBindings(){const e=new Set(this._dirtyDeps);this._pendingBindings.forEach((t=>{t.dependencies.forEach((t=>e.add(t))),t.update()})),this._pendingBindings.clear(),this._dirtyDeps.clear(),this._updateScheduled=!1,this._effects.forEach((t=>{if(t.__static)return;const s=t.__deps||new Set;if(0===s.size||[...s].some((t=>e.has(t)))){const e=this._activeSection;this._activeSection=t.__sectionId??null;try{t()}catch(e){console.error("effect error:",e)}this._activeSection=e}}))}scheduleFlush(){this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this._updateScheduled=!1,this.flushBindings()})))}scopeKey(e){const t=this._currentScopeId();if(!t)return e;const s=this._sharedStateMap.get(t);if(s?.has(e)){const s=this._sectionParentMap.get(t);return s?`${s}_${e}`:e}return e.startsWith(`${t}_`)?e:`${t}_${e}`}_currentScopeId(){const e=document.currentScript;return this.getScopeId(e)}getNested(e,t){return t.split(".").reduce(((e,t)=>e?e[t]:void 0),e)}setNested(e,t,s){const n=t.split("."),r=n.pop();n.reduce(((e,t)=>e[t]??={}),e)[r]=s}hasNested(e,t){return void 0!==this.getNested(e,t)}state(e,t){if("string"!=typeof e||""===e.trim())throw new Error("PPHP.state: missing or invalid key—make sure your build-time injector ran and you wrote `const [foo, setFoo] = pphp.state(0)` so it became `pphp.state('foo', 0)`.");arguments.length<2&&(t=void 0);const s=this._currentScopeId(),n=e;if(this._reservedWords.has(n))throw new Error(`'${n}' is reserved – choose another state key.`);const r=this.scopeKey(n);this._declaredStateRoots.add(r),s&&(this._scopedKeys.has(s)||this._scopedKeys.set(s,new Set),this._scopedKeys.get(s).add(n)),this.hasNested(pphp.props,r)||this.setNested(pphp.props,r,t);const i=()=>this.getNested(pphp.props,r),a=e=>{const t=i(),s="function"==typeof e?e(t):e;this.setNested(pphp.props,r,s),this._dirtyDeps.add(r.split(".")[0]),this.scheduleFlush()},o=()=>i();Object.defineProperty(o,"value",{get:()=>i(),set:e=>a(e)}),Object.defineProperties(o,{valueOf:{value:()=>i()},toString:{value:()=>String(i())}}),o.__pphp_key=r;const c=i();if(null===c||"object"!=typeof c)return[o,a];return[new Proxy(o,{apply:(e,t,s)=>Reflect.apply(e,t,s),get(e,t,s){if("value"===t)return i();if(t in e)return Reflect.get(e,t,s);return i()[t]},set(e,t,s){if("value"===t)return a(s),!0;return i()[t]=s,!0},has(e,t){if("value"===t||t in o)return!0;return t in i()}}),a]}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 s=>{const n=e.get(s);if(void 0!==n)return n;const r=s in globalThis||t.some((e=>s in e));return e.set(s,r),r}})();extractDependencies(e){const t=e.trim();if(this.isPlainText(t))return new Set;let s=e.replace(/\?\./g,".");const n=new Set,r=/(?:^|[^\w$])(?:\(\s*([^)]*?)\s*\)|([A-Za-z_$][\w$]*))\s*=>/g;for(let e;e=r.exec(s);){(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(s);)e[1].split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>n.add(e)));const a=e=>{let t="",s=0;for(;s<e.length;)if("`"===e[s])for(s++;s<e.length;)if("\\"===e[s])s+=2;else if("$"===e[s]&&"{"===e[s+1]){s+=2;let n=1;const r=s;for(;s<e.length&&n>0;)"{"===e[s]?n++:"}"===e[s]&&n--,s++;const i=e.slice(r,s-1);t+=a(i)+" "}else{if("`"===e[s]){s++;break}s++}else t+=e[s++];return t};s=a(s),s=s.replace(/(['"])(?:\\.|[^\\])*?\1/g,""),s=s.replace(/\/(?:\\.|[^\/\\])+\/[gimsuy]*/g,"");const o=new Set,c=/\b[A-Za-z_$]\w*(?:\.[A-Za-z_$]\w*)*\b/g;for(const t of s.match(c)??[]){const[s,...r]=t.split(".");n.has(s)||(0===r.length&&PPHP._isBuiltIn(s)&&new RegExp(`\\.${s}\\b`).test(e)||o.add(t))}return o}isPlainText(e){const t=e.trim();if(/^['"`]/.test(t))return!1;return![/[+\-*/%=<>!&|?:]/,/\.\w+/,/\[\s*\w+\s*\]/,/\(\s*[^)]*\s*\)/,/=>/,/\b(true|false|null|undefined|typeof|new|delete|void|in|of|instanceof)\b/,/\?\./,/\?\?/,/\.\.\./,/\{[^}]*\}/,/\[[^\]]*\]/].some((e=>e.test(t)))&&(!!t.includes(" ")&&(!/\w+\.\w+/.test(t)&&!/\w+\[\w+\]/.test(t)))}async initializeAllReferencedProps(){const e=PPHP._mustachePattern,t=PPHP._mustacheTest,s=this.props,n=new Set,r=(e,t)=>{const s=e.getAttribute("pp-section-id"),n=this.getScopeId(e.parentElement);return s??n?`${s??n}_${t}`:t},i=(()=>{const e=new Set([...Object.getOwnPropertyNames(String.prototype),...Object.getOwnPropertyNames(Array.prototype),...Object.getOwnPropertyNames(Number.prototype),...Object.getOwnPropertyNames(Boolean.prototype),...Object.getOwnPropertyNames(Object.prototype),...Object.getOwnPropertyNames(Date.prototype),...Object.getOwnPropertyNames(RegExp.prototype)]);return t=>e.has(t)})(),a=(e,t)=>{const[s,a,...o]=t.split(".");if(this._reservedWords.has(s))return void console.warn(`Invalid path “${t}” – “${s}” is a reserved word.`);if(PPHP._isBuiltIn(s)&&console.warn(`Path “${t}” shadows the built-in “${s}”. It will be stored in pphp.props.`),a&&i(a))return void n.add(r(e,s));const c=r(e,s);n.add(a?`${c}.${[a,...o].join(".")}`:c)};for(const s of document.body.getElementsByTagName("*"))for(const{name:n,value:r}of Array.from(s.attributes))if(r){if(t.test(r))for(const t of r.matchAll(e))this.extractDependencies(t[1]).forEach((e=>a(s,e)));"pp-if"!==n&&"pp-elseif"!==n||this.extractDependencies(r).forEach((e=>a(s,e))),n.startsWith("pp-bind")&&this.extractDependencies(r).forEach((e=>a(s,e)))}const o=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT,{acceptNode:e=>t.test(e.nodeValue??"")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT});for(let t;t=o.nextNode();){const s=t.parentElement;for(const n of t.nodeValue.matchAll(e))this.extractDependencies(n[1]).forEach((e=>a(s,e)))}const c=Array.from(n).sort(((e,t)=>t.split(".").length-e.split(".").length));for(const e of c){const t=e.split(".");let n=s;for(let e=0;e<t.length;e++){const s=t[e],r=e===t.length-1,i=0===e,a=t.slice(0,e+1).join(".");i&&PPHP._isBuiltIn(s)&&console.warn(`Root “${s}” shadows the built-in. The placeholder will still be created in pphp.props.`),s in n&&(r||null!=n[s]&&"object"==typeof n[s])||r&&this._declaredStateRoots.has(a)||(n[s]=r?void 0:{}),n=n[s]}}}setNestedProperty(e,t,s){const n=t.split(".");let r=e;for(let e=0;e<n.length-1;e++)n[e]in r||(r[n[e]]={}),r=r[n[e]];r[n[n.length-1]]=s}attachWireFunctionEvents(){this.handleHiddenAttribute(),this.handleAnchorTag();const e=e=>Array.from(this._eventHandlers).map((t=>`[${e}${t}]`)),t=[...e(""),...e("pp-inc-"),...e("data-pp-child-"),...e("data-pp-parent-")].flat().join(","),s=document.body.querySelectorAll(t);for(const e of s){const t=this.getSectionId(e),s=this.getPhpxId(e),n=this.getPhpxParentId(e);for(const r of this._eventHandlers){const i=r,a=`pp-inc-${r}`,o=`data-pp-child-${r}`,c=`data-pp-parent-${r}`,l=e.getAttribute(i),h=e.getAttribute(a),p=e.getAttribute(o),u=e.getAttribute(c),d=l?this.decodeEntities(l).trim():"",f=h?this.decodeEntities(h).trim():"",m=p?this.decodeEntities(p).trim():"",g=u?this.decodeEntities(u).trim():"";if(!(d||f||m||g))continue;const y=[];if(d&&y.push(this.unwrapArrowBody(this.buildHandlerFromRawBody(d,null))),f&&y.push(this.unwrapArrowBody(this.buildHandlerFromRawBody(f,t))),m&&y.push(this.unwrapArrowBody(this.buildHandlerFromRawBody(m,s))),g){const e=n||t||null;y.push(this.unwrapArrowBody(this.buildHandlerFromRawBody(g,e)))}const b=`(event) => { ${[...new Set(y)].join(" ")} }`;[i,a,o,c].forEach((t=>e.removeAttribute(t)));const w=r.slice(2);e.removeAllEventListeners(w),e instanceof HTMLInputElement&&this.handleInputAppendParams(e,w),this.handleDebounce(e,w,b)}}}alreadyScoped(e,t){const s=`${t}_${e}`;return this._scopedKeys.get(t)?.has(s)??!1}prefixFunctionCalls(e,t){return e.replace(/\b([A-Za-z_$][\w$]*)\s*\(/g,((e,s)=>this._reservedWords.has(s)||s.startsWith(`${t}_`)?e:this.alreadyScoped(s,t)?`${t}_${s}(`:e))}prefixIds(e,t,s=new Set){let n="",r=0,i=(e=this.prefixFunctionCalls(e,t)).length,a=!1,o=!1,c=!1;for(;r<i;){const l=e[r];if("'"!==l||o||c||"\\"===e[r-1])if('"'!==l||a||c||"\\"===e[r-1])if("`"!==l||a||o||"\\"===e[r-1])if(a||o||c)n+=l,r++;else if(/[A-Za-z_$]/.test(l)){let a=r+1;for(;a<i&&/[\w$]/.test(e[a]);)a++;const o=e.slice(r,a),c=e[r-1]??"",l=this._reservedWords.has(o),h="."===c;n+=!(o.startsWith(`${t}_`)||h||l||s.has(o))?`${t}_${o}`:o,r=a}else n+=l,r++;else c=!c,n+=l,r++;else o=!o,n+=l,r++;else a=!a,n+=l,r++}return n}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};shouldPrefixForSection(e,t){if(!e||!t)return!1;const s=this.getSectionStateKeys(t);if(!s||0===s.size)return!1;const n=this.extractFunctionCalls(e);for(const e of n)if(this.isStateFunctionForSection(e,s))return!0;const r=this.extractVariableAssignments(e);for(const e of r)if(s.has(e))return!0;return!1}getSectionStateKeys(e){const t=this._scopedKeys.get(e);if(!t)return null;const s=new Set;for(const e of t){const t=e.includes("_")?e.split("_").pop():e;s.add(t)}return s}extractFunctionCalls(e){const t=[],s=/\b([A-Za-z_$][\w$]*)\s*\(/g;let n;for(;null!==(n=s.exec(e));)t.push(n[1]);return t}extractVariableAssignments(e){const t=[],s=/\b([A-Za-z_$][\w$]*)\s*=/g;let n;for(;null!==(n=s.exec(e));){const s=e[n.index-1],r=e[n.index+n[0].length];"="!==s&&"="!==r&&t.push(n[1])}return t}isStateFunctionForSection(e,t){const s=e.match(/^set([A-Z][a-zA-Z]*)$/);if(s){const e=s[1].charAt(0).toLowerCase()+s[1].slice(1);return t.has(e)}const n=e.match(/^toggle([A-Z][a-zA-Z]*)$/);if(n){const e=n[1].charAt(0).toLowerCase()+n[1].slice(1);return t.has(e)}return t.has(e)}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 s=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>\s*/);if(s){let t=e.substring(s[0].length).trim();return t&&!t.endsWith(";")&&(t+=";"),t}let n=e.trim();return n&&!n.endsWith(";")&&(n+=";"),n};buildHandlerFromRawBody(e,t){const{normalized:s,originalParam:n}=this.normalizeToArrow(e),r=this.renameEventParam(s,n),i=this.replaceThisReferences(r);return t?this.prefixBareIdentifiers(i,t):i}replaceThisReferences(e){return e.replace(/\bthis\./g,"event.target.")}collectInlineOnAttributes(e){const t=[];for(const{name:s,value:n}of Array.from(e.attributes))s.startsWith("pp-event-on")&&n.trim().length&&t.push({name:s,rawValue:n});return t}isBareCall(e){return!e.includes("=>")&&PPHP._bareCallRe.test(e)&&!/^[A-Za-z_$]\w*_/.test(e)}normalizeToArrow(e){const t=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>/);if(!t)return{normalized:`() => { ${e} }`,originalParam:null};const s=t[0].replace(/\s*=>\s*$/,"").trim().replace(/^\(|\)$/g,"").trim();return{normalized:e,originalParam:/^[A-Za-z_$]\w*$/.test(s)?s:null}}renameEventParam(e,t){if(!t||"event"===t)return e;const s=new RegExp(`\\b${this.escapeRegex(t)}\\b`,"g");return e.replace(s,((e,t,s)=>{const n=s[t-1],r=s[t+e.length];return n&&/[\w$]/.test(n)||r&&/[\w$]/.test(r)?e:"event"}))}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}prefixBareIdentifiers(e,t){const s=e.indexOf("=>");if(-1!==s){const n=e.slice(0,s+2),r=e.slice(s+2);return n+this.prefixIds(r,t,new Set(["event"]))}const n=this.prefixIds(e,t,new Set(["event"]));return/^[A-Za-z_$].*\)$/.test(n.trim())?`() => ${n}`:`(event) => { ${n}; }`}processFormOnSubmit(e){const t=e.getAttribute("onsubmit")?.trim();if(!t)return;let s,n=t;/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>/.test(n)||(console.warn("PPHP: Inline handler on [onsubmit] should use arrow syntax. Auto-wrapping it."),n=`() => { ${n} }`);const r=this.getScopeId(e);r&&this.isBareCall(n)&&(n=`${r}_${n}`),s=this.buildHandlerFromRawBody(n,r),e.removeAttribute("onsubmit"),this.handleDebounce(e,"submit",s)}async handleDebounce(e,t,s){const n=e.getAttribute("pp-debounce"),r=n?this.parseTime(n):0,i=e.getAttribute("pp-before-request")??"",a=e.getAttribute("pp-after-request")??"",o=PPHP._cancelableEvents,c=async n=>{o.has(t)&&n.cancelable&&n.preventDefault();try{i&&await this.invokeHandler(e,i,n),await this.invokeHandler(e,s,n),a&&"@close"!==a&&await this.invokeHandler(e,a,n),this.handlerAutofocusAttribute()}catch(e){console.error("Error in debounced handler:",e)}},l={passive:PPHP._passiveEvents.has(t)&&!o.has(t)},h=`${t}::${e.__pphpId||e.tagName}`,p=e=>{if(r>0){const t=PPHP.debounceTimers.get(h);t&&clearTimeout(t);const s=setTimeout((()=>{PPHP.debounceTimers.delete(h),c(e)}),r);PPHP.debounceTimers.set(h,s)}else c(e)};e instanceof HTMLFormElement&&"submit"===t?e.addEventListener("submit",(e=>{e.cancelable&&e.preventDefault(),p(e)}),l):e.addEventListener(t,p,l)}debounce(e,t=300,s=!1){let n;return function(...r){const i=this;n&&clearTimeout(n),n=setTimeout((()=>{n=null,s||e.apply(i,r)}),t),s&&!n&&e.apply(i,r)}}handlerAutofocusAttribute(){const e=document.querySelector("dialog[open]");let t=null;if(e&&(t=e.querySelector("[pp-autofocus]")),t||(t=document.querySelector("[pp-autofocus]")),!t)return;const s=t.getAttribute("pp-autofocus");if(!this.isJsonLike(s))return;const n=this.parseJson(s);requestAnimationFrame((()=>{t.focus(),(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&"function"==typeof this.setCursorPosition&&(t instanceof HTMLInputElement&&"number"===t.type?(t.type="text",this.setCursorPosition(t,n),t.type="number"):this.setCursorPosition(t,n))}))}async invokeHandler(e,t,s){this._activeSection=this.getScopeId(e);try{const n=t.trim();let r=this._handlerCache.get(n);r||(r=this.parseHandler(n),this._handlerCache.set(n,r)),await this.executeHandler(r,e,s,n)}catch(s){this.handleInvokeError(s,t,e)}finally{this.scheduleFlush()}}parseHandler(e){const t=e.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").trim();if(this.isArrowFunction(t))return this.parseArrowFunction(t);const s=t.match(/^(\w+(?:\.\w+)*)\s*\(\s*(.*?)\s*\)$/s);if(s)return{type:"call",name:s[1],args:s[2],isAsync:this.isAsyncFunction(s[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,s="",n=0;for(let r=0;r<e.length-1;r++){const i=e[r],a=e[r+1];if(t||'"'!==i&&"'"!==i&&"`"!==i){if(t&&i===s&&"\\"!==e[r-1])t=!1,s="";else if(!t&&("("===i&&n++,")"===i&&n--,"="===i&&">"===a&&n>=0))return!0}else t=!0,s=i}return!1}parseArrowFunction(e){const t=this.findArrowIndex(e);let s=e.substring(t+2).trim();return s.startsWith("{")&&s.endsWith("}")&&(s=s.slice(1,-1).trim()),{type:"arrow",body:s,isAsync:e.includes("async")||this.containsAwait(s)}}findArrowIndex(e){let t=!1,s="";for(let n=0;n<e.length-1;n++){const r=e[n],i=e[n+1];if(t||'"'!==r&&"'"!==r&&"`"!==r){if(t&&r===s&&"\\"!==e[n-1])t=!1;else if(!t&&"="===r&&">"===i)return n}else t=!0,s=r}return-1}async executeArrowHandler(e,t,s){const n=this.parseStatements(e.body);let r=!1;for(const e of n)await this.executeSingleStatement(e,t,s)&&(r=!0);r||await this.executeDynamic(e.body,t,s)}async executeComplexHandler(e,t,s){await this.executeDynamic(e.body,t,s)}parseStatements(e){const t=[];let s="",n=0,r=!1,i="";for(let a=0;a<e.length;a++){const o=e[a];r||'"'!==o&&"'"!==o&&"`"!==o?r&&o===i&&"\\"!==e[a-1]&&(r=!1,i=""):(r=!0,i=o),r||("("!==o&&"{"!==o&&"["!==o||n++,")"!==o&&"}"!==o&&"]"!==o||n--,";"!==o||0!==n)?s+=o:s.trim()&&(t.push(s.trim()),s="")}return s.trim()&&t.push(s.trim()),t}async executeInlineModule(e,t,s,n,r){if(t&&t.trim())if(this.isJsonLike(t)){const r=this.parseJson(t);null!==r&&"object"==typeof r?await this.callInlineModule(e,{...r,element:s,event:n}):await this.callInlineModule(e,r)}else try{const s=this.getOrCreateEvaluator(t)(this.props);await this.callInlineModule(e,s)}catch{await this.callInlineModule(e,{element:s,event:n})}else await this.handleParsedCallback(s,r,n)}async executeSingleStatement(e,t,s){const n=e.trim();if(!n)return!1;const r=n.match(/^\(\s*\)\s*=>\s*(.+)$/);if(r)return await this.executeSingleStatement(r[1],t,s);if(/^\s*(if|for|while|switch|try|return|throw|var|let|const|function|class)\b/.test(n))return await this.executeDynamic(n,t,s),!0;const i=n.match(/^(\w+)\s*\(\s*(.*?)\s*\)$/s);if(i){const[,e,r]=i;if(this._inlineModuleFns.has(e))return await this.executeInlineModule(e,r,t,s,n),!0;const a=globalThis[e];return"function"==typeof a?(await this.executeGlobalFunction(a,r,t,s),!0):(await this.handleParsedCallback(t,n,s),!0)}const a=n.match(/^(\w+)$/);if(a){const e=a[1];if(this._inlineModuleFns.has(e))return await this.handleParsedCallback(t,`${e}()`,s),!0;const n=globalThis[e];return"function"==typeof n?(n.call(globalThis,s),!0):(await this.handleParsedCallback(t,`${e}()`,s),!0)}return await this.executeDynamic(n,t,s),!0}async executeCallHandler(e,t,s,n){const{name:r,args:i}=e;if(this._inlineModuleFns.has(r))return void await this.executeInlineModule(r,i||"",t,s,n);const a=globalThis[r];"function"!=typeof a?await this.handleParsedCallback(t,n,s):await this.executeGlobalFunction(a,i||"",t,s)}async executeSimpleHandler(e,t,s){const{name:n}=e;if(this._inlineModuleFns.has(n))return void await this.handleParsedCallback(t,`${n}()`,s);const r=globalThis[n];"function"!=typeof r?await this.handleParsedCallback(t,`${n}()`,s):r.call(globalThis,s)}async executeHandler(e,t,s,n){switch(e.type){case"arrow":await this.executeArrowHandler(e,t,s);break;case"call":await this.executeCallHandler(e,t,s,n);break;case"simple":await this.executeSimpleHandler(e,t,s);break;case"complex":await this.executeComplexHandler(e,t,s);break;default:await this.handleParsedCallback(t,n,s)}}async executeGlobalFunction(e,t,s,n){if(t.trim())if(this.isJsonLike(t)){const r=this.parseJson(t)??{};e.call(globalThis,{...r,element:s,event:n})}else{const r=this.getOrCreateProxy(this.props);new Function("event","proxy","props","fn",`with (proxy) { return fn(${t}); }`).call(s,n,r,this.props,e)}else e.call(globalThis,n)}async executeDynamic(e,t,s){const n=this.getOrCreateProxy(this.props);let r=e;this._activeSection&&(r=this.prefixFunctionCalls(e,this._activeSection));const i=new Function("event","proxy","props",`\n with (proxy) {\n ${r}\n }`);await i.call(t,s,n,this.props)}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._inlineModuleFns;return new Proxy(e,{get(e,s,n){if("string"==typeof s){if(t.has(s))return t.get(s);if(s in e){const t=Reflect.get(e,s,n),r=globalThis[s];if(!(null==t||"object"==typeof t&&0===Object.keys(t).length||PPHP._isBuiltIn(s)&&typeof t!=typeof r))return t}if(s in globalThis){const e=globalThis[s];return"function"==typeof e&&/^[a-z]/.test(s)?e.bind(globalThis):e}}return Reflect.get(e,s,n)},set:(e,t,s,n)=>Reflect.set(e,t,s,n),has:(e,s)=>"string"==typeof s&&t.has(s)||s in e||s 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,s){const n=e instanceof Error?e.message:String(e),r=s.tagName+(s.id?`#${s.id}`:"");console.error(`Handler execution failed on ${r}:\nHandler: "${t}"\nError: ${n}`,e),s.dispatchEvent(new CustomEvent("pphp:handler-error",{detail:{handler:t,error:e,element:s},bubbles:!0}))}clearHandlerCaches(){this._handlerCache.clear(),this._evaluatorCache.clear()}async handleParsedCallback(e,t,s){const{funcName:n,data:r}=this.parseCallback(e,t);if(!n)return;const i=Array.isArray(n)?n:[n];let a;for(const e of i){const t=this._inlineModuleFns.get(e);if("function"==typeof t){a=t;break}const s=this[e];if("function"==typeof s){a=s;break}const n=window[e];if("function"==typeof n){a=n;break}}if(a){const t=e.hasAttribute("pp-after-request"),n=Array.isArray(r.args)?r.args:[],i=this._responseData?this.parseJson(this._responseData):{response:this._responseData};let o={args:n,element:e,data:r,event:s};return t&&(o={...o,...i}),void await a.call(this,o)}this._responseData=null,this._responseData=await this.handleUndefinedFunction(e,Array.isArray(n)?n[0]:n,r)}async handleUndefinedFunction(e,t,s){const n={callback:t,...s},r=this.createFetchOptions(n),i=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});try{this.saveElementOriginalState(e),this.handleSuspenseElement(e);const n=new URL(window.location.href);let a="",o="",c={success:!1};const l=e.querySelector("input[type='file']");if(l){if(a=await this.fetchFileWithData(n.href,t,l,s),o=this.extractJson(a)||"",o)try{c=this.parseJson(o)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}else{const e=await this.fetch(n.href,r);if(a=await e.text(),this.getRedirectUrl(a))return void await this.redirect(this.getRedirectUrl(a)||"");if(o=this.extractJson(a)||"",o)try{c=this.parseJson(o)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}const h=e.getAttribute("pp-before-request")||"",p=e.getAttribute("pp-after-request")||"";if((h||p&&c.success)&&this.restoreSuspenseElement(e),h||p){let e="";if(c.success){e=a.replace(o,"")}else e=a;if(this.appendAfterbegin(e),!p&&!c.success)return}if(p&&c.success){this.handleAfterRequest(p,o);const e=a.replace(o,"");return this.appendAfterbegin(e),o}if("@close"===p)return c.success?o:void 0;const u=await this.fetch(n.href,i),d=await u.text();if(this.getRedirectUrl(d))return void await this.redirect(this.getRedirectUrl(d)||"");await this.handleResponseRedirectOrUpdate(a,d,o,c)}catch(e){console.error(`Error handling undefined function "${t}". Please ensure the function is defined and accessible.`,e)}}handleAfterRequest(e,t){if(!this.isJsonLike(e))return;const s=this.parseJson(e),n=t?this.parseJson(t):null,r=s.targets;Array.isArray(r)&&r.forEach((e=>{const{id:t,...s}=e,r=document.querySelector(t);let i={};if(n){for(const t in s)if(s.hasOwnProperty(t))switch(t){case"innerHTML":case"outerHTML":case"textContent":case"innerText":"response"===s[t]&&(i[t]=e.responseKey?n[e.responseKey]:n.response);break;default:i[t]=s[t]}}else i=s;r&&this.updateElementAttributes(r,i)}))}sanitizePassiveHandlers(e){return e.replace(/\s+onwheel\s*=\s*(['"])([\s\S]*?)\1/gi,((e,t,s)=>` data-onwheel-code="${encodeURIComponent(s)}"`)).replace(/\s+onmousewheel\s*=\s*(['"])[\s\S]*?\1/gi,"")}handlePassiveWheelStashes(e){(e instanceof Document?e.body:e).querySelectorAll("[data-onwheel-code]").forEach((e=>{let t=decodeURIComponent(e.dataset.onwheelCode||"").trim();delete e.dataset.onwheelCode,e.onwheel=null;const s=this.getScopeId(e);if(s){const e=t.indexOf("=>");if(e>=0){const n=t.slice(0,e+2),r=t.slice(e+2);t=n+this.prefixIds(r,s)}else t=this.prefixIds(t,s)}e.removeAllEventListeners("wheel"),this.handleDebounce(e,"wheel",t)}))}async handleResponseRedirectOrUpdate(e,t,s,n){const r=this.sanitizePassiveHandlers(t),i=this.getUpdatedHTMLContent(e,s,n),a=(new DOMParser).parseFromString(r,"text/html");i&&a.body.insertAdjacentElement("afterbegin",i),this.updateBodyContent(a.body.outerHTML)}getUpdatedHTMLContent(e,t,s){const n=document.createElement("div");if(n.id="afterbegin-8D95D",s&&t?.success){const t=e.replace(s,"");n.innerHTML=t}else n.innerHTML=e;return n.innerHTML?n:null}async updateBodyContent(e){const t=this.saveScrollPositions();this.saveElementState();const s=(new DOMParser).parseFromString(e,"text/html");await this.appendCallbackResponse(s),this.restoreElementState(),this.restoreScrollPositions(t),await this.processInlineModuleScripts(),await this.initMakeReactive()}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)}await this.populateDocumentBody(e)}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 s in t)if(t.hasOwnProperty(s))switch(s){case"innerHTML":case"outerHTML":case"textContent":case"innerText":e[s]=this.decodeHTML(t[s]);break;case"insertAdjacentHTML":e.insertAdjacentHTML(t.position||"beforeend",this.decodeHTML(t[s].html));break;case"insertAdjacentText":e.insertAdjacentText(t.position||"beforeend",this.decodeHTML(t[s].text));break;case"setAttribute":e.setAttribute(t.attrName,this.decodeHTML(t[s]));break;case"removeAttribute":e.removeAttribute(t[s]);break;case"className":e.className=this.decodeHTML(t[s]);break;case"classList.add":e.classList.add(...this.decodeHTML(t[s]).split(","));break;case"classList.remove":e.classList.remove(...this.decodeHTML(t[s]).split(","));break;case"classList.toggle":e.classList.toggle(this.decodeHTML(t[s]));break;case"classList.replace":const[n,r]=this.decodeHTML(t[s]).split(",");e.classList.replace(n,r);break;case"dataset":e.dataset[t.attrName]=this.decodeHTML(t[s]);break;case"style":Object.assign(e.style,t[s]);break;case"value":e.value=this.decodeHTML(t[s]);break;case"checked":e.checked=t[s];break;default:e.setAttribute(s,this.decodeHTML(t[s]))}}decodeHTML(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}appendAfterbegin(e){if(!e)return;const t="afterbegin-8D95D";let s=document.getElementById(t);s?(s.innerHTML=e,document.body.insertAdjacentElement("afterbegin",s)):(s=document.createElement("div"),s.id=t,s.innerHTML=e,document.body.insertAdjacentElement("afterbegin",s))}restoreSuspenseElement(e){const t=e.getAttribute("pp-original-state");if(e.hasAttribute("pp-suspense")&&t){const s=(e,t)=>{for(const s in t)t.hasOwnProperty(s)&&("textContent"===s?e.textContent=t[s]:"innerHTML"===s?e.innerHTML=t[s]:"disabled"===s?!0===t[s]?e.setAttribute("disabled","true"):e.removeAttribute("disabled"):e.setAttribute(s,t[s]));for(const s of Array.from(e.attributes))t.hasOwnProperty(s.name)||e.removeAttribute(s.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);s(t,n)}else r(t,e);t.removeAttribute("pp-original-state")}}},r=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},i=(e,t)=>{e instanceof HTMLFormElement?n(e,t):s(e,t)};try{const r=this.parseJson(t);if(r)if(e instanceof HTMLFormElement){const t=e.id;if(t){const e=document.querySelector(`[form="${t}"]`);if(e){const t=e.getAttribute("pp-original-state");if(t&&this.isJsonLike(t)){const n=this.parseJson(t);s(e,n)}}}const r=new FormData(e),i={};if(r.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(r.targets){r.targets.forEach((e=>{const{id:t,...s}=e,n=document.querySelector(t);n&&i(n,s)}));const{targets:t,...n}=r;s(e,n)}else{const{empty:t,...n}=r;s(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,s,n={}){const r=new FormData,i=s.files;if(i)for(let e=0;e<i.length;e++)r.append("file[]",i[e]);r.append("callback",t);for(const e in n)n.hasOwnProperty(e)&&r.append(e,n[e]);const a=await this.fetch(e,{method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:r});return await a.text()}async handleSuspenseElement(e){let t=e.getAttribute("pp-suspense")||"";const s=(e,t)=>{for(const s in t)if(t.hasOwnProperty(s))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 s=this.parseJson(e);"disabled"!==s.onsubmit&&this.updateElementAttributes(t,s),s.targets&&s.targets.forEach((e=>{const{id:t,...s}=e,n=document.querySelector(t);n&&r(n,s)}))}else n(t,e)}},n=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},r=(e,t)=>{e instanceof HTMLFormElement?s(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),r={};t.forEach(((e,t)=>{r[t]=e})),n.disabled&&this.toggleFormElements(e,!0);const{disabled:i,...a}=n;this.updateElementAttributes(e,a),s(e,r)}else if(n.targets){n.targets.forEach((e=>{const{id:t,...s}=e,n=document.querySelector(t);n&&r(n,s)}));const{targets:t,...s}=n;this.updateElementAttributes(e,s)}else{if("disabled"===n.empty&&""===e.value)return;const{empty:t,...s}=n;this.updateElementAttributes(e,s)}}else if(t)n(e,t);else if(e instanceof HTMLFormElement){const t=new FormData(e),n={};t.forEach(((e,t)=>{n[t]=e})),s(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 s=0;s<e.attributes.length;s++){const n=e.attributes[s];t[n.name]=n.value}e.setAttribute("pp-original-state",JSON.stringify(t))}if(e instanceof HTMLFormElement){let t=null;const s=e.id;s&&(t=document.querySelector(`[form="${s}"]`)),s&&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,s)=>{e[s]=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 s={};const n=e.closest("form");if(n){new FormData(n).forEach(((e,t)=>{s[t]?Array.isArray(s[t])?s[t].push(e):s[t]=[s[t],e]:s[t]=e}))}else e instanceof HTMLInputElement?s=this.handleInputElement(e):(e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(s[e.name]=e.value);const r=t.match(/^(\w+)\(([\s\S]*)\)$/);if(r){const e=r[1];let t=r[2].trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))if(this.isJsonLike(t))try{const e=this.parseJson(t);Array.isArray(e)?s.args=e:e&&"object"==typeof e&&(s={...s,...e})}catch(e){console.error("Error parsing JSON args:",e),s.rawArgs=t}else try{const e=this.evaluateJavaScriptObject(t);Array.isArray(e)?s.args=e:e&&"object"==typeof e?s={...s,...e}:s.rawArgs=t}catch(e){console.error("Error evaluating JS object args:",e),s.rawArgs=t}else try{const e=this.getOrCreateEvaluator(t)(this.props);s.args=[e]}catch{s.args=t.split(/,(?=(?:[^'"]*['"][^'"]*['"])*[^'"]*$)/).map((e=>e.trim().replace(/^['"]|['"]$/g,"")))}return{funcName:e,data:s}}return{funcName:t,data:s}}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 s=document.querySelector(`input[name="${e.name}"]:checked`);t[e.name]=s?s.value:null}else t[e.name]=e.value;else"checkbox"===e.type||"radio"===e.type?t.value=e.checked:t.value=e.value;return t}setCursorPosition(e,t){if(t.start)e.setSelectionRange(0,0);else if(t.end){const t=e.value.length||0;e.setSelectionRange(t,t)}else if(t.length){const s=parseInt(t.length,10)||0;e.setSelectionRange(s,s)}}handleInputAppendParams(e,t){const s=e.getAttribute("pp-append-params"),n=e.getAttribute("pp-append-params-sync");if("true"===s){if("true"===n){const t=e.name||e.id;if(t){const s=new URL(window.location.href),n=new URLSearchParams(s.search);n.has(t)&&(e.value=n.get(t)||"")}}e.addEventListener(t,(e=>{const t=e.currentTarget,s=t.value,n=new URL(window.location.href),r=new URLSearchParams(n.search),i=t.name||t.id;if(i){s?r.set(i,s):r.delete(i);const e=r.toString()?`${n.pathname}?${r.toString()}`:n.pathname;history.replaceState(null,"",e)}}))}}handleHiddenAttribute(){const e=document.querySelectorAll("[pp-visibility]"),t=document.querySelectorAll("[pp-display]"),s=this.handleElementVisibility.bind(this),n=this.handleElementDisplay.bind(this);e.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-visibility",s))),t.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-display",n)))}handleVisibilityElementAttribute(e,t,s){const n=e.getAttribute(t);if(n)if(this.isJsonLike(n)){s(e,this.parseJson(n))}else{const s=this.parseTime(n);if(s>0){const n="pp-visibility"===t?"visibility":"display",r="visibility"===n?"hidden":"none";this.scheduleChange(e,s,n,r)}}}handleElementVisibility(e,t){this.handleElementChange(e,t,"visibility","hidden","visible")}handleElementDisplay(e,t){this.handleElementChange(e,t,"display","none","block")}handleElementChange(e,t,s,n,r){const i=t.start?this.parseTime(t.start):0,a=t.end?this.parseTime(t.end):0;i>0?(e.style[s]=n,this.scheduleChange(e,i,s,r),a>0&&this.scheduleChange(e,i+a,s,n)):a>0&&this.scheduleChange(e,a,s,n)}handleAnchorTag(){document.querySelectorAll("a").forEach((e=>{e.addEventListener("click",(async e=>{const t=e.currentTarget,s=t.getAttribute("href"),n=t.getAttribute("target");if(s&&"_blank"!==n&&!e.metaKey&&!e.ctrlKey&&(e.preventDefault(),!this._isNavigating)){this._isNavigating=!0;try{if(/^(https?:)?\/\//i.test(s)&&!s.startsWith(window.location.origin))window.location.href=s;else{const e=t.getAttribute("pp-append-params");if(s.startsWith("?")&&"true"===e){const e=new URL(window.location.href),t=new URLSearchParams(e.search);let n="";const[r,i]=s.split("#");i&&(n=`#${i}`);new URLSearchParams(r.split("?")[1]).forEach(((e,s)=>{t.set(s,e)}));const a=`${e.pathname}?${t.toString()}${n}`;history.pushState(null,"",a)}else{const[e,t]=s.split("#"),n=`${e}${t?`#${t}`:""}`;history.pushState(null,"",n)}const n=s.indexOf("#");if(-1!==n){const e=s.slice(n+1),t=document.getElementById(e);if(t)t.scrollIntoView({behavior:"smooth"});else{await this.handleNavigation();const t=document.getElementById(e);t&&t.scrollIntoView({behavior:"smooth"})}}else await this.handleNavigation()}}catch(e){console.error("Anchor click error:",e)}finally{this._isNavigating=!1}}}))}))}handlePopState(){window.addEventListener("popstate",(async()=>{await this.handleNavigation()}))}async handleNavigation(){try{const e=document.getElementById("loading-file-1B87E");if(e){const t=this.findLoadingElement(e,window.location.pathname);t&&await this.updateContentWithTransition(t)}const t=await this.fetch(window.location.href);if(!t.ok)return void console.error(`Navigation error: ${t.status} ${t.statusText}`);const s=await t.text(),n=s.match(this._redirectRegex);if(n&&n[1])return void await this.redirect(n[1]);await this.updateDocumentContent(s)}catch(e){console.error("Navigation error:",e)}}findLoadingElement(e,t){let s=t;for(;;){const t=e.querySelector(`div[pp-loading-url='${s}']`);if(t)return t;if("/"===s)break;const n=s.lastIndexOf("/");s=n<=0?"/":s.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:s,fadeOut:n}=this.parseTransition(e);await this.fadeOut(t,n),t.innerHTML=e.innerHTML,this.fadeIn(t,s)}parseTransition(e){let t=250,s=250;const n=e.querySelector("[pp-loading-transition]"),r=n?.getAttribute("pp-loading-transition");if(r){const e=this.parseJson(r);e&&"object"==typeof e?(t=this.parseTime(e.fadeIn??t),s=this.parseTime(e.fadeOut??s)):console.warn("pp-loading-transition is not valid JSON → default values (250 ms) will be used. String:",r)}return{fadeIn:t,fadeOut:s}}fadeOut(e,t){return new Promise((s=>{e.style.transition=`opacity ${t}ms ease-out`,e.style.opacity="0",setTimeout((()=>{e.style.transition="",s()}),t)}))}fadeIn(e,t){e.style.transition=`opacity ${t}ms ease-in`,e.style.opacity="1",setTimeout((()=>{e.style.transition=""}),t)}async updateDocumentContent(e){const t=this.saveScrollPositions(),s=this.sanitizePassiveHandlers(e),n=(new DOMParser).parseFromString(s,"text/html"),r="pp-dynamic-script",i="pp-dynamic-link";document.head.querySelectorAll("[pp-dynamic-meta]").forEach((e=>e.remove()));document.head.querySelectorAll(`[${i}]`).forEach((e=>e.remove()));document.head.querySelectorAll(`[${r}]`).forEach((e=>e.remove()));await(async e=>{Array.from(e.head.children).forEach((e=>{const t=e.tagName;if("SCRIPT"===t&&e.hasAttribute(r)){const t=document.createElement("script");Array.from(e.attributes).forEach((e=>t.setAttribute(e.name,e.value))),e.textContent&&(t.textContent=e.textContent),document.head.appendChild(t)}else if("META"===t){if(e.getAttribute("charset")||"viewport"===e.getAttribute("name"))return;const t=e.name,s=e.getAttribute("property"),n=document.head.querySelector(t?`meta[name="${t}"]`:`meta[property="${s}"]`),r=document.head.querySelector("title");n?document.head.replaceChild(e.cloneNode(!0),n):r?.nextSibling?document.head.insertBefore(e.cloneNode(!0),r.nextSibling):document.head.appendChild(e.cloneNode(!0))}else if("TITLE"===t){const t=document.head.querySelector("title");t?document.head.replaceChild(e.cloneNode(!0),t):document.head.appendChild(e.cloneNode(!0))}else if("LINK"===t){const t=t=>{const s=document.head.querySelector('link[rel="icon"]');if(s)document.head.replaceChild(e.cloneNode(!0),s);else{const e=document.createElement("link");e.rel="icon",e.href=t,document.head.appendChild(e)}};if("icon"===e.getAttribute("rel")){t(e.href)}else if(e.hasAttribute(i)){const t=e.cloneNode(!0);document.head.appendChild(t)}}})),await this.updateDocumentBody(e)})(n),this.restoreScrollPositions(t),this.resetProps(),await this.processInlineModuleScripts(),await this.initMakeReactive(),this.handlerAutofocusAttribute()}restoreScrollPositions(e){requestAnimationFrame((()=>{const t=e.window;t&&window.scrollTo(t.scrollLeft,t.scrollTop),document.querySelectorAll("*").forEach((t=>{const s=this.getElementKey(t);e[s]&&(t.scrollTop=e[s].scrollTop,t.scrollLeft=e[s].scrollLeft)}))}))}PRESERVE_HANDLERS={DETAILS:(e,t)=>(t.open=e.open,!0),INPUT(e,t){const s=e,n=t;return s.value!==n.value&&(n.value=s.value),n.checked=s.checked,document.activeElement!==s||(null!=s.selectionStart&&(n.selectionStart=s.selectionStart,n.selectionEnd=s.selectionEnd),!1)},TEXTAREA(e,t){const s=e,n=t;return s.value!==n.value&&(n.value=s.value),document.activeElement!==s||(n.selectionStart=s.selectionStart,n.selectionEnd=s.selectionEnd,!1)},SELECT(e,t){const s=e;return t.selectedIndex=s.selectedIndex,document.activeElement!==s},VIDEO(e,t){const s=e,n=t;return n.currentTime=s.currentTime,s.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,s=e.body;this._wheelHandlersStashed||(document.querySelectorAll("[onwheel]").forEach((e=>{const t=e.getAttribute("onwheel").trim();if(e.removeAttribute("onwheel"),t){const s=new Function("event",t);e.addEventListener("wheel",s,{passive:!0})}})),this._wheelHandlersStashed=!0);const n=this.PRESERVE_HANDLERS;morphdom(t,s,{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 s=e.tagName;if("SCRIPT"===s||e.hasAttribute("data-nomorph"))return!1;const r=n[s];return!r||r(e,t)},onBeforeNodeDiscarded:e=>(e instanceof HTMLElement&&e.dataset.timerId&&clearTimeout(Number(e.dataset.timerId)),!0)})}catch(e){console.error("Error populating document body:",e)}}async updateDocumentBody(e){try{const t=e.body.cloneNode(!0);this.manageScriptTags(t),document.body.replaceWith(t)}catch(e){console.error("Error populating document body:",e)}}manageScriptTags(e,t){const s=e.querySelectorAll("script"),n=t?.querySelectorAll("script")||s;s.forEach(((e,t)=>{const s=document.createElement("script"),r=n[t]||e;Array.from(r.attributes).forEach((e=>{s.setAttribute(e.name,e.value)})),r.hasAttribute("src")||(s.textContent=r.textContent),e.parentNode?.replaceChild(s,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 redirect(e){if(e)try{const t=new URL(e,window.location.origin);t.origin!==window.location.origin?window.location.href=e:(history.pushState(null,"",e),await this.handleNavigation())}catch(e){console.error("Redirect error:",e)}}abortActiveRequest(){this._activeAbortController&&this._activeAbortController.abort()}async fetch(e,t,s=!1){let n;return s?(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-Requested-With":"XMLHttpRequest"}})}isJsonLike(e){if("string"!=typeof e)return!1;const t=e.trim();return!(!/^\{[\s\S]*\}$/.test(t)&&!/^\[[\s\S]*\]$/.test(t))&&!(t.includes("(")||t.includes(")")||t.includes("=>"))}parseJson(e){try{return JSON5.parse(e)}catch(e){return console.error(`Error parsing JSON: ${e.message}. Please ensure the JSON string is valid.`,e),{}}}parseTime(e){if("number"==typeof e)return e;const t=e.match(/^(\d+)(ms|s|m)?$/);if(t){const e=parseInt(t[1],10);switch(t[2]||"ms"){case"ms":default:return e;case"s":return 1e3*e;case"m":return 60*e*1e3}}return 0}scheduleChange(e,t,s,n){setTimeout((()=>{requestAnimationFrame((()=>{e.style[s]=n}))}),t)}async fetchFunction(e,t={},s=!1){try{const n={callback:e,...t},r=window.location.href;let i;if(Object.keys(n).some((e=>{const t=n[e];return t instanceof File||t instanceof FileList&&t.length>0}))){const e=new FormData;Object.keys(n).forEach((t=>{const s=n[t];s instanceof File?e.append(t,s):s instanceof FileList?Array.from(s).forEach((s=>e.append(t,s))):e.append(t,s)})),i={method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:e}}else i=this.createFetchOptions(n);const a=await this.fetch(r,i,s);if(!a.ok)throw new Error(`Fetch failed with status: ${a.status} ${a.statusText}`);const o=await a.text();try{return JSON.parse(o)}catch{return o}}catch(e){throw console.error("Error in fetchFunction:",e),new Error("Failed to fetch data.")}}processSyncScripts(e){e.forEach((e=>{const t=`script[pp-sync-script="${CSS.escape(e)}"]`,s=document.querySelector(t);if(s){s.remove();const e=document.createElement("script");Array.from(s.attributes).forEach((t=>{e.setAttribute(t.name,t.value)})),s.src?e.src=s.src:e.textContent=s.textContent,e.type=s.type||"module",document.body.appendChild(e)}}))}async sync(...e){try{const t=this.saveScrollPositions();this.saveElementState();const s=e.length>0?e.map((e=>`pp-sync="${e}"`)):['pp-sync="true"'],n=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()}),r=await this.fetch(window.location.href,n),i=await r.text(),a=(new DOMParser).parseFromString(i,"text/html"),o=new Set;s.forEach((e=>{const t=document.querySelectorAll(`[${e}]`),s=a.body.querySelectorAll(`[${e}]`);t.forEach(((e,t)=>{const n=s[t];if(n){if(n.hasAttribute("pp-sync-script")){const e=n.getAttribute("pp-sync-script")||"";e&&o.add(e)}n.querySelectorAll("[pp-sync-script]").forEach((e=>{const t=e.getAttribute("pp-sync-script")||"";t&&o.add(t)})),e.innerHTML=n.innerHTML,this.reRunScripts(e)}}))})),this.processSyncScripts(o),this.restoreElementState(),this.restoreScrollPositions(t),this.attachWireFunctionEvents()}catch(e){console.error("Error in pphpSync:",e)}}async fetchAndUpdateBodyContent(){const e=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});this.abortActiveRequest();const t=await this.fetch(window.location.href,e,!0),s=await t.text();await this.updateBodyContent(s)}reRunScripts(e){e.querySelectorAll("script").forEach((e=>{const t=document.createElement("script");Array.from(e.attributes).forEach((e=>{t.setAttribute(e.name,e.value)})),e.hasAttribute("src")||(t.textContent=e.textContent),e.parentNode?.replaceChild(t,e)}))}copyCode(e,t,s,n,r="img",i=2e3){if(!(e instanceof HTMLElement))return;const a=e.closest(`.${t}`)?.querySelector("pre code"),o=a?.textContent?.trim()||"";o?navigator.clipboard.writeText(o).then((()=>{const t=e.querySelector(r);if(t)for(const[e,s]of Object.entries(n))e in t?t[e]=s:t.setAttribute(e,s);setTimeout((()=>{if(t)for(const[e,n]of Object.entries(s))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;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.loadState()}static getInstance(e={}){return PPHPLocalStore.instance||(PPHPLocalStore.instance=new PPHPLocalStore(e)),PPHPLocalStore.instance}setState(e,t=!1){if(this.state={...this.state,...e},this.listeners.forEach((e=>e(this.state))),this.saveState(),t){const e=localStorage.getItem(this.STORAGE_KEY);e&&this.pphp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]: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})}}}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 s=this.params;s.set(e,t),this.updateURL(s)}delete(e){const t=this.params;t.delete(e),this.updateURL(t)}replace(e){const t=new URLSearchParams;for(const s in e){const n=e[s];null!==n&&t.set(s,n)}this.updateURL(t,!0)}updateURL(e,t=!1){const s=`${window.location.pathname}?${e.toString()}`;t?history.replaceState(null,"",s):history.pushState(null,"",s),this.notifyListeners(e)}listen(e){this.listeners.push(e)}notifyListeners(e){for(const t of this.listeners)t(e)}enablePopStateListener(){window.addEventListener("popstate",(()=>{this.notifyListeners(this.params)}))}}var pphp=PPHP.instance,store=PPHPLocalStore.getInstance(),searchParams=SearchParamsManager.getInstance();
|
|
1
|
+
(()=>{const e=EventTarget.prototype.addEventListener,t=EventTarget.prototype.removeEventListener,s=new Map,n=new Set(["wheel","mousewheel","touchstart","touchmove","touchend","touchcancel","scroll"]);EventTarget.prototype.addEventListener=function(t,r,i){let a=i;n.has(t)&&(void 0===a?a={passive:!0}:"boolean"==typeof a?a={capture:a,passive:!0}:a&&void 0===a.passive&&(a={...a,passive:!0})),s.has(this)||s.set(this,new Map);const o=s.get(this),c=o.get(t)||new Set;c.add(r),o.set(t,c),e.call(this,t,r,a)},EventTarget.prototype.removeEventListener=function(e,n,r){if(s.has(this)&&s.get(this).has(e)){const t=s.get(this).get(e);t.delete(n),0===t.size&&s.get(this).delete(e)}t.call(this,e,n,r)},EventTarget.prototype.removeAllEventListeners=function(e){if(!s.has(this))return;const n=s.get(this).get(e);n&&(n.forEach((s=>{t.call(this,e,s)})),s.get(this).delete(e))}})();class PPHP{props={};_isNavigating=!1;_responseData=null;_elementState={checkedElements:new Set};_activeAbortController=null;_reservedWords;_declaredStateRoots=new Set;_arrayMethodCache=new WeakMap;_scopedKeys=new Map;_updateScheduled=!1;_pendingBindings=new Set;_effects=new Set;_pendingEffects=new Set;_processedPhpSections=new Set;_processedPhpScripts=new WeakSet;_bindings=[];_templateStore=new WeakMap;_inlineDepth=0;_activeSection=null;_inlineModuleFns=new Map;_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 Map;_sectionParentMap=new Map;_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 _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"]);static _bareCallRe=/^[A-Za-z_$]\w*\s*\(.*\)$/;static _autoPrefixes=new Set;constructor(){const e=Object.getOwnPropertyNames(HTMLElement.prototype).filter((e=>e.startsWith("on"))),t=Object.getOwnPropertyNames(Document.prototype).filter((e=>e.startsWith("on"))),s=Object.getOwnPropertyNames(Window.prototype).filter((e=>e.startsWith("on")));this._eventHandlers=new Set([...e,...t,...s].map((e=>e.toLowerCase()))),this._reservedWords=new Set(["null","undefined","true","false","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","finally","for","function","if","import","in","instanceof","let","new","return","super","switch","this","throw","try","typeof","var","void","while","with","yield","async","await","implements","interface","event","NaN","Infinity","Number","String","Boolean","Object","Array","Function","Date","RegExp","Error","JSON","Math","Map","Set"]),this._mutators=new Set(["push","pop","shift","unshift","splice","sort","reverse","copyWithin","fill"]),this.handlePopState(),this._proxyCache=new WeakMap,this._evaluatorCache.clear(),this._depsCache.clear(),this.props=this.makeReactive(this._rawProps),this.scheduleInitialHydration()}static get instance(){return PPHP._instance||(PPHP._instance=new PPHP),PPHP._instance}scheduleInitialHydration(){const e=async()=>{await this.initRefs(),await this.processInlineModuleScripts(),await this.initializeAllReferencedProps(),await this.initBindings(),await this.initLoopBindings(),this.attachWireFunctionEvents(),this._bindings.forEach((e=>e.update())),document.body.removeAttribute("hidden")};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e,{once:!0}):e()}getScopeId(e){for(;e;){const t=e.getAttribute("pp-phpx-id");if(t)return t;const s=e.getAttribute("pp-section-id");if(s)return s;e=e.parentElement}return null}getSectionId(e){for(;e;){const t=e.getAttribute("pp-section-id");if(t)return t;e=e.parentElement}return null}getPhpxId(e){for(;e;){const t=e.getAttribute("pp-phpx-id");if(t)return t;e=e.parentElement}return null}getPhpxParentId(e){if(!e)return null;let t=e,s=null;for(;t&&!s;)s=t.getAttribute("pp-phpx-id"),s||(t=t.parentElement);let n=t?.parentElement;for(;n;){const e=n.getAttribute("pp-phpx-id");if(e&&e!==s)return e;n=n.parentElement}return null}ref(e,t){const s=this._activeSection;let n=[];if(s&&(n=this._sectionRefs.get(s)?.get(e)??[]),0===n.length&&(n=this._refs.get(e)??[]),null!=t){const s=n[t];if(!s)throw new Error(`pphp.ref('${e}', ${t}) — no element at that index`);return s}if(0===n.length)throw new Error(`pphp.ref('${e}') failed — no element was found`);return 1===n.length?n[0]:n}effect(e,t){const s=this._currentScopeId(),n=Array.isArray(t),r=n?t:[],i=n&&0===r.length,a=r.map((e=>{if("function"==typeof e&&e.__pphp_key)return e.__pphp_key;if("string"!=typeof e)return"";if(e.includes("_"))return e;for(const[t,s]of this._scopedKeys)if(s.has(e))return`${t}_${e}`;if(s){const t=this._sharedStateMap.get(s);if(t?.has(e)){const t=this._sectionParentMap.get(s);return t?`${t}_${e}`:e}}return e})).filter(Boolean),o=new Set(a),c=new Map;for(const e of a){const t=this.getNested(this.props,e);c.set(e,t)}let l=0;PPHP._effectCleanups||(PPHP._effectCleanups=new WeakMap);const h=PPHP._effectCleanups,p=()=>{const t=h.get(p);if(t){try{t()}catch(e){console.error("cleanup error:",e)}h.delete(p)}if(++l>50)throw new Error("PPHP: effect ran >50 times — possible loop");if(!i&&a.length>0){let e=!1;for(const t of a){if(this.getNested(this.props,t)!==c.get(t)){e=!0;break}}if(!e)return;for(const e of a)c.set(e,this.getNested(this.props,e))}try{const t=e();"function"==typeof t&&h.set(p,t)}catch(e){console.error("effect error:",e)}};Object.assign(p,{__deps:o,__sectionId:s??null,__static:i});try{const t=e();"function"==typeof t&&h.set(p,t)}catch(e){console.error("effect error (initial):",e)}for(const e of a)c.set(e,this.getNested(this.props,e));const u=n&&this._inlineDepth>0?this._pendingEffects:this._effects;return i?this._effects.add(p):u.add(p),()=>{const e=h.get(p);if(e){try{e()}catch(e){console.error("cleanup error:",e)}h.delete(p)}this._effects.delete(p),this._pendingEffects.delete(p)}}resetProps(){Object.keys(this._rawProps).forEach((e=>{if(window.hasOwnProperty(e)){const t=Object.getOwnPropertyDescriptor(window,e);t&&t.configurable&&delete window[e]}})),this._rawProps={},this._proxyCache=new WeakMap,this._templateStore=new WeakMap,this._arrayMethodCache=new WeakMap,this._handlerProxyCache=new WeakMap,this._depsCache.clear(),this._evaluatorCache.clear(),this._handlerCache.clear(),this._sharedStateMap.clear(),this._sectionParentMap.clear(),this._processedPhpSections.clear(),this._processedPhpScripts=new WeakSet,this._scopedKeys=new Map,this._declaredStateRoots.clear(),this._inlineModuleFns.clear(),PPHP._autoPrefixes.clear(),this._bindings=[],this._pendingBindings.clear(),this._effects.clear(),this._pendingEffects.clear(),this._refs.clear(),this._sectionRefs.clear(),this.clearHandlerCaches(),this.props=this.makeReactive(this._rawProps)}async initMakeReactive(){await this.initRefs(),await this.initializeAllReferencedProps(),await this.initBindings(),await this.initLoopBindings(),this.attachWireFunctionEvents(),this._bindings.forEach((e=>e.update())),document.body.removeAttribute("hidden")}async initLoopBindings(){document.querySelectorAll("[pp-for]").forEach((e=>this.registerLoop(e)))}registerLoop(e){const t=this.getScopeId(e),s=e.getAttribute("pp-for").trim(),[n,r]=s.split(/\s+in\s+/),[i,a]=n.replace(/^\(|\)$/g,"").split(",").map((e=>e.trim())),o=t?`${t}_${i}`:i,c=a?t?`${t}_${a}`:a:null,l=t?r.replace(/\b([A-Za-z_$]\w*)\b/g,((e,s,n,r)=>"."===r[n-1]||this._reservedWords.has(s)||s.startsWith(t+"_")?e:`${t}_${s}`)):r,h=e.parentNode,p=document.createComment("pp-for");h.insertBefore(p,e),h.removeChild(e);const u=this.makeSafeEvaluator(l),d=e=>t?e.replace(new RegExp(`\\b${i}\\b`,"g"),o).replace(a?new RegExp(`\\b${a}\\b`,"g"):/$^/,c??""):e,f=this.extractDependencies(l),m=l.match(/^\s*([A-Za-z_$]\w*)\s*\(/);if(m){const e=m[1],t=this._inlineModuleFns.get(e);if("function"==typeof t){const e=t.toString();this.extractDependencies(e).forEach((e=>f.add(e.split(".")[0])))}}this._bindings.push({dependencies:f,update:()=>{const t=document.activeElement;let s=null,n=null;if((t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&h.contains(t)){const e=t.closest("[key]");s=e?.getAttribute("key")??null,n=t.selectionStart}for(let e=p.nextSibling;e&&e.nodeType!==Node.COMMENT_NODE;){const t=e.nextSibling;h.removeChild(e),e=t}const r=this.getOrCreateProxy(this.props),l=u(r);Array.isArray(l)||console.warn("[pp-for] expected an Array but got:",l);if((Array.isArray(l)?l:[]).forEach(((t,s)=>{this.props[o]=t,c&&(this.props[c]=s);const n=e.content.cloneNode(!0),r=document.createTreeWalker(n,NodeFilter.SHOW_TEXT);for(let e;e=r.nextNode();)e.nodeValue=(e.nodeValue||"").replace(PPHP._mustachePattern,((e,t)=>{try{const e=d(t);return this.formatValue(this.makeSafeEvaluator(e)(this.props))}catch{return""}}));n.querySelectorAll("*").forEach((e=>{for(const{name:t,value:s}of Array.from(e.attributes)){if("pp-bind"===t){const t=d(s),n=this.makeSafeEvaluator(t)(this.props);e.textContent=this.formatValue(n);continue}if("pp-bind-expr"===t){const t=this.decodeEntities?this.decodeEntities(s):s,n=d(t),r=this.makeSafeEvaluator(n)(this.props);e.textContent=this.formatValue(r);continue}const n=t.match(/^pp-bind-(.+)$/);if(!n)continue;const r=n[1],i=d(s),a=this.makeSafeEvaluator(i)(this.props);if(this._boolAttrs.has(r)){const t=!!a;e[r]=t,t?e.setAttribute(r,""):e.removeAttribute(r)}else r in e?e[r]=a:e.setAttribute(r,String(a))}})),n.querySelectorAll("*").forEach((e=>{for(const{name:t,value:s}of Array.from(e.attributes)){const n=t.match(/^pp-bind-(.+)$/);if(!n)continue;const r=n[1],i=d(s),a=this.makeSafeEvaluator(i)(this.props);if(this._boolAttrs.has(r)){const t=!!a;e[r]=t,t?e.setAttribute(r,""):e.removeAttribute(r)}else r in e?e[r]=a:e.setAttribute(r,String(a))}})),n.querySelectorAll("*").forEach((e=>{Array.from(e.attributes).forEach((n=>{const r=n.name.startsWith("on"),o=n.name.startsWith("pp-inc-on"),c=n.name.startsWith("pp-comp-on");if(!r&&!o&&!c)return;let l=n.value;/\b(?:i|idx)\b/.test(l)&&(l=((e,t)=>e.replace(/\[\s*(?:i|idx)\s*\]/g,`[${t}]`).replace(/(^|[^\w$])(?:i|idx)(?!\w)/g,((e,s)=>s+t)))(l,s));const h=new RegExp(`\\b${i}\\b`,"g");var p;if(l=l.replace(h,(p=t,JSON.stringify(p))),a){const e=new RegExp(`\\b${a}\\b`,"g");l=l.replace(e,String(s))}e.setAttribute(n.name,l)}))})),h.insertBefore(n,p.nextSibling)})),null!==s){const e=h.querySelector(`[key="${s}"]`),t=e?.querySelector("input,textarea");if((t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&(t.focus({preventScroll:!0}),null!==n)){const e=Math.min(n,t.value.length);t.setSelectionRange(e,e)}}this.attachWireFunctionEvents()}})}_sectionRefs=new Map;async initRefs(){document.querySelectorAll("[pp-ref]").forEach((e=>{const t=e.getAttribute("pp-ref"),s=this.getScopeId(e)??"__global__",n=this._sectionRefs.get(s)??new Map,r=n.get(t)??[];r.push(e),n.set(t,r),this._sectionRefs.set(s,n);const i=this._refs.get(t)??[];i.push(e),this._refs.set(t,i),e.removeAttribute("pp-ref")}))}scheduleBindingUpdate(e){this._pendingBindings.add(e),this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this.flushBindings()})))}makeReactive(e,t=[]){const s=this._proxyCache.get(e);if(s)return s;if(e instanceof Map||e instanceof Set||"object"!=typeof e||null===e)return e;const n=this,r=new Proxy(e,{get(e,s,r){const i=Reflect.get(e,s,r);if(Array.isArray(e)&&"string"==typeof s&&n._mutators.has(s)){let a=n._arrayMethodCache.get(e);if(a||(a=new Map,n._arrayMethodCache.set(e,a)),!a.has(s)){const e=i.bind(r),o=t.join("."),c=function(...t){const s=e(...t);return queueMicrotask((()=>{n._bindings.forEach((e=>{e.dependencies.has(o)&&n.scheduleBindingUpdate(e)}))})),s};a.set(s,c)}return a.get(s)}return null!==i&&"object"==typeof i?n.makeReactive(i,[...t,s]):i},set(e,s,r,i){let a=r;null!==r&&"object"==typeof r&&(a=n.makeReactive(r,[...t,s]));const o=e[s],c=Reflect.set(e,s,a,i);if(o===a)return c;const l=[...t,s].join(".");return n._bindings.forEach((e=>{for(const t of e.dependencies)if(l===t||l.startsWith(t+".")||t.startsWith(l+".")){n.scheduleBindingUpdate(e);break}})),c}});return this._proxyCache.set(e,r),r}makeAttrTemplateUpdater(e,t,s,n){let r=this._templateStore.get(e);r||(r=new Map,this._templateStore.set(e,r)),r.has(t)||r.set(t,e.getAttribute(t)||"");const i=n??r.get(t)??"",a=this.getScopeId(e),o=a&&this._scopedKeys.get(a)||new Set,c=a&&this._sharedStateMap.get(a)||new Set,l=a?this._sectionParentMap.get(a)??null:null,h=e=>a?e.replace(/\b([A-Za-z_$][\w$]*)\b/g,((e,t,s,n)=>{if("."===n[s-1]||this._reservedWords.has(t))return e;if(c.has(t))return l?`${l}_${t}`:t;if(o.has(t)||this._declaredStateRoots.has(`${a}_${t}`))return`${a}_${t}`;let r=this._sectionParentMap.get(a)||null;for(;r;){if(this._scopedKeys.get(r)?.has(t)||this.hasNested(this.props,`${r}_${t}`))return`${r}_${t}`;r=this._sectionParentMap.get(r)||null}return e})):e;return(i.match(this._mustacheRe)||[]).forEach((e=>{const t=e.replace(/^\{\{\s*|\s*\}\}$/g,"");this.extractDependencies(h(t)).forEach((e=>s.add(e)))})),()=>{try{const s=i.replace(this._mustacheRe,((e,t)=>{try{const e=h(t),s=this.makeSafeEvaluator(e);return this.formatValue(s(this.props))}catch(e){return console.error("Error token:",t,e),""}}));e.getAttribute(t)!==s&&e.setAttribute(t,s)}catch(e){console.error(`Error evaluating the template for attribute "${t}". Please check the template syntax and dependencies.`,e)}}}makePrimitiveUpdater(e,t,s){const n={};return this._eventHandlers.forEach((e=>{if(e.startsWith("on")){const t=e.slice(2);n[t]=t}})),n.value="input",n.checked="change",()=>{try{const r=s(this.props),i=this.formatValue(r);let a=!1;if("value"===t){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,s="true"===i;"checked"in e&&t.checked!==s?(t.checked=s,a=!0):"checked"in e||(e.setAttribute("checked",i),a=!0)}if(!a||e instanceof HTMLInputElement&&("hidden"===e.type||e.disabled||e.readOnly))return;const o=n[t]||t,c="click"===o?new MouseEvent(o,{bubbles:!0,cancelable:!0}):new Event(o,{bubbles:!0});e.dispatchEvent(c)}catch(e){console.error(`Error evaluating attribute "${t}":`,e)}}}formatValue(e){return null!==e&&"object"==typeof e&&1===Object.keys(e).length&&Object.prototype.hasOwnProperty.call(e,"value")?this.formatValue(e.value):"function"==typeof e?"":"boolean"==typeof e?e?"true":"false":Array.isArray(e)?e.map((e=>"object"==typeof e?JSON.stringify(e):String(e))).join(", "):e&&"object"==typeof e?Object.keys(e).length?JSON.stringify(e,null,2):"":e?.toString()??""}registerBinding(e,t,s="text",n){if(this._assignmentRe.test(t))return;const r=this.getScopeId(e);let i=t;if(r){const e=this._scopedKeys.get(r)||new Set,s=this._sharedStateMap.get(r)||new Set,n=this._sectionParentMap.get(r);i=t.replace(/\b([A-Za-z_$][\w$]*)\b/g,((t,i,a,o)=>{if("."===o[a-1]||this._reservedWords.has(i))return t;if(s.has(i))return n?`${n}_${i}`:i;if(e.has(i)||this._declaredStateRoots.has(`${r}_${i}`))return`${r}_${i}`;let c=this._sectionParentMap.get(r)||null;for(;c;){if(this._scopedKeys.get(c)?.has(i)||this.hasNested(this.props,`${c}_${i}`))return`${c}_${i}`;c=this._sectionParentMap.get(c)||null}return t}))}const a=new Set([...this.extractDependencies(i)].map((e=>e.split(".")[0])).filter((e=>e in this.props&&!this._reservedWords.has(e)))),o=this.makeSafeEvaluator(i);if("value"===n||"checked"===n){const t=this.makePrimitiveUpdater(e,n,o);return void this._bindings.push({dependencies:a,update:t})}if(n){const s=n.toLowerCase();if(this._boolAttrs.has(s)){e.removeAttribute(s);const r=()=>{try{const t=!!o(this.props);e[n]!==t&&(e[n]=t),t?e.setAttribute(s,""):e.removeAttribute(s)}catch(e){console.error(`PPHP: error evaluating boolean attribute ${n}="${t}"`,e)}};return void this._bindings.push({dependencies:a,update:r})}const c=e.getAttribute(n)??"";if(this._mustacheRe.test(i)||this._mustacheRe.test(c)){const t=this._scopedKeys.get(r??"")||new Set,s=this._sharedStateMap.get(r??"")||new Set,i=this._sectionParentMap.get(r??"")||null,o=c.replace(this._mustacheRe,((e,n)=>`{{ ${n.replace(/\b([A-Za-z_$][\w$]*)\b/g,((e,n,a,o)=>{if("."===o[a-1]||this._reservedWords.has(n))return e;if(s.has(n))return i?`${i}_${n}`:n;if(t.has(n)||this._declaredStateRoots.has(`${r}_${n}`))return`${r}_${n}`;let c=this._sectionParentMap.get(r??"")||null;for(;c;){if(this._scopedKeys.get(c)?.has(n)||this.hasNested(this.props,`${c}_${n}`))return`${c}_${n}`;c=this._sectionParentMap.get(c)||null}return e}))} }}`)),l=this.makeAttrTemplateUpdater(e,n,a,o);return void this._bindings.push({dependencies:a,update:l})}const l=()=>{try{const t=o(this.props),s=this.formatValue(t);n in e&&(e[n]=s),e.setAttribute(n,s)}catch(e){console.error(`Error evaluating attribute ${n}="${t}"`,e)}};return void this._bindings.push({dependencies:a,update:l})}const c={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:a,update:()=>{try{const t=o(this.props),n=this.formatValue(t);c[s](e,n)}catch(e){console.error(`Error evaluating expression "${t}"`,e)}}})}makeSafeEvaluator(e){const t=e.trim(),s=`\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",s)}catch(t){const s=JSON.stringify(e);n=new Function("ctx",`try { return ${s}; } catch { return ""; }`)}return e=>{try{const t=n(e);return null==t?"":t}catch{return""}}}async initBindings(){this._bindings=[];const e=new WeakSet;document.body.querySelectorAll("[pp-if]").forEach((t=>{if(e.has(t))return;const s=[];let n=t;for(;n;){if(n.hasAttribute("pp-if"))s.push({el:n,expr:n.getAttribute("pp-if")});else if(n.hasAttribute("pp-elseif"))s.push({el:n,expr:n.getAttribute("pp-elseif")});else{if(!n.hasAttribute("pp-else"))break;s.push({el:n,expr:null})}e.add(n),n=n.nextElementSibling}s.forEach((e=>{if(null!==e.expr){const t=e.expr.replace(/^{\s*|\s*}$/g,"");e.deps=this.extractDependencies(t);const s=this.makeSafeEvaluator(t);e.evaluate=()=>!!s(this.props)}}));const r=new Set;s.forEach((e=>e.deps?.forEach((e=>r.add(e)))));this._bindings.push({dependencies:r,update:()=>{let e=!1;for(const{el:t,expr:n,evaluate:r}of s)!e&&null!==n&&r()?(t.removeAttribute("hidden"),e=!0):e||null!==n?t.setAttribute("hidden",""):(t.removeAttribute("hidden"),e=!0)}})})),document.body.querySelectorAll("*").forEach((e=>{["pp-bind","pp-bind-expr"].forEach((t=>{const s=e.getAttribute(t);s&&this.registerBinding(e,s,"text")})),Array.from(e.attributes).forEach((t=>{const s=t.name.toLowerCase(),n=t.value.trim();this._boolAttrs.has(s)&&!t.name.startsWith("pp-bind-")&&/^[A-Za-z_$][\w$]*$/.test(n)&&(e.removeAttribute(t.name),this.registerBinding(e,n,"text",s))})),Array.from(e.attributes).forEach((t=>{if(!t.name.startsWith("pp-bind-"))return;if("pp-bind"===t.name||"pp-bind-expr"===t.name||"pp-bind-spread"===t.name)return;const s=this.decodeEntities(t.value).replace(/^{{\s*|\s*}}$/g,"");let n=t.name.replace(/^(pp-bind-)+/,"");const r="value"===n?"value":"checked"===n?"checked":"text";this.registerBinding(e,s,r,n)})),Array.from(e.attributes).forEach((t=>{if("pp-bind-spread"!==t.name)return;const s=this.decodeEntities(t.value).split(",").map((e=>e.trim())).filter(Boolean),n=new Set;s.forEach((e=>n.add(e.split(".")[0])));const r=new Set;this._bindings.push({dependencies:n,update:()=>{try{const t={};s.forEach((e=>{const s=this.getNested(this.props,e)??{};Object.assign(t,s)})),r.forEach((s=>{s in t||e.hasAttribute(s)||(e.removeAttribute(s),r.delete(s))})),Object.entries(t).forEach((([t,s])=>{if(!r.has(t)&&e.hasAttribute(t))return;if(!1===s||null==s)return void(r.has(t)&&(e.removeAttribute(t),r.delete(t)));const n="object"==typeof s?JSON.stringify(s):String(s);e.getAttribute(t)!==n&&e.setAttribute(t,n),r.add(t)}))}catch(e){console.error("pp-spread error:",e)}}})}))}))}callInlineModule(e,...t){const s=this._inlineModuleFns.get(e);if(!s)throw new Error(`PPHP: no inline module named "${e}"`);return s(...t)}async processInlineModuleScripts(){this._inlineDepth++,this._sharedStateMap.clear(),this._sectionParentMap.clear();try{const e=Array.from(document.body.querySelectorAll('script[type="text/php"]:not([src])')).filter((e=>{const t=this.getScopeId(e);return t?!this._processedPhpSections.has(t):!this._processedPhpScripts.has(e)}));if(!e.length)return;document.querySelectorAll("[pp-section-id]").forEach((e=>{const t=e.getAttribute("pp-section-id"),s=this.findParentSectionId(e);s&&this._sectionParentMap.set(t,s)})),document.querySelectorAll("[pp-phpx-id]").forEach((e=>{const t=e.getAttribute("pp-phpx-id"),s=this.findParentSectionId(e);s&&this._sectionParentMap.set(t,s)}));const t=this.sortScriptsByDependency(e),s={};for(const e of t){const t=this.getScopeId(e);if(!t)continue;const n=e.textContent||"";for(const[,e]of[...n.matchAll(/export\s+const\s+([A-Za-z_$]\w*)/g),...n.matchAll(/export\s+function\s+([A-Za-z_$]\w*)/g)])s[e]=t}for(const[e,t]of Object.entries(s))this._scopedKeys.has(t)||this._scopedKeys.set(t,new Set),this._scopedKeys.get(t).add(e);for(const e of t){const t=this.getScopeId(e);let n=(e.textContent||"").trim();if(n=this.decodeEntities(n),n=this.stripComments(n),n=this.transformStateDeclarations(n,t),t){const e=this._sectionParentMap.get(t)??null,s=t+"_",r=e?e+"_":"",i=new Set;if(this._declaredStateRoots.forEach((e=>{e.startsWith(s)?i.add(e.slice(s.length)):r&&e.startsWith(r)?i.add(e.slice(r.length)):e.includes("_")||i.add(e)})),i.size){let e="";for(const a of i){const i=this.hasNested(pphp.props,s+a)?s+a:this.hasNested(pphp.props,r+a)?r+a:a,o="set"+a[0].toUpperCase()+a.slice(1),c=t?`${t}_${a}`:a,l=t?`${t}_${o}`:o;new RegExp(`\\b(?:const|let|var)\\s+\\[?\\s*${a}\\b`).test(n)||(e+=`\n const ${a} = (() => {\n const fn = () => pphp.props.${i};\n fn.__pphp_key = '${i}';\n Object.defineProperty(fn, 'value', {\n get(){ return pphp.props.${i}; },\n set(v){ pphp.props.${i} = v; }\n });\n return fn;\n })();\n const ${o} = v => {\n pphp.props.${i} = typeof v === 'function' ? v(pphp.props.${i}) : v;\n };\n pphp._inlineModuleFns.set('${c}', ${a});\n pphp._inlineModuleFns.set('${l}', ${o});\n `)}n=e+"\n"+n}}const r=this.extractSetters(n,t);if(r.length){n+="\n\n";for(const e of r){n+=`pphp._inlineModuleFns.set('${t?`${t}_${e}`:e}', ${e});\n`}}if(t){const e=this._sectionParentMap.get(t)??null,s=e?e+"_":"";n=n.replace(/(\bpphp\.state\(\s*['"])([^'"]+)(['"])/g,((e,n,r,i)=>r.startsWith(t+"_")||s&&r.startsWith(s)||!r.includes("_")?n+r+i:n+`${t}_${r}`+i))}n=n.replace(/\b([A-Za-z_$]\w*)\s*\(/g,((e,t,n,r)=>{const i=r.slice(Math.max(0,n-20),n);if(/\b(?:function|export\s+function)\s*$/.test(i.trim()))return e;const a=s[t];return a?`${a}_${t}(`:e}));const i=new Blob([n],{type:"application/javascript"}),a=URL.createObjectURL(i),o=PPHP.prototype._currentScopeId;t&&(PPHP.prototype._currentScopeId=()=>t);try{const e=await import(a);for(const[s,n]of Object.entries(e))if("function"==typeof n){const e=t?`${t}_${s}`:s;this._inlineModuleFns.set(e,n)}}catch(e){console.error("Inline module import failed:",e)}finally{PPHP.prototype._currentScopeId=o,URL.revokeObjectURL(a),t?this._processedPhpSections.add(t):this._processedPhpScripts.add(e)}}}finally{this._inlineDepth--,0===this._inlineDepth&&requestAnimationFrame((()=>{this._pendingEffects.forEach((e=>this._effects.add(e))),this._pendingEffects.clear()}))}}stripComments(e){let t="",s=0,n=!1,r="",i=!1;for(;s<e.length;){const a=e[s],o=e[s+1];if(i||"'"!==a&&'"'!==a&&"`"!==a||"\\"===e[s-1])if(n)t+=a,s++;else if(i||"/"!==a||"*"!==o)if(i)"*"===a&&"/"===o?(i=!1,s+=2):s++;else if("/"!==a||"/"!==o)t+=a,s++;else for(;s<e.length&&"\n"!==e[s];)s++;else i=!0,s+=2;else n=!n,r=n?a:"",t+=a,s++}return t}findParentSectionId(e){const t=e.parentElement?.closest("[pp-section-id]");return t?t.getAttribute("pp-section-id"):null}extractSetters(e,t){const s=[],n=/\[\s*([A-Za-z_$]\w*)\s*,\s*([A-Za-z_$]\w*)\s*\]\s*=\s*pphp\.state\(/g;let r;for(;null!==(r=n.exec(e));){const[,,e]=r,n=r[1];t&&this._sharedStateMap.get(t)?.has(n)||s.push(e)}return s}transformStateDeclarations(e,t){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\s*\(\s*)/g,((e,s,n,r,i)=>t&&this._sharedStateMap.get(t)?.has(n)?e:`${s}${n}, ${r}${i}'${n}', `))).replace(/(\b(?:const|let|var)\s+\[\s*)([A-Za-z_$]\w*)\s*(\]\s*=\s*pphp\.state\s*\(\s*)/g,((e,s,n,r)=>t&&this._sharedStateMap.get(t)?.has(n)?e:`${s}${n}${r}'${n}', `))).replace(/(\b(?:const|let|var)\s+)([A-Za-z_$]\w*)(\s*=\s*pphp\.state\s*\(\s*)/g,((e,s,n,r)=>t&&this._sharedStateMap.get(t)?.has(n)?e:`${s}[${n}] = pphp.state('${n}', `))}sortScriptsByDependency(e){const t=new Map;for(const s of e){const e=this.getScopeId(s);t.has(e)||t.set(e,[]),t.get(e).push(s)}const s=[],n=new Set,r=e=>{if(!e)return[];const t=this._sectionParentMap.get(e);if(t)return[t];const s=this._sharedStateMap.get(e);return s&&s.size>0?[t||null]:[]},i=e=>{if(n.has(e))return;for(const t of r(e))i(t);const a=t.get(e)||[];s.push(...a),n.add(e)};i(null);for(const e of t.keys())null!==e&&i(e);return s}flushBindings(){const e=new Set(this._dirtyDeps);this._pendingBindings.forEach((t=>{t.dependencies.forEach((t=>e.add(t))),t.update()})),this._pendingBindings.clear(),this._dirtyDeps.clear(),this._updateScheduled=!1,this._effects.forEach((t=>{if(t.__static)return;const s=t.__deps||new Set;if(0===s.size||[...s].some((t=>e.has(t)))){const e=this._activeSection;this._activeSection=t.__sectionId??null;try{t()}catch(e){console.error("effect error:",e)}this._activeSection=e}}))}scheduleFlush(){this._updateScheduled||(this._updateScheduled=!0,requestAnimationFrame((()=>{this._updateScheduled=!1,this.flushBindings()})))}scopeKey(e){const t=this._currentScopeId();if(!t)return e;const s=this._sharedStateMap.get(t);if(s?.has(e)){const s=this._sectionParentMap.get(t);return s?`${s}_${e}`:e}return e.startsWith(`${t}_`)?e:`${t}_${e}`}_currentScopeId(){const e=document.currentScript;return this.getScopeId(e)}getNested(e,t){return t.split(".").reduce(((e,t)=>e?e[t]:void 0),e)}setNested(e,t,s){const n=t.split("."),r=n.pop();n.reduce(((e,t)=>e[t]??={}),e)[r]=s}hasNested(e,t){return void 0!==this.getNested(e,t)}state(e,t){if("string"!=typeof e||""===e.trim())throw new Error("PPHP.state: missing or invalid key—make sure your build-time injector ran and you wrote `const [foo, setFoo] = pphp.state(0)` so it became `pphp.state('foo', 0)`.");arguments.length<2&&(t=void 0);const s=this._currentScopeId(),n=e;if(this._reservedWords.has(n))throw new Error(`'${n}' is reserved – choose another state key.`);const r=this.scopeKey(n);this._declaredStateRoots.add(r),s&&(this._scopedKeys.has(s)||this._scopedKeys.set(s,new Set),this._scopedKeys.get(s).add(n)),this.hasNested(pphp.props,r)||this.setNested(pphp.props,r,t);const i=()=>this.getNested(pphp.props,r),a=e=>{const t=i(),s="function"==typeof e?e(t):e;this.setNested(pphp.props,r,s),this._dirtyDeps.add(r.split(".")[0]),this.scheduleFlush()},o=()=>i();Object.defineProperty(o,"value",{get:()=>i(),set:e=>a(e)}),Object.defineProperties(o,{valueOf:{value:()=>i()},toString:{value:()=>String(i())}}),o.__pphp_key=r;const c=i();if(null===c||"object"!=typeof c)return[o,a];return[new Proxy(o,{apply:(e,t,s)=>Reflect.apply(e,t,s),get(e,t,s){if("value"===t)return i();if(t in e)return Reflect.get(e,t,s);return i()[t]},set(e,t,s){if("value"===t)return a(s),!0;return i()[t]=s,!0},has(e,t){if("value"===t||t in o)return!0;return t in i()}}),a]}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 s=>{const n=e.get(s);if(void 0!==n)return n;const r=s in globalThis||t.some((e=>s in e));return e.set(s,r),r}})();extractDependencies(e){const t=e.trim();if(this.isPlainText(t))return new Set;let s=e.replace(/\?\./g,".");const n=new Set,r=/(?:^|[^\w$])(?:\(\s*([^)]*?)\s*\)|([A-Za-z_$][\w$]*))\s*=>/g;for(let e;e=r.exec(s);){(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(s);)e[1].split(",").map((e=>e.trim())).filter(Boolean).forEach((e=>n.add(e)));const a=e=>{let t="",s=0;for(;s<e.length;)if("`"===e[s])for(s++;s<e.length;)if("\\"===e[s])s+=2;else if("$"===e[s]&&"{"===e[s+1]){s+=2;let n=1;const r=s;for(;s<e.length&&n>0;)"{"===e[s]?n++:"}"===e[s]&&n--,s++;const i=e.slice(r,s-1);t+=a(i)+" "}else{if("`"===e[s]){s++;break}s++}else t+=e[s++];return t};s=a(s),s=s.replace(/(['"])(?:\\.|[^\\])*?\1/g,""),s=s.replace(/\/(?:\\.|[^\/\\])+\/[gimsuy]*/g,"");const o=new Set,c=/\b[A-Za-z_$]\w*(?:\.[A-Za-z_$]\w*)*\b/g;for(const t of s.match(c)??[]){const[s,...r]=t.split(".");n.has(s)||(0===r.length&&PPHP._isBuiltIn(s)&&new RegExp(`\\.${s}\\b`).test(e)||o.add(t))}return o}isPlainText(e){const t=e.trim();if(/^['"`]/.test(t))return!1;return![/[+\-*/%=<>!&|?:]/,/\.\w+/,/\[\s*\w+\s*\]/,/\(\s*[^)]*\s*\)/,/=>/,/\b(true|false|null|undefined|typeof|new|delete|void|in|of|instanceof)\b/,/\?\./,/\?\?/,/\.\.\./,/\{[^}]*\}/,/\[[^\]]*\]/].some((e=>e.test(t)))&&(!!t.includes(" ")&&(!/\w+\.\w+/.test(t)&&!/\w+\[\w+\]/.test(t)))}async initializeAllReferencedProps(){const e=PPHP._mustachePattern,t=PPHP._mustacheTest,s=this.props,n=new Set,r=(e,t)=>{if(this.hasNested(this.props,t))return t;const s=e.getAttribute("pp-section-id"),n=this.getScopeId(e.parentElement);return s??n?`${s??n}_${t}`:t},i=(()=>{const e=new Set([...Object.getOwnPropertyNames(String.prototype),...Object.getOwnPropertyNames(Array.prototype),...Object.getOwnPropertyNames(Number.prototype),...Object.getOwnPropertyNames(Boolean.prototype),...Object.getOwnPropertyNames(Object.prototype),...Object.getOwnPropertyNames(Date.prototype),...Object.getOwnPropertyNames(RegExp.prototype)]);return t=>e.has(t)})(),a=(e,t)=>{const[s,a,...o]=t.split(".");if(this._reservedWords.has(s))return void console.warn(`Invalid path “${t}” – “${s}” is a reserved word.`);if(PPHP._isBuiltIn(s)&&console.warn(`Path “${t}” shadows the built-in “${s}”. It will be stored in pphp.props.`),a&&i(a))return void n.add(r(e,s));const c=r(e,s);n.add(a?`${c}.${[a,...o].join(".")}`:c)};for(const s of document.body.getElementsByTagName("*"))for(const{name:n,value:r}of Array.from(s.attributes))if(r){if(t.test(r))for(const t of r.matchAll(e))this.extractDependencies(t[1]).forEach((e=>a(s,e)));"pp-if"!==n&&"pp-elseif"!==n||this.extractDependencies(r).forEach((e=>a(s,e))),n.startsWith("pp-bind")&&this.extractDependencies(r).forEach((e=>a(s,e)))}const o=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT,{acceptNode:e=>t.test(e.nodeValue??"")?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT});for(let t;t=o.nextNode();){const s=t.parentElement;for(const n of t.nodeValue.matchAll(e))this.extractDependencies(n[1]).forEach((e=>a(s,e)))}const c=Array.from(n).sort(((e,t)=>t.split(".").length-e.split(".").length));for(const e of c){const t=e.split(".");let n=s;for(let e=0;e<t.length;e++){const s=t[e],r=e===t.length-1,i=0===e,a=t.slice(0,e+1).join(".");i&&PPHP._isBuiltIn(s)&&console.warn(`Root “${s}” shadows the built-in. The placeholder will still be created in pphp.props.`),s in n&&(r||null!=n[s]&&"object"==typeof n[s])||r&&this._declaredStateRoots.has(a)||(n[s]=r?void 0:{}),n=n[s]}}}setNestedProperty(e,t,s){const n=t.split(".");let r=e;for(let e=0;e<n.length-1;e++)n[e]in r||(r[n[e]]={}),r=r[n[e]];r[n[n.length-1]]=s}attachWireFunctionEvents(){this.handleHiddenAttribute(),this.handleAnchorTag();const e=e=>Array.from(this._eventHandlers).map((t=>`[${e}${t}]`)),t=[...e(""),...e("pp-inc-"),...e("data-pp-child-"),...e("data-pp-parent-")].flat().join(","),s=document.body.querySelectorAll(t);for(const e of s){const t=this.getSectionId(e),s=this.getPhpxId(e),n=this.getPhpxParentId(e);t&&PPHP._autoPrefixes.add(`${t}_`),s&&PPHP._autoPrefixes.add(`${s}_`),n&&PPHP._autoPrefixes.add(`${n}_`);for(const r of this._eventHandlers){const i=r,a=`pp-inc-${r}`,o=`data-pp-child-${r}`,c=`data-pp-parent-${r}`,l=e.getAttribute(i),h=e.getAttribute(a),p=e.getAttribute(o),u=e.getAttribute(c),d=l?this.decodeEntities(l).trim():"",f=h?this.decodeEntities(h).trim():"",m=p?this.decodeEntities(p).trim():"",g=u?this.decodeEntities(u).trim():"";if(!(d||f||m||g))continue;const y=[];if(d&&y.push(this.unwrapArrowBody(this.buildHandlerFromRawBody(d,null))),f&&y.push(this.unwrapArrowBody(this.buildHandlerFromRawBody(f,t))),m&&y.push(this.unwrapArrowBody(this.buildHandlerFromRawBody(m,s))),g){const e=n||t||null;y.push(this.unwrapArrowBody(this.buildHandlerFromRawBody(g,e)))}const b=`(event) => { ${[...new Set(y)].join(" ")} }`;[i,a,o,c].forEach((t=>e.removeAttribute(t)));const S=r.slice(2);e.removeAllEventListeners(S),e instanceof HTMLInputElement&&this.handleInputAppendParams(e,S),this.handleDebounce(e,S,b)}}}alreadyScoped(e,t){return this._scopedKeys.get(t)?.has(e)??!1}prefixFunctionCalls(e,t){const s=this._scopedKeys.get(t)||new Set,n=e=>s.has(e)||this._declaredStateRoots.has(`${t}_${e}`);return e.replace(/\b([A-Za-z_$][\w$]*)\s*\(/g,((e,s)=>this._reservedWords.has(s)||s.startsWith(`${t}_`)||!n(s)?e:`${t}_${s}(`))}prefixIds(e,t,s=new Set){let n="",r=0,i=(e=this.prefixFunctionCalls(e,t)).length,a=!1,o=!1,c=!1;for(;r<i;){const l=e[r];if("'"!==l||o||c||"\\"===e[r-1])if('"'!==l||a||c||"\\"===e[r-1])if("`"!==l||a||o||"\\"===e[r-1])if(a||o||c)n+=l,r++;else if(/[A-Za-z_$]/.test(l)){let a=r+1;for(;a<i&&/[\w$]/.test(e[a]);)a++;const o=e.slice(r,a),c=e[r-1]??"",l=this._reservedWords.has(o),h="."===c;n+=!(o.startsWith(`${t}_`)||h||l||s.has(o))?`${t}_${o}`:o,r=a}else n+=l,r++;else c=!c,n+=l,r++;else o=!o,n+=l,r++;else a=!a,n+=l,r++}return n}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};shouldPrefixForSection(e,t){if(!e||!t)return!1;const s=this.getSectionStateKeys(t);if(!s||0===s.size)return!1;const n=this.extractFunctionCalls(e);for(const e of n)if(this.isStateFunctionForSection(e,s))return!0;const r=this.extractVariableAssignments(e);for(const e of r)if(s.has(e))return!0;return!1}getSectionStateKeys(e){const t=this._scopedKeys.get(e);if(!t)return null;const s=new Set;for(const e of t){const t=e.includes("_")?e.split("_").pop():e;s.add(t)}return s}extractFunctionCalls(e){const t=[],s=/\b([A-Za-z_$][\w$]*)\s*\(/g;let n;for(;null!==(n=s.exec(e));)t.push(n[1]);return t}extractVariableAssignments(e){const t=[],s=/\b([A-Za-z_$][\w$]*)\s*=/g;let n;for(;null!==(n=s.exec(e));){const s=e[n.index-1],r=e[n.index+n[0].length];"="!==s&&"="!==r&&t.push(n[1])}return t}isStateFunctionForSection(e,t){const s=e.match(/^set([A-Z][a-zA-Z]*)$/);if(s){const e=s[1].charAt(0).toLowerCase()+s[1].slice(1);return t.has(e)}const n=e.match(/^toggle([A-Z][a-zA-Z]*)$/);if(n){const e=n[1].charAt(0).toLowerCase()+n[1].slice(1);return t.has(e)}return t.has(e)}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 s=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>\s*/);if(s){let t=e.substring(s[0].length).trim();return t&&!t.endsWith(";")&&(t+=";"),t}let n=e.trim();return n&&!n.endsWith(";")&&(n+=";"),n};buildHandlerFromRawBody(e,t){const{normalized:s,originalParam:n}=this.normalizeToArrow(e),r=this.renameEventParam(s,n),i=this.replaceThisReferences(r);return t?this.prefixBareIdentifiers(i,t):i}replaceThisReferences(e){return e.replace(/\bthis\./g,"event.target.")}isBareCall(e){return!e.includes("=>")&&PPHP._bareCallRe.test(e)&&!/^[A-Za-z_$]\w*_/.test(e)}normalizeToArrow(e){const t=e.match(/^\s*(?:\([\w\s,]*\)|[A-Za-z_$][\w$]*)\s*=>/);if(!t)return{normalized:`() => { ${e} }`,originalParam:null};const s=t[0].replace(/\s*=>\s*$/,"").trim().replace(/^\(|\)$/g,"").trim();return{normalized:e,originalParam:/^[A-Za-z_$]\w*$/.test(s)?s:null}}renameEventParam(e,t){if(!t||"event"===t)return e;const s=new RegExp(`\\b${this.escapeRegex(t)}\\b`,"g");return e.replace(s,((e,t,s)=>{const n=s[t-1],r=s[t+e.length];return n&&/[\w$]/.test(n)||r&&/[\w$]/.test(r)?e:"event"}))}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}prefixBareIdentifiers(e,t){const s=e.indexOf("=>");if(-1!==s){const n=e.slice(0,s+2),r=e.slice(s+2);return n+this.prefixIds(r,t,new Set(["event"]))}const n=this.prefixIds(e,t,new Set(["event"]));return/^[A-Za-z_$].*\)$/.test(n.trim())?`() => ${n}`:`(event) => { ${n}; }`}async handleDebounce(e,t,s){const n=e.getAttribute("pp-debounce"),r=n?this.parseTime(n):0,i=e.getAttribute("pp-before-request")??"",a=e.getAttribute("pp-after-request")??"",o=PPHP._cancelableEvents,c=async n=>{o.has(t)&&n.cancelable&&n.preventDefault();try{const t=this.getScopeId(e);if(i){const s=t?`${t}_${i}`:i;await this.invokeHandler(e,s,n)}if(await this.invokeHandler(e,s,n),a&&!a.startsWith("@close")){const s=t?`${t}_${a}`:a;await this.invokeHandler(e,s,n)}this.handlerAutofocusAttribute()}catch(e){console.error("Error in debounced handler:",e)}},l={passive:PPHP._passiveEvents.has(t)&&!o.has(t)},h=`${t}::${e.__pphpId||e.tagName}`,p=e=>{if(r>0){const t=PPHP.debounceTimers.get(h);t&&clearTimeout(t);const s=setTimeout((()=>{PPHP.debounceTimers.delete(h),c(e)}),r);PPHP.debounceTimers.set(h,s)}else c(e)};e instanceof HTMLFormElement&&"submit"===t?e.addEventListener("submit",(e=>{e.cancelable&&e.preventDefault(),p(e)}),l):e.addEventListener(t,p,l)}debounce(e,t=300,s=!1){let n;return function(...r){const i=this;n&&clearTimeout(n),n=setTimeout((()=>{n=null,s||e.apply(i,r)}),t),s&&!n&&e.apply(i,r)}}handlerAutofocusAttribute(){const e=document.querySelector("dialog[open]");let t=null;if(e&&(t=e.querySelector("[pp-autofocus]")),t||(t=document.querySelector("[pp-autofocus]")),!t)return;const s=t.getAttribute("pp-autofocus");if(!this.isJsonLike(s))return;const n=this.parseJson(s);requestAnimationFrame((()=>{t.focus(),(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement)&&"function"==typeof this.setCursorPosition&&(t instanceof HTMLInputElement&&"number"===t.type?(t.type="text",this.setCursorPosition(t,n),t.type="number"):this.setCursorPosition(t,n))}))}async invokeHandler(e,t,s){this._activeSection=this.getScopeId(e);try{const n=t.trim();let r=this._handlerCache.get(n);r||(r=this.parseHandler(n),this._handlerCache.set(n,r)),await this.executeHandler(r,e,s,n)}catch(s){this.handleInvokeError(s,t,e)}finally{this.scheduleFlush()}}parseHandler(e){const t=e.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").trim();if(this.isArrowFunction(t))return this.parseArrowFunction(t);const s=t.match(/^(\w+(?:\.\w+)*)\s*\(\s*(.*?)\s*\)$/s);if(s)return{type:"call",name:s[1],args:s[2],isAsync:this.isAsyncFunction(s[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,s="",n=0;for(let r=0;r<e.length-1;r++){const i=e[r],a=e[r+1];if(t||'"'!==i&&"'"!==i&&"`"!==i){if(t&&i===s&&"\\"!==e[r-1])t=!1,s="";else if(!t&&("("===i&&n++,")"===i&&n--,"="===i&&">"===a&&n>=0))return!0}else t=!0,s=i}return!1}parseArrowFunction(e){const t=this.findArrowIndex(e);let s=e.substring(t+2).trim();return s.startsWith("{")&&s.endsWith("}")&&(s=s.slice(1,-1).trim()),{type:"arrow",body:s,isAsync:e.includes("async")||this.containsAwait(s)}}findArrowIndex(e){let t=!1,s="";for(let n=0;n<e.length-1;n++){const r=e[n],i=e[n+1];if(t||'"'!==r&&"'"!==r&&"`"!==r){if(t&&r===s&&"\\"!==e[n-1])t=!1;else if(!t&&"="===r&&">"===i)return n}else t=!0,s=r}return-1}async executeArrowHandler(e,t,s){const n=this.parseStatements(e.body);let r=!1;for(const e of n)await this.executeSingleStatement(e,t,s)&&(r=!0);r||await this.executeDynamic(e.body,t,s)}async executeComplexHandler(e,t,s){await this.executeDynamic(e.body,t,s)}parseStatements(e){const t=[];let s="",n=0,r=!1,i="";for(let a=0;a<e.length;a++){const o=e[a];r||'"'!==o&&"'"!==o&&"`"!==o?r&&o===i&&"\\"!==e[a-1]&&(r=!1,i=""):(r=!0,i=o),r||("("!==o&&"{"!==o&&"["!==o||n++,")"!==o&&"}"!==o&&"]"!==o||n--,";"!==o||0!==n)?s+=o:s.trim()&&(t.push(s.trim()),s="")}return s.trim()&&t.push(s.trim()),t}async executeInlineModule(e,t,s,n,r){if(t&&t.trim())if(this.isJsonLike(t)){const r=this.parseJson(t);null!==r&&"object"==typeof r?await this.callInlineModule(e,{...r,element:s,event:n}):await this.callInlineModule(e,r)}else try{const s=this.getOrCreateEvaluator(t)(this.props);await this.callInlineModule(e,s)}catch{await this.callInlineModule(e,{element:s,event:n})}else await this.handleParsedCallback(s,r,n)}async executeSingleStatement(e,t,s){const n=e.trim();if(!n)return!1;const r=n.match(/^\(\s*\)\s*=>\s*(.+)$/);if(r)return await this.executeSingleStatement(r[1],t,s);if(/^\s*(if|for|while|switch|try|return|throw|var|let|const|function|class)\b/.test(n))return await this.executeDynamic(n,t,s),!0;const i=n.match(/^(\w+)\s*\(\s*(.*?)\s*\)$/s);if(i){const[,e,r]=i,a=this.resolveFunctionName(e);if(a&&this._inlineModuleFns.has(a))return await this.executeInlineModule(a,r,t,s,n),!0;if(a){const e=globalThis[a];if("function"==typeof e)return await this.executeGlobalFunction(e,r,t,s),!0}return await this.handleParsedCallback(t,n,s),!0}const a=n.match(/^(\w+)$/);if(a){const e=a[1],n=this.resolveFunctionName(e);if(n&&this._inlineModuleFns.has(n))return await this.handleParsedCallback(t,`${n}()`,s),!0;if(n){const e=globalThis[n];if("function"==typeof e)return e.call(globalThis,s),!0}return await this.handleParsedCallback(t,`${e}()`,s),!0}return await this.executeDynamic(n,t,s),!0}async executeCallHandler(e,t,s,n){const{name:r,args:i}=e,a=this.resolveFunctionName(r);if(a){if(this._inlineModuleFns.has(a))return void await this.executeInlineModule(a,i||"",t,s,n);const e=globalThis[a];if("function"==typeof e)return void await this.executeGlobalFunction(e,i||"",t,s)}await this.handleParsedCallback(t,n,s)}resolveFunctionName(e){if(this._inlineModuleFns.has(e))return e;if(!e.includes("_")&&"function"==typeof globalThis[e])return e;if(e.includes("_")){const[t,...s]=e.split("_"),n=s.join("_"),r=this._sectionParentMap.get(t);if(r){const e=`${r}_${n}`;if(this._inlineModuleFns.has(e))return e}if(this._inlineModuleFns.has(n))return n;if("function"==typeof globalThis[n])return n}return null}async executeSimpleHandler(e,t,s){const{name:n}=e,r=this.resolveFunctionName(n);if(r){if(this._inlineModuleFns.has(r))return void await this.handleParsedCallback(t,`${r}()`,s);const e=globalThis[r];if("function"==typeof e)return void e.call(globalThis,s)}await this.handleParsedCallback(t,`${n}()`,s)}async executeHandler(e,t,s,n){switch(e.type){case"arrow":await this.executeArrowHandler(e,t,s);break;case"call":await this.executeCallHandler(e,t,s,n);break;case"simple":await this.executeSimpleHandler(e,t,s);break;case"complex":await this.executeComplexHandler(e,t,s);break;default:await this.handleParsedCallback(t,n,s)}}async executeGlobalFunction(e,t,s,n){if(t.trim())if(this.isJsonLike(t)){const r=this.parseJson(t)??{};e.call(globalThis,{...r,element:s,event:n})}else{const r=this.getOrCreateProxy(this.props);new Function("event","proxy","props","fn",`with (proxy) { return fn(${t}); }`).call(s,n,r,this.props,e)}else e.call(globalThis,n)}async executeDynamic(e,t,s){const n=this.getOrCreateProxy(this.props);let r=e;this._activeSection&&(r=this.prefixFunctionCalls(e,this._activeSection));const i=new Function("event","proxy","props",`\n with (proxy) {\n ${r}\n }`);await i.call(t,s,n,this.props)}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._inlineModuleFns;return new Proxy(e,{get(e,s,n){if("string"==typeof s){if(t.has(s))return t.get(s);if(s in e){const t=Reflect.get(e,s,n),r=globalThis[s];if(!(null==t||"object"==typeof t&&0===Object.keys(t).length||PPHP._isBuiltIn(s)&&typeof t!=typeof r))return t}if(s in globalThis){const e=globalThis[s];return"function"==typeof e&&/^[a-z]/.test(s)?e.bind(globalThis):e}}return Reflect.get(e,s,n)},set:(e,t,s,n)=>Reflect.set(e,t,s,n),has:(e,s)=>"string"==typeof s&&t.has(s)||s in e||s 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,s){const n=e instanceof Error?e.message:String(e),r=s.tagName+(s.id?`#${s.id}`:"");console.error(`Handler execution failed on ${r}:\nHandler: "${t}"\nError: ${n}`,e),s.dispatchEvent(new CustomEvent("pphp:handler-error",{detail:{handler:t,error:e,element:s},bubbles:!0}))}clearHandlerCaches(){this._handlerCache.clear(),this._evaluatorCache.clear()}async handleParsedCallback(e,t,s){const{funcName:n,data:r}=this.parseCallback(e,t);if(!n)return;const i=Array.isArray(n)?n:[n];let a;for(const e of i){const t=this._inlineModuleFns.get(e);if("function"==typeof t){a=t;break}const s=this[e];if("function"==typeof s){a=s;break}const n=window[e];if("function"==typeof n){a=n;break}}if(a){const t=e.hasAttribute("pp-after-request"),n=Array.isArray(r.args)?r.args:[],i=this._responseData?this.parseJson(this._responseData):{response:this._responseData};let o={args:n,element:e,data:r,event:s};return t&&(o={...o,...i}),void await a.call(this,o)}this._responseData=null,this._responseData=await this.handleUndefinedFunction(e,Array.isArray(n)?n[0]:n,r)}stripAutoPrefix(e){for(const t of PPHP._autoPrefixes)if(e.startsWith(t))return e.slice(t.length);return e}async handleUndefinedFunction(e,t,s){const n=this.stripAutoPrefix(t),r={callback:n,...s},i=this.createFetchOptions(r),a=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});try{this.saveElementOriginalState(e),this.handleSuspenseElement(e);const t=new URL(window.location.href);let r="",o="",c={success:!1};const l=e.querySelector("input[type='file']");if(l){if(r=await this.fetchFileWithData(t.href,n,l,s),o=this.extractJson(r)||"",o)try{c=this.parseJson(o)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}else{const e=await this.fetch(t.href,i);if(r=await e.text(),this.getRedirectUrl(r))return void await this.redirect(this.getRedirectUrl(r)||"");if(o=this.extractJson(r)||"",o)try{c=this.parseJson(o)}catch(e){console.error("Error parsing JSON response. Please ensure the response is in valid JSON format.",e)}}const h=e.getAttribute("pp-before-request")||"",p=e.getAttribute("pp-after-request")||"";if((h||p&&c.success)&&this.restoreSuspenseElement(e),h||p){let e="";if(c.success){e=r.replace(o,"")}else e=r;if(this.appendAfterbegin(e),!p&&!c.success)return}if(p&&c.success){this.handleAfterRequest(p,o);const e=r.replace(o,"");return this.appendAfterbegin(e),o}if("@close"===p)return c.success?o:void 0;const u=await this.fetch(t.href,a),d=await u.text();if(this.getRedirectUrl(d))return void await this.redirect(this.getRedirectUrl(d)||"");await this.handleResponseRedirectOrUpdate(r,d,o,c)}catch(e){console.error(`Error handling undefined function "${n}". Please ensure the function is defined and accessible.`,e)}}handleAfterRequest(e,t){if(!this.isJsonLike(e))return;const s=this.parseJson(e),n=t?this.parseJson(t):null,r=s.targets;Array.isArray(r)&&r.forEach((e=>{const{id:t,...s}=e,r=document.querySelector(t);let i={};if(n){for(const t in s)if(s.hasOwnProperty(t))switch(t){case"innerHTML":case"outerHTML":case"textContent":case"innerText":"response"===s[t]&&(i[t]=e.responseKey?n[e.responseKey]:n.response);break;default:i[t]=s[t]}}else i=s;r&&this.updateElementAttributes(r,i)}))}sanitizePassiveHandlers(e){return e.replace(/\s+onwheel\s*=\s*(['"])([\s\S]*?)\1/gi,((e,t,s)=>` data-onwheel-code="${encodeURIComponent(s)}"`)).replace(/\s+onmousewheel\s*=\s*(['"])[\s\S]*?\1/gi,"")}handlePassiveWheelStashes(e){(e instanceof Document?e.body:e).querySelectorAll("[data-onwheel-code]").forEach((e=>{let t=decodeURIComponent(e.dataset.onwheelCode||"").trim();delete e.dataset.onwheelCode,e.onwheel=null;const s=this.getScopeId(e);if(s){const e=t.indexOf("=>");if(e>=0){const n=t.slice(0,e+2),r=t.slice(e+2);t=n+this.prefixIds(r,s)}else t=this.prefixIds(t,s)}e.removeAllEventListeners("wheel"),this.handleDebounce(e,"wheel",t)}))}async handleResponseRedirectOrUpdate(e,t,s,n){const r=this.sanitizePassiveHandlers(t),i=this.getUpdatedHTMLContent(e,s,n),a=(new DOMParser).parseFromString(r,"text/html");i&&a.body.insertAdjacentElement("afterbegin",i),this.updateBodyContent(a.body.outerHTML)}getUpdatedHTMLContent(e,t,s){const n=document.createElement("div");if(n.id="afterbegin-8D95D",s&&t?.success){const t=e.replace(s,"");n.innerHTML=t}else n.innerHTML=e;return n.innerHTML?n:null}async updateBodyContent(e){const t=this.saveScrollPositions();this.saveElementState();const s=(new DOMParser).parseFromString(e,"text/html");await this.appendCallbackResponse(s),this.restoreElementState(),this.restoreScrollPositions(t),await this.processInlineModuleScripts(),await this.initMakeReactive()}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)}await this.populateDocumentBody(e)}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 s in t)if(t.hasOwnProperty(s))switch(s){case"innerHTML":case"outerHTML":case"textContent":case"innerText":e[s]=this.decodeHTML(t[s]);break;case"insertAdjacentHTML":e.insertAdjacentHTML(t.position||"beforeend",this.decodeHTML(t[s].html));break;case"insertAdjacentText":e.insertAdjacentText(t.position||"beforeend",this.decodeHTML(t[s].text));break;case"setAttribute":e.setAttribute(t.attrName,this.decodeHTML(t[s]));break;case"removeAttribute":e.removeAttribute(t[s]);break;case"className":e.className=this.decodeHTML(t[s]);break;case"classList.add":e.classList.add(...this.decodeHTML(t[s]).split(","));break;case"classList.remove":e.classList.remove(...this.decodeHTML(t[s]).split(","));break;case"classList.toggle":e.classList.toggle(this.decodeHTML(t[s]));break;case"classList.replace":const[n,r]=this.decodeHTML(t[s]).split(",");e.classList.replace(n,r);break;case"dataset":e.dataset[t.attrName]=this.decodeHTML(t[s]);break;case"style":Object.assign(e.style,t[s]);break;case"value":e.value=this.decodeHTML(t[s]);break;case"checked":e.checked=t[s];break;default:e.setAttribute(s,this.decodeHTML(t[s]))}}decodeHTML(e){const t=document.createElement("textarea");return t.innerHTML=e,t.value}appendAfterbegin(e){if(!e)return;const t="afterbegin-8D95D";let s=document.getElementById(t);s?(s.innerHTML=e,document.body.insertAdjacentElement("afterbegin",s)):(s=document.createElement("div"),s.id=t,s.innerHTML=e,document.body.insertAdjacentElement("afterbegin",s))}restoreSuspenseElement(e){const t=e.getAttribute("pp-original-state");if(e.hasAttribute("pp-suspense")&&t){const s=(e,t)=>{for(const s in t)t.hasOwnProperty(s)&&("textContent"===s?e.textContent=t[s]:"innerHTML"===s?e.innerHTML=t[s]:"disabled"===s?!0===t[s]?e.setAttribute("disabled","true"):e.removeAttribute("disabled"):e.setAttribute(s,t[s]));for(const s of Array.from(e.attributes))t.hasOwnProperty(s.name)||e.removeAttribute(s.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);s(t,n)}else r(t,e);t.removeAttribute("pp-original-state")}}},r=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},i=(e,t)=>{e instanceof HTMLFormElement?n(e,t):s(e,t)};try{const r=this.parseJson(t);if(r)if(e instanceof HTMLFormElement){const t=e.id;if(t){const e=document.querySelector(`[form="${t}"]`);if(e){const t=e.getAttribute("pp-original-state");if(t&&this.isJsonLike(t)){const n=this.parseJson(t);s(e,n)}}}const r=new FormData(e),i={};if(r.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(r.targets){r.targets.forEach((e=>{const{id:t,...s}=e,n=document.querySelector(t);n&&i(n,s)}));const{targets:t,...n}=r;s(e,n)}else{const{empty:t,...n}=r;s(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,s,n={}){const r=new FormData,i=s.files;if(i)for(let e=0;e<i.length;e++)r.append("file[]",i[e]);r.append("callback",t);for(const e in n)n.hasOwnProperty(e)&&r.append(e,n[e]);const a=await this.fetch(e,{method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:r});return await a.text()}async handleSuspenseElement(e){let t=e.getAttribute("pp-suspense")||"";const s=(e,t)=>{for(const s in t)if(t.hasOwnProperty(s))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 s=this.parseJson(e);"disabled"!==s.onsubmit&&this.updateElementAttributes(t,s),s.targets&&s.targets.forEach((e=>{const{id:t,...s}=e,n=document.querySelector(t);n&&r(n,s)}))}else n(t,e)}},n=(e,t)=>{e instanceof HTMLInputElement?e.value=t:e.textContent=t},r=(e,t)=>{e instanceof HTMLFormElement?s(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),r={};t.forEach(((e,t)=>{r[t]=e})),n.disabled&&this.toggleFormElements(e,!0);const{disabled:i,...a}=n;this.updateElementAttributes(e,a),s(e,r)}else if(n.targets){n.targets.forEach((e=>{const{id:t,...s}=e,n=document.querySelector(t);n&&r(n,s)}));const{targets:t,...s}=n;this.updateElementAttributes(e,s)}else{if("disabled"===n.empty&&""===e.value)return;const{empty:t,...s}=n;this.updateElementAttributes(e,s)}}else if(t)n(e,t);else if(e instanceof HTMLFormElement){const t=new FormData(e),n={};t.forEach(((e,t)=>{n[t]=e})),s(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 s=0;s<e.attributes.length;s++){const n=e.attributes[s];t[n.name]=n.value}e.setAttribute("pp-original-state",JSON.stringify(t))}if(e instanceof HTMLFormElement){let t=null;const s=e.id;s&&(t=document.querySelector(`[form="${s}"]`)),s&&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,s)=>{e[s]=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 s={};const n=e.closest("form");if(n){new FormData(n).forEach(((e,t)=>{s[t]?Array.isArray(s[t])?s[t].push(e):s[t]=[s[t],e]:s[t]=e}))}else e instanceof HTMLInputElement?s=this.handleInputElement(e):(e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement)&&(s[e.name]=e.value);const r=t.match(/^(\w+)\(([\s\S]*)\)$/);if(r){const e=r[1];let t=r[2].trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))if(this.isJsonLike(t))try{const e=this.parseJson(t);Array.isArray(e)?s.args=e:e&&"object"==typeof e&&(s={...s,...e})}catch(e){console.error("Error parsing JSON args:",e),s.rawArgs=t}else try{const e=this.evaluateJavaScriptObject(t);Array.isArray(e)?s.args=e:e&&"object"==typeof e?s={...s,...e}:s.rawArgs=t}catch(e){console.error("Error evaluating JS object args:",e),s.rawArgs=t}else try{const e=this.getOrCreateEvaluator(t)(this.props);s.args=[e]}catch{s.args=t.split(/,(?=(?:[^'"]*['"][^'"]*['"])*[^'"]*$)/).map((e=>e.trim().replace(/^['"]|['"]$/g,"")))}return{funcName:e,data:s}}return{funcName:t,data:s}}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 s=document.querySelector(`input[name="${e.name}"]:checked`);t[e.name]=s?s.value:null}else t[e.name]=e.value;else"checkbox"===e.type||"radio"===e.type?t.value=e.checked:t.value=e.value;return t}setCursorPosition(e,t){if(t.start)e.setSelectionRange(0,0);else if(t.end){const t=e.value.length||0;e.setSelectionRange(t,t)}else if(t.length){const s=parseInt(t.length,10)||0;e.setSelectionRange(s,s)}}handleInputAppendParams(e,t){const s=e.getAttribute("pp-append-params"),n=e.getAttribute("pp-append-params-sync");if("true"===s){if("true"===n){const t=e.name||e.id;if(t){const s=new URL(window.location.href),n=new URLSearchParams(s.search);n.has(t)&&(e.value=n.get(t)||"")}}e.addEventListener(t,(e=>{const t=e.currentTarget,s=t.value,n=new URL(window.location.href),r=new URLSearchParams(n.search),i=t.name||t.id;if(i){s?r.set(i,s):r.delete(i);const e=r.toString()?`${n.pathname}?${r.toString()}`:n.pathname;history.replaceState(null,"",e)}}))}}handleHiddenAttribute(){const e=document.querySelectorAll("[pp-visibility]"),t=document.querySelectorAll("[pp-display]"),s=this.handleElementVisibility.bind(this),n=this.handleElementDisplay.bind(this);e.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-visibility",s))),t.forEach((e=>this.handleVisibilityElementAttribute(e,"pp-display",n)))}handleVisibilityElementAttribute(e,t,s){const n=e.getAttribute(t);if(n)if(this.isJsonLike(n)){s(e,this.parseJson(n))}else{const s=this.parseTime(n);if(s>0){const n="pp-visibility"===t?"visibility":"display",r="visibility"===n?"hidden":"none";this.scheduleChange(e,s,n,r)}}}handleElementVisibility(e,t){this.handleElementChange(e,t,"visibility","hidden","visible")}handleElementDisplay(e,t){this.handleElementChange(e,t,"display","none","block")}handleElementChange(e,t,s,n,r){const i=t.start?this.parseTime(t.start):0,a=t.end?this.parseTime(t.end):0;i>0?(e.style[s]=n,this.scheduleChange(e,i,s,r),a>0&&this.scheduleChange(e,i+a,s,n)):a>0&&this.scheduleChange(e,a,s,n)}handleAnchorTag(){document.querySelectorAll("a").forEach((e=>{e.addEventListener("click",(async e=>{const t=e.currentTarget,s=t.getAttribute("href"),n=t.getAttribute("target");if(s&&"_blank"!==n&&!e.metaKey&&!e.ctrlKey&&(e.preventDefault(),!this._isNavigating)){this._isNavigating=!0;try{if(/^(https?:)?\/\//i.test(s)&&!s.startsWith(window.location.origin))window.location.href=s;else{const e=t.getAttribute("pp-append-params");if(s.startsWith("?")&&"true"===e){const e=new URL(window.location.href),t=new URLSearchParams(e.search);let n="";const[r,i]=s.split("#");i&&(n=`#${i}`);new URLSearchParams(r.split("?")[1]).forEach(((e,s)=>{t.set(s,e)}));const a=`${e.pathname}?${t.toString()}${n}`;history.pushState(null,"",a)}else{const[e,t]=s.split("#"),n=`${e}${t?`#${t}`:""}`;history.pushState(null,"",n)}const n=s.indexOf("#");if(-1!==n){const e=s.slice(n+1),t=document.getElementById(e);if(t)t.scrollIntoView({behavior:"smooth"});else{await this.handleNavigation();const t=document.getElementById(e);t&&t.scrollIntoView({behavior:"smooth"})}}else await this.handleNavigation()}}catch(e){console.error("Anchor click error:",e)}finally{this._isNavigating=!1}}}))}))}handlePopState(){window.addEventListener("popstate",(async()=>{await this.handleNavigation()}))}async handleNavigation(){try{const e=document.getElementById("loading-file-1B87E");if(e){const t=this.findLoadingElement(e,window.location.pathname);t&&await this.updateContentWithTransition(t)}const t=await this.fetch(window.location.href);if(!t.ok)return void console.error(`Navigation error: ${t.status} ${t.statusText}`);const s=await t.text(),n=s.match(this._redirectRegex);if(n&&n[1])return void await this.redirect(n[1]);await this.updateDocumentContent(s)}catch(e){console.error("Navigation error:",e)}}findLoadingElement(e,t){let s=t;for(;;){const t=e.querySelector(`div[pp-loading-url='${s}']`);if(t)return t;if("/"===s)break;const n=s.lastIndexOf("/");s=n<=0?"/":s.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:s,fadeOut:n}=this.parseTransition(e);await this.fadeOut(t,n),t.innerHTML=e.innerHTML,this.fadeIn(t,s)}parseTransition(e){let t=250,s=250;const n=e.querySelector("[pp-loading-transition]"),r=n?.getAttribute("pp-loading-transition");if(r){const e=this.parseJson(r);e&&"object"==typeof e?(t=this.parseTime(e.fadeIn??t),s=this.parseTime(e.fadeOut??s)):console.warn("pp-loading-transition is not valid JSON → default values (250 ms) will be used. String:",r)}return{fadeIn:t,fadeOut:s}}fadeOut(e,t){return new Promise((s=>{e.style.transition=`opacity ${t}ms ease-out`,e.style.opacity="0",setTimeout((()=>{e.style.transition="",s()}),t)}))}fadeIn(e,t){e.style.transition=`opacity ${t}ms ease-in`,e.style.opacity="1",setTimeout((()=>{e.style.transition=""}),t)}async updateDocumentContent(e){const t=this.saveScrollPositions(),s=this.sanitizePassiveHandlers(e),n=(new DOMParser).parseFromString(s,"text/html"),r="pp-dynamic-script",i="pp-dynamic-link";document.head.querySelectorAll("[pp-dynamic-meta]").forEach((e=>e.remove()));document.head.querySelectorAll(`[${i}]`).forEach((e=>e.remove()));document.head.querySelectorAll(`[${r}]`).forEach((e=>e.remove()));await(async e=>{Array.from(e.head.children).forEach((e=>{const t=e.tagName;if("SCRIPT"===t&&e.hasAttribute(r)){const t=document.createElement("script");Array.from(e.attributes).forEach((e=>t.setAttribute(e.name,e.value))),e.textContent&&(t.textContent=e.textContent),document.head.appendChild(t)}else if("META"===t){if(e.getAttribute("charset")||"viewport"===e.getAttribute("name"))return;const t=e.name,s=e.getAttribute("property"),n=document.head.querySelector(t?`meta[name="${t}"]`:`meta[property="${s}"]`),r=document.head.querySelector("title");n?document.head.replaceChild(e.cloneNode(!0),n):r?.nextSibling?document.head.insertBefore(e.cloneNode(!0),r.nextSibling):document.head.appendChild(e.cloneNode(!0))}else if("TITLE"===t){const t=document.head.querySelector("title");t?document.head.replaceChild(e.cloneNode(!0),t):document.head.appendChild(e.cloneNode(!0))}else if("LINK"===t){const t=t=>{const s=document.head.querySelector('link[rel="icon"]');if(s)document.head.replaceChild(e.cloneNode(!0),s);else{const e=document.createElement("link");e.rel="icon",e.href=t,document.head.appendChild(e)}};if("icon"===e.getAttribute("rel")){t(e.href)}else if(e.hasAttribute(i)){const t=e.cloneNode(!0);document.head.appendChild(t)}}})),await this.updateDocumentBody(e)})(n),this.restoreScrollPositions(t),this.resetProps(),await this.processInlineModuleScripts(),await this.initMakeReactive(),this.handlerAutofocusAttribute()}restoreScrollPositions(e){requestAnimationFrame((()=>{const t=e.window;t&&window.scrollTo(t.scrollLeft,t.scrollTop),document.querySelectorAll("*").forEach((t=>{const s=this.getElementKey(t);e[s]&&(t.scrollTop=e[s].scrollTop,t.scrollLeft=e[s].scrollLeft)}))}))}PRESERVE_HANDLERS={DETAILS:(e,t)=>(t.open=e.open,!0),INPUT(e,t){const s=e,n=t;return s.value!==n.value&&(n.value=s.value),n.checked=s.checked,document.activeElement!==s||(null!=s.selectionStart&&(n.selectionStart=s.selectionStart,n.selectionEnd=s.selectionEnd),!1)},TEXTAREA(e,t){const s=e,n=t;return s.value!==n.value&&(n.value=s.value),document.activeElement!==s||(n.selectionStart=s.selectionStart,n.selectionEnd=s.selectionEnd,!1)},SELECT(e,t){const s=e;return t.selectedIndex=s.selectedIndex,document.activeElement!==s},VIDEO(e,t){const s=e,n=t;return n.currentTime=s.currentTime,s.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,s=e.body;this._wheelHandlersStashed||(document.querySelectorAll("[onwheel]").forEach((e=>{const t=e.getAttribute("onwheel").trim();if(e.removeAttribute("onwheel"),t){const s=new Function("event",t);e.addEventListener("wheel",s,{passive:!0})}})),this._wheelHandlersStashed=!0);const n=this.PRESERVE_HANDLERS;morphdom(t,s,{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 s=e.tagName;if("SCRIPT"===s||e.hasAttribute("data-nomorph"))return!1;const r=n[s];return!r||r(e,t)},onBeforeNodeDiscarded:e=>(e instanceof HTMLElement&&e.dataset.timerId&&clearTimeout(Number(e.dataset.timerId)),!0)})}catch(e){console.error("Error populating document body:",e)}}async updateDocumentBody(e){try{const t=e.body.cloneNode(!0);this.manageScriptTags(t),document.body.replaceWith(t)}catch(e){console.error("Error populating document body:",e)}}manageScriptTags(e,t){const s=e.querySelectorAll("script"),n=t?.querySelectorAll("script")||s;s.forEach(((e,t)=>{const s=document.createElement("script"),r=n[t]||e;Array.from(r.attributes).forEach((e=>{s.setAttribute(e.name,e.value)})),r.hasAttribute("src")||(s.textContent=r.textContent),e.parentNode?.replaceChild(s,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 redirect(e){if(e)try{const t=new URL(e,window.location.origin);t.origin!==window.location.origin?window.location.href=e:(history.pushState(null,"",e),await this.handleNavigation())}catch(e){console.error("Redirect error:",e)}}abortActiveRequest(){this._activeAbortController&&this._activeAbortController.abort()}async fetch(e,t,s=!1){let n;return s?(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-Requested-With":"XMLHttpRequest"}})}isJsonLike(e){if("string"!=typeof e)return!1;const t=e.trim();return!(!/^\{[\s\S]*\}$/.test(t)&&!/^\[[\s\S]*\]$/.test(t))&&!(t.includes("(")||t.includes(")")||t.includes("=>"))}parseJson(e){try{return JSON5.parse(e)}catch(e){return console.error(`Error parsing JSON: ${e.message}. Please ensure the JSON string is valid.`,e),{}}}parseTime(e){if("number"==typeof e)return e;const t=e.match(/^(\d+)(ms|s|m)?$/);if(t){const e=parseInt(t[1],10);switch(t[2]||"ms"){case"ms":default:return e;case"s":return 1e3*e;case"m":return 60*e*1e3}}return 0}scheduleChange(e,t,s,n){setTimeout((()=>{requestAnimationFrame((()=>{e.style[s]=n}))}),t)}async fetchFunction(e,t={},s=!1){try{const n={callback:e,...t},r=window.location.href;let i;if(Object.keys(n).some((e=>{const t=n[e];return t instanceof File||t instanceof FileList&&t.length>0}))){const e=new FormData;Object.keys(n).forEach((t=>{const s=n[t];s instanceof File?e.append(t,s):s instanceof FileList?Array.from(s).forEach((s=>e.append(t,s))):e.append(t,s)})),i={method:"POST",headers:{HTTP_PPHP_WIRE_REQUEST:"true"},body:e}}else i=this.createFetchOptions(n);const a=await this.fetch(r,i,s);if(!a.ok)throw new Error(`Fetch failed with status: ${a.status} ${a.statusText}`);const o=await a.text();try{return JSON.parse(o)}catch{return o}}catch(e){throw console.error("Error in fetchFunction:",e),new Error("Failed to fetch data.")}}processSyncScripts(e){e.forEach((e=>{const t=`script[pp-sync-script="${CSS.escape(e)}"]`,s=document.querySelector(t);if(s){s.remove();const e=document.createElement("script");Array.from(s.attributes).forEach((t=>{e.setAttribute(t.name,t.value)})),s.src?e.src=s.src:e.textContent=s.textContent,e.type=s.type||"module",document.body.appendChild(e)}}))}async sync(...e){try{const t=this.saveScrollPositions();this.saveElementState();const s=e.length>0?e.map((e=>`pp-sync="${e}"`)):['pp-sync="true"'],n=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()}),r=await this.fetch(window.location.href,n),i=await r.text(),a=(new DOMParser).parseFromString(i,"text/html"),o=new Set;s.forEach((e=>{const t=document.querySelectorAll(`[${e}]`),s=a.body.querySelectorAll(`[${e}]`);t.forEach(((e,t)=>{const n=s[t];if(n){if(n.hasAttribute("pp-sync-script")){const e=n.getAttribute("pp-sync-script")||"";e&&o.add(e)}n.querySelectorAll("[pp-sync-script]").forEach((e=>{const t=e.getAttribute("pp-sync-script")||"";t&&o.add(t)})),e.innerHTML=n.innerHTML,this.reRunScripts(e)}}))})),this.processSyncScripts(o),this.restoreElementState(),this.restoreScrollPositions(t),this.attachWireFunctionEvents()}catch(e){console.error("Error in pphpSync:",e)}}async fetchAndUpdateBodyContent(){const e=this.createFetchOptions({secondRequestC69CD:!0,...this.getUrlParams()});this.abortActiveRequest();const t=await this.fetch(window.location.href,e,!0),s=await t.text();await this.updateBodyContent(s)}reRunScripts(e){e.querySelectorAll("script").forEach((e=>{const t=document.createElement("script");Array.from(e.attributes).forEach((e=>{t.setAttribute(e.name,e.value)})),e.hasAttribute("src")||(t.textContent=e.textContent),e.parentNode?.replaceChild(t,e)}))}copyCode(e,t,s,n,r="img",i=2e3){if(!(e instanceof HTMLElement))return;const a=e.closest(`.${t}`)?.querySelector("pre code"),o=a?.textContent?.trim()||"";o?navigator.clipboard.writeText(o).then((()=>{const t=e.querySelector(r);if(t)for(const[e,s]of Object.entries(n))e in t?t[e]=s:t.setAttribute(e,s);setTimeout((()=>{if(t)for(const[e,n]of Object.entries(s))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;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.loadState()}static getInstance(e={}){return PPHPLocalStore.instance||(PPHPLocalStore.instance=new PPHPLocalStore(e)),PPHPLocalStore.instance}setState(e,t=!1){if(this.state={...this.state,...e},this.listeners.forEach((e=>e(this.state))),this.saveState(),t){const e=localStorage.getItem(this.STORAGE_KEY);e&&this.pphp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]: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})}}}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 s=this.params;s.set(e,t),this.updateURL(s)}delete(e){const t=this.params;t.delete(e),this.updateURL(t)}replace(e){const t=new URLSearchParams;for(const s in e){const n=e[s];null!==n&&t.set(s,n)}this.updateURL(t,!0)}updateURL(e,t=!1){const s=`${window.location.pathname}?${e.toString()}`;t?history.replaceState(null,"",s):history.pushState(null,"",s),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();
|