create-prisma-php-app 4.1.0-alpha.6 → 4.1.0-alpha.7
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.
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function n(r,e,o=window,c=!0){if(Object.defineProperty(o,r,{get(){return e&&(typeof e=="function"||typeof e=="object")&&"getInstance"in e&&typeof e.getInstance=="function"?e.getInstance():e},set(t){console.warn(`[${r}] Cannot override global ${r}; ignoring.`,t)},configurable:!1,enumerable:!0}),c)try{o[r]}catch(t){console.error(`Failed to initialize ${r}:`,t)}}export{n as c};
|
|
@@ -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: ${s}
|
|
14
14
|
`),{endIndex:-1,expression:""}}static checkForMismatchedQuotes(e){let s=0,i=0,n=!1;for(let r=0;r<e.length;r++){if(n){n=!1;continue}if(e[r]==="\\"){n=!0;continue}e[r]==="'"&&s++,e[r]==='"'&&i++}return s%2!==0?{hasIssue:!0,message:`Unmatched single quotes (found ${s})`}:i%2!==0?{hasIssue:!0,message:`Unmatched double quotes (found ${i})`}:{hasIssue:!1,message:""}}static isSingleExpression(e){const s=P.decodeEntities(e),i=P.parseContentWithNesting(s);return i.length===1&&i[0].type==="expression"?i[0].expression:null}static extractExpressions(e){const s=P.decodeEntities(e),i=P.parseContentWithNesting(s),n=i.filter(r=>r.type==="expression").map(r=>r.expression).filter(r=>r);return i.some(r=>r.type==="expression")&&n.length===0&&(console.error(`
|
|
15
15
|
❌ Failed to extract expressions from content:`),console.error(` Content: ${e}`),console.error(` Parsed ${i.length} parts, but extracted 0 expressions`),console.error(` This usually means malformed mustache syntax
|
|
16
|
-
`)),n}}class Ps{textNodeBindings=new Map;expressionEvaluator;stateManager;componentManager;cleanupObserver;bindingCount=0;constructor(e,s){this.expressionEvaluator=e,this.stateManager=s,this.cleanupObserver=new MutationObserver(i=>{this.cleanupDetachedNodes(i)}),this.cleanupObserver.observe(document.body,{childList:!0,subtree:!0})}cleanupDetachedNodes(e){const s=[];for(const i of e)i.type==="childList"&&i.removedNodes.forEach(n=>{if(n.nodeType===Node.TEXT_NODE)s.push(n);else if(n.nodeType===Node.ELEMENT_NODE){const r=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null);let a;for(;a=r.nextNode();)s.push(a)}});Promise.resolve().then(()=>{s.forEach(i=>{document.contains(i)||this.cleanupTextNode(i)})})}processTextNode(e,s){if(this.textNodeBindings.has(e)||y.isTextNodeInsideScript(e)||this.isInsideLoopItem(e))return;const i=e.parentElement,n=i?y.getContextComponent(i):s,r=e.textContent||"",a=P.parse(r);if(!a.some(l=>l.type==="expression"))return;const c={originalContent:r,expressions:a,subscriptionIds:[]};a.filter(l=>l.type==="expression").forEach(l=>{if(!l.expression)return;const h=`text_${Date.now()}_${Math.random()}`,p=this.expressionEvaluator.extractDependencies(l.expression,n,this.stateManager),f={id:h,selector:"",dependencies:new Set(p),callback:()=>{this.updateTextNode(e)},element:e.parentElement??void 0,component:n};this.stateManager.addSubscription(f),c.subscriptionIds.push(h)}),this.textNodeBindings.set(e,c),this.bindingCount++,this.updateTextNode(e)}isInsideLoopItem(e){let s=e.parentElement;for(;s&&s!==document.body;){const i=s.previousSibling;if(i&&i.nodeType===Node.COMMENT_NODE&&i.textContent?.startsWith("pp-for:"))return!0;let n=s.parentElement?.firstChild||null;for(;n;){if(n.nodeType===Node.COMMENT_NODE&&n.textContent?.startsWith("pp-for:")&&n!==s)return!0;n=n.nextSibling}s=s.parentElement}return!1}updateTextNode(e){const s=this.textNodeBindings.get(e);if(!s||!e.parentElement)return;const i=e.parentElement,n=y.getContextComponent(i),r=this.resolveComponentRootForElement(e,n),a=this.getContextForComponent(n,r);let o="";for(const c of s.expressions)if(c.type==="static")o+=c.content;else if(c.expression)try{const l=this.expressionEvaluator.evaluateExpression(c.expression,a,n);o+=ie(l)}catch(l){const h=typeof l=="object"&&l!==null&&"message"in l?l.message:String(l);console.warn(`Text binding evaluation warning for "${c.expression}": ${h}`),o+=""}e.textContent!==o&&(e.textContent=o)}resolveComponentRootForElement(e,s){let i=e.parentElement;for(;i&&i.nodeType===Node.ELEMENT_NODE;){const n=i;if(n.getAttribute(d.ATTR_PREFIXES.COMPONENT)===s)return n;i=i.parentElement}}getContextForComponent(e,s){return this.componentManager?this.componentManager.buildComponentContextWithProps(e,s):{}}cleanupTextNode(e){const s=this.textNodeBindings.get(e);s&&(s.subscriptionIds.forEach(i=>{this.stateManager.removeSubscription(i)}),this.textNodeBindings.delete(e),this.bindingCount=Math.max(0,this.bindingCount-1))}getBindingCount(){return this.textNodeBindings.size}getAllBindings(){return new Map(this.textNodeBindings)}clearAllBindings(){for(const[e]of this.textNodeBindings)this.cleanupTextNode(e)}destroy(){this.cleanupObserver.disconnect(),this.clearAllBindings()}}class ks{listeners=new Map;on(e,s){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(s),()=>this.off(e,s)}off(e,s){this.listeners.get(e)?.delete(s)}emit(e,...s){const i=this.listeners.get(e);i&&i.forEach(n=>{try{n(...s)}catch(r){console.error(`Event listener error for ${e}:`,r)}})}}class Is{stateStore={};subscriptions=new Map;updateQueue=new Set;isUpdating=!1;eventBus=new ks;contextCache=new Map;previousValues=new Map;_subscriptionManager=new Ts;originalStateStore={};domUpdateCallbacks=[];domUpdateScheduled=!1;constructor(){this.setupGlobalStateProxy(),setInterval(()=>{this.subscriptionManager.cleanupStaleSubscriptions()},3e4)}onDOMUpdateComplete(e){this.domUpdateCallbacks.push(e),this.domUpdateScheduled||(this.domUpdateScheduled=!0,requestAnimationFrame(()=>{requestAnimationFrame(()=>{const s=[...this.domUpdateCallbacks];this.domUpdateCallbacks=[],this.domUpdateScheduled=!1,s.forEach(i=>{try{i()}catch(n){console.error("DOM update callback error:",n)}})})}))}setInitialState(e,s){if(this.previousValues.set(e,void 0),this.originalStateStore[e]=s,this.previousValues.size>100){const i=this.previousValues.keys().next().value;typeof i=="string"&&this.previousValues.delete(i)}}get subscriptionManager(){return this._subscriptionManager}batchStateUpdates(e){const s=this.isUpdating;this.isUpdating=!0;try{return e()}finally{this.isUpdating=s,!this.isUpdating&&this.updateQueue.size>0&&this.scheduleFlush()}}invalidateContextCache(){this.contextCache.clear()}setupGlobalStateProxy(){this.originalStateStore=this.stateStore,this.stateStore=new Proxy(this.stateStore,{set:(e,s,i,n)=>{const r=e[s],a=Reflect.set(e,s,i,n);return r!==i&&this.notifySubscribers(s),a},get:(e,s)=>Reflect.get(e,s)})}notifySubscribers(e){if(this.eventBus.emit("stateChanged",e),this.updateQueue.add(e),e.includes(".")){const s=e.split(".")[0];this.updateQueue.add(s)}this.notifyPathBasedSubscribers(e),this.isUpdating||this.scheduleFlush()}notifyPathBasedSubscribers(e){const s=this.stateStore[e],i=this.previousValues?.get(e);for(const[n,r]of this.subscriptions)for(const a of r.dependencies)if(this.isPathDependency(a)&&a.startsWith(e+".")){const o=a.substring(e.length+1),c=this.getPathValue(i,o),l=this.getPathValue(s,o);this.deepEqual(c,l)||this.updateQueue.add(a)}}isPathDependency(e){return e.includes(".")&&e.split(".").length>1}getPathValue(e,s){if(!e||typeof e!="object")return;const i=s.split(".");let n=e;for(const r of i){if(n==null)return;if(Array.isArray(n))return r==="length"?n.length:n.map(a=>a?.[r]).filter(a=>a!==void 0);n=n[r]}return n}deepEqual(e,s){if(e===s)return!0;if(e==null||s==null)return!1;if(Array.isArray(e)&&Array.isArray(s))return e.length!==s.length?!1:e.every((i,n)=>this.deepEqual(i,s[n]));if(typeof e=="object"&&typeof s=="object"){const i=Object.keys(e),n=Object.keys(s);return i.length!==n.length?!1:i.every(r=>this.deepEqual(e[r],s[r]))}return!1}scheduleFlush=As(()=>{this.flushUpdates()},d.DEBOUNCE_MS);flushUpdates(){if(!this.isUpdating){this.isUpdating=!0;try{const e=new Set,s=this.subscriptionManager.getSubscriptionsForKey("*");if(s&&s.size>0&&this.updateQueue.size>0)for(const i of s){const n=this.subscriptionManager.getSubscription(i);if(!n)continue;if(n.element&&!document.contains(n.element)){this.subscriptionManager.removeSubscription(i);continue}const r=n.element??document.body;try{const a=Array.from(this.updateQueue)[0];n.callback(r,{key:a})}catch(a){console.error("Wildcard subscription callback failed:",a)}}for(const i of this.updateQueue){if(e.has(i))continue;e.add(i);const n=this.subscriptionManager.getSubscriptionsForKey(i);if(n)for(const r of n){const a=this.subscriptionManager.getSubscription(r);if(!a)continue;if(a.element&&!document.contains(a.element)){this.subscriptionManager.removeSubscription(r);continue}const o=a.element??document.body;try{a.callback(o,{key:i})}catch(c){console.error("Subscription callback failed:",c)}}}}finally{this.updateQueue.clear(),this.isUpdating=!1}}}getState(){return this.stateStore}setState(e,s){if(this.previousValues.set(e,this.stateStore[e]),this.stateStore[e]=s,this.previousValues.size>100){const i=this.previousValues.keys().next().value;typeof i=="string"&&this.previousValues.delete(i)}}hasState(e){return e in this.originalStateStore}addSubscription(e){this._subscriptionManager.addSubscription(e)}removeSubscription(e){this._subscriptionManager.removeSubscription(e)}onStateChange(e){return this.eventBus.on("stateChanged",e)}batch(e){const s=this.isUpdating;this.isUpdating=!0;try{return e()}finally{this.isUpdating=s,!this.isUpdating&&this.updateQueue.size&&this.flushUpdates()}}getSubscriptions(){return this.subscriptionManager.getAllSubscriptions()}getKeyIndex(){const e=new Map,s=this.subscriptionManager.getAllSubscriptions();for(const[i,n]of s)for(const r of n.dependencies)e.has(r)||e.set(r,new Set),e.get(r).add(i);return e}}class ce{expressionCache=new $(d.MAX_CACHE_SIZE);dependencyCache=new $(d.MAX_CACHE_SIZE);commonExpressionsCache=new $(100);dependencyParser=new Ns;static CACHE_KEYS={EXPRESSION:(e,s)=>`expr:${e}:${s}`,DEPENDENCY:(e,s)=>`deps:${e}:${s}`,COMMON:e=>`common:${e}`};constructor(){this.precompileCommonExpressions()}normalizeExpression(e){return e.replace(/\r\n/g," ").replace(/\r/g," ").replace(/\n/g," ").replace(/\s+/g," ").trim()}precompileCommonExpressions(){["true","false","null","undefined"].forEach(s=>{const i={fn:new Function("return "+s),contextMap:new Map,dependencies:[s],timestamp:Date.now(),hitCount:0},n=ce.CACHE_KEYS.COMMON(s);this.commonExpressionsCache.set(n,i)})}extractDependencies(e,s,i){const n=this.normalizeExpression(e),r=ce.CACHE_KEYS.DEPENDENCY(s,n);let a=this.dependencyCache.get(r);return a||(a=this.dependencyParser.extract(n,s,i),this.dependencyCache.set(r,a),a)}evaluateExpression(e,s,i){const n=this.normalizeExpression(e),r=ce.CACHE_KEYS.COMMON(n);let a=this.commonExpressionsCache.get(r);if(a){a.hitCount++;try{return a.fn()}catch(c){console.error(`Common expression evaluation failed: "${n}"`,c);return}}const o=ce.CACHE_KEYS.EXPRESSION(i,n);a=this.expressionCache.get(o),(!a||this.isStale(a))&&(a=this.compileExpression(n,s,i),this.expressionCache.set(o,a)),a.hitCount++;try{const c=this.buildArguments(a.contextMap,s);return a.fn(...c)}catch(c){console.error(`Expression evaluation failed: "${n}"`,c),console.error("Available context:",Object.keys(s));return}}compileExpression(e,s,i){const n=this.prepareSafeContext(s),r=new Map,a=[];Object.keys(n).forEach((c,l)=>{r.set(c,l),a.push(c)});const o=this.dependencyParser.extract(e,i);return{fn:new Function(...a,`return (${e})`),contextMap:r,dependencies:o,timestamp:Date.now(),hitCount:0}}buildArguments(e,s){const i=new Array(e.size);for(const[n,r]of e)i[r]=s[n];return i}isStale(e){return Date.now()-e.timestamp>3e5}prepareSafeContext(e){const s={};for(const[i,n]of Object.entries(e))xe.has(i)||!this.isValidJavaScriptIdentifier(i)||(s[i]=n);return s}isValidJavaScriptIdentifier(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)&&!xe.has(e)}invalidateCache(e){switch(e){case"expressions":this.expressionCache.clear();break;case"dependencies":this.dependencyCache.clear();break;case"common":this.commonExpressionsCache.clear(),this.precompileCommonExpressions();break;case"parser":this.dependencyParser.clearCache();break;default:this.clearAllCaches()}}invalidateByComponent(e){this.expressionCache.deleteByPrefix(`expr:${e}:`),this.dependencyCache.deleteByPrefix(`deps:${e}:`)}clearAllCaches(){this.expressionCache.clear(),this.dependencyCache.clear(),this.commonExpressionsCache.clear(),this.dependencyParser.clearCache(),this.precompileCommonExpressions()}getCacheStats(){return{expressions:this.expressionCache.getStats(),dependencies:this.dependencyCache.getStats(),commonExpressions:this.commonExpressionsCache.getStats(),dependencyParser:this.getDependencyParserStats()}}getDependencyParserStats(){return this.dependencyParser.getCacheSize?{size:this.dependencyParser.getCacheSize(),maxSize:500,hitRate:0,hits:0,misses:0}:{size:0,maxSize:0,hitRate:0,hits:0,misses:0}}cleanupStaleExpressions(){let e=0;return this.expressionCache.keys().forEach(i=>{const n=this.expressionCache.get(i);n&&this.isStale(n)&&(this.expressionCache.delete(i),e++)}),e}}class Ns{parseCache=new $(500);extract(e,s,i){const n=this.normalizeExpression(e),r=`${s}:${n}`;if(this.parseCache.has(r))return this.parseCache.get(r);const a=this.parseExpression(n,s,i);return this.parseCache.set(r,a),a}normalizeExpression(e){return e.replace(/\r\n/g," ").replace(/\r/g," ").replace(/\n/g," ").replace(/\s+/g," ").trim()}parseExpression(e,s,i){const n=this.extractIdentifiers(e),r=[],a=i?.getState()||{};for(const c of n){if(xe.has(c))continue;const l=c.indexOf("."),h=l===-1?c:c.substring(0,l),p=Be.findExistingStateKey(h,s,a);if(p)r.push(p);else{const f=s==="app"?[`app.${h}`]:[`${s}.${h}`,`app.${h}`];r.push(...f)}if(l!==-1){const f=s==="app"?[`app.${h}`]:[`${s}.${h}`,`app.${h}`];r.push(...f)}}return Array.from(new Set(r))}extractIdentifiers(e){const s=[];let i=0;for(;i<e.length;){const n=e[i];if(n==="'"){i=this.skipString(e,i,"'");continue}if(n==='"'){i=this.skipString(e,i,'"');continue}if(n==="`"){i=this.skipTemplateLiteral(e,i,s);continue}if(this.isIdentifierStart(n)){const r=this.extractIdentifier(e,i);s.push(r.value),i=r.endIndex;continue}i++}return s}skipString(e,s,i){let n=s+1;for(;n<e.length&&e[n]!==i;)e[n]==="\\"&&n++,n++;return n+1}skipTemplateLiteral(e,s,i){let n=s+1;for(;n<e.length&&e[n]!=="`";){if(e[n]==="$"&&n+1<e.length&&e[n+1]==="{"){n+=2;let r=1;for(;n<e.length&&r>0;){const a=e[n];if(a==='"'||a==="'"){n=this.skipString(e,n,a);continue}if(a==="{"?r++:a==="}"&&r--,r>0&&this.isIdentifierStart(a)){const o=this.extractIdentifier(e,n);i.push(o.value),n=o.endIndex-1}n++}continue}e[n]==="\\"&&n++,n++}return n+1}extractIdentifier(e,s){let i=s;for(;i<e.length&&(this.isIdentifierPart(e[i])||e[i]===".");)i++;return{value:e.substring(s,i),endIndex:i}}isIdentifierStart(e){return/[a-zA-Z_$]/.test(e)}isIdentifierPart(e){return/[a-zA-Z0-9_$]/.test(e)}clearCache(){this.parseCache.clear()}getCacheSize(){return this.parseCache.cache.size}}class Ms{componentStack=["app"];elementProps=new WeakMap;contextCache=new $(100);contextIndex=new Map;contextInvalidated=new Set;stateManager;processedScripts=new WeakSet;componentFunctions=new Map;expressionEvaluator;domBindingManager;loopManager;templateRenderer;updateTimeouts;updateBatcher=new et;propDependencyCache=new Map;constructor(e){this.stateManager=e,this.updateBatcher=new et,this.stateManager.onStateChange(s=>this.invalidateContextCache(s))}getPropDependencies(e,s){const i=this.findElementWithProps(s);if(!i)return[];const n=this.elementProps.get(i);if(!n||!n.has(e))return[];const r=n.get(e);return this.templateRenderer?.dependencies(r.expression,r.component,this.stateManager)||[]}buildRestrictedComponentContext(e,s=!1){const i={};window[e]&&Object.assign(i,window[e]);const n=this.componentFunctions.get(e);if(n)for(const[a,o]of n)i[a]=o;const r=this.stateManager.getState();for(const a of Object.keys(r))if(a.startsWith(e+".")){const o=a.substring(e.length+1);o in i||(i[o]=r[a])}if(s){if(window.app)for(const[o,c]of Object.entries(window.app))o in i||(i[o]=c);const a=this.componentFunctions.get("app");if(a)for(const[o,c]of a)o in i||(i[o]=c);for(const o of Object.keys(r))if(o.startsWith("app.")){const c=o.substring(4);c in i||(i[c]=r[o])}}return i}getComponentPropDependencies(e,s){if(this.propDependencyCache.has(e))return this.propDependencyCache.get(e);const i=[],n=this.elementProps.get(e);n&&this.templateRenderer&&n.forEach(a=>{const o=this.templateRenderer?.dependencies(a.expression,a.component,this.stateManager);i.push(...o??[])});const r=Array.from(new Set(i));return this.propDependencyCache.set(e,r),r}setDOMBindingManager(e){this.domBindingManager=e,this.updateBatcher.setManagers(this,e)}hasStoredProps(e){return this.elementProps.has(e)&&this.elementProps.get(e).size>0}setExpressionEvaluator(e){this.expressionEvaluator=e,this.templateRenderer=new Ke(e),this.loopManager=new Ft(this.stateManager,e)}extractProps(e,s){const i=new Map,n=e.attributes,r=e.getAttribute(d.ATTR_PREFIXES.CONTEXT),a=e.getAttribute(d.ATTR_PREFIXES.COMPONENT);let o=s;r&&(r==="app"?o="app":r==="parent"?o=y.getParentOfComponent(a||"app",e):o=r);for(let c=0;c<n.length;c++){const l=n[c];if(!(l.name===d.ATTR_PREFIXES.COMPONENT||l.name===d.ATTR_PREFIXES.CONTEXT||l.name===d.ATTR_PREFIXES.SPREAD||l.name===d.ATTR_PREFIXES.LOOP)&&!oe.isEventAttribute(l.name)&&l.value&&_s.containsMustacheExpression(l.value)){if(a&&this.mightReferenceSelfProps(l.value,e))continue;const h=this.attributeToPropName(l.name),p={name:h,expression:l.value,component:o,subscriptionIds:[]};i.set(h,p)}}return i}mightReferenceSelfProps(e,s){const i=this.elementProps.get(s);return i?Array.from(i.keys()).some(r=>e.includes(r)&&r!=="dataState"):!1}attributeToPropName(e){return e.replace(/-([a-z])/g,(s,i)=>i.toUpperCase())}setupProps(e,s){const i=this.extractProps(e,s);i.size!==0&&(this.elementProps.set(e,i),this.expressionEvaluator&&i.forEach((n,r)=>{this.setupPropBinding(e,n)}))}setupPropBinding(e,s){if(!this.expressionEvaluator)return;const i=`prop_${Date.now()}_${Math.random()}`,n=this.templateRenderer?.dependencies(s.expression,s.component,this.stateManager)||[],r={id:i,selector:"",dependencies:new Set(n),callback:()=>{const a=e.getAttribute(d.ATTR_PREFIXES.COMPONENT);a&&(this.updateBatcher.scheduleUpdate(a,e),this.refreshComponentBindings(e,a))},element:e,component:s.component};this.stateManager.addSubscription(r),s.subscriptionIds.push(i)}refreshComponentBindings(e,s){this.contextInvalidated.add(s),this.contextCache.delete(s),this.domBindingManager&&this.domBindingManager.refreshComponentElement(e,s)}evaluateProps(e){const s={},i=this.elementProps.get(e);if(!i||!this.expressionEvaluator)return s;const n=i.values().next().value;if(!n)return s;const r=this.buildComponentContext(n.component);return i.forEach((a,o)=>{try{const c=this.templateRenderer?.render(a.expression,r,a.component);typeof c=="function"?s[o]=(...l)=>c.apply(this,l):s[o]=c}catch(c){console.error(`❌ Failed to evaluate prop "${o}":`,c),s[o]=void 0}}),s}cleanupProps(e){const s=this.elementProps.get(e);s&&(s.forEach(i=>{i.subscriptionIds.forEach(n=>{this.stateManager.removeSubscription(n)})}),this.elementProps.delete(e))}buildComponentContextWithProps(e,s){const i=this.buildComponentContext(e);let n=this.findElementWithProps(e);if(s&&this.elementProps.has(s)&&(n=s),n)try{const r=this.evaluatePropsWithContext(n,e,s);Object.keys(r).length>0&&Object.keys(r).forEach(a=>{i[a]=r[a]})}catch(r){console.error(`❌ Error evaluating props for ${e}:`,r)}return i}evaluatePropsWithContext(e,s,i){const n={},r=this.elementProps.get(e);if(!r||!this.expressionEvaluator)return n;const a=r.values().next().value;if(!a)return n;let o;const c=e.getAttribute(d.ATTR_PREFIXES.CONTEXT),l=e.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(c)if(c==="app")o=this.buildComponentContext("app");else if(c==="parent"){const C=y.getParentOfComponent(l||"app",e);o=this.buildComponentContext(C)}else o=this.buildComponentContext(c);else o=this.buildComponentContext(a.component);const h=this.loopManager?.getLoopContextForElement(e);h&&(o={...o,...h});const p=new Map,f=new Map,m=Array.from(r.keys());r.forEach((C,v)=>{m.some(I=>I!==v&&C.expression.includes(I))?f.set(v,C):p.set(v,C)}),p.forEach((C,v)=>{try{const A=this.templateRenderer?.render(C.expression,o,c||C.component);typeof A=="function"?this.isFunctionExplicitlyPassed(C.expression)?n[v]=(...fe)=>A.apply(this,fe):(console.warn(`⚠️ Function "${v}" not passed - not from shared namespace or explicitly passed`),n[v]=void 0):n[v]=A}catch(A){console.error(`❌ Failed to evaluate simple prop "${v}":`,A),console.error("Expression:",C.expression),console.error("Available context keys:",Object.keys(o)),n[v]=void 0}});const x={...o,...n};return f.forEach((C,v)=>{try{const A=this.templateRenderer?.render(C.expression,x,c||C.component);typeof A=="function"?this.isFunctionExplicitlyPassed(C.expression)?n[v]=(...fe)=>A.apply(this,fe):(console.warn(`⚠️ Function "${v}" not passed - not from shared namespace or explicitly passed`),n[v]=void 0):n[v]=A}catch(A){console.error(`❌ Failed to evaluate complex prop "${v}":`,A),console.error("Expression:",C.expression),console.error("Available context keys:",Object.keys(x)),n[v]=void 0}}),n}isFunctionExplicitlyPassed(e){const s=P.isSingleExpression(e);return s?/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(s.trim()):!1}findElementWithProps(e){const s=document.querySelectorAll(`[${d.ATTR_PREFIXES.COMPONENT}="${e}"]`);for(const i of s){const n=this.elementProps.get(i);if(n&&n.size>0)return i}return null}pushComponent(e){this.componentStack.push(e)}popComponent(){return this.componentStack.pop()}getCurrentComponent(){return this.componentStack[this.componentStack.length-1]}buildComponentContext(e){if(!this.contextInvalidated.has(e)&&this.contextCache.has(e))return this.contextCache.get(e);const s=this.computeComponentContext(e);return this.contextCache.set(e,s),this.contextInvalidated.delete(e),s}computeComponentContext(e){const s={};e!=="app"&&window[e]&&Object.assign(s,window[e]),e==="app"&&window.app&&Object.assign(s,window.app);const i=this.componentFunctions.get(e);if(i)for(const[r,a]of i)s[r]=a;if(e!=="app"){const r=this.componentFunctions.get("app");if(r)for(const[a,o]of r)a in s||(s[a]=o)}const n=this.stateManager.getState();for(const r of Object.keys(n))if(r.startsWith(e+".")){const a=r.substring(e.length+1);a in s||(s[a]=n[r])}if(e!=="app"){for(const r of Object.keys(n))if(r.startsWith("app.")){const a=r.substring(4);a in s||(s[a]=n[r])}}return s}invalidateContextCache(e){if(e.startsWith("app.")){this.contextCache.clear();for(const i of this.contextInvalidated.keys())this.contextInvalidated.add(i);return}const s=e.indexOf(".");if(s!==-1){const i=e.slice(0,s);this.invalidateComponent(i)}}invalidateComponent(e){this.contextInvalidated.add(e),this.contextIndex.delete(e)}executePhpScripts(e){const s=this.componentStack.length,i=e.getAttribute(d.ATTR_PREFIXES.COMPONENT),n=e===document.body;if(i||n){if(i){this.pushComponent(i);const a=this.getParentComponent(e);this.setupProps(e,a)}this.getRelevantScripts(e,n).forEach(a=>{const o=a.getAttribute(d.ATTR_PREFIXES.COMPONENT);o&&o!==i?(this.pushComponent(o),this.executeScript(a),this.popComponent()):this.executeScript(a)})}for(Array.from(e.children).forEach(r=>this.executePhpScripts(r));this.componentStack.length>s;)this.popComponent()}getParentComponent(e){let s=e.parentElement;for(;s;){const i=s.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(i)return i;s=s.parentElement}return"app"}getRelevantScripts(e,s){return Array.from(e.querySelectorAll(`script[type="${d.SCRIPT_TYPE}"]`)).filter(i=>{if(this.processedScripts.has(i))return!1;if(s)return i.hasAttribute(d.ATTR_PREFIXES.COMPONENT)?!0:!i.closest(`[${d.ATTR_PREFIXES.COMPONENT}]`);let n=i.parentElement;for(;n&&n!==e;){if(n.hasAttribute(d.ATTR_PREFIXES.COMPONENT))return!1;n=n.parentElement}return n===e||e.contains(i)})}executeScript(e){if(this.processedScripts.has(e))return;this.processedScripts.add(e);const s=this.getCurrentComponent(),i=e.textContent||"",n=P.decodeEntities(i);try{const r=this.findComponentElementForScript(e,s);if(r===e){const o=this.getParentComponent(e);this.setupProps(e,o)}const a=this.buildComponentContextWithProps(s,r);window[s]||(window[s]={}),this.executeScriptFunctions(n,s,a)}catch(r){console.error(`Script execution failed in component ${s}:`,r),console.error("Script content:",n)}}findComponentElementForScript(e,s){if(e.getAttribute(d.ATTR_PREFIXES.COMPONENT)===s)return e;let i=e.parentElement;for(;i;){if(i.getAttribute(d.ATTR_PREFIXES.COMPONENT)===s)return i;i=i.parentElement}const n=document.querySelectorAll(`[${d.ATTR_PREFIXES.COMPONENT}="${s}"]`);for(const r of n)if(this.elementProps.has(r))return r;return n[0]||void 0}executeScriptFunctions(e,s,i){const n=this.extractFunctionNames(e),r=this.findElementWithProps(s),a=this.extractVariableDeclarations(e);let o={...i};if(a.forEach(x=>{delete o[x];const C=`set${Vt(x)}`,v=`${x}Getter`;delete o[C],delete o[v]}),r){const x=this.evaluateProps(r);Object.assign(o,x)}o.getContext=()=>this.buildComponentContextWithProps(s),o.withContext=x=>{const C=this.buildComponentContextWithProps(s);return x.call(C,C)},o.__getProp=x=>{if(r)return this.evaluateProps(r)[x]};let l=q.getInstance().transformStateDeclarations(e);l=this.modifyScriptForReactiveProps(l,s,r||void 0);const h=`
|
|
16
|
+
`)),n}}class Ps{textNodeBindings=new Map;expressionEvaluator;stateManager;componentManager;cleanupObserver;bindingCount=0;constructor(e,s){this.expressionEvaluator=e,this.stateManager=s,this.cleanupObserver=new MutationObserver(i=>{this.cleanupDetachedNodes(i)}),this.cleanupObserver.observe(document.body,{childList:!0,subtree:!0})}cleanupDetachedNodes(e){const s=[];for(const i of e)i.type==="childList"&&i.removedNodes.forEach(n=>{if(n.nodeType===Node.TEXT_NODE)s.push(n);else if(n.nodeType===Node.ELEMENT_NODE){const r=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null);let a;for(;a=r.nextNode();)s.push(a)}});Promise.resolve().then(()=>{s.forEach(i=>{document.contains(i)||this.cleanupTextNode(i)})})}processTextNode(e,s){if(this.textNodeBindings.has(e)||y.isTextNodeInsideScript(e)||this.isInsideLoopItem(e))return;const i=e.parentElement,n=i?y.getContextComponent(i):s,r=e.textContent||"",a=P.parse(r);if(!a.some(l=>l.type==="expression"))return;const c={originalContent:r,expressions:a,subscriptionIds:[]};a.filter(l=>l.type==="expression").forEach(l=>{if(!l.expression)return;const h=`text_${Date.now()}_${Math.random()}`,p=this.expressionEvaluator.extractDependencies(l.expression,n,this.stateManager),f={id:h,selector:"",dependencies:new Set(p),callback:()=>{this.updateTextNode(e)},element:e.parentElement??void 0,component:n};this.stateManager.addSubscription(f),c.subscriptionIds.push(h)}),this.textNodeBindings.set(e,c),this.bindingCount++,this.updateTextNode(e)}isInsideLoopItem(e){let s=e.parentElement;for(;s&&s!==document.body;){const i=s.previousSibling;if(i&&i.nodeType===Node.COMMENT_NODE&&i.textContent?.startsWith("pp-for:"))return!0;let n=s.parentElement?.firstChild||null;for(;n;){if(n.nodeType===Node.COMMENT_NODE&&n.textContent?.startsWith("pp-for:")&&n!==s)return!0;n=n.nextSibling}s=s.parentElement}return!1}updateTextNode(e){const s=this.textNodeBindings.get(e);if(!s||!e.parentElement)return;const i=e.parentElement,n=y.getContextComponent(i),r=this.resolveComponentRootForElement(e,n),a=this.getContextForComponent(n,r);let o="";for(const c of s.expressions)if(c.type==="static")o+=c.content;else if(c.expression)try{const l=this.expressionEvaluator.evaluateExpression(c.expression,a,n);o+=ie(l)}catch(l){const h=typeof l=="object"&&l!==null&&"message"in l?l.message:String(l);console.warn(`Text binding evaluation warning for "${c.expression}": ${h}`),o+=""}e.textContent!==o&&(e.textContent=o)}resolveComponentRootForElement(e,s){let i=e.parentElement;for(;i&&i.nodeType===Node.ELEMENT_NODE;){const n=i;if(n.getAttribute(d.ATTR_PREFIXES.COMPONENT)===s)return n;i=i.parentElement}}getContextForComponent(e,s){return this.componentManager?this.componentManager.buildComponentContextWithProps(e,s):{}}cleanupTextNode(e){const s=this.textNodeBindings.get(e);s&&(s.subscriptionIds.forEach(i=>{this.stateManager.removeSubscription(i)}),this.textNodeBindings.delete(e),this.bindingCount=Math.max(0,this.bindingCount-1))}getBindingCount(){return this.textNodeBindings.size}getAllBindings(){return new Map(this.textNodeBindings)}clearAllBindings(){for(const[e]of this.textNodeBindings)this.cleanupTextNode(e)}destroy(){this.cleanupObserver.disconnect(),this.clearAllBindings()}}class ks{listeners=new Map;on(e,s){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(s),()=>this.off(e,s)}off(e,s){this.listeners.get(e)?.delete(s)}emit(e,...s){const i=this.listeners.get(e);i&&i.forEach(n=>{try{n(...s)}catch(r){console.error(`Event listener error for ${e}:`,r)}})}}class Is{stateStore={};subscriptions=new Map;updateQueue=new Set;isUpdating=!1;eventBus=new ks;contextCache=new Map;previousValues=new Map;_subscriptionManager=new Ts;originalStateStore={};domUpdateCallbacks=[];domUpdateScheduled=!1;constructor(){this.setupGlobalStateProxy(),setInterval(()=>{this.subscriptionManager.cleanupStaleSubscriptions()},3e4)}clearSubscriptions(){const e=this._subscriptionManager.getAllSubscriptions();for(const[s]of e)this._subscriptionManager.removeSubscription(s);this.updateQueue.clear()}clearComponentSubscriptions(e){const s=this._subscriptionManager.getAllSubscriptions();for(const[i,n]of s)n.component===e&&this._subscriptionManager.removeSubscription(i)}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(i=>i.startsWith(`${e}.`)).forEach(i=>{delete this.stateStore[i],delete this.originalStateStore[i],this.previousValues.delete(i)})}onDOMUpdateComplete(e){this.domUpdateCallbacks.push(e),this.domUpdateScheduled||(this.domUpdateScheduled=!0,requestAnimationFrame(()=>{requestAnimationFrame(()=>{const s=[...this.domUpdateCallbacks];this.domUpdateCallbacks=[],this.domUpdateScheduled=!1,s.forEach(i=>{try{i()}catch(n){console.error("DOM update callback error:",n)}})})}))}setInitialState(e,s){if(this.previousValues.set(e,void 0),this.originalStateStore[e]=s,this.previousValues.size>100){const i=this.previousValues.keys().next().value;typeof i=="string"&&this.previousValues.delete(i)}}get subscriptionManager(){return this._subscriptionManager}batchStateUpdates(e){const s=this.isUpdating;this.isUpdating=!0;try{return e()}finally{this.isUpdating=s,!this.isUpdating&&this.updateQueue.size>0&&this.scheduleFlush()}}invalidateContextCache(){this.contextCache.clear()}setupGlobalStateProxy(){this.originalStateStore=this.stateStore,this.stateStore=new Proxy(this.stateStore,{set:(e,s,i,n)=>{const r=e[s],a=Reflect.set(e,s,i,n);return r!==i&&this.notifySubscribers(s),a},get:(e,s)=>Reflect.get(e,s)})}notifySubscribers(e){if(this.eventBus.emit("stateChanged",e),this.updateQueue.add(e),e.includes(".")){const s=e.split(".")[0];this.updateQueue.add(s)}this.notifyPathBasedSubscribers(e),this.isUpdating||this.scheduleFlush()}notifyPathBasedSubscribers(e){const s=this.stateStore[e],i=this.previousValues?.get(e);for(const[n,r]of this.subscriptions)for(const a of r.dependencies)if(this.isPathDependency(a)&&a.startsWith(e+".")){const o=a.substring(e.length+1),c=this.getPathValue(i,o),l=this.getPathValue(s,o);this.deepEqual(c,l)||this.updateQueue.add(a)}}isPathDependency(e){return e.includes(".")&&e.split(".").length>1}getPathValue(e,s){if(!e||typeof e!="object")return;const i=s.split(".");let n=e;for(const r of i){if(n==null)return;if(Array.isArray(n))return r==="length"?n.length:n.map(a=>a?.[r]).filter(a=>a!==void 0);n=n[r]}return n}deepEqual(e,s){if(e===s)return!0;if(e==null||s==null)return!1;if(Array.isArray(e)&&Array.isArray(s))return e.length!==s.length?!1:e.every((i,n)=>this.deepEqual(i,s[n]));if(typeof e=="object"&&typeof s=="object"){const i=Object.keys(e),n=Object.keys(s);return i.length!==n.length?!1:i.every(r=>this.deepEqual(e[r],s[r]))}return!1}scheduleFlush=As(()=>{this.flushUpdates()},d.DEBOUNCE_MS);flushUpdates(){if(!this.isUpdating){this.isUpdating=!0;try{const e=new Set,s=this.subscriptionManager.getSubscriptionsForKey("*");if(s&&s.size>0&&this.updateQueue.size>0)for(const i of s){const n=this.subscriptionManager.getSubscription(i);if(!n)continue;if(n.element&&!document.contains(n.element)){this.subscriptionManager.removeSubscription(i);continue}const r=n.element??document.body;try{const a=Array.from(this.updateQueue)[0];n.callback(r,{key:a})}catch(a){console.error("Wildcard subscription callback failed:",a)}}for(const i of this.updateQueue){if(e.has(i))continue;e.add(i);const n=this.subscriptionManager.getSubscriptionsForKey(i);if(n)for(const r of n){const a=this.subscriptionManager.getSubscription(r);if(!a)continue;if(a.element&&!document.contains(a.element)){this.subscriptionManager.removeSubscription(r);continue}const o=a.element??document.body;try{a.callback(o,{key:i})}catch(c){console.error("Subscription callback failed:",c)}}}}finally{this.updateQueue.clear(),this.isUpdating=!1}}}getState(){return this.stateStore}setState(e,s){if(this.previousValues.set(e,this.stateStore[e]),this.stateStore[e]=s,this.previousValues.size>100){const i=this.previousValues.keys().next().value;typeof i=="string"&&this.previousValues.delete(i)}}hasState(e){return e in this.originalStateStore}addSubscription(e){this._subscriptionManager.addSubscription(e)}removeSubscription(e){this._subscriptionManager.removeSubscription(e)}onStateChange(e){return this.eventBus.on("stateChanged",e)}batch(e){const s=this.isUpdating;this.isUpdating=!0;try{return e()}finally{this.isUpdating=s,!this.isUpdating&&this.updateQueue.size&&this.flushUpdates()}}getSubscriptions(){return this.subscriptionManager.getAllSubscriptions()}getKeyIndex(){const e=new Map,s=this.subscriptionManager.getAllSubscriptions();for(const[i,n]of s)for(const r of n.dependencies)e.has(r)||e.set(r,new Set),e.get(r).add(i);return e}}class ce{expressionCache=new $(d.MAX_CACHE_SIZE);dependencyCache=new $(d.MAX_CACHE_SIZE);commonExpressionsCache=new $(100);dependencyParser=new Ns;static CACHE_KEYS={EXPRESSION:(e,s)=>`expr:${e}:${s}`,DEPENDENCY:(e,s)=>`deps:${e}:${s}`,COMMON:e=>`common:${e}`};constructor(){this.precompileCommonExpressions()}normalizeExpression(e){return e.replace(/\r\n/g," ").replace(/\r/g," ").replace(/\n/g," ").replace(/\s+/g," ").trim()}precompileCommonExpressions(){["true","false","null","undefined"].forEach(s=>{const i={fn:new Function("return "+s),contextMap:new Map,dependencies:[s],timestamp:Date.now(),hitCount:0},n=ce.CACHE_KEYS.COMMON(s);this.commonExpressionsCache.set(n,i)})}extractDependencies(e,s,i){const n=this.normalizeExpression(e),r=ce.CACHE_KEYS.DEPENDENCY(s,n);let a=this.dependencyCache.get(r);return a||(a=this.dependencyParser.extract(n,s,i),this.dependencyCache.set(r,a),a)}evaluateExpression(e,s,i){const n=this.normalizeExpression(e),r=ce.CACHE_KEYS.COMMON(n);let a=this.commonExpressionsCache.get(r);if(a){a.hitCount++;try{return a.fn()}catch(c){console.error(`Common expression evaluation failed: "${n}"`,c);return}}const o=ce.CACHE_KEYS.EXPRESSION(i,n);a=this.expressionCache.get(o),(!a||this.isStale(a))&&(a=this.compileExpression(n,s,i),this.expressionCache.set(o,a)),a.hitCount++;try{const c=this.buildArguments(a.contextMap,s);return a.fn(...c)}catch(c){console.error(`Expression evaluation failed: "${n}"`,c),console.error("Available context:",Object.keys(s));return}}compileExpression(e,s,i){const n=this.prepareSafeContext(s),r=new Map,a=[];Object.keys(n).forEach((c,l)=>{r.set(c,l),a.push(c)});const o=this.dependencyParser.extract(e,i);return{fn:new Function(...a,`return (${e})`),contextMap:r,dependencies:o,timestamp:Date.now(),hitCount:0}}buildArguments(e,s){const i=new Array(e.size);for(const[n,r]of e)i[r]=s[n];return i}isStale(e){return Date.now()-e.timestamp>3e5}prepareSafeContext(e){const s={};for(const[i,n]of Object.entries(e))xe.has(i)||!this.isValidJavaScriptIdentifier(i)||(s[i]=n);return s}isValidJavaScriptIdentifier(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)&&!xe.has(e)}invalidateCache(e){switch(e){case"expressions":this.expressionCache.clear();break;case"dependencies":this.dependencyCache.clear();break;case"common":this.commonExpressionsCache.clear(),this.precompileCommonExpressions();break;case"parser":this.dependencyParser.clearCache();break;default:this.clearAllCaches()}}invalidateByComponent(e){this.expressionCache.deleteByPrefix(`expr:${e}:`),this.dependencyCache.deleteByPrefix(`deps:${e}:`)}clearAllCaches(){this.expressionCache.clear(),this.dependencyCache.clear(),this.commonExpressionsCache.clear(),this.dependencyParser.clearCache(),this.precompileCommonExpressions()}getCacheStats(){return{expressions:this.expressionCache.getStats(),dependencies:this.dependencyCache.getStats(),commonExpressions:this.commonExpressionsCache.getStats(),dependencyParser:this.getDependencyParserStats()}}getDependencyParserStats(){return this.dependencyParser.getCacheSize?{size:this.dependencyParser.getCacheSize(),maxSize:500,hitRate:0,hits:0,misses:0}:{size:0,maxSize:0,hitRate:0,hits:0,misses:0}}cleanupStaleExpressions(){let e=0;return this.expressionCache.keys().forEach(i=>{const n=this.expressionCache.get(i);n&&this.isStale(n)&&(this.expressionCache.delete(i),e++)}),e}}class Ns{parseCache=new $(500);extract(e,s,i){const n=this.normalizeExpression(e),r=`${s}:${n}`;if(this.parseCache.has(r))return this.parseCache.get(r);const a=this.parseExpression(n,s,i);return this.parseCache.set(r,a),a}normalizeExpression(e){return e.replace(/\r\n/g," ").replace(/\r/g," ").replace(/\n/g," ").replace(/\s+/g," ").trim()}parseExpression(e,s,i){const n=this.extractIdentifiers(e),r=[],a=i?.getState()||{};for(const c of n){if(xe.has(c))continue;const l=c.indexOf("."),h=l===-1?c:c.substring(0,l),p=Be.findExistingStateKey(h,s,a);if(p)r.push(p);else{const f=s==="app"?[`app.${h}`]:[`${s}.${h}`,`app.${h}`];r.push(...f)}if(l!==-1){const f=s==="app"?[`app.${h}`]:[`${s}.${h}`,`app.${h}`];r.push(...f)}}return Array.from(new Set(r))}extractIdentifiers(e){const s=[];let i=0;for(;i<e.length;){const n=e[i];if(n==="'"){i=this.skipString(e,i,"'");continue}if(n==='"'){i=this.skipString(e,i,'"');continue}if(n==="`"){i=this.skipTemplateLiteral(e,i,s);continue}if(this.isIdentifierStart(n)){const r=this.extractIdentifier(e,i);s.push(r.value),i=r.endIndex;continue}i++}return s}skipString(e,s,i){let n=s+1;for(;n<e.length&&e[n]!==i;)e[n]==="\\"&&n++,n++;return n+1}skipTemplateLiteral(e,s,i){let n=s+1;for(;n<e.length&&e[n]!=="`";){if(e[n]==="$"&&n+1<e.length&&e[n+1]==="{"){n+=2;let r=1;for(;n<e.length&&r>0;){const a=e[n];if(a==='"'||a==="'"){n=this.skipString(e,n,a);continue}if(a==="{"?r++:a==="}"&&r--,r>0&&this.isIdentifierStart(a)){const o=this.extractIdentifier(e,n);i.push(o.value),n=o.endIndex-1}n++}continue}e[n]==="\\"&&n++,n++}return n+1}extractIdentifier(e,s){let i=s;for(;i<e.length&&(this.isIdentifierPart(e[i])||e[i]===".");)i++;return{value:e.substring(s,i),endIndex:i}}isIdentifierStart(e){return/[a-zA-Z_$]/.test(e)}isIdentifierPart(e){return/[a-zA-Z0-9_$]/.test(e)}clearCache(){this.parseCache.clear()}getCacheSize(){return this.parseCache.cache.size}}class Ms{componentStack=["app"];elementProps=new WeakMap;contextCache=new $(100);contextIndex=new Map;contextInvalidated=new Set;stateManager;processedScripts=new WeakSet;componentFunctions=new Map;expressionEvaluator;domBindingManager;loopManager;templateRenderer;updateTimeouts;updateBatcher=new et;propDependencyCache=new Map;constructor(e){this.stateManager=e,this.updateBatcher=new et,this.stateManager.onStateChange(s=>this.invalidateContextCache(s))}getPropDependencies(e,s){const i=this.findElementWithProps(s);if(!i)return[];const n=this.elementProps.get(i);if(!n||!n.has(e))return[];const r=n.get(e);return this.templateRenderer?.dependencies(r.expression,r.component,this.stateManager)||[]}buildRestrictedComponentContext(e,s=!1){const i={};window[e]&&Object.assign(i,window[e]);const n=this.componentFunctions.get(e);if(n)for(const[a,o]of n)i[a]=o;const r=this.stateManager.getState();for(const a of Object.keys(r))if(a.startsWith(e+".")){const o=a.substring(e.length+1);o in i||(i[o]=r[a])}if(s){if(window.app)for(const[o,c]of Object.entries(window.app))o in i||(i[o]=c);const a=this.componentFunctions.get("app");if(a)for(const[o,c]of a)o in i||(i[o]=c);for(const o of Object.keys(r))if(o.startsWith("app.")){const c=o.substring(4);c in i||(i[c]=r[o])}}return i}getComponentPropDependencies(e,s){if(this.propDependencyCache.has(e))return this.propDependencyCache.get(e);const i=[],n=this.elementProps.get(e);n&&this.templateRenderer&&n.forEach(a=>{const o=this.templateRenderer?.dependencies(a.expression,a.component,this.stateManager);i.push(...o??[])});const r=Array.from(new Set(i));return this.propDependencyCache.set(e,r),r}setDOMBindingManager(e){this.domBindingManager=e,this.updateBatcher.setManagers(this,e)}hasStoredProps(e){return this.elementProps.has(e)&&this.elementProps.get(e).size>0}setExpressionEvaluator(e){this.expressionEvaluator=e,this.templateRenderer=new Ke(e),this.loopManager=new Ft(this.stateManager,e)}extractProps(e,s){const i=new Map,n=e.attributes,r=e.getAttribute(d.ATTR_PREFIXES.CONTEXT),a=e.getAttribute(d.ATTR_PREFIXES.COMPONENT);let o=s;r&&(r==="app"?o="app":r==="parent"?o=y.getParentOfComponent(a||"app",e):o=r);for(let c=0;c<n.length;c++){const l=n[c];if(!(l.name===d.ATTR_PREFIXES.COMPONENT||l.name===d.ATTR_PREFIXES.CONTEXT||l.name===d.ATTR_PREFIXES.SPREAD||l.name===d.ATTR_PREFIXES.LOOP)&&!oe.isEventAttribute(l.name)&&l.value&&_s.containsMustacheExpression(l.value)){if(a&&this.mightReferenceSelfProps(l.value,e))continue;const h=this.attributeToPropName(l.name),p={name:h,expression:l.value,component:o,subscriptionIds:[]};i.set(h,p)}}return i}mightReferenceSelfProps(e,s){const i=this.elementProps.get(s);return i?Array.from(i.keys()).some(r=>e.includes(r)&&r!=="dataState"):!1}attributeToPropName(e){return e.replace(/-([a-z])/g,(s,i)=>i.toUpperCase())}setupProps(e,s){const i=this.extractProps(e,s);i.size!==0&&(this.elementProps.set(e,i),this.expressionEvaluator&&i.forEach((n,r)=>{this.setupPropBinding(e,n)}))}setupPropBinding(e,s){if(!this.expressionEvaluator)return;const i=`prop_${Date.now()}_${Math.random()}`,n=this.templateRenderer?.dependencies(s.expression,s.component,this.stateManager)||[],r={id:i,selector:"",dependencies:new Set(n),callback:()=>{const a=e.getAttribute(d.ATTR_PREFIXES.COMPONENT);a&&(this.updateBatcher.scheduleUpdate(a,e),this.refreshComponentBindings(e,a))},element:e,component:s.component};this.stateManager.addSubscription(r),s.subscriptionIds.push(i)}refreshComponentBindings(e,s){this.contextInvalidated.add(s),this.contextCache.delete(s),this.domBindingManager&&this.domBindingManager.refreshComponentElement(e,s)}evaluateProps(e){const s={},i=this.elementProps.get(e);if(!i||!this.expressionEvaluator)return s;const n=i.values().next().value;if(!n)return s;const r=this.buildComponentContext(n.component);return i.forEach((a,o)=>{try{const c=this.templateRenderer?.render(a.expression,r,a.component);typeof c=="function"?s[o]=(...l)=>c.apply(this,l):s[o]=c}catch(c){console.error(`❌ Failed to evaluate prop "${o}":`,c),s[o]=void 0}}),s}cleanupProps(e){const s=this.elementProps.get(e);s&&(s.forEach(i=>{i.subscriptionIds.forEach(n=>{this.stateManager.removeSubscription(n)})}),this.elementProps.delete(e))}buildComponentContextWithProps(e,s){const i=this.buildComponentContext(e);let n=this.findElementWithProps(e);if(s&&this.elementProps.has(s)&&(n=s),n)try{const r=this.evaluatePropsWithContext(n,e,s);Object.keys(r).length>0&&Object.keys(r).forEach(a=>{i[a]=r[a]})}catch(r){console.error(`❌ Error evaluating props for ${e}:`,r)}return i}evaluatePropsWithContext(e,s,i){const n={},r=this.elementProps.get(e);if(!r||!this.expressionEvaluator)return n;const a=r.values().next().value;if(!a)return n;let o;const c=e.getAttribute(d.ATTR_PREFIXES.CONTEXT),l=e.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(c)if(c==="app")o=this.buildComponentContext("app");else if(c==="parent"){const C=y.getParentOfComponent(l||"app",e);o=this.buildComponentContext(C)}else o=this.buildComponentContext(c);else o=this.buildComponentContext(a.component);const h=this.loopManager?.getLoopContextForElement(e);h&&(o={...o,...h});const p=new Map,f=new Map,m=Array.from(r.keys());r.forEach((C,v)=>{m.some(I=>I!==v&&C.expression.includes(I))?f.set(v,C):p.set(v,C)}),p.forEach((C,v)=>{try{const A=this.templateRenderer?.render(C.expression,o,c||C.component);typeof A=="function"?this.isFunctionExplicitlyPassed(C.expression)?n[v]=(...fe)=>A.apply(this,fe):(console.warn(`⚠️ Function "${v}" not passed - not from shared namespace or explicitly passed`),n[v]=void 0):n[v]=A}catch(A){console.error(`❌ Failed to evaluate simple prop "${v}":`,A),console.error("Expression:",C.expression),console.error("Available context keys:",Object.keys(o)),n[v]=void 0}});const x={...o,...n};return f.forEach((C,v)=>{try{const A=this.templateRenderer?.render(C.expression,x,c||C.component);typeof A=="function"?this.isFunctionExplicitlyPassed(C.expression)?n[v]=(...fe)=>A.apply(this,fe):(console.warn(`⚠️ Function "${v}" not passed - not from shared namespace or explicitly passed`),n[v]=void 0):n[v]=A}catch(A){console.error(`❌ Failed to evaluate complex prop "${v}":`,A),console.error("Expression:",C.expression),console.error("Available context keys:",Object.keys(x)),n[v]=void 0}}),n}isFunctionExplicitlyPassed(e){const s=P.isSingleExpression(e);return s?/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(s.trim()):!1}findElementWithProps(e){const s=document.querySelectorAll(`[${d.ATTR_PREFIXES.COMPONENT}="${e}"]`);for(const i of s){const n=this.elementProps.get(i);if(n&&n.size>0)return i}return null}pushComponent(e){this.componentStack.push(e)}popComponent(){return this.componentStack.pop()}getCurrentComponent(){return this.componentStack[this.componentStack.length-1]}buildComponentContext(e){if(!this.contextInvalidated.has(e)&&this.contextCache.has(e))return this.contextCache.get(e);const s=this.computeComponentContext(e);return this.contextCache.set(e,s),this.contextInvalidated.delete(e),s}computeComponentContext(e){const s={};e!=="app"&&window[e]&&Object.assign(s,window[e]),e==="app"&&window.app&&Object.assign(s,window.app);const i=this.componentFunctions.get(e);if(i)for(const[r,a]of i)s[r]=a;if(e!=="app"){const r=this.componentFunctions.get("app");if(r)for(const[a,o]of r)a in s||(s[a]=o);if(window.app)for(const[a,o]of Object.entries(window.app))a in s||(s[a]=o)}const n=this.stateManager.getState();for(const r of Object.keys(n))if(r.startsWith(e+".")){const a=r.substring(e.length+1);a in s||(s[a]=n[r])}if(e!=="app"){for(const r of Object.keys(n))if(r.startsWith("app.")){const a=r.substring(4);a in s||(s[a]=n[r])}}return s}invalidateContextCache(e){if(e.startsWith("app.")){this.contextCache.clear();for(const i of this.contextInvalidated.keys())this.contextInvalidated.add(i);return}const s=e.indexOf(".");if(s!==-1){const i=e.slice(0,s);this.invalidateComponent(i)}}invalidateComponent(e){this.contextInvalidated.add(e),this.contextIndex.delete(e)}executePhpScripts(e){const s=this.componentStack.length,i=e.getAttribute(d.ATTR_PREFIXES.COMPONENT),n=e===document.body;if(i||n){if(i){this.pushComponent(i);const a=this.getParentComponent(e);this.setupProps(e,a)}this.getRelevantScripts(e,n).forEach(a=>{const o=a.getAttribute(d.ATTR_PREFIXES.COMPONENT);o&&o!==i?(this.pushComponent(o),this.executeScript(a),this.popComponent()):this.executeScript(a)})}for(Array.from(e.children).forEach(r=>this.executePhpScripts(r));this.componentStack.length>s;)this.popComponent()}getParentComponent(e){let s=e.parentElement;for(;s;){const i=s.getAttribute(d.ATTR_PREFIXES.COMPONENT);if(i)return i;s=s.parentElement}return"app"}getRelevantScripts(e,s){return Array.from(e.querySelectorAll(`script[type="${d.SCRIPT_TYPE}"]`)).filter(i=>{if(this.processedScripts.has(i))return!1;if(s)return i.hasAttribute(d.ATTR_PREFIXES.COMPONENT)?!0:!i.closest(`[${d.ATTR_PREFIXES.COMPONENT}]`);let n=i.parentElement;for(;n&&n!==e;){if(n.hasAttribute(d.ATTR_PREFIXES.COMPONENT))return!1;n=n.parentElement}return n===e||e.contains(i)})}executeScript(e){if(this.processedScripts.has(e))return;this.processedScripts.add(e);const s=this.getCurrentComponent(),i=e.textContent||"",n=P.decodeEntities(i);try{const r=this.findComponentElementForScript(e,s);if(r===e){const o=this.getParentComponent(e);this.setupProps(e,o)}const a=this.buildComponentContextWithProps(s,r);window[s]||(window[s]={}),this.executeScriptFunctions(n,s,a)}catch(r){console.error(`Script execution failed in component ${s}:`,r),console.error("Script content:",n)}}findComponentElementForScript(e,s){if(e.getAttribute(d.ATTR_PREFIXES.COMPONENT)===s)return e;let i=e.parentElement;for(;i;){if(i.getAttribute(d.ATTR_PREFIXES.COMPONENT)===s)return i;i=i.parentElement}const n=document.querySelectorAll(`[${d.ATTR_PREFIXES.COMPONENT}="${s}"]`);for(const r of n)if(this.elementProps.has(r))return r;return n[0]||void 0}executeScriptFunctions(e,s,i){const n=this.extractFunctionNames(e),r=this.findElementWithProps(s),a=this.extractVariableDeclarations(e);let o={...i};if(a.forEach(x=>{delete o[x];const C=`set${Vt(x)}`,v=`${x}Getter`;delete o[C],delete o[v]}),r){const x=this.evaluateProps(r);Object.assign(o,x)}o.getContext=()=>this.buildComponentContextWithProps(s),o.withContext=x=>{const C=this.buildComponentContextWithProps(s);return x.call(C,C)},o.__getProp=x=>{if(r)return this.evaluateProps(r)[x]};let l=q.getInstance().transformStateDeclarations(e);l=this.modifyScriptForReactiveProps(l,s,r||void 0);const h=`
|
|
17
17
|
${l}
|
|
18
18
|
|
|
19
19
|
${n.map(x=>`
|
|
@@ -39,4 +39,4 @@ Defaulting to 2020, but this will stop working in the future.`)),e.ecmaVersion=1
|
|
|
39
39
|
console.error('Component:', '${s}');
|
|
40
40
|
console.error('Available context keys:', Object.keys(context));
|
|
41
41
|
}
|
|
42
|
-
`);return this.handlerCache.set(i,r),r}executeHandler(e,s,i){if(!this.componentManager||!this.expressionEvaluator){console.warn("EventDelegationManager dependencies not set");return}try{let n=e.component,r=s;for(;r;){const m=r.__uniqueComponentName;if(m){n=m;break}r=r.parentElement}const a=s.getAttribute(d.ATTR_PREFIXES.CONTEXT),o=a==="app"||a==="parent",l=y.getElementComponent(s)==="app",h=y.findElementForComponent(s,n);let p;if(o||l)p=this.componentManager.buildComponentContextWithProps(n==="app"||a==="app"?"app":n,h||void 0);else if(p=this.componentManager.buildRestrictedComponentContext(n,!1),h){const m=this.componentManager.evaluateProps(h);Object.assign(p,m)}const f=this.loopManager?.getLoopContextForElement(s);if(f){const m={};for(const[x,C]of Object.entries(f))typeof C!="function"&&(m[x]=C);p={...m,...p}}e.compiledFn||(e.compiledFn=this.compileHandler(e.code,n)),e.compiledFn&&e.compiledFn(i,s,p)}catch(n){console.error("💥 Event handler execution failed:",n),console.error("Handler code:",e.code),console.error("Handler component:",e.component)}}attachDirectListener(e,s,i){const n=r=>{this.executeHandler(i,e,r)};e.addEventListener(s,n),e[`__${s}_listener`]=n}removeEventHandler(e,s){const i=this.elementHandlers.get(e);i&&(i.delete(s),i.size===0&&this.elementHandlers.delete(e));const n=this.delegatedEvents.get(s);n&&n.elements.delete?.(e);const r=e[`__${s}_listener`];r&&(e.removeEventListener(s,r),delete e[`__${s}_listener`])}cleanup(){for(const[e,s]of this.delegatedEvents)document.removeEventListener(e,s.listener,!0);this.delegatedEvents.clear(),this.handlerCache.clear(),this.setupEvents.clear()}}class Os{stateManager=new Is;expressionEvaluator=new ce;componentManager=new Ms(this.stateManager);domBindingManager=new Rs(this.stateManager,this.componentManager,this.expressionEvaluator);initialized=!1;hydrationDone=!1;hydrationResolve;hydrationPromise;hydrationCallbacks=new Set;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.componentManager.executePhpScripts(document.body),this.domBindingManager.processElement(document.body,!0),this.domBindingManager.processPendingBindings(),Promise.resolve().then(()=>{requestAnimationFrame(()=>{this.markHydrated()})}))}ref(e=null){return{current:e}}hydrated(){return this.hydrationPromise}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,s){const i=this.componentManager.getCurrentComponent();let n,r;typeof e=="string"&&arguments.length===2?(n=e,r=s):typeof e=="string"&&arguments.length===1?this.looksLikeVariableName(e)?(n=e,r=void 0):(console.warn("pp.state() called with string that doesn't look like variable name:",e),n="unknownState",r=e):(console.warn("pp.state() called without explicit key - this should be handled by AST transformation"),n="unknownState",r=e),r&&typeof r=="function"&&"__pphp_key"in r&&(r=r.value);let a;const o=this.getLoopExecutionContext();if(o){const p=this.generateLoopInstanceId(o);a=`${i}.${p}.${n}`}else a=`${i}.${n}`;this.stateManager.hasState(a)||this.stateManager.setInitialState(a,r);const c=(()=>this.stateManager.getState()[a]),l=new Proxy(c,{get(p,f,m){if(f==="__pphp_key"||f==="__pphp_fullKey"||f==="__pphp_component"||f==="value"||f==="valueOf"||f==="toString")return Reflect.get(p,f,m);const x=p();if(x!=null){if(f in Object(x)){const C=x[f];return typeof C=="function"?C.bind(x):C}return Reflect.get(p,f,m)}},has(p,f){if(f==="__pphp_key"||f==="__pphp_fullKey"||f==="__pphp_component"||f==="value"||f==="valueOf"||f==="toString")return Reflect.has(p,f);const m=p();return m!=null&&f in Object(m)?!0:Reflect.has(p,f)},apply(p,f,m){return Reflect.apply(p,f,m)}});Object.defineProperty(l,"__pphp_key",{value:n,enumerable:!1,writable:!1}),Object.defineProperty(l,"__pphp_fullKey",{value:a,enumerable:!1,writable:!1}),Object.defineProperty(l,"__pphp_component",{value:i,enumerable:!1,writable:!1}),Object.defineProperty(l,"value",{get:()=>this.stateManager.getState()[a],enumerable:!0,configurable:!0}),c.valueOf=()=>this.stateManager.getState()[a],c.toString=()=>ie(this.stateManager.getState()[a]);const h=p=>{const f=this.stateManager.getState()[a],m=typeof p=="function"?p(f):p;this.stateManager.setState(a,m)};return this.createComponentScopedGlobals(i,n,l,h),[l,h]}currentLoopContext=null;getLoopExecutionContext(){return this.currentLoopContext}generateLoopInstanceId(e){const i=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(i.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(" ")&&!xe.has(e)}effect(e,s){const i=`effect_${Date.now()}_${Math.random()}`,n=this.componentManager.getCurrentComponent();let r,a=!1,o,c;if(arguments.length===1)o="always",c={immediate:!0,detectDeps:!0};else if(Array.isArray(s)){const h=this.extractDependencyNames(s,n);h.length===0?(o="once",c={deps:h,immediate:!0}):(o="deps",c={deps:h,immediate:!0})}else{const h={immediate:!0,...s||{}};if(!h.deps||h.deps.length===0)o="always",c={immediate:h.immediate,detectDeps:!0};else{const p=this.extractDependencyNames(h.deps,n);o="deps",c={deps:p,immediate:h.immediate,detectDeps:h.detectDeps}}}const l=()=>{a||this.stateManager.onDOMUpdateComplete(()=>{if(!a){if(r&&typeof r=="function")try{r()}catch(h){console.error("Effect cleanup error:",h)}try{r=e()}catch(h){console.error("Effect callback error:",h)}}})};switch(o){case"always":const h=["*"],p={id:i,selector:"",dependencies:new Set(h),callback:l,component:n};this.stateManager.addSubscription(p);break;case"once":break;case"deps":const f=this.resolveDependencies(c.deps,n);if(f.length){const m={id:i,selector:"",dependencies:new Set(f),callback:l,component:n};this.stateManager.addSubscription(m)}break}return c.immediate!==!1&&l(),()=>{if(a=!0,r&&typeof r=="function")try{r()}catch(h){console.error("Effect cleanup error:",h)}this.stateManager.removeSubscription(i)}}extractDependencyNames(e,s){const i=[];for(const n of e)typeof n=="string"?i.push(n):typeof n=="function"&&n.__pphp_key?i.push(n.__pphp_key):console.warn("Invalid dependency in effect:",n);return i.filter(Boolean)}resolveDependencies(e,s){const i=[],n=this.stateManager.getState();for(const r of e)if(r.includes(".")){const a=r.split("."),o=a[0],c=a.slice(1).join("."),l=this.componentManager.getPropDependencies(o,s);if(l.length>0)i.push(...l);else{const h=Be.findExistingStateKey(o,s,n);h?i.push(`${h}.${c}`):i.push(`${s}.${r}`)}}else{const a=this.componentManager.getPropDependencies(r,s);if(a.length>0)i.push(...a);else{const o=Be.findExistingStateKey(r,s,n);o?i.push(o):i.push(`${s}.${r}`)}}return Array.from(new Set(i))}createComponentScopedGlobals(e,s,i,n){window[e]||(window[e]={});const r=`set${Vt(s)}`;Object.defineProperty(window[e],s,{get:()=>i.valueOf(),configurable:!0,enumerable:!0}),window[e][r]=n,window[e][`${s}Getter`]=i}}export{Os as P};
|
|
42
|
+
`);return this.handlerCache.set(i,r),r}executeHandler(e,s,i){if(!this.componentManager||!this.expressionEvaluator){console.warn("EventDelegationManager dependencies not set");return}try{let n=e.component,r=s;for(;r;){const m=r.__uniqueComponentName;if(m){n=m;break}r=r.parentElement}const a=s.getAttribute(d.ATTR_PREFIXES.CONTEXT),o=a==="app"||a==="parent",l=y.getElementComponent(s)==="app",h=y.findElementForComponent(s,n);let p;if(o||l)p=this.componentManager.buildComponentContextWithProps(n==="app"||a==="app"?"app":n,h||void 0);else if(p=this.componentManager.buildRestrictedComponentContext(n,!1),h){const m=this.componentManager.evaluateProps(h);Object.assign(p,m)}const f=this.loopManager?.getLoopContextForElement(s);if(f){const m={};for(const[x,C]of Object.entries(f))typeof C!="function"&&(m[x]=C);p={...m,...p}}e.compiledFn||(e.compiledFn=this.compileHandler(e.code,n)),e.compiledFn&&e.compiledFn(i,s,p)}catch(n){console.error("💥 Event handler execution failed:",n),console.error("Handler code:",e.code),console.error("Handler component:",e.component)}}attachDirectListener(e,s,i){const n=r=>{this.executeHandler(i,e,r)};e.addEventListener(s,n),e[`__${s}_listener`]=n}removeEventHandler(e,s){const i=this.elementHandlers.get(e);i&&(i.delete(s),i.size===0&&this.elementHandlers.delete(e));const n=this.delegatedEvents.get(s);n&&n.elements.delete?.(e);const r=e[`__${s}_listener`];r&&(e.removeEventListener(s,r),delete e[`__${s}_listener`])}cleanup(){for(const[e,s]of this.delegatedEvents)document.removeEventListener(e,s.listener,!0);this.delegatedEvents.clear(),this.handlerCache.clear(),this.setupEvents.clear()}}class Os{stateManager=new Is;expressionEvaluator=new ce;componentManager=new Ms(this.stateManager);domBindingManager=new Rs(this.stateManager,this.componentManager,this.expressionEvaluator);initialized=!1;hydrationDone=!1;hydrationResolve;hydrationPromise;hydrationCallbacks=new Set;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.componentManager.executePhpScripts(document.body),this.domBindingManager.processElement(document.body,!0),this.domBindingManager.processPendingBindings(),Promise.resolve().then(()=>{requestAnimationFrame(()=>{this.markHydrated()})}))}reinitialize(){this.componentManager.setExpressionEvaluator(this.expressionEvaluator),this.componentManager.executePhpScripts(document.body),this.domBindingManager.processElement(document.body,!0),this.domBindingManager.processPendingBindings()}cleanup(e){e?(this.stateManager.clearComponentState(e),this.stateManager.clearComponentSubscriptions(e),window[e]&&delete window[e]):(this.stateManager.clearState(),this.stateManager.clearSubscriptions(),this.hydrationCallbacks.clear()),this.stateManager.invalidateContextCache()}ref(e=null){return{current:e}}hydrated(){return this.hydrationPromise}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,s){const i=this.componentManager.getCurrentComponent();let n,r;typeof e=="string"&&arguments.length===2?(n=e,r=s):typeof e=="string"&&arguments.length===1?this.looksLikeVariableName(e)?(n=e,r=void 0):(console.warn("pp.state() called with string that doesn't look like variable name:",e),n="unknownState",r=e):(console.warn("pp.state() called without explicit key - this should be handled by AST transformation"),n="unknownState",r=e),r&&typeof r=="function"&&"__pphp_key"in r&&(r=r.value);let a;const o=this.getLoopExecutionContext();if(o){const p=this.generateLoopInstanceId(o);a=`${i}.${p}.${n}`}else a=`${i}.${n}`;this.stateManager.hasState(a)||this.stateManager.setInitialState(a,r);const c=(()=>this.stateManager.getState()[a]),l=new Proxy(c,{get(p,f,m){if(f==="__pphp_key"||f==="__pphp_fullKey"||f==="__pphp_component"||f==="value"||f==="valueOf"||f==="toString")return Reflect.get(p,f,m);const x=p();if(x!=null){if(f in Object(x)){const C=x[f];return typeof C=="function"?C.bind(x):C}return Reflect.get(p,f,m)}},has(p,f){if(f==="__pphp_key"||f==="__pphp_fullKey"||f==="__pphp_component"||f==="value"||f==="valueOf"||f==="toString")return Reflect.has(p,f);const m=p();return m!=null&&f in Object(m)?!0:Reflect.has(p,f)},apply(p,f,m){return Reflect.apply(p,f,m)}});Object.defineProperty(l,"__pphp_key",{value:n,enumerable:!1,writable:!1}),Object.defineProperty(l,"__pphp_fullKey",{value:a,enumerable:!1,writable:!1}),Object.defineProperty(l,"__pphp_component",{value:i,enumerable:!1,writable:!1}),Object.defineProperty(l,"value",{get:()=>this.stateManager.getState()[a],enumerable:!0,configurable:!0}),c.valueOf=()=>this.stateManager.getState()[a],c.toString=()=>ie(this.stateManager.getState()[a]);const h=p=>{const f=this.stateManager.getState()[a],m=typeof p=="function"?p(f):p;this.stateManager.setState(a,m)};return this.createComponentScopedGlobals(i,n,l,h),[l,h]}currentLoopContext=null;getLoopExecutionContext(){return this.currentLoopContext}generateLoopInstanceId(e){const i=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(i.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(" ")&&!xe.has(e)}effect(e,s){const i=`effect_${Date.now()}_${Math.random()}`,n=this.componentManager.getCurrentComponent();let r,a=!1,o,c;if(arguments.length===1)o="always",c={immediate:!0,detectDeps:!0};else if(Array.isArray(s)){const h=this.extractDependencyNames(s,n);h.length===0?(o="once",c={deps:h,immediate:!0}):(o="deps",c={deps:h,immediate:!0})}else{const h={immediate:!0,...s||{}};if(!h.deps||h.deps.length===0)o="always",c={immediate:h.immediate,detectDeps:!0};else{const p=this.extractDependencyNames(h.deps,n);o="deps",c={deps:p,immediate:h.immediate,detectDeps:h.detectDeps}}}const l=()=>{a||this.stateManager.onDOMUpdateComplete(()=>{if(!a){if(r&&typeof r=="function")try{r()}catch(h){console.error("Effect cleanup error:",h)}try{r=e()}catch(h){console.error("Effect callback error:",h)}}})};switch(o){case"always":const h=["*"],p={id:i,selector:"",dependencies:new Set(h),callback:l,component:n};this.stateManager.addSubscription(p);break;case"once":break;case"deps":const f=this.resolveDependencies(c.deps,n);if(f.length){const m={id:i,selector:"",dependencies:new Set(f),callback:l,component:n};this.stateManager.addSubscription(m)}break}return c.immediate!==!1&&l(),()=>{if(a=!0,r&&typeof r=="function")try{r()}catch(h){console.error("Effect cleanup error:",h)}this.stateManager.removeSubscription(i)}}extractDependencyNames(e,s){const i=[];for(const n of e)typeof n=="string"?i.push(n):typeof n=="function"&&n.__pphp_key?i.push(n.__pphp_key):console.warn("Invalid dependency in effect:",n);return i.filter(Boolean)}resolveDependencies(e,s){const i=[],n=this.stateManager.getState();for(const r of e)if(r.includes(".")){const a=r.split("."),o=a[0],c=a.slice(1).join("."),l=this.componentManager.getPropDependencies(o,s);if(l.length>0)i.push(...l);else{const h=Be.findExistingStateKey(o,s,n);h?i.push(`${h}.${c}`):i.push(`${s}.${r}`)}}else{const a=this.componentManager.getPropDependencies(r,s);if(a.length>0)i.push(...a);else{const o=Be.findExistingStateKey(r,s,n);o?i.push(o):i.push(`${s}.${r}`)}}return Array.from(new Set(i))}createComponentScopedGlobals(e,s,i,n){window[e]||(window[e]={});const r=`set${Vt(s)}`;Object.defineProperty(window[e],s,{get:()=>i.valueOf(),configurable:!0,enumerable:!0}),window[e][r]=n,window[e][`${s}Getter`]=i}}export{Os as P};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{P as w}from"./pp-reactive-v1.js";class f extends w{cryptoKey=null;activeAbortController=null;static instance=null;constructor(){super(),this.hydrated().then(()=>{document.body.hidden=!1}).catch(t=>{console.error("PPHPUtilities hydration error:",t),document.body.hidden=!1})}static getInstance(){return this.instance||(this.instance=new f),this.instance}async redirect(t){if(t)try{new URL(t,window.location.origin).origin!==window.location.origin?window.location.href=t:history.pushState(null,"",t)}catch(r){console.error("Redirect error:",r)}}async initCryptoKey(){const t=document.cookie.split("; ").find(s=>s.startsWith("pp_function_call_jwt="))?.split("=",2)[1];if(!t)throw new Error("Missing function-call token");const[,r]=t.split("."),a=atob(r.replace(/-/g,"+").replace(/_/g,"/")),{k:e,exp:o}=JSON.parse(a);if(Date.now()/1e3>o)throw new Error("Function-call token expired");const n=Uint8Array.from(atob(e),s=>s.charCodeAt(0));this.cryptoKey=await crypto.subtle.importKey("raw",n,{name:"AES-CBC"},!1,["encrypt","decrypt"])}async encryptCallbackName(t){await this.initCryptoKey();const r=crypto.getRandomValues(new Uint8Array(16)),a=new TextEncoder().encode(t),e=await crypto.subtle.encrypt({name:"AES-CBC",iv:r},this.cryptoKey,a),o=btoa(String.fromCharCode(...r)),n=btoa(String.fromCharCode(...new Uint8Array(e)));return`${o}:${n}`}createFetchOptions(t){return{method:"POST",headers:{"Content-Type":"application/json",HTTP_PP_WIRE_REQUEST:"true"},body:JSON.stringify(t)}}async fetchFunction(t,r={},a=!1){let e=null;try{a&&this.activeAbortController&&(this.activeAbortController.abort(),this.activeAbortController=null),e=new AbortController,a&&(this.activeAbortController=e);const n={callback:await this.encryptCallbackName(t),...r},s=window.location.href;let d;if(Object.keys(n).some(c=>{const i=n[c];return i instanceof File||i instanceof FileList&&i.length>0})){const c=new FormData;Object.keys(n).forEach(i=>{const l=n[i];l instanceof File?c.append(i,l):l instanceof FileList?Array.from(l).forEach(u=>c.append(i,u)):c.append(i,l)}),d={method:"POST",headers:{HTTP_PP_WIRE_REQUEST:"true"},body:c,signal:e.signal}}else d={signal:e.signal,...this.createFetchOptions(n)};const h=await fetch(s,d);if(!h.ok)throw new Error(`Fetch failed with status: ${h.status} ${h.statusText}`);const y=await h.text();e&&this.activeAbortController===e&&(this.activeAbortController=null);try{return JSON.parse(y)}catch{return y}}catch(o){if(e&&this.activeAbortController===e&&(this.activeAbortController=null),o instanceof Error&&o.name==="AbortError")return console.log("Request was cancelled"),{cancelled:!0};throw console.error("Error in fetchFunction:",o),new Error("Failed to fetch data.")}}}Object.defineProperty(window,"pp",{get:()=>f.getInstance(),set(p){console.warn("[pp] Attempted to override global pp; ignoring.",p)},configurable:!1,enumerable:!0});try{window.pp}catch(p){console.error("PPHPUtilities singleton initialization failed:",p)}
|
|
1
|
+
import{P as g}from"./pp-reactive-v1.js";import{c as y}from"./global-functions.js";class m extends g{cryptoKey=null;activeAbortController=null;static instance=null;navigationEnabled=!1;boundHandleLinkClick=null;boundHandlePopState=null;constructor(){super(),this.hydrated().then(()=>{document.body.hidden=!1,this.enableSPANavigation()}).catch(t=>{console.error("PPHPUtilities hydration error:",t),document.body.hidden=!1})}static getInstance(){return this.instance||(this.instance=new m),this.instance}enableSPANavigation(){this.navigationEnabled||(this.navigationEnabled=!0,this.boundHandleLinkClick=this.handleLinkClick.bind(this),this.boundHandlePopState=this.handlePopState.bind(this),document.addEventListener("click",this.boundHandleLinkClick),window.addEventListener("popstate",this.boundHandlePopState))}disableSPANavigation(){this.navigationEnabled=!1,this.boundHandleLinkClick&&(document.removeEventListener("click",this.boundHandleLinkClick),this.boundHandleLinkClick=null),this.boundHandlePopState&&(window.removeEventListener("popstate",this.boundHandlePopState),this.boundHandlePopState=null)}handleLinkClick(t){if(!this.navigationEnabled)return;const n=t.target.closest("a");if(!(!n||!n.href))try{const a=new URL(n.href),o=a.origin!==window.location.origin,i=a.pathname===window.location.pathname&&a.search===window.location.search;if(o||n.target==="_blank"||n.hasAttribute("download")||n.getAttribute("pp-no-spa")==="true"||t.ctrlKey||t.metaKey||t.shiftKey||t.altKey)return;if(t.preventDefault(),i){const s=a.hash;if(s){const r=document.querySelector(s);r&&r.scrollIntoView({behavior:"smooth"})}else window.scrollTo({top:0,behavior:"smooth"});return}this.navigateTo(a.pathname+a.search+a.hash)}catch(a){console.error("Link click navigation error:",a)}}async handlePopState(){const t=window.location.pathname+window.location.search+window.location.hash;await this.navigateTo(t,!1)}async navigateTo(t,e=!0){try{document.dispatchEvent(new CustomEvent("pp:navigation:start",{detail:{url:t}}));const n=document.getElementById("loading-file-1B87E");if(n){const c=this.findLoadingElement(n,window.location.pathname);c&&await this.updateContentWithTransition(c)}const a=await fetch(t,{headers:{"X-Requested-With":"XMLHttpRequest",Accept:"text/html"}});if(!a.ok)throw new Error(`Navigation failed: ${a.status} ${a.statusText}`);const o=await a.text(),s=new DOMParser().parseFromString(o,"text/html");s.title&&(document.title=s.title),this.cleanup(),this.reconcileHead(s);const r=s.body;document.body.innerHTML=r.innerHTML,e&&history.pushState(null,"",t),this.reinitialize(),document.body.hidden=!1;const d=new URL(t,window.location.origin).hash;if(d){const c=document.querySelector(d);c&&c.scrollIntoView({behavior:"smooth"})}else window.scrollTo({top:0,behavior:"instant"});document.dispatchEvent(new CustomEvent("pp:navigation:complete",{detail:{url:t}}))}catch(n){console.error("Navigation error:",n),document.body.hidden=!1,document.dispatchEvent(new CustomEvent("pp:navigation:error",{detail:{url:t,error:n}})),window.location.href=t}}findLoadingElement(t,e){let n=e;for(;;){const a=t.querySelector(`div[pp-loading-url='${n}']`);if(a)return a;if(n==="/")break;const o=n.lastIndexOf("/");o<=0?n="/":n=n.substring(0,o)}return t.querySelector("div[pp-loading-url='/' ]")}async updateContentWithTransition(t){const e=document.querySelector("[pp-loading-content='true']")||document.body;if(!e)return;const{fadeIn:n,fadeOut:a}=this.parseTransition(t);await this.fadeOut(e,a),e.innerHTML=t.innerHTML,this.fadeIn(e,n)}parseTransition(t){let e=250,n=250;const o=t.querySelector("[pp-loading-transition]")?.getAttribute("pp-loading-transition");if(o){let i=JSON.parse(o);i&&typeof i=="object"?(e=this.parseTime(i.fadeIn??e),n=this.parseTime(i.fadeOut??n)):console.warn("pp-loading-transition is not valid JSON → default values (250 ms) will be used. String:",o)}return{fadeIn:e,fadeOut:n}}fadeOut(t,e){return new Promise(n=>{t.style.transition=`opacity ${e}ms ease-out`,t.style.opacity="0",setTimeout(()=>{t.style.transition="",n()},e)})}fadeIn(t,e){t.style.transition=`opacity ${e}ms ease-in`,t.style.opacity="1",setTimeout(()=>{t.style.transition=""},e)}parseTime(t){if(typeof t=="number")return t;const e=t.match(/^(\d+)(ms|s|m)?$/);if(e){const n=parseInt(e[1],10);switch(e[2]||"ms"){case"ms":return n;case"s":return n*1e3;case"m":return n*60*1e3;default:return n}}return 0}reconcileHead(t){const e="pp-dynamic-script",n="pp-dynamic-meta",a="pp-dynamic-link";document.head.querySelectorAll(`[${n}]`).forEach(o=>o.remove()),document.head.querySelectorAll(`[${a}]`).forEach(o=>o.remove()),document.head.querySelectorAll(`[${e}]`).forEach(o=>o.remove()),Array.from(t.head.children).forEach(o=>{switch(o.tagName){case"SCRIPT":if(o.hasAttribute(e)){const i=document.createElement("script");Array.from(o.attributes).forEach(s=>i.setAttribute(s.name,s.value)),i.textContent=o.textContent,document.head.appendChild(i)}break;case"META":{const i=o;if(i.getAttribute("charset")||i.name==="viewport")break;const s=i.name?`meta[name="${i.name}"]`:`meta[property="${i.getAttribute("property")}"]`,r=i.cloneNode(!0),d=document.head.querySelector(s);d?document.head.replaceChild(r,d):document.head.insertBefore(r,document.head.querySelector("title")?.nextSibling||null);break}case"TITLE":{const i=o.cloneNode(!0),s=document.head.querySelector("title");s?document.head.replaceChild(i,s):document.head.appendChild(i);break}case"LINK":{const i=o;if(i.rel==="icon"){const s=i.cloneNode(!0),r=document.head.querySelector('link[rel="icon"]');r?document.head.replaceChild(s,r):document.head.appendChild(s)}else i.hasAttribute(a)&&document.head.appendChild(i.cloneNode(!0));break}}})}async redirect(t){if(t)try{const e=new URL(t,window.location.origin);e.origin!==window.location.origin?window.location.href=t:this.navigationEnabled?await this.navigateTo(e.pathname+e.search+e.hash):window.location.href=t}catch(e){console.error("Redirect error:",e)}}async initCryptoKey(){const t=document.cookie.split("; ").find(s=>s.startsWith("pp_function_call_jwt="))?.split("=",2)[1];if(!t)throw new Error("Missing function-call token");const[,e]=t.split("."),n=atob(e.replace(/-/g,"+").replace(/_/g,"/")),{k:a,exp:o}=JSON.parse(n);if(Date.now()/1e3>o)throw new Error("Function-call token expired");const i=Uint8Array.from(atob(a),s=>s.charCodeAt(0));this.cryptoKey=await crypto.subtle.importKey("raw",i,{name:"AES-CBC"},!1,["encrypt","decrypt"])}async encryptCallbackName(t){await this.initCryptoKey();const e=crypto.getRandomValues(new Uint8Array(16)),n=new TextEncoder().encode(t),a=await crypto.subtle.encrypt({name:"AES-CBC",iv:e},this.cryptoKey,n),o=btoa(String.fromCharCode(...e)),i=btoa(String.fromCharCode(...new Uint8Array(a)));return`${o}:${i}`}createFetchOptions(t){return{method:"POST",headers:{"Content-Type":"application/json",HTTP_PP_WIRE_REQUEST:"true"},body:JSON.stringify(t)}}async fetchFunction(t,e={},n=!1){let a=null;try{n&&this.activeAbortController&&(this.activeAbortController.abort(),this.activeAbortController=null),a=new AbortController,n&&(this.activeAbortController=a);const i={callback:await this.encryptCallbackName(t),...e},s=window.location.href;let r;if(Object.keys(i).some(h=>{const l=i[h];return l instanceof File||l instanceof FileList&&l.length>0})){const h=new FormData;Object.keys(i).forEach(l=>{const f=i[l];f instanceof File?h.append(l,f):f instanceof FileList?Array.from(f).forEach(S=>h.append(l,S)):h.append(l,f)}),r={method:"POST",headers:{HTTP_PP_WIRE_REQUEST:"true"},body:h,signal:a.signal}}else r={signal:a.signal,...this.createFetchOptions(i)};const c=await fetch(s,r);if(!c.ok)throw new Error(`Fetch failed with status: ${c.status} ${c.statusText}`);const w=await c.text();a&&this.activeAbortController===a&&(this.activeAbortController=null);try{return JSON.parse(w)}catch{return w}}catch(o){if(a&&this.activeAbortController===a&&(this.activeAbortController=null),o instanceof Error&&o.name==="AbortError")return console.log("Request was cancelled"),{cancelled:!0};throw console.error("Error in fetchFunction:",o),new Error("Failed to fetch data.")}}}class u{state;static instance=null;listeners;pp;STORAGE_KEY;lastSyncedState=null;constructor(t={}){this.state=t,this.listeners=[],this.pp=m.getInstance(),this.STORAGE_KEY=this.getCookie("pp_local_store_key")||"pp_local_store_59e13",this.lastSyncedState=localStorage.getItem(this.STORAGE_KEY),this.loadState()}static getInstance(t={}){return u.instance||(u.instance=new u(t)),u.instance}getCookie(t){return document.cookie.split("; ").find(e=>e.startsWith(t+"="))?.split("=")[1]||null}setState(t,e=!1){const n={...this.state,...t};if(JSON.stringify(n)!==JSON.stringify(this.state)&&(this.state=n,this.listeners.forEach(a=>a(this.state)),this.saveState(),e)){const a=localStorage.getItem(this.STORAGE_KEY);a&&a!==this.lastSyncedState&&(this.pp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]:a}),this.lastSyncedState=a)}}saveState(){localStorage.setItem(this.STORAGE_KEY,JSON.stringify(this.state))}loadState(){const t=localStorage.getItem(this.STORAGE_KEY);t&&(this.state=JSON.parse(t),this.listeners.forEach(e=>e(this.state)))}resetState(t,e=!1){if(t?(delete this.state[t],this.saveState()):(this.state={},localStorage.removeItem(this.STORAGE_KEY)),this.listeners.forEach(n=>n(this.state)),e){const n=t?localStorage.getItem(this.STORAGE_KEY):null;this.pp.fetchFunction(this.STORAGE_KEY,{[this.STORAGE_KEY]:n}),this.lastSyncedState=n}}}class p{static instance=null;listeners=[];constructor(){}static getInstance(){return p.instance||(p.instance=new p),p.instance}get params(){return new URLSearchParams(window.location.search)}get(t){return this.params.get(t)}set(t,e){const n=this.params;n.set(t,e),this.updateURL(n)}delete(t){const e=this.params;e.delete(t),this.updateURL(e)}replace(t){const e=new URLSearchParams;for(const n in t){const a=t[n];a!==null&&e.set(n,a)}this.updateURL(e,!0)}updateURL(t,e=!1){const n=`${window.location.pathname}?${t.toString()}`;e?history.replaceState(null,"",n):history.pushState(null,"",n),this.notifyListeners(t)}listen(t){this.listeners.push(t)}notifyListeners(t){for(const e of this.listeners)e(t)}enablePopStateListener(){window.addEventListener("popstate",()=>{this.notifyListeners(this.params)})}}y("pp",m);y("store",u);y("searchParams",p);
|