create-prisma-php-app 4.0.0-beta.2 → 4.0.0-beta.4
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.
|
@@ -13,7 +13,7 @@ Defaulting to 2020, but this will stop working in the future.`)),e.ecmaVersion=1
|
|
|
13
13
|
⚠️ Failed to extract mustache expression - unclosed braces`),console.warn(` Content: ${e}`),console.warn(` Starting at position: ${t}
|
|
14
14
|
`),{endIndex:-1,expression:""}}static checkForMismatchedQuotes(e){let t=0,n=0,i=!1;for(let r=0;r<e.length;r++){if(i){i=!1;continue}if(e[r]==="\\"){i=!0;continue}e[r]==="'"&&t++,e[r]==='"'&&n++}return t%2!==0?{hasIssue:!0,message:`Unmatched single quotes (found ${t})`}:n%2!==0?{hasIssue:!0,message:`Unmatched double quotes (found ${n})`}:{hasIssue:!1,message:""}}static isSingleExpression(e){const t=N.decodeEntities(e),n=N.parseContentWithNesting(t);return n.length===1&&n[0].type==="expression"?n[0].expression:null}static extractExpressions(e){const t=N.decodeEntities(e),n=N.parseContentWithNesting(t),i=n.filter(r=>r.type==="expression").map(r=>r.expression).filter(r=>r);return n.some(r=>r.type==="expression")&&i.length===0&&(console.error(`
|
|
15
15
|
❌ Failed to extract expressions from content:`),console.error(` Content: ${e}`),console.error(` Parsed ${n.length} parts, but extracted 0 expressions`),console.error(` This usually means malformed mustache syntax
|
|
16
|
-
`)),i}}class Os{textNodeBindings=new Map;expressionEvaluator;stateManager;componentManager;cleanupObserver;bindingCount=0;constructor(e,t){this.expressionEvaluator=e,this.stateManager=t,this.cleanupObserver=new MutationObserver(n=>{this.cleanupDetachedNodes(n)}),this.cleanupObserver.observe(document.body,{childList:!0,subtree:!0})}cleanupDetachedNodes(e){const t=[];for(const n of e)n.type==="childList"&&n.removedNodes.forEach(i=>{if(i.nodeType===Node.TEXT_NODE)t.push(i);else if(i.nodeType===Node.ELEMENT_NODE){const r=document.createTreeWalker(i,NodeFilter.SHOW_TEXT,null);let a;for(;a=r.nextNode();)t.push(a)}});Promise.resolve().then(()=>{t.forEach(n=>{document.contains(n)||this.cleanupTextNode(n)})})}processTextNode(e,t){if(this.textNodeBindings.has(e)||T.isTextNodeInsideScript(e)||this.isInsideLoopItem(e))return;const n=this.findSlotContext(e),i=e.parentElement,r=n||(i?T.getContextComponent(i):t),a=e.textContent||"",o=N.parse(a);if(!o.some(h=>h.type==="expression"))return;const u=this.resolveComponentRootForElement(e,r),p={originalContent:a,expressions:o,subscriptionIds:[],component:r,componentElement:u};o.filter(h=>h.type==="expression").forEach(h=>{if(!h.expression)return;const f=`text_${Date.now()}_${Math.random()}`,g=this.expressionEvaluator.extractDependencies(h.expression,r,this.stateManager);if(u&&this.componentManager){const E=this.componentManager.getComponentPropDependencies(u,r);g.push(...E)}const m={id:f,selector:"",dependencies:new Set(g),callback:()=>{this.updateTextNode(e)},element:e.parentElement??void 0,component:r};this.stateManager.addSubscription(m),p.subscriptionIds.push(f)}),this.textNodeBindings.set(e,p),this.bindingCount++,this.updateTextNode(e)}findSlotContext(e){let t=e.previousSibling,n=0;for(;t;){if(t.nodeType===Node.COMMENT_NODE){const a=t.textContent||"";if(a==="/pp-slot-context")n++;else if(a.startsWith("pp-slot-context:")){if(n===0)return a.substring(16);n--}}t=t.previousSibling}let i=e.parentElement;for(;i&&i!==document.body;){for(t=i.previousSibling;t;){if(t.nodeType===Node.COMMENT_NODE){const a=t.textContent||"";if(a==="/pp-slot-context")n++;else if(a.startsWith("pp-slot-context:")){if(n===0)return a.substring(16);n--}}t=t.previousSibling}i=i.parentElement}return null}isInsideLoopItem(e){let t=e.parentElement;for(;t&&t!==document.body;){const n=t.previousSibling;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent?.startsWith("pp-for:"))return!0;let i=t.parentElement?.firstChild||null;for(;i;){if(i.nodeType===Node.COMMENT_NODE&&i.textContent?.startsWith("pp-for:")&&i!==t)return!0;i=i.nextSibling}t=t.parentElement}return!1}updateTextNode(e){const t=this.textNodeBindings.get(e);if(!t||!e.parentElement)return;const n=t.component;let i=t.componentElement;(!i||!document.contains(i))&&(i=this.resolveComponentRootForElement(e,n),t.componentElement=i);const a=e.parentElement?.hasAttribute(d.ATTR_PREFIXES.CONTEXT);let o;if(a&&i)o=this.componentManager.buildRestrictedComponentContextWithProps(n,i);else if(o=this.componentManager.buildRestrictedComponentContext(n,!1),i&&this.componentManager.hasStoredProps(i)){const p=this.componentManager.evaluateProps(i);Object.assign(o,p)}const c={};for(const[p,h]of Object.entries(o))typeof h=="function"&&"__pphp_key"in h?c[p]=h.value:c[p]=h;let u="";for(const p of t.expressions)if(p.type==="static")u+=p.content;else if(p.expression)try{const h=this.expressionEvaluator.evaluateExpression(p.expression,c,n);u+=ce(h)}catch(h){console.error(`❌ Text binding evaluation error for "${p.expression}":`,h),console.error(`Component: ${n}`),console.error(`Available variables: [${Object.keys(c).join(", ")}]`),u+=""}e.textContent!==u&&(e.textContent=u)}resolveComponentRootForElement(e,t){const n=document.querySelectorAll(`[${d.ATTR_PREFIXES.COMPONENT}="${t}"]`);if(this.componentManager){for(const i of n)if(this.componentManager.hasStoredProps(i))return i}return n[0]||void 0}cleanupTextNode(e){const t=this.textNodeBindings.get(e);t&&(t.subscriptionIds.forEach(n=>{this.stateManager.removeSubscription(n)}),this.textNodeBindings.delete(e),this.bindingCount=Math.max(0,this.bindingCount-1))}getBindingCount(){return this.textNodeBindings.size}getAllBindings(){return new Map(this.textNodeBindings)}clearAllBindings(){for(const[e]of this.textNodeBindings)this.cleanupTextNode(e)}destroy(){this.cleanupObserver.disconnect(),this.clearAllBindings()}}class Ls{listeners=new Map;on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,...t){const n=this.listeners.get(e);n&&n.forEach(i=>{try{i(...t)}catch(r){console.error(`Event listener error for ${e}:`,r)}})}}class Fs{stateStore={};subscriptions=new Map;updateQueue=new Set;isUpdating=!1;eventBus=new Ls;contextCache=new Map;previousValues=new Map;_subscriptionManager=new Ms;originalStateStore={};domUpdateCallbacks=[];domUpdateScheduled=!1;constructor(){this.setupGlobalStateProxy(),setInterval(()=>{this.subscriptionManager.cleanupStaleSubscriptions()},3e4)}clearSubscriptions(){const e=this._subscriptionManager.getAllSubscriptions();for(const[t]of e)this._subscriptionManager.removeSubscription(t);this.updateQueue.clear()}clearComponentSubscriptions(e){const t=this._subscriptionManager.getAllSubscriptions();for(const[n,i]of t)i.component===e&&this._subscriptionManager.removeSubscription(n)}clearState(){Object.keys(this.stateStore).forEach(e=>{delete this.stateStore[e],delete this.originalStateStore[e]}),this.previousValues.clear(),this.updateQueue.clear(),this.contextCache.clear()}clearComponentState(e){Object.keys(this.stateStore).filter(n=>n.startsWith(`${e}.`)).forEach(n=>{delete this.stateStore[n],delete this.originalStateStore[n],this.previousValues.delete(n)})}onDOMUpdateComplete(e){this.domUpdateCallbacks.push(e),this.domUpdateScheduled||(this.domUpdateScheduled=!0,requestAnimationFrame(()=>{requestAnimationFrame(()=>{const t=[...this.domUpdateCallbacks];this.domUpdateCallbacks=[],this.domUpdateScheduled=!1,t.forEach(n=>{try{n()}catch(i){console.error("DOM update callback error:",i)}})})}))}setInitialState(e,t){if(this.previousValues.set(e,void 0),this.originalStateStore[e]=t,this.previousValues.size>100){const n=this.previousValues.keys().next().value;typeof n=="string"&&this.previousValues.delete(n)}}get subscriptionManager(){return this._subscriptionManager}batchStateUpdates(e){const t=this.isUpdating;this.isUpdating=!0;try{return e()}finally{this.isUpdating=t,!this.isUpdating&&this.updateQueue.size>0&&this.scheduleFlush()}}invalidateContextCache(){this.contextCache.clear()}setupGlobalStateProxy(){this.originalStateStore=this.stateStore,this.stateStore=new Proxy(this.stateStore,{set:(e,t,n,i)=>{const r=e[t],a=Reflect.set(e,t,n,i);return r!==n&&this.notifySubscribers(t),a},get:(e,t)=>Reflect.get(e,t)})}notifySubscribers(e){if(this.eventBus.emit("stateChanged",e),this.updateQueue.add(e),e.includes(".")){const t=e.split(".")[0];this.updateQueue.add(t)}this.notifyPathBasedSubscribers(e),this.isUpdating||this.scheduleFlush()}notifyPathBasedSubscribers(e){const t=this.stateStore[e],n=this.previousValues?.get(e);for(const[i,r]of this.subscriptions)for(const a of r.dependencies)if(this.isPathDependency(a)&&a.startsWith(e+".")){const o=a.substring(e.length+1),c=this.getPathValue(n,o),u=this.getPathValue(t,o);this.deepEqual(c,u)||this.updateQueue.add(a)}}isPathDependency(e){return e.includes(".")&&e.split(".").length>1}getPathValue(e,t){if(!e||typeof e!="object")return;const n=t.split(".");let i=e;for(const r of n){if(i==null)return;if(Array.isArray(i))return r==="length"?i.length:i.map(a=>a?.[r]).filter(a=>a!==void 0);i=i[r]}return i}deepEqual(e,t){if(e===t)return!0;if(e==null||t==null)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length!==t.length?!1:e.every((n,i)=>this.deepEqual(n,t[i]));if(typeof e=="object"&&typeof t=="object"){const n=Object.keys(e),i=Object.keys(t);return n.length!==i.length?!1:n.every(r=>this.deepEqual(e[r],t[r]))}return!1}scheduleFlush=Ns(()=>{this.flushUpdates()},d.DEBOUNCE_MS);flushUpdates(){if(!this.isUpdating){this.isUpdating=!0;try{const e=new Set,t=this.subscriptionManager.getSubscriptionsForKey("*");if(t&&t.size>0&&this.updateQueue.size>0)for(const n of t){const i=this.subscriptionManager.getSubscription(n);if(!i)continue;if(i.element&&!document.contains(i.element)){this.subscriptionManager.removeSubscription(n);continue}const r=i.element??document.body;try{const a=Array.from(this.updateQueue)[0];i.callback(r,{key:a})}catch(a){console.error("Wildcard subscription callback failed:",a)}}for(const n of this.updateQueue){if(e.has(n))continue;e.add(n);const i=this.subscriptionManager.getSubscriptionsForKey(n);if(i)for(const r of i){const a=this.subscriptionManager.getSubscription(r);if(!a)continue;if(a.element&&!document.contains(a.element)){this.subscriptionManager.removeSubscription(r);continue}const o=a.element??document.body;try{a.callback(o,{key:n})}catch(c){console.error("Subscription callback failed:",c)}}}}finally{this.updateQueue.clear(),this.isUpdating=!1}}}getState(){return this.stateStore}setState(e,t){if(this.previousValues.set(e,this.stateStore[e]),this.stateStore[e]=t,this.previousValues.size>100){const n=this.previousValues.keys().next().value;typeof n=="string"&&this.previousValues.delete(n)}}hasState(e){return e in this.originalStateStore}addSubscription(e){this._subscriptionManager.addSubscription(e)}removeSubscription(e){this._subscriptionManager.removeSubscription(e)}onStateChange(e){return this.eventBus.on("stateChanged",e)}batch(e){const t=this.isUpdating;this.isUpdating=!0;try{return e()}finally{this.isUpdating=t,!this.isUpdating&&this.updateQueue.size&&this.flushUpdates()}}getSubscriptions(){return this.subscriptionManager.getAllSubscriptions()}getKeyIndex(){const e=new Map,t=this.subscriptionManager.getAllSubscriptions();for(const[n,i]of t)for(const r of i.dependencies)e.has(r)||e.set(r,new Set),e.get(r).add(n);return e}destroy(){this.clearState(),this.clearSubscriptions(),this.contextCache.clear(),this.previousValues.clear(),this.domUpdateCallbacks=[]}}class de{expressionCache=new z(d.MAX_CACHE_SIZE);dependencyCache=new z(d.MAX_CACHE_SIZE);commonExpressionsCache=new z(100);dependencyParser=new Vs;static CACHE_KEYS={EXPRESSION:(e,t)=>`expr:${e}:${t}`,DEPENDENCY:(e,t)=>`deps:${e}:${t}`,COMMON:e=>`common:${e}`};constructor(){this.precompileCommonExpressions()}normalizeExpression(e){return e.replace(/\r\n/g," ").replace(/\r/g," ").replace(/\n/g," ").replace(/\s+/g," ").trim()}precompileCommonExpressions(){["true","false","null","undefined"].forEach(t=>{const n={fn:new Function("return "+t),contextMap:new Map,dependencies:[t],timestamp:Date.now(),hitCount:0},i=de.CACHE_KEYS.COMMON(t);this.commonExpressionsCache.set(i,n)})}extractDependencies(e,t,n){const i=this.normalizeExpression(e),r=de.CACHE_KEYS.DEPENDENCY(t,i);let a=this.dependencyCache.get(r);return a||(a=this.dependencyParser.extract(i,t,n),this.dependencyCache.set(r,a),a)}evaluateExpression(e,t,n){const i=this.normalizeExpression(e),r=de.CACHE_KEYS.COMMON(i);let a=this.commonExpressionsCache.get(r);if(a){a.hitCount++;try{return a.fn()}catch(u){console.error(`Common expression evaluation failed: "${i}"`,u);return}}const o=de.CACHE_KEYS.EXPRESSION(n,i);a=this.expressionCache.get(o);const c=this.transformContextForEvaluation(t,i);(!a||this.isStale(a))&&(a=this.compileExpression(i,c,n),this.expressionCache.set(o,a)),a.hitCount++;try{const u=this.buildArguments(a.contextMap,c);return a.fn(...u)}catch(u){console.error(`Expression evaluation failed: "${i}"`,u),console.error("Available context:",Object.keys(c));return}}transformContextForEvaluation(e,t){const n={},i=t&&(t.includes("?")||t.includes("&&")||t.includes("||")||t.includes("===")||t.includes("!==")||t.includes("==")||t.includes("!=")||t.includes(">=")||t.includes("<=")||t.includes(">")||t.includes("<")||/^!/.test(t.trim()));for(const[r,a]of Object.entries(e))if(typeof a=="function"&&"__pphp_key"in a){const o=a.value;i||o===null||o===void 0||typeof o=="boolean"||typeof o=="string"||typeof o=="number"?n[r]=o:n[r]=a}else n[r]=a;return n}compileExpression(e,t,n){const i=this.prepareSafeContext(t),r=new Map,a=[];Object.keys(i).forEach((c,u)=>{r.set(c,u),a.push(c)});const o=this.dependencyParser.extract(e,n);return{fn:new Function(...a,`return (${e})`),contextMap:r,dependencies:o,timestamp:Date.now(),hitCount:0}}buildArguments(e,t){const n=new Array(e.size);for(const[i,r]of e)n[r]=t[i];return n}isStale(e){return Date.now()-e.timestamp>3e5}prepareSafeContext(e){const t={};for(const[n,i]of Object.entries(e))Se.has(n)||!this.isValidJavaScriptIdentifier(n)||(t[n]=i);return t}isValidJavaScriptIdentifier(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)&&!Se.has(e)}invalidateCache(e){switch(e){case"expressions":this.expressionCache.clear();break;case"dependencies":this.dependencyCache.clear();break;case"common":this.commonExpressionsCache.clear(),this.precompileCommonExpressions();break;case"parser":this.dependencyParser.clearCache();break;default:this.clearAllCaches()}}invalidateByComponent(e){this.expressionCache.deleteByPrefix(`expr:${e}:`),this.dependencyCache.deleteByPrefix(`deps:${e}:`)}clearAllCaches(){this.expressionCache.clear(),this.dependencyCache.clear(),this.commonExpressionsCache.clear(),this.dependencyParser.clearCache(),this.precompileCommonExpressions()}getCacheStats(){return{expressions:this.expressionCache.getStats(),dependencies:this.dependencyCache.getStats(),commonExpressions:this.commonExpressionsCache.getStats(),dependencyParser:this.getDependencyParserStats()}}getDependencyParserStats(){return this.dependencyParser.getCacheSize?{size:this.dependencyParser.getCacheSize(),maxSize:500,hitRate:0,hits:0,misses:0}:{size:0,maxSize:0,hitRate:0,hits:0,misses:0}}cleanupStaleExpressions(){let e=0;return this.expressionCache.keys().forEach(n=>{const i=this.expressionCache.get(n);i&&this.isStale(i)&&(this.expressionCache.delete(n),e++)}),e}}class Vs{parseCache=new z(500);extract(e,t,n){const i=this.normalizeExpression(e),r=`${t}:${i}`;if(this.parseCache.has(r))return this.parseCache.get(r);const a=this.parseExpression(i,t,n);return this.parseCache.set(r,a),a}normalizeExpression(e){return e.replace(/\r\n/g," ").replace(/\r/g," ").replace(/\n/g," ").replace(/\s+/g," ").trim()}parseExpression(e,t,n){const i=this.extractIdentifiers(e),r=[],a=n?.getState()||{};for(const c of i){if(Se.has(c))continue;const u=c.indexOf("."),p=u===-1?c:c.substring(0,u),h=Ue.findExistingStateKey(p,t,a);if(h)r.push(h);else{const f=t==="app"?[`app.${p}`]:[`${t}.${p}`,`app.${p}`];r.push(...f)}if(u!==-1){const f=t==="app"?[`app.${p}`]:[`${t}.${p}`,`app.${p}`];r.push(...f)}}return Array.from(new Set(r))}extractIdentifiers(e){const t=[];let n=0;for(;n<e.length;){const i=e[n];if(i==="'"){n=this.skipString(e,n,"'");continue}if(i==='"'){n=this.skipString(e,n,'"');continue}if(i==="`"){n=this.skipTemplateLiteral(e,n,t);continue}if(this.isIdentifierStart(i)){const r=this.extractIdentifier(e,n);t.push(r.value),n=r.endIndex;continue}n++}return t}skipString(e,t,n){let i=t+1;for(;i<e.length&&e[i]!==n;)e[i]==="\\"&&i++,i++;return i+1}skipTemplateLiteral(e,t,n){let i=t+1;for(;i<e.length&&e[i]!=="`";){if(e[i]==="$"&&i+1<e.length&&e[i+1]==="{"){i+=2;let r=1;for(;i<e.length&&r>0;){const a=e[i];if(a==='"'||a==="'"){i=this.skipString(e,i,a);continue}if(a==="{"?r++:a==="}"&&r--,r>0&&this.isIdentifierStart(a)){const o=this.extractIdentifier(e,i);n.push(o.value),i=o.endIndex-1}i++}continue}e[i]==="\\"&&i++,i++}return i+1}extractIdentifier(e,t){let n=t;for(;n<e.length&&(this.isIdentifierPart(e[n])||e[n]===".");)n++;return{value:e.substring(t,n),endIndex:n}}isIdentifierStart(e){return/[a-zA-Z_$]/.test(e)}isIdentifierPart(e){return/[a-zA-Z0-9_$]/.test(e)}clearCache(){this.parseCache.clear()}getCacheSize(){return this.parseCache.cache.size}}class Ds{componentStack=["app"];elementProps=new WeakMap;contextCache=new z(100);contextIndex=new Map;contextInvalidated=new Set;stateManager;processedScripts=new WeakSet;componentFunctions=new Map;expressionEvaluator;domBindingManager;loopManager;templateRenderer;updateTimeouts;updateBatcher=new rt;propDependencyCache=new Map;constructor(e){this.stateManager=e,this.updateBatcher=new rt,this.stateManager.onStateChange(t=>this.invalidateContextCache(t))}getPropDependencies(e,t){const n=this.findElementWithProps(t);if(!n)return[];const i=this.elementProps.get(n);if(!i||!i.has(e))return[];const r=i.get(e);return this.templateRenderer?.dependencies(r.expression,r.component,this.stateManager)||[]}buildRestrictedComponentContext(e,t=!1){const n={};window[e]&&Object.assign(n,window[e]);const i=this.componentFunctions.get(e);if(i)for(const[a,o]of i)n[a]=o;const r=this.stateManager.getState();for(const a of Object.keys(r))if(a.startsWith(e+".")){const o=a.substring(e.length+1);o in n||(n[o]=r[a])}if(t){if(window.app)for(const[o,c]of Object.entries(window.app))o in n||(n[o]=c);const a=this.componentFunctions.get("app");if(a)for(const[o,c]of a)o in n||(n[o]=c);for(const o of Object.keys(r))if(o.startsWith("app.")){const c=o.substring(4);c in n||(n[c]=r[o])}}return n}getComponentPropDependencies(e,t){if(this.propDependencyCache.has(e))return this.propDependencyCache.get(e);const n=[],i=this.elementProps.get(e);i&&this.templateRenderer&&i.forEach(a=>{const o=this.templateRenderer?.dependencies(a.expression,a.component,this.stateManager);n.push(...o??[])});const r=Array.from(new Set(n));return this.propDependencyCache.set(e,r),r}setDOMBindingManager(e){this.domBindingManager=e,this.updateBatcher.setManagers(this,e)}hasStoredProps(e){return this.elementProps.has(e)&&this.elementProps.get(e).size>0}setExpressionEvaluator(e){this.expressionEvaluator=e,this.templateRenderer=new Je(e),this.loopManager=new jt(this.stateManager,e)}extractProps(e,t){const n=new Map,i=e.attributes,r=e.getAttribute(d.ATTR_PREFIXES.CONTEXT),a=e.getAttribute(d.ATTR_PREFIXES.COMPONENT);let o=t;r&&(r==="app"?o="app":o=r);for(let c=0;c<i.length;c++){const u=i[c];if(!(u.name===d.ATTR_PREFIXES.COMPONENT||u.name===d.ATTR_PREFIXES.CONTEXT||u.name===d.ATTR_PREFIXES.SPREAD||u.name===d.ATTR_PREFIXES.LOOP)&&!fe.isEventAttribute(u.name)&&u.value&&Rs.containsMustacheExpression(u.value)){if(a&&this.mightReferenceSelfProps(u.value,e))continue;const p=this.attributeToPropName(u.name),h={name:p,expression:u.value,component:o,subscriptionIds:[]};n.set(p,h)}}return n}mightReferenceSelfProps(e,t){const n=this.elementProps.get(t);if(!n)return!1;const i=Array.from(n.keys()),r=N.extractExpressions(e);if(r.length===0)return!1;for(const a of r)try{const o=F(a,{ecmaVersion:2022,sourceType:"script"}),c=new Set,u=new Set;H(o,{Identifier:(p,h)=>{const f=h?.[h.length-1];f?.type==="MemberExpression"&&f.property===p&&!f.computed||(f?.type==="FunctionExpression"||f?.type==="ArrowFunctionExpression")&&(f.params||[]).includes(p)||(f?.type==="MemberExpression"&&f.object===p?u.add(p.name):c.add(p.name))}});for(const p of i){if(p==="dataState")continue;const h=c.has(p),f=u.has(p)&&!c.has(p);if(h&&!f)return!0}}catch(o){console.error(`❌ Failed to parse mustache expression "${a}":`,o);continue}return!1}attributeToPropName(e){return e.replace(/-([a-z])/g,(t,n)=>n.toUpperCase())}setupProps(e,t){const n=this.extractProps(e,t);n.size!==0&&(this.elementProps.set(e,n),this.expressionEvaluator&&n.forEach((i,r)=>{this.setupPropBinding(e,i)}))}setupPropBinding(e,t){if(!this.expressionEvaluator)return;const n=`prop_${Date.now()}_${Math.random()}`,i=this.templateRenderer?.dependencies(t.expression,t.component,this.stateManager)||[],r={id:n,selector:"",dependencies:new Set(i),callback:()=>{const a=e.getAttribute(d.ATTR_PREFIXES.COMPONENT);a&&(this.updateBatcher.scheduleUpdate(a,e),this.refreshComponentBindings(e,a))},element:e,component:t.component};this.stateManager.addSubscription(r),t.subscriptionIds.push(n)}refreshComponentBindings(e,t){this.contextInvalidated.add(t),this.contextCache.delete(t),this.domBindingManager&&this.domBindingManager.refreshComponentElement(e,t)}evaluateProps(e){const t={},n=this.elementProps.get(e);if(!n||!this.expressionEvaluator)return t;const i=n.values().next().value;if(!i)return t;const r=this.buildComponentContext(i.component);return n.forEach((a,o)=>{try{const c=this.templateRenderer?.render(a.expression,r,a.component);typeof c=="function"?"__pphp_key"in c?t[o]=c:t[o]=(...u)=>c.apply(this,u):t[o]=c}catch(c){console.error(`❌ Failed to evaluate prop "${o}":`,c),t[o]=void 0}}),t}cleanupProps(e){const t=this.elementProps.get(e);t&&(t.forEach(n=>{n.subscriptionIds.forEach(i=>{this.stateManager.removeSubscription(i)})}),this.elementProps.delete(e))}buildComponentContextWithProps(e,t){const n=this.buildComponentContext(e);let i=this.findElementWithProps(e);if(t&&this.elementProps.has(t)&&(i=t),i)try{const r=this.evaluatePropsWithContext(i,e,t);Object.keys(r).length>0&&Object.keys(r).forEach(a=>{n[a]=r[a]})}catch(r){console.error(`❌ Error evaluating props for ${e}:`,r)}return n}buildRestrictedComponentContextWithProps(e,t){const n=this.buildRestrictedComponentContext(e,!1);if(this.elementProps.has(t)){const i=this.evaluateProps(t);Object.assign(n,i)}return n}evaluatePropsWithContext(e,t,n){const i={},r=this.elementProps.get(e);if(!r||!this.expressionEvaluator)return i;const a=r.values().next().value;if(!a)return i;const o=e.getAttribute(d.ATTR_PREFIXES.CONTEXT);let c;o?o==="app"?c=this.buildComponentContext("app"):c=this.buildComponentContext(o):c=this.buildComponentContext(a.component);const u=this.loopManager?.getLoopContextForElement(e);u&&(c={...c,...u});const p=new Map,h=new Map,f=Array.from(r.keys());r.forEach((m,E)=>{f.some(v=>v!==E&&m.expression.includes(v))?h.set(E,m):p.set(E,m)}),p.forEach((m,E)=>{try{const y=this.templateRenderer?.render(m.expression,c,o||m.component);i[E]=y}catch(y){console.error(`❌ Failed to evaluate prop "${E}":`,y),i[E]=void 0}});const g={...c,...i};return h.forEach((m,E)=>{try{const y=this.templateRenderer?.render(m.expression,g,o||m.component);i[E]=y}catch(y){console.error(`❌ Failed to evaluate prop "${E}":`,y),i[E]=void 0}}),i}findElementWithProps(e){const t=document.querySelectorAll(`[${d.ATTR_PREFIXES.COMPONENT}="${e}"]`);for(const n of t){const i=this.elementProps.get(n);if(i&&i.size>0)return n}return null}pushComponent(e){this.componentStack.push(e)}popComponent(){return this.componentStack.pop()}getCurrentComponent(){return this.componentStack[this.componentStack.length-1]}buildComponentContext(e){if(!this.contextInvalidated.has(e)&&this.contextCache.has(e))return this.contextCache.get(e);const t=this.computeComponentContext(e);return this.contextCache.set(e,t),this.contextInvalidated.delete(e),t}computeComponentContext(e){const t={};if(e.includes("_loop_")||e.match(/_[a-zA-Z0-9]{8}$/)){const r=e.split("_");r.pop();const a=r.join("_");window[a]&&Object.assign(t,window[a])}e!=="app"&&window[e]&&Object.assign(t,window[e]),e==="app"&&window.app&&Object.assign(t,window.app);const n=this.componentFunctions.get(e);if(n)for(const[r,a]of n)t[r]=a;if(e!=="app"){const r=this.componentFunctions.get("app");if(r)for(const[a,o]of r)a in t||(t[a]=o);if(window.app)for(const[a,o]of Object.entries(window.app))a in t||(t[a]=o)}const i=this.stateManager.getState();for(const r of Object.keys(i))if(r.startsWith(e+".")){const a=r.substring(e.length+1);a in t||(t[a]=i[r])}if(e!=="app"){for(const r of Object.keys(i))if(r.startsWith("app.")){const a=r.substring(4);a in t||(t[a]=i[r])}}return t}invalidateContextCache(e){if(e.startsWith("app.")){this.contextCache.clear();for(const n of this.contextInvalidated.keys())this.contextInvalidated.add(n);return}const t=e.indexOf(".");if(t!==-1){const n=e.slice(0,t);this.invalidateComponent(n)}}invalidateComponent(e){this.contextInvalidated.add(e),this.contextIndex.delete(e)}executePhpScripts(e){const t=this.componentStack.length,n=e.getAttribute(d.ATTR_PREFIXES.COMPONENT),i=e===document.body;if(n||i){if(n){this.pushComponent(n);const a=this.getParentComponent(e);this.setupProps(e,a)}this.getRelevantScripts(e,i).forEach(a=>{const o=a.getAttribute(d.ATTR_PREFIXES.COMPONENT);o&&o!==n?(this.pushComponent(o),this.executeScript(a),this.popComponent()):this.executeScript(a)})}for(Array.from(e.children).forEach(r=>this.executePhpScripts(r));this.componentStack.length>t;)this.popComponent()}getParentComponent(e){let t=e.parentElement;for(;t;){const n=t.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(n)return n;t=t.parentElement}return"app"}getRelevantScripts(e,t){return Array.from(e.querySelectorAll(`script[type="${d.SCRIPT_TYPE}"]`)).filter(n=>{if(this.processedScripts.has(n))return!1;if(t)return n.hasAttribute(d.ATTR_PREFIXES.COMPONENT)?!0:!n.closest(`[${d.ATTR_PREFIXES.COMPONENT}]`);let i=n.parentElement;for(;i&&i!==e;){if(i.hasAttribute(d.ATTR_PREFIXES.COMPONENT))return!1;i=i.parentElement}return i===e||e.contains(n)})}executeScript(e){if(this.processedScripts.has(e))return;this.processedScripts.add(e);const t=this.getCurrentComponent(),n=e.textContent||"",i=N.decodeEntities(n);try{const r=this.findComponentElementForScript(e,t);if(r===e){const c=this.getParentComponent(e);this.setupProps(e,c)}const a=this.hasExplicitContext(r||e,t);let o;if(a)o=this.buildComponentContextWithProps(t,r);else if(o=this.buildRestrictedComponentContext(t,!1),r&&this.hasStoredProps(r)){const c=this.evaluateProps(r);Object.assign(o,c)}window[t]||(window[t]={}),this.executeScriptFunctions(i,t,o)}catch(r){console.error(`Script execution failed in component ${t}:`,r),console.error("Script content:",i)}}hasExplicitContext(e,t){if(e.hasAttribute(d.ATTR_PREFIXES.CONTEXT))return!0;let n=e;for(;n&&n!==document.body;){if(n.getAttribute(d.ATTR_PREFIXES.COMPONENT)===t){if(n.hasAttribute(d.ATTR_PREFIXES.CONTEXT))return!0;break}n=n.parentElement}for(n=e.parentElement;n&&n!==document.body;){if(n.hasAttribute(d.ATTR_PREFIXES.CONTEXT)&&n.getAttribute(d.ATTR_PREFIXES.CONTEXT)==="app")return!0;n=n.parentElement}return!1}findComponentElementForScript(e,t){if(e.getAttribute(d.ATTR_PREFIXES.COMPONENT)===t)return e;let n=e.parentElement;for(;n;){if(n.getAttribute(d.ATTR_PREFIXES.COMPONENT)===t)return n;n=n.parentElement}const i=document.querySelectorAll(`[${d.ATTR_PREFIXES.COMPONENT}="${t}"]`);for(const r of i)if(this.elementProps.has(r))return r;return i[0]||void 0}executeScriptFunctions(e,t,n){const i=this.extractFunctionNames(e),r=this.findElementWithProps(t),a=this.extractVariableDeclarations(e);let o={...n};if(a.forEach(E=>{delete o[E];const y=`set${Wt(E)}`,v=`${E}Getter`;delete o[y],delete o[v]}),r){const E=this.evaluateProps(r);Object.assign(o,E)}o.getContext=()=>this.buildComponentContextWithProps(t),o.withContext=E=>{const y=this.buildComponentContextWithProps(t);return E.call(y,y)},o.__getProp=E=>{if(r)return this.evaluateProps(r)[E]};const c=Q.getInstance(),u=new Set;if(r){const E=this.evaluateProps(r);for(const[y,v]of Object.entries(E))typeof v=="function"&&"__pphp_key"in v&&(u.add(y),/^set[A-Z]/.test(y)&&u.add(y))}let p=c.transformStateDeclarations(e,u);p=this.modifyScriptForReactiveProps(p,t,r||void 0);const h=`
|
|
16
|
+
`)),i}}class Os{textNodeBindings=new Map;expressionEvaluator;stateManager;componentManager;cleanupObserver;bindingCount=0;constructor(e,t){this.expressionEvaluator=e,this.stateManager=t,this.cleanupObserver=new MutationObserver(n=>{this.cleanupDetachedNodes(n)}),this.cleanupObserver.observe(document.body,{childList:!0,subtree:!0})}cleanupDetachedNodes(e){const t=[];for(const n of e)n.type==="childList"&&n.removedNodes.forEach(i=>{if(i.nodeType===Node.TEXT_NODE)t.push(i);else if(i.nodeType===Node.ELEMENT_NODE){const r=document.createTreeWalker(i,NodeFilter.SHOW_TEXT,null);let a;for(;a=r.nextNode();)t.push(a)}});Promise.resolve().then(()=>{t.forEach(n=>{document.contains(n)||this.cleanupTextNode(n)})})}processTextNode(e,t){if(this.textNodeBindings.has(e)||T.isTextNodeInsideScript(e)||this.isInsideLoopItem(e))return;const n=this.findSlotContext(e),i=e.parentElement,r=n||(i?T.getContextComponent(i):t),a=e.textContent||"",o=N.parse(a);if(!o.some(h=>h.type==="expression"))return;const u=this.resolveComponentRootForElement(e,r),p={originalContent:a,expressions:o,subscriptionIds:[],component:r,componentElement:u};o.filter(h=>h.type==="expression").forEach(h=>{if(!h.expression)return;const f=`text_${Date.now()}_${Math.random()}`,g=this.expressionEvaluator.extractDependencies(h.expression,r,this.stateManager);if(u&&this.componentManager){const E=this.componentManager.getComponentPropDependencies(u,r);g.push(...E)}const m={id:f,selector:"",dependencies:new Set(g),callback:()=>{this.updateTextNode(e)},element:e.parentElement??void 0,component:r};this.stateManager.addSubscription(m),p.subscriptionIds.push(f)}),this.textNodeBindings.set(e,p),this.bindingCount++,this.updateTextNode(e)}findSlotContext(e){let t=e.previousSibling,n=0;for(;t;){if(t.nodeType===Node.COMMENT_NODE){const a=t.textContent||"";if(a==="/pp-slot-context")n++;else if(a.startsWith("pp-slot-context:")){if(n===0)return a.substring(16);n--}}t=t.previousSibling}let i=e.parentElement;for(;i&&i!==document.body;){for(t=i.previousSibling;t;){if(t.nodeType===Node.COMMENT_NODE){const a=t.textContent||"";if(a==="/pp-slot-context")n++;else if(a.startsWith("pp-slot-context:")){if(n===0)return a.substring(16);n--}}t=t.previousSibling}i=i.parentElement}return null}isInsideLoopItem(e){let t=e.parentElement;for(;t&&t!==document.body;){const n=t.previousSibling;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent?.startsWith("pp-for:"))return!0;let i=t.parentElement?.firstChild||null;for(;i;){if(i.nodeType===Node.COMMENT_NODE&&i.textContent?.startsWith("pp-for:")&&i!==t)return!0;i=i.nextSibling}t=t.parentElement}return!1}updateTextNode(e){const t=this.textNodeBindings.get(e);if(!t||!e.parentElement)return;const n=t.component;let i=t.componentElement;(!i||!document.contains(i))&&(i=this.resolveComponentRootForElement(e,n),t.componentElement=i);const a=e.parentElement?.hasAttribute(d.ATTR_PREFIXES.CONTEXT);let o;if(a&&i)o=this.componentManager.buildRestrictedComponentContextWithProps(n,i);else if(o=this.componentManager.buildRestrictedComponentContext(n,!1),i&&this.componentManager.hasStoredProps(i)){const p=this.componentManager.evaluateProps(i);Object.assign(o,p)}const c={};for(const[p,h]of Object.entries(o))typeof h=="function"&&"__pphp_key"in h?c[p]=h.value:c[p]=h;let u="";for(const p of t.expressions)if(p.type==="static")u+=p.content;else if(p.expression)try{const h=this.expressionEvaluator.evaluateExpression(p.expression,c,n);u+=ce(h)}catch(h){console.error(`❌ Text binding evaluation error for "${p.expression}":`,h),console.error(`Component: ${n}`),console.error(`Available variables: [${Object.keys(c).join(", ")}]`),u+=""}e.textContent!==u&&(e.textContent=u)}resolveComponentRootForElement(e,t){const n=document.querySelectorAll(`[${d.ATTR_PREFIXES.COMPONENT}="${t}"]`);if(this.componentManager){for(const i of n)if(this.componentManager.hasStoredProps(i))return i}return n[0]||void 0}cleanupTextNode(e){const t=this.textNodeBindings.get(e);t&&(t.subscriptionIds.forEach(n=>{this.stateManager.removeSubscription(n)}),this.textNodeBindings.delete(e),this.bindingCount=Math.max(0,this.bindingCount-1))}getBindingCount(){return this.textNodeBindings.size}getAllBindings(){return new Map(this.textNodeBindings)}clearAllBindings(){for(const[e]of this.textNodeBindings)this.cleanupTextNode(e)}destroy(){this.cleanupObserver.disconnect(),this.clearAllBindings()}}class Ls{listeners=new Map;on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,...t){const n=this.listeners.get(e);n&&n.forEach(i=>{try{i(...t)}catch(r){console.error(`Event listener error for ${e}:`,r)}})}}class Fs{subscriptionManager=new Ms;stateStore={};updateQueue=new Set;isUpdating=!1;eventBus=new Ls;contextCache=new Map;previousValues=new Map;originalStateStore={};domUpdateCallbacks=[];domUpdateScheduled=!1;constructor(){this.setupGlobalStateProxy(),setInterval(()=>{this.subscriptionManager.cleanupStaleSubscriptions()},3e4)}clearSubscriptions(){const e=this.subscriptionManager.getAllSubscriptions();for(const[t]of e)this.subscriptionManager.removeSubscription(t);this.updateQueue.clear()}clearComponentSubscriptions(e){const t=this.subscriptionManager.getAllSubscriptions();for(const[n,i]of t)i.component===e&&this.subscriptionManager.removeSubscription(n)}clearState(){Object.keys(this.stateStore).forEach(e=>{delete this.stateStore[e],delete this.originalStateStore[e]}),this.previousValues.clear(),this.updateQueue.clear(),this.contextCache.clear()}clearComponentState(e){Object.keys(this.stateStore).filter(n=>n.startsWith(`${e}.`)).forEach(n=>{delete this.stateStore[n],delete this.originalStateStore[n],this.previousValues.delete(n)})}onDOMUpdateComplete(e){this.domUpdateCallbacks.push(e),this.domUpdateScheduled||(this.domUpdateScheduled=!0,requestAnimationFrame(()=>{requestAnimationFrame(()=>{const t=[...this.domUpdateCallbacks];this.domUpdateCallbacks=[],this.domUpdateScheduled=!1,t.forEach(n=>{try{n()}catch(i){console.error("DOM update callback error:",i)}})})}))}setInitialState(e,t){if(this.previousValues.set(e,void 0),this.originalStateStore[e]=t,this.previousValues.size>100){const n=this.previousValues.keys().next().value;typeof n=="string"&&this.previousValues.delete(n)}}batchStateUpdates(e){const t=this.isUpdating;this.isUpdating=!0;try{return e()}finally{this.isUpdating=t,!this.isUpdating&&this.updateQueue.size>0&&this.scheduleFlush()}}invalidateContextCache(){this.contextCache.clear()}setupGlobalStateProxy(){this.originalStateStore=this.stateStore,this.stateStore=new Proxy(this.stateStore,{set:(e,t,n,i)=>{const r=e[t],a=Reflect.set(e,t,n,i);return r!==n&&this.notifySubscribers(t),a},get:(e,t)=>Reflect.get(e,t)})}notifySubscribers(e){if(this.eventBus.emit("stateChanged",e),this.updateQueue.add(e),e.includes(".")){const t=e.split(".")[0];this.updateQueue.add(t)}this.notifyPathBasedSubscribers(e),this.isUpdating||this.scheduleFlush()}notifyPathBasedSubscribers(e){const t=this.stateStore[e],n=this.previousValues?.get(e),i=this.subscriptionManager.getAllSubscriptions();for(const[r,a]of i)for(const o of a.dependencies)if(this.isPathDependency(o)&&o.startsWith(e+".")){const c=o.substring(e.length+1),u=this.getPathValue(n,c),p=this.getPathValue(t,c);this.deepEqual(u,p)||this.updateQueue.add(o)}}isPathDependency(e){return e.includes(".")&&e.split(".").length>1}getPathValue(e,t){if(!e||typeof e!="object")return;const n=t.split(".");let i=e;for(const r of n){if(i==null)return;if(Array.isArray(i))return r==="length"?i.length:i.map(a=>a?.[r]).filter(a=>a!==void 0);i=i[r]}return i}deepEqual(e,t){if(e===t)return!0;if(e==null||t==null)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length!==t.length?!1:e.every((n,i)=>this.deepEqual(n,t[i]));if(typeof e=="object"&&typeof t=="object"){const n=Object.keys(e),i=Object.keys(t);return n.length!==i.length?!1:n.every(r=>this.deepEqual(e[r],t[r]))}return!1}scheduleFlush=Ns(()=>{this.flushUpdates()},d.DEBOUNCE_MS);flushUpdates(){if(!this.isUpdating){this.isUpdating=!0;try{const e=new Set,t=this.subscriptionManager.getSubscriptionsForKey("*");if(t&&t.size>0&&this.updateQueue.size>0)for(const n of t){const i=this.subscriptionManager.getSubscription(n);if(!i)continue;if(i.element&&!document.contains(i.element)){this.subscriptionManager.removeSubscription(n);continue}const r=i.element??document.body;try{const a=Array.from(this.updateQueue)[0];i.callback(r,{key:a})}catch(a){console.error("Wildcard subscription callback failed:",a)}}for(const n of this.updateQueue){if(e.has(n))continue;e.add(n);const i=this.subscriptionManager.getSubscriptionsForKey(n);if(i)for(const r of i){const a=this.subscriptionManager.getSubscription(r);if(!a)continue;if(a.element&&!document.contains(a.element)){this.subscriptionManager.removeSubscription(r);continue}const o=a.element??document.body;try{a.callback(o,{key:n})}catch(c){console.error("Subscription callback failed:",c)}}}}finally{this.updateQueue.clear(),this.isUpdating=!1}}}getState(){return this.stateStore}setState(e,t){if(this.previousValues.set(e,this.stateStore[e]),this.stateStore[e]=t,this.previousValues.size>100){const n=this.previousValues.keys().next().value;typeof n=="string"&&this.previousValues.delete(n)}}hasState(e){return e in this.originalStateStore}addSubscription(e){this.subscriptionManager.addSubscription(e)}removeSubscription(e){this.subscriptionManager.removeSubscription(e)}onStateChange(e){return this.eventBus.on("stateChanged",e)}batch(e){const t=this.isUpdating;this.isUpdating=!0;try{return e()}finally{this.isUpdating=t,!this.isUpdating&&this.updateQueue.size&&this.flushUpdates()}}getSubscriptions(){return this.subscriptionManager.getAllSubscriptions()}getKeyIndex(){const e=new Map,t=this.subscriptionManager.getAllSubscriptions();for(const[n,i]of t)for(const r of i.dependencies)e.has(r)||e.set(r,new Set),e.get(r).add(n);return e}destroy(){this.clearState(),this.clearSubscriptions(),this.contextCache.clear(),this.previousValues.clear(),this.domUpdateCallbacks=[]}}class de{expressionCache=new z(d.MAX_CACHE_SIZE);dependencyCache=new z(d.MAX_CACHE_SIZE);commonExpressionsCache=new z(100);dependencyParser=new Vs;static CACHE_KEYS={EXPRESSION:(e,t)=>`expr:${e}:${t}`,DEPENDENCY:(e,t)=>`deps:${e}:${t}`,COMMON:e=>`common:${e}`};constructor(){this.precompileCommonExpressions()}normalizeExpression(e){return e.replace(/\r\n/g," ").replace(/\r/g," ").replace(/\n/g," ").replace(/\s+/g," ").trim()}precompileCommonExpressions(){["true","false","null","undefined"].forEach(t=>{const n={fn:new Function("return "+t),contextMap:new Map,dependencies:[t],timestamp:Date.now(),hitCount:0},i=de.CACHE_KEYS.COMMON(t);this.commonExpressionsCache.set(i,n)})}extractDependencies(e,t,n){const i=this.normalizeExpression(e),r=de.CACHE_KEYS.DEPENDENCY(t,i);let a=this.dependencyCache.get(r);return a||(a=this.dependencyParser.extract(i,t,n),this.dependencyCache.set(r,a),a)}evaluateExpression(e,t,n){const i=this.normalizeExpression(e),r=de.CACHE_KEYS.COMMON(i);let a=this.commonExpressionsCache.get(r);if(a){a.hitCount++;try{return a.fn()}catch(u){console.error(`Common expression evaluation failed: "${i}"`,u);return}}const o=de.CACHE_KEYS.EXPRESSION(n,i);a=this.expressionCache.get(o);const c=this.transformContextForEvaluation(t,i);(!a||this.isStale(a))&&(a=this.compileExpression(i,c,n),this.expressionCache.set(o,a)),a.hitCount++;try{const u=this.buildArguments(a.contextMap,c);return a.fn(...u)}catch(u){console.error(`Expression evaluation failed: "${i}"`,u),console.error("Available context:",Object.keys(c));return}}transformContextForEvaluation(e,t){const n={},i=t&&(t.includes("?")||t.includes("&&")||t.includes("||")||t.includes("===")||t.includes("!==")||t.includes("==")||t.includes("!=")||t.includes(">=")||t.includes("<=")||t.includes(">")||t.includes("<")||/^!/.test(t.trim()));for(const[r,a]of Object.entries(e))if(typeof a=="function"&&"__pphp_key"in a){const o=a.value;i||o===null||o===void 0||typeof o=="boolean"||typeof o=="string"||typeof o=="number"?n[r]=o:n[r]=a}else n[r]=a;return n}compileExpression(e,t,n){const i=this.prepareSafeContext(t),r=new Map,a=[];Object.keys(i).forEach((c,u)=>{r.set(c,u),a.push(c)});const o=this.dependencyParser.extract(e,n);return{fn:new Function(...a,`return (${e})`),contextMap:r,dependencies:o,timestamp:Date.now(),hitCount:0}}buildArguments(e,t){const n=new Array(e.size);for(const[i,r]of e)n[r]=t[i];return n}isStale(e){return Date.now()-e.timestamp>3e5}prepareSafeContext(e){const t={};for(const[n,i]of Object.entries(e))Se.has(n)||!this.isValidJavaScriptIdentifier(n)||(t[n]=i);return t}isValidJavaScriptIdentifier(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)&&!Se.has(e)}invalidateCache(e){switch(e){case"expressions":this.expressionCache.clear();break;case"dependencies":this.dependencyCache.clear();break;case"common":this.commonExpressionsCache.clear(),this.precompileCommonExpressions();break;case"parser":this.dependencyParser.clearCache();break;default:this.clearAllCaches()}}invalidateByComponent(e){this.expressionCache.deleteByPrefix(`expr:${e}:`),this.dependencyCache.deleteByPrefix(`deps:${e}:`)}clearAllCaches(){this.expressionCache.clear(),this.dependencyCache.clear(),this.commonExpressionsCache.clear(),this.dependencyParser.clearCache(),this.precompileCommonExpressions()}getCacheStats(){return{expressions:this.expressionCache.getStats(),dependencies:this.dependencyCache.getStats(),commonExpressions:this.commonExpressionsCache.getStats(),dependencyParser:this.getDependencyParserStats()}}getDependencyParserStats(){return this.dependencyParser.getCacheSize?{size:this.dependencyParser.getCacheSize(),maxSize:500,hitRate:0,hits:0,misses:0}:{size:0,maxSize:0,hitRate:0,hits:0,misses:0}}cleanupStaleExpressions(){let e=0;return this.expressionCache.keys().forEach(n=>{const i=this.expressionCache.get(n);i&&this.isStale(i)&&(this.expressionCache.delete(n),e++)}),e}}class Vs{parseCache=new z(500);extract(e,t,n){const i=this.normalizeExpression(e),r=`${t}:${i}`;if(this.parseCache.has(r))return this.parseCache.get(r);const a=this.parseExpression(i,t,n);return this.parseCache.set(r,a),a}normalizeExpression(e){return e.replace(/\r\n/g," ").replace(/\r/g," ").replace(/\n/g," ").replace(/\s+/g," ").trim()}parseExpression(e,t,n){const i=this.extractIdentifiers(e),r=[],a=n?.getState()||{};for(const c of i){if(Se.has(c))continue;const u=c.indexOf("."),p=u===-1?c:c.substring(0,u),h=Ue.findExistingStateKey(p,t,a);if(h)r.push(h);else{const f=t==="app"?[`app.${p}`]:[`${t}.${p}`,`app.${p}`];r.push(...f)}if(u!==-1){const f=t==="app"?[`app.${p}`]:[`${t}.${p}`,`app.${p}`];r.push(...f)}}return Array.from(new Set(r))}extractIdentifiers(e){const t=[];let n=0;for(;n<e.length;){const i=e[n];if(i==="'"){n=this.skipString(e,n,"'");continue}if(i==='"'){n=this.skipString(e,n,'"');continue}if(i==="`"){n=this.skipTemplateLiteral(e,n,t);continue}if(this.isIdentifierStart(i)){const r=this.extractIdentifier(e,n);t.push(r.value),n=r.endIndex;continue}n++}return t}skipString(e,t,n){let i=t+1;for(;i<e.length&&e[i]!==n;)e[i]==="\\"&&i++,i++;return i+1}skipTemplateLiteral(e,t,n){let i=t+1;for(;i<e.length&&e[i]!=="`";){if(e[i]==="$"&&i+1<e.length&&e[i+1]==="{"){i+=2;let r=1;for(;i<e.length&&r>0;){const a=e[i];if(a==='"'||a==="'"){i=this.skipString(e,i,a);continue}if(a==="{"?r++:a==="}"&&r--,r>0&&this.isIdentifierStart(a)){const o=this.extractIdentifier(e,i);n.push(o.value),i=o.endIndex-1}i++}continue}e[i]==="\\"&&i++,i++}return i+1}extractIdentifier(e,t){let n=t;for(;n<e.length&&(this.isIdentifierPart(e[n])||e[n]===".");)n++;return{value:e.substring(t,n),endIndex:n}}isIdentifierStart(e){return/[a-zA-Z_$]/.test(e)}isIdentifierPart(e){return/[a-zA-Z0-9_$]/.test(e)}clearCache(){this.parseCache.clear()}getCacheSize(){return this.parseCache.cache.size}}class Ds{componentStack=["app"];elementProps=new WeakMap;contextCache=new z(100);contextIndex=new Map;contextInvalidated=new Set;stateManager;processedScripts=new WeakSet;componentFunctions=new Map;expressionEvaluator;domBindingManager;loopManager;templateRenderer;updateTimeouts;updateBatcher=new rt;propDependencyCache=new Map;constructor(e){this.stateManager=e,this.updateBatcher=new rt,this.stateManager.onStateChange(t=>this.invalidateContextCache(t))}getPropDependencies(e,t){const n=this.findElementWithProps(t);if(!n)return[];const i=this.elementProps.get(n);if(!i||!i.has(e))return[];const r=i.get(e);return this.templateRenderer?.dependencies(r.expression,r.component,this.stateManager)||[]}buildRestrictedComponentContext(e,t=!1){const n={};window[e]&&Object.assign(n,window[e]);const i=this.componentFunctions.get(e);if(i)for(const[a,o]of i)n[a]=o;const r=this.stateManager.getState();for(const a of Object.keys(r))if(a.startsWith(e+".")){const o=a.substring(e.length+1);o in n||(n[o]=r[a])}if(t){if(window.app)for(const[o,c]of Object.entries(window.app))o in n||(n[o]=c);const a=this.componentFunctions.get("app");if(a)for(const[o,c]of a)o in n||(n[o]=c);for(const o of Object.keys(r))if(o.startsWith("app.")){const c=o.substring(4);c in n||(n[c]=r[o])}}return n}getComponentPropDependencies(e,t){if(this.propDependencyCache.has(e))return this.propDependencyCache.get(e);const n=[],i=this.elementProps.get(e);i&&this.templateRenderer&&i.forEach(a=>{const o=this.templateRenderer?.dependencies(a.expression,a.component,this.stateManager);n.push(...o??[])});const r=Array.from(new Set(n));return this.propDependencyCache.set(e,r),r}setDOMBindingManager(e){this.domBindingManager=e,this.updateBatcher.setManagers(this,e)}hasStoredProps(e){return this.elementProps.has(e)&&this.elementProps.get(e).size>0}setExpressionEvaluator(e){this.expressionEvaluator=e,this.templateRenderer=new Je(e),this.loopManager=new jt(this.stateManager,e)}extractProps(e,t){const n=new Map,i=e.attributes,r=e.getAttribute(d.ATTR_PREFIXES.CONTEXT),a=e.getAttribute(d.ATTR_PREFIXES.COMPONENT);let o=t;r&&(r==="app"?o="app":o=r);for(let c=0;c<i.length;c++){const u=i[c];if(!(u.name===d.ATTR_PREFIXES.COMPONENT||u.name===d.ATTR_PREFIXES.CONTEXT||u.name===d.ATTR_PREFIXES.SPREAD||u.name===d.ATTR_PREFIXES.LOOP)&&!fe.isEventAttribute(u.name)&&u.value&&Rs.containsMustacheExpression(u.value)){if(a&&this.mightReferenceSelfProps(u.value,e))continue;const p=this.attributeToPropName(u.name),h={name:p,expression:u.value,component:o,subscriptionIds:[]};n.set(p,h)}}return n}mightReferenceSelfProps(e,t){const n=this.elementProps.get(t);if(!n)return!1;const i=Array.from(n.keys()),r=N.extractExpressions(e);if(r.length===0)return!1;for(const a of r)try{const o=F(a,{ecmaVersion:2022,sourceType:"script"}),c=new Set,u=new Set;H(o,{Identifier:(p,h)=>{const f=h?.[h.length-1];f?.type==="MemberExpression"&&f.property===p&&!f.computed||(f?.type==="FunctionExpression"||f?.type==="ArrowFunctionExpression")&&(f.params||[]).includes(p)||(f?.type==="MemberExpression"&&f.object===p?u.add(p.name):c.add(p.name))}});for(const p of i){if(p==="dataState")continue;const h=c.has(p),f=u.has(p)&&!c.has(p);if(h&&!f)return!0}}catch(o){console.error(`❌ Failed to parse mustache expression "${a}":`,o);continue}return!1}attributeToPropName(e){return e.replace(/-([a-z])/g,(t,n)=>n.toUpperCase())}setupProps(e,t){const n=this.extractProps(e,t);n.size!==0&&(this.elementProps.set(e,n),this.expressionEvaluator&&n.forEach((i,r)=>{this.setupPropBinding(e,i)}))}setupPropBinding(e,t){if(!this.expressionEvaluator)return;const n=`prop_${Date.now()}_${Math.random()}`,i=this.templateRenderer?.dependencies(t.expression,t.component,this.stateManager)||[],r={id:n,selector:"",dependencies:new Set(i),callback:()=>{const a=e.getAttribute(d.ATTR_PREFIXES.COMPONENT);a&&(this.updateBatcher.scheduleUpdate(a,e),this.refreshComponentBindings(e,a))},element:e,component:t.component};this.stateManager.addSubscription(r),t.subscriptionIds.push(n)}refreshComponentBindings(e,t){this.contextInvalidated.add(t),this.contextCache.delete(t),this.domBindingManager&&this.domBindingManager.refreshComponentElement(e,t)}evaluateProps(e){const t={},n=this.elementProps.get(e);if(!n||!this.expressionEvaluator)return t;const i=n.values().next().value;if(!i)return t;const r=this.buildComponentContext(i.component);return n.forEach((a,o)=>{try{const c=this.templateRenderer?.render(a.expression,r,a.component);typeof c=="function"?"__pphp_key"in c?t[o]=c:t[o]=(...u)=>c.apply(this,u):t[o]=c}catch(c){console.error(`❌ Failed to evaluate prop "${o}":`,c),t[o]=void 0}}),t}cleanupProps(e){const t=this.elementProps.get(e);t&&(t.forEach(n=>{n.subscriptionIds.forEach(i=>{this.stateManager.removeSubscription(i)})}),this.elementProps.delete(e))}buildComponentContextWithProps(e,t){const n=this.buildComponentContext(e);let i=this.findElementWithProps(e);if(t&&this.elementProps.has(t)&&(i=t),i)try{const r=this.evaluatePropsWithContext(i,e,t);Object.keys(r).length>0&&Object.keys(r).forEach(a=>{n[a]=r[a]})}catch(r){console.error(`❌ Error evaluating props for ${e}:`,r)}return n}buildRestrictedComponentContextWithProps(e,t){const n=this.buildRestrictedComponentContext(e,!1);if(this.elementProps.has(t)){const i=this.evaluateProps(t);Object.assign(n,i)}return n}evaluatePropsWithContext(e,t,n){const i={},r=this.elementProps.get(e);if(!r||!this.expressionEvaluator)return i;const a=r.values().next().value;if(!a)return i;const o=e.getAttribute(d.ATTR_PREFIXES.CONTEXT);let c;o?o==="app"?c=this.buildComponentContext("app"):c=this.buildComponentContext(o):c=this.buildComponentContext(a.component);const u=this.loopManager?.getLoopContextForElement(e);u&&(c={...c,...u});const p=new Map,h=new Map,f=Array.from(r.keys());r.forEach((m,E)=>{f.some(v=>v!==E&&m.expression.includes(v))?h.set(E,m):p.set(E,m)}),p.forEach((m,E)=>{try{const y=this.templateRenderer?.render(m.expression,c,o||m.component);i[E]=y}catch(y){console.error(`❌ Failed to evaluate prop "${E}":`,y),i[E]=void 0}});const g={...c,...i};return h.forEach((m,E)=>{try{const y=this.templateRenderer?.render(m.expression,g,o||m.component);i[E]=y}catch(y){console.error(`❌ Failed to evaluate prop "${E}":`,y),i[E]=void 0}}),i}findElementWithProps(e){const t=document.querySelectorAll(`[${d.ATTR_PREFIXES.COMPONENT}="${e}"]`);for(const n of t){const i=this.elementProps.get(n);if(i&&i.size>0)return n}return null}pushComponent(e){this.componentStack.push(e)}popComponent(){return this.componentStack.pop()}getCurrentComponent(){return this.componentStack[this.componentStack.length-1]}buildComponentContext(e){if(!this.contextInvalidated.has(e)&&this.contextCache.has(e))return this.contextCache.get(e);const t=this.computeComponentContext(e);return this.contextCache.set(e,t),this.contextInvalidated.delete(e),t}computeComponentContext(e){const t={};if(e.includes("_loop_")||e.match(/_[a-zA-Z0-9]{8}$/)){const r=e.split("_");r.pop();const a=r.join("_");window[a]&&Object.assign(t,window[a])}e!=="app"&&window[e]&&Object.assign(t,window[e]),e==="app"&&window.app&&Object.assign(t,window.app);const n=this.componentFunctions.get(e);if(n)for(const[r,a]of n)t[r]=a;if(e!=="app"){const r=this.componentFunctions.get("app");if(r)for(const[a,o]of r)a in t||(t[a]=o);if(window.app)for(const[a,o]of Object.entries(window.app))a in t||(t[a]=o)}const i=this.stateManager.getState();for(const r of Object.keys(i))if(r.startsWith(e+".")){const a=r.substring(e.length+1);a in t||(t[a]=i[r])}if(e!=="app"){for(const r of Object.keys(i))if(r.startsWith("app.")){const a=r.substring(4);a in t||(t[a]=i[r])}}return t}invalidateContextCache(e){if(e.startsWith("app.")){this.contextCache.clear();for(const n of this.contextInvalidated.keys())this.contextInvalidated.add(n);return}const t=e.indexOf(".");if(t!==-1){const n=e.slice(0,t);this.invalidateComponent(n)}}invalidateComponent(e){this.contextInvalidated.add(e),this.contextIndex.delete(e)}executePhpScripts(e){const t=this.componentStack.length,n=e.getAttribute(d.ATTR_PREFIXES.COMPONENT),i=e===document.body;if(n||i){if(n){this.pushComponent(n);const a=this.getParentComponent(e);this.setupProps(e,a)}this.getRelevantScripts(e,i).forEach(a=>{const o=a.getAttribute(d.ATTR_PREFIXES.COMPONENT);o&&o!==n?(this.pushComponent(o),this.executeScript(a),this.popComponent()):this.executeScript(a)})}for(Array.from(e.children).forEach(r=>this.executePhpScripts(r));this.componentStack.length>t;)this.popComponent()}getParentComponent(e){let t=e.parentElement;for(;t;){const n=t.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(n)return n;t=t.parentElement}return"app"}getRelevantScripts(e,t){return Array.from(e.querySelectorAll(`script[type="${d.SCRIPT_TYPE}"]`)).filter(n=>{if(this.processedScripts.has(n))return!1;if(t)return n.hasAttribute(d.ATTR_PREFIXES.COMPONENT)?!0:!n.closest(`[${d.ATTR_PREFIXES.COMPONENT}]`);let i=n.parentElement;for(;i&&i!==e;){if(i.hasAttribute(d.ATTR_PREFIXES.COMPONENT))return!1;i=i.parentElement}return i===e||e.contains(n)})}executeScript(e){if(this.processedScripts.has(e))return;this.processedScripts.add(e);const t=this.getCurrentComponent(),n=e.textContent||"",i=N.decodeEntities(n);try{const r=this.findComponentElementForScript(e,t);if(r===e){const c=this.getParentComponent(e);this.setupProps(e,c)}const a=this.hasExplicitContext(r||e,t);let o;if(a)o=this.buildComponentContextWithProps(t,r);else if(o=this.buildRestrictedComponentContext(t,!1),r&&this.hasStoredProps(r)){const c=this.evaluateProps(r);Object.assign(o,c)}window[t]||(window[t]={}),this.executeScriptFunctions(i,t,o)}catch(r){console.error(`Script execution failed in component ${t}:`,r),console.error("Script content:",i)}}hasExplicitContext(e,t){if(e.hasAttribute(d.ATTR_PREFIXES.CONTEXT))return!0;let n=e;for(;n&&n!==document.body;){if(n.getAttribute(d.ATTR_PREFIXES.COMPONENT)===t){if(n.hasAttribute(d.ATTR_PREFIXES.CONTEXT))return!0;break}n=n.parentElement}for(n=e.parentElement;n&&n!==document.body;){if(n.hasAttribute(d.ATTR_PREFIXES.CONTEXT)&&n.getAttribute(d.ATTR_PREFIXES.CONTEXT)==="app")return!0;n=n.parentElement}return!1}findComponentElementForScript(e,t){if(e.getAttribute(d.ATTR_PREFIXES.COMPONENT)===t)return e;let n=e.parentElement;for(;n;){if(n.getAttribute(d.ATTR_PREFIXES.COMPONENT)===t)return n;n=n.parentElement}const i=document.querySelectorAll(`[${d.ATTR_PREFIXES.COMPONENT}="${t}"]`);for(const r of i)if(this.elementProps.has(r))return r;return i[0]||void 0}executeScriptFunctions(e,t,n){const i=this.extractFunctionNames(e),r=this.findElementWithProps(t),a=this.extractVariableDeclarations(e);let o={...n};if(a.forEach(E=>{delete o[E];const y=`set${Wt(E)}`,v=`${E}Getter`;delete o[y],delete o[v]}),r){const E=this.evaluateProps(r);Object.assign(o,E)}o.getContext=()=>this.buildComponentContextWithProps(t),o.withContext=E=>{const y=this.buildComponentContextWithProps(t);return E.call(y,y)},o.__getProp=E=>{if(r)return this.evaluateProps(r)[E]};const c=Q.getInstance(),u=new Set;if(r){const E=this.evaluateProps(r);for(const[y,v]of Object.entries(E))typeof v=="function"&&"__pphp_key"in v&&(u.add(y),/^set[A-Z]/.test(y)&&u.add(y))}let p=c.transformStateDeclarations(e,u);p=this.modifyScriptForReactiveProps(p,t,r||void 0);const h=`
|
|
17
17
|
${p}
|
|
18
18
|
|
|
19
19
|
${i.map(E=>`
|
|
@@ -39,4 +39,4 @@ Defaulting to 2020, but this will stop working in the future.`)),e.ecmaVersion=1
|
|
|
39
39
|
console.error('Component:', '${t}');
|
|
40
40
|
console.error('Available context keys:', Object.keys(context));
|
|
41
41
|
}
|
|
42
|
-
`);return this.handlerCache.set(n,r),r}executeHandler(e,t,n){if(!this.componentManager||!this.expressionEvaluator){console.warn("EventDelegationManager dependencies not set");return}try{const i=t.getAttribute(d.ATTR_PREFIXES.CONTEXT),r=t.getAttribute(d.ATTR_PREFIXES.COMPONENT);let a=null;if(r)a=t;else{let f=t;for(;f&&f!==document.body;){if(f.getAttribute(d.ATTR_PREFIXES.COMPONENT)===e.component){a=f;break}f=f.parentElement}}let o=null,c=t.parentElement;for(;c&&c!==document.body;){if(c.hasAttribute(d.ATTR_PREFIXES.COMPONENT)){o=c;break}c=c.parentElement}let u;if(i&&a)u=this.componentManager.buildRestrictedComponentContextWithProps(e.component,a);else if(u=this.componentManager.buildRestrictedComponentContext(e.component,!1),a&&this.componentManager.hasStoredProps(a)){const f=this.componentManager.evaluateProps(a);Object.assign(u,f)}if(o&&o!==a&&this.componentManager.hasStoredProps(o)){const f=this.componentManager.evaluateProps(o);u={...u,...f}}const p={...u};for(const[f,g]of Object.entries(u))typeof g=="function"&&"__pphp_key"in g&&(p[f]=g.value);const h=this.loopManager?.getLoopContextForElement(t);if(h){const f={};for(const[g,m]of Object.entries(h))typeof m=="function"&&"__pphp_key"in m?f[g]=m.value:f[g]=m;u={...p,...f}}else u=p;e.compiledFn||(e.compiledFn=this.compileHandler(e.code,e.component)),e.compiledFn&&e.compiledFn(n,t,u)}catch(i){console.error("💥 Event handler execution failed:",i),console.error("Handler code:",e.code),console.error("Handler component:",e.component)}}attachDirectListener(e,t,n){const i=r=>{this.executeHandler(n,e,r)};e.addEventListener(t,i),e[`__${t}_listener`]=i}removeEventHandler(e,t){const n=this.elementHandlers.get(e);n&&(n.delete(t),n.size===0&&this.elementHandlers.delete(e));const i=this.delegatedEvents.get(t);i&&i.elements.delete?.(e);const r=e[`__${t}_listener`];r&&(e.removeEventListener(t,r),delete e[`__${t}_listener`])}cleanup(){for(const[e,t]of this.delegatedEvents)document.removeEventListener(e,t.listener,!0);this.delegatedEvents.clear(),this.handlerCache.clear(),this.setupEvents.clear()}}class $s{static instance=null;stateManager=new Fs;expressionEvaluator=new de;componentManager=new Ds(this.stateManager);domBindingManager=new Bs(this.stateManager,this.componentManager,this.expressionEvaluator);hydrationCallbacks=new Set;portalManager=new ks;initialized=!1;hydrationDone=!1;hydrationResolve;hydrationPromise;portalHydrationPromises=new Set;portalHydrationResolvers=new Map;constructor(){document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>this.initialize()):setTimeout(()=>this.initialize(),0),this.hydrationPromise=new Promise(e=>this.hydrationResolve=e)}initialize(){this.initialized||(this.initialized=!0,this.markHydrationStart(),this.componentManager.setExpressionEvaluator(this.expressionEvaluator),this.portalManager.setDependencies(this.componentManager,this.domBindingManager,this.stateManager,this),this.componentManager.executePhpScripts(document.body),this.domBindingManager.processElement(document.body,!0),this.domBindingManager.processPendingBindings(),Promise.resolve().then(()=>{requestAnimationFrame(()=>{this.markHydrated()})}))}createPortal(e,t,n){const i=this.portalManager.createPortal(e,t,n),r=new Promise(a=>{this.portalHydrationResolvers.set(i,a)});return this.portalHydrationPromises.add(r),r.finally(()=>{this.portalHydrationPromises.delete(r),this.portalHydrationResolvers.delete(i)}),i}removePortal(e){return this.markPortalHydrated(e),this.portalManager.removePortal(e)}markPortalHydrated(e){const t=this.portalHydrationResolvers.get(e);t&&t()}updatePortal(e,t,n){return this.portalManager.updatePortal(e,t,n)}cleanup(){this.portalManager.destroy(),this.domBindingManager.destroy(),this.componentManager.destroy(),this.stateManager.clearState(),this.stateManager.clearSubscriptions(),this.expressionEvaluator.clearAllCaches(),this.hydrationCallbacks.clear(),this.deleteAllComponentObjects()}ref(e=null){return{current:e}}async hydrated(){await Promise.all([this.hydrationPromise,...Array.from(this.portalHydrationPromises)])}onHydrated(e){this.hydrationDone?queueMicrotask(e):this.hydrationCallbacks.add(e)}get isHydrated(){return this.hydrationDone}markHydrationStart(){document.dispatchEvent(new CustomEvent("pp:hydrationstart"))}markHydrated(){if(!this.hydrationDone){this.hydrationDone=!0,this.hydrationResolve();for(const e of this.hydrationCallbacks)try{e()}catch{}this.hydrationCallbacks.clear(),document.dispatchEvent(new CustomEvent("pp:hydrated",{detail:{at:performance.now()}}))}}state(e,t){const n=this.componentManager.getCurrentComponent();let i,r;typeof e=="string"&&arguments.length===2?(i=e,r=t):typeof e=="string"&&arguments.length===1?this.looksLikeVariableName(e)?(i=e,r=void 0):(console.warn("pp.state() called with string that doesn't look like variable name:",e),i="unknownState",r=e):(console.warn("pp.state() called without explicit key - this should be handled by AST transformation"),i="unknownState",r=e),r&&typeof r=="function"&&"__pphp_key"in r&&(r=r.value);let a;const o=this.getLoopExecutionContext();if(o){const h=this.generateLoopInstanceId(o);a=`${n}.${h}.${i}`}else a=`${n}.${i}`;this.stateManager.hasState(a)||this.stateManager.setInitialState(a,r);const c=(()=>this.stateManager.getState()[a]),u=new Proxy(c,{get(h,f,g){if(f==="__pphp_key"||f==="__pphp_fullKey"||f==="__pphp_component"||f==="value"||f==="valueOf"||f==="toString")return Reflect.get(h,f,g);const m=h();if(m!=null){if(f in Object(m)){const E=m[f];return typeof E=="function"?E.bind(m):E}return Reflect.get(h,f,g)}},has(h,f){if(f==="__pphp_key"||f==="__pphp_fullKey"||f==="__pphp_component"||f==="value"||f==="valueOf"||f==="toString")return Reflect.has(h,f);const g=h();return g!=null&&f in Object(g)?!0:Reflect.has(h,f)},apply(h,f,g){return Reflect.apply(h,f,g)}});Object.defineProperty(u,"__pphp_key",{value:i,enumerable:!1,writable:!1}),Object.defineProperty(u,"__pphp_fullKey",{value:a,enumerable:!1,writable:!1}),Object.defineProperty(u,"__pphp_component",{value:n,enumerable:!1,writable:!1}),Object.defineProperty(u,"value",{get:()=>this.stateManager.getState()[a],enumerable:!0,configurable:!0}),c.valueOf=()=>this.stateManager.getState()[a],c.toString=()=>ce(this.stateManager.getState()[a]);const p=h=>{const f=this.stateManager.getState()[a],g=typeof h=="function"?h(f):h;this.stateManager.setState(a,g)};return this.createComponentScopedGlobals(n,i,u,p),[u,p]}currentLoopContext=null;getLoopExecutionContext(){return this.currentLoopContext}generateLoopInstanceId(e){const n=Object.keys(e).sort().map(r=>{const a=e[r];return a&&typeof a=="object"&&"id"in a?`${r}:${a.id}`:`${r}:${JSON.stringify(a)}`});return`loop_${btoa(n.join("|")).replace(/[^a-zA-Z0-9]/g,"").substring(0,8)}`}looksLikeVariableName(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)&&e.length<=50&&!e.includes(" ")&&!Se.has(e)}effect(e,t){const n=`effect_${Date.now()}_${Math.random()}`,i=this.componentManager.getCurrentComponent();let r,a=!1,o,c;if(arguments.length===1)o="always",c={immediate:!0,detectDeps:!0};else if(Array.isArray(t)){const p=this.extractDependencyNames(t,i);p.length===0?(o="once",c={deps:p,immediate:!0}):(o="deps",c={deps:p,immediate:!0})}else{const p={immediate:!0,...t||{}};if(!p.deps||p.deps.length===0)o="always",c={immediate:p.immediate,detectDeps:!0};else{const h=this.extractDependencyNames(p.deps,i);o="deps",c={deps:h,immediate:p.immediate,detectDeps:p.detectDeps}}}const u=()=>{a||this.stateManager.onDOMUpdateComplete(()=>{if(!a){if(r&&typeof r=="function")try{r()}catch(p){console.error("Effect cleanup error:",p)}try{r=e()}catch(p){console.error("Effect callback error:",p)}}})};switch(o){case"always":const p=["*"],h={id:n,selector:"",dependencies:new Set(p),callback:u,component:i};this.stateManager.addSubscription(h);break;case"once":break;case"deps":const f=this.resolveDependencies(c.deps,i);if(f.length){const g={id:n,selector:"",dependencies:new Set(f),callback:u,component:i};this.stateManager.addSubscription(g)}break}return c.immediate!==!1&&u(),()=>{if(a=!0,r&&typeof r=="function")try{r()}catch(p){console.error("Effect cleanup error:",p)}this.stateManager.removeSubscription(n)}}extractDependencyNames(e,t){const n=[];for(const i of e)typeof i=="string"?n.push(i):typeof i=="function"&&i.__pphp_key?n.push(i.__pphp_key):console.warn("Invalid dependency in effect:",i);return n.filter(Boolean)}resolveDependencies(e,t){const n=[],i=this.stateManager.getState();for(const r of e)if(r.includes(".")){const a=r.split("."),o=a[0],c=a.slice(1).join("."),u=this.componentManager.getPropDependencies(o,t);if(u.length>0)n.push(...u);else{const p=Ue.findExistingStateKey(o,t,i);p?n.push(`${p}.${c}`):n.push(`${t}.${r}`)}}else{const a=this.componentManager.getPropDependencies(r,t);if(a.length>0)n.push(...a);else{const o=Ue.findExistingStateKey(r,t,i);o?n.push(o):n.push(`${t}.${r}`)}}return Array.from(new Set(n))}createComponentScopedGlobals(e,t,n,i){window[e]||(window[e]={});const r=`set${Wt(t)}`;window[e][t]=n,window[e][r]=i,window[e][`${t}Getter`]=n}deleteAllComponentObjects(){const e=Object.keys(window),t=new Set(["window","self","document","location","customElements","history","navigation","locationbar","menubar","personalbar","scrollbars","statusbar","toolbar","frames","top","parent","navigator","external","screen","visualViewport","crypto","performance","localStorage","sessionStorage","indexedDB","fetch","XMLHttpRequest","WebSocket","Worker","SharedWorker","MessageChannel","MessagePort","Notification","Push","BroadcastChannel","Cache","CacheStorage","requestAnimationFrame","cancelAnimationFrame","requestIdleCallback","cancelIdleCallback","setInterval","clearInterval","setTimeout","clearTimeout","queueMicrotask","atob","btoa","alert","confirm","prompt","open","close","focus","blur","print","stop","getComputedStyle","getSelection","matchMedia","scroll","scrollBy","scrollTo","resizeBy","resizeTo","moveBy","moveTo","pp","store","searchParams"]);for(const n of e){if(t.has(n))continue;const i=window[n];(/^s[a-z0-9]+$/i.test(n)||n==="app")&&i&&typeof i=="object"&&delete window[n]}}static resetInstance(){this.instance&&(this.instance.destroy(),this.instance=null)}destroy(){this.cleanup(),this.initialized=!1,this.hydrationDone=!1}}export{$s as P};
|
|
42
|
+
`);return this.handlerCache.set(n,r),r}executeHandler(e,t,n){if(!this.componentManager||!this.expressionEvaluator){console.warn("EventDelegationManager dependencies not set");return}try{const i=t.getAttribute(d.ATTR_PREFIXES.CONTEXT),r=t.getAttribute(d.ATTR_PREFIXES.COMPONENT);let a=null;if(r)a=t;else{let f=t;for(;f&&f!==document.body;){if(f.getAttribute(d.ATTR_PREFIXES.COMPONENT)===e.component){a=f;break}f=f.parentElement}if(!a){const g=document.querySelectorAll(`[${d.ATTR_PREFIXES.COMPONENT}="${e.component}"]`);for(const m of g)if(this.componentManager.hasStoredProps(m)){a=m;break}!a&&g.length>0&&(a=g[0])}}let o=null,c=t.parentElement;for(;c&&c!==document.body;){if(c.hasAttribute(d.ATTR_PREFIXES.COMPONENT)){o=c;break}c=c.parentElement}let u;if(i&&a)u=this.componentManager.buildRestrictedComponentContextWithProps(e.component,a);else if(u=this.componentManager.buildRestrictedComponentContext(e.component,!1),a&&this.componentManager.hasStoredProps(a)){const f=this.componentManager.evaluateProps(a);Object.assign(u,f)}if(o&&o!==a&&this.componentManager.hasStoredProps(o)){const f=this.componentManager.evaluateProps(o);u={...u,...f}}const p={...u};for(const[f,g]of Object.entries(u))typeof g=="function"&&"__pphp_key"in g&&(p[f]=g.value);const h=this.loopManager?.getLoopContextForElement(t);if(h){const f={};for(const[g,m]of Object.entries(h))typeof m=="function"&&"__pphp_key"in m?f[g]=m.value:f[g]=m;u={...p,...f}}else u=p;e.compiledFn||(e.compiledFn=this.compileHandler(e.code,e.component)),e.compiledFn&&e.compiledFn(n,t,u)}catch(i){console.error("💥 Event handler execution failed:",i),console.error("Handler code:",e.code),console.error("Handler component:",e.component)}}attachDirectListener(e,t,n){const i=r=>{this.executeHandler(n,e,r)};e.addEventListener(t,i),e[`__${t}_listener`]=i}removeEventHandler(e,t){const n=this.elementHandlers.get(e);n&&(n.delete(t),n.size===0&&this.elementHandlers.delete(e));const i=this.delegatedEvents.get(t);i&&i.elements.delete?.(e);const r=e[`__${t}_listener`];r&&(e.removeEventListener(t,r),delete e[`__${t}_listener`])}cleanup(){for(const[e,t]of this.delegatedEvents)document.removeEventListener(e,t.listener,!0);this.delegatedEvents.clear(),this.handlerCache.clear(),this.setupEvents.clear()}}class $s{static instance=null;stateManager=new Fs;expressionEvaluator=new de;componentManager=new Ds(this.stateManager);domBindingManager=new Bs(this.stateManager,this.componentManager,this.expressionEvaluator);hydrationCallbacks=new Set;portalManager=new ks;initialized=!1;hydrationDone=!1;hydrationResolve;hydrationPromise;portalHydrationPromises=new Set;portalHydrationResolvers=new Map;constructor(){document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>this.initialize()):setTimeout(()=>this.initialize(),0),this.hydrationPromise=new Promise(e=>this.hydrationResolve=e)}initialize(){this.initialized||(this.initialized=!0,this.markHydrationStart(),this.componentManager.setExpressionEvaluator(this.expressionEvaluator),this.portalManager.setDependencies(this.componentManager,this.domBindingManager,this.stateManager,this),this.componentManager.executePhpScripts(document.body),this.domBindingManager.processElement(document.body,!0),this.domBindingManager.processPendingBindings(),Promise.resolve().then(()=>{requestAnimationFrame(()=>{this.markHydrated()})}))}createPortal(e,t,n){const i=this.portalManager.createPortal(e,t,n),r=new Promise(a=>{this.portalHydrationResolvers.set(i,a)});return this.portalHydrationPromises.add(r),r.finally(()=>{this.portalHydrationPromises.delete(r),this.portalHydrationResolvers.delete(i)}),i}removePortal(e){return this.markPortalHydrated(e),this.portalManager.removePortal(e)}markPortalHydrated(e){const t=this.portalHydrationResolvers.get(e);t&&t()}updatePortal(e,t,n){return this.portalManager.updatePortal(e,t,n)}cleanup(){this.portalManager.destroy(),this.domBindingManager.destroy(),this.componentManager.destroy(),this.stateManager.clearState(),this.stateManager.clearSubscriptions(),this.expressionEvaluator.clearAllCaches(),this.hydrationCallbacks.clear(),this.deleteAllComponentObjects()}ref(e=null){return{current:e}}async hydrated(){await Promise.all([this.hydrationPromise,...Array.from(this.portalHydrationPromises)])}onHydrated(e){this.hydrationDone?queueMicrotask(e):this.hydrationCallbacks.add(e)}get isHydrated(){return this.hydrationDone}markHydrationStart(){document.dispatchEvent(new CustomEvent("pp:hydrationstart"))}markHydrated(){if(!this.hydrationDone){this.hydrationDone=!0,this.hydrationResolve();for(const e of this.hydrationCallbacks)try{e()}catch{}this.hydrationCallbacks.clear(),document.dispatchEvent(new CustomEvent("pp:hydrated",{detail:{at:performance.now()}}))}}state(e,t){const n=this.componentManager.getCurrentComponent();let i,r;typeof e=="string"&&arguments.length===2?(i=e,r=t):typeof e=="string"&&arguments.length===1?this.looksLikeVariableName(e)?(i=e,r=void 0):(console.warn("pp.state() called with string that doesn't look like variable name:",e),i="unknownState",r=e):(console.warn("pp.state() called without explicit key - this should be handled by AST transformation"),i="unknownState",r=e),r&&typeof r=="function"&&"__pphp_key"in r&&(r=r.value);let a;const o=this.getLoopExecutionContext();if(o){const h=this.generateLoopInstanceId(o);a=`${n}.${h}.${i}`}else a=`${n}.${i}`;this.stateManager.hasState(a)||this.stateManager.setInitialState(a,r);const c=(()=>this.stateManager.getState()[a]),u=new Proxy(c,{get(h,f,g){if(f==="__pphp_key"||f==="__pphp_fullKey"||f==="__pphp_component"||f==="value"||f==="valueOf"||f==="toString")return Reflect.get(h,f,g);const m=h();if(m!=null){if(f in Object(m)){const E=m[f];return typeof E=="function"?E.bind(m):E}return Reflect.get(h,f,g)}},has(h,f){if(f==="__pphp_key"||f==="__pphp_fullKey"||f==="__pphp_component"||f==="value"||f==="valueOf"||f==="toString")return Reflect.has(h,f);const g=h();return g!=null&&f in Object(g)?!0:Reflect.has(h,f)},apply(h,f,g){return Reflect.apply(h,f,g)}});Object.defineProperty(u,"__pphp_key",{value:i,enumerable:!1,writable:!1}),Object.defineProperty(u,"__pphp_fullKey",{value:a,enumerable:!1,writable:!1}),Object.defineProperty(u,"__pphp_component",{value:n,enumerable:!1,writable:!1}),Object.defineProperty(u,"value",{get:()=>this.stateManager.getState()[a],enumerable:!0,configurable:!0}),c.valueOf=()=>this.stateManager.getState()[a],c.toString=()=>ce(this.stateManager.getState()[a]);const p=h=>{const f=this.stateManager.getState()[a],g=typeof h=="function"?h(f):h;this.stateManager.setState(a,g)};return this.createComponentScopedGlobals(n,i,u,p),[u,p]}currentLoopContext=null;getLoopExecutionContext(){return this.currentLoopContext}generateLoopInstanceId(e){const n=Object.keys(e).sort().map(r=>{const a=e[r];return a&&typeof a=="object"&&"id"in a?`${r}:${a.id}`:`${r}:${JSON.stringify(a)}`});return`loop_${btoa(n.join("|")).replace(/[^a-zA-Z0-9]/g,"").substring(0,8)}`}looksLikeVariableName(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)&&e.length<=50&&!e.includes(" ")&&!Se.has(e)}effect(e,t){const n=`effect_${Date.now()}_${Math.random()}`,i=this.componentManager.getCurrentComponent();let r,a=!1,o,c;if(arguments.length===1)o="always",c={immediate:!0,detectDeps:!0};else if(Array.isArray(t)){const p=this.extractDependencyNames(t,i);p.length===0?(o="once",c={deps:p,immediate:!0}):(o="deps",c={deps:p,immediate:!0})}else{const p={immediate:!0,...t||{}};if(!p.deps||p.deps.length===0)o="always",c={immediate:p.immediate,detectDeps:!0};else{const h=this.extractDependencyNames(p.deps,i);o="deps",c={deps:h,immediate:p.immediate,detectDeps:p.detectDeps}}}const u=()=>{a||this.stateManager.onDOMUpdateComplete(()=>{if(!a){if(r&&typeof r=="function")try{r()}catch(p){console.error("Effect cleanup error:",p)}try{r=e()}catch(p){console.error("Effect callback error:",p)}}})};switch(o){case"always":const p=["*"],h={id:n,selector:"",dependencies:new Set(p),callback:u,component:i};this.stateManager.addSubscription(h);break;case"once":break;case"deps":const f=this.resolveDependencies(c.deps,i);if(f.length){const g={id:n,selector:"",dependencies:new Set(f),callback:u,component:i};this.stateManager.addSubscription(g)}break}return c.immediate!==!1&&u(),()=>{if(a=!0,r&&typeof r=="function")try{r()}catch(p){console.error("Effect cleanup error:",p)}this.stateManager.removeSubscription(n)}}extractDependencyNames(e,t){const n=[];for(const i of e)typeof i=="string"?n.push(i):typeof i=="function"&&i.__pphp_key?n.push(i.__pphp_key):console.warn("Invalid dependency in effect:",i);return n.filter(Boolean)}resolveDependencies(e,t){const n=[],i=this.stateManager.getState();for(const r of e)if(r.includes(".")){const a=r.split("."),o=a[0],c=a.slice(1).join("."),u=this.componentManager.getPropDependencies(o,t);if(u.length>0)n.push(...u);else{const p=Ue.findExistingStateKey(o,t,i);p?n.push(`${p}.${c}`):n.push(`${t}.${r}`)}}else{const a=this.componentManager.getPropDependencies(r,t);if(a.length>0)n.push(...a);else{const o=Ue.findExistingStateKey(r,t,i);o?n.push(o):n.push(`${t}.${r}`)}}return Array.from(new Set(n))}createComponentScopedGlobals(e,t,n,i){window[e]||(window[e]={});const r=`set${Wt(t)}`;window[e][t]=n,window[e][r]=i,window[e][`${t}Getter`]=n}deleteAllComponentObjects(){const e=Object.keys(window),t=new Set(["window","self","document","location","customElements","history","navigation","locationbar","menubar","personalbar","scrollbars","statusbar","toolbar","frames","top","parent","navigator","external","screen","visualViewport","crypto","performance","localStorage","sessionStorage","indexedDB","fetch","XMLHttpRequest","WebSocket","Worker","SharedWorker","MessageChannel","MessagePort","Notification","Push","BroadcastChannel","Cache","CacheStorage","requestAnimationFrame","cancelAnimationFrame","requestIdleCallback","cancelIdleCallback","setInterval","clearInterval","setTimeout","clearTimeout","queueMicrotask","atob","btoa","alert","confirm","prompt","open","close","focus","blur","print","stop","getComputedStyle","getSelection","matchMedia","scroll","scrollBy","scrollTo","resizeBy","resizeTo","moveBy","moveTo","pp","store","searchParams"]);for(const n of e){if(t.has(n))continue;const i=window[n];(/^s[a-z0-9]+$/i.test(n)||n==="app")&&i&&typeof i=="object"&&delete window[n]}}static resetInstance(){this.instance&&(this.instance.destroy(),this.instance=null)}destroy(){this.cleanup(),this.initialized=!1,this.hydrationDone=!1}}export{$s as P};
|