@coherent.js/express 1.0.0-beta.3 → 1.0.0-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -0
- package/dist/index.cjs +0 -2368
- package/dist/index.cjs.map +4 -4
- package/dist/index.js +0 -2368
- package/dist/index.js.map +4 -4
- package/package.json +3 -2
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../core/src/
|
|
4
|
-
"sourcesContent": ["/**\n * Enhanced Performance Monitoring System\n *\n * Provides comprehensive performance monitoring with:\n * - Custom metrics\n * - Sampling strategies\n * - Automated reporting\n * - Alert rules\n * - Resource monitoring\n * - Performance budgets\n */\n\n/**\n * Create an enhanced performance monitor\n *\n * @param {Object} options - Configuration options\n * @param {boolean} [options.enabled=true] - Enable monitoring\n * @param {Object} [options.metrics] - Custom metrics configuration\n * @param {Object} [options.sampling] - Sampling strategy configuration\n * @param {Object} [options.reporting] - Automated reporting configuration\n * @param {Object} [options.alerts] - Alert rules configuration\n * @param {Object} [options.resources] - Resource monitoring configuration\n * @param {Object} [options.profiling] - Profiling configuration\n * @returns {Object} Enhanced performance monitor instance\n */\nexport function createPerformanceMonitor(options = {}) {\n const opts = {\n enabled: true,\n metrics: {\n custom: {}\n },\n sampling: {\n enabled: false,\n rate: 1.0,\n strategy: 'random'\n },\n reporting: {\n enabled: false,\n interval: 60000,\n format: 'json',\n batch: {\n enabled: false,\n maxSize: 100,\n flushInterval: 5000\n },\n onReport: null\n },\n alerts: {\n enabled: true,\n rules: []\n },\n resources: {\n enabled: false,\n track: ['memory'],\n interval: 1000\n },\n profiling: {\n enabled: false,\n mode: 'production',\n flamegraph: false,\n tracing: {\n enabled: false,\n sampleRate: 0.01\n }\n },\n ...options\n };\n\n // Ensure nested defaults are preserved\n opts.reporting.batch = {\n enabled: false,\n maxSize: 100,\n flushInterval: 5000,\n ...(options.reporting?.batch || {})\n };\n\n // Metrics storage\n const metrics = {\n builtin: {\n renderTime: { type: 'histogram', unit: 'ms', values: [] },\n componentCount: { type: 'counter', unit: 'renders', value: 0 },\n errorCount: { type: 'counter', unit: 'errors', value: 0 },\n memoryUsage: { type: 'gauge', unit: 'MB', values: [] }\n },\n custom: {}\n };\n\n // Initialize custom metrics\n Object.entries(opts.metrics.custom).forEach(([name, config]) => {\n metrics.custom[name] = {\n type: config.type || 'counter',\n unit: config.unit || '',\n threshold: config.threshold,\n values: config.type === 'histogram' ? [] : undefined,\n value: config.type === 'counter' || config.type === 'gauge' ? 0 : undefined\n };\n });\n\n // Sampling state\n const samplingState = {\n count: 0,\n sampled: 0,\n adaptiveRate: opts.sampling.rate\n };\n\n // Reporting state\n const reportingState = {\n batch: [],\n lastReport: Date.now(),\n reportTimer: null,\n flushTimer: null\n };\n\n // Alert state\n const alertState = {\n triggered: new Map(),\n history: []\n };\n\n // Resource monitoring state\n const resourceState = {\n samples: [],\n timer: null\n };\n\n // Profiling state\n const profilingState = {\n traces: [],\n flamegraphData: []\n };\n\n // Statistics\n const stats = {\n metricsRecorded: 0,\n sampleRate: opts.sampling.rate,\n reportsGenerated: 0,\n alertsTriggered: 0\n };\n\n /**\n * Check if event should be sampled\n */\n function shouldSample() {\n if (!opts.sampling.enabled) return true;\n\n samplingState.count++;\n\n if (opts.sampling.strategy === 'random') {\n return Math.random() < samplingState.adaptiveRate;\n } else if (opts.sampling.strategy === 'deterministic') {\n return samplingState.count % Math.ceil(1 / samplingState.adaptiveRate) === 0;\n } else if (opts.sampling.strategy === 'adaptive') {\n // Adaptive sampling based on recent metric values\n const recentRenderTimes = metrics.builtin.renderTime.values.slice(-10);\n if (recentRenderTimes.length > 0) {\n const avgTime = recentRenderTimes.reduce((a, b) => a + b, 0) / recentRenderTimes.length;\n // Sample more when performance is poor\n samplingState.adaptiveRate = avgTime > 16 ? Math.min(1.0, opts.sampling.rate * 2) : opts.sampling.rate;\n }\n return Math.random() < samplingState.adaptiveRate;\n }\n\n return true;\n }\n\n /**\n * Record a metric value\n */\n function recordMetric(name, value, metadata = {}) {\n if (!opts.enabled) return;\n if (!shouldSample()) return;\n\n stats.metricsRecorded++;\n\n // Check if it's a built-in metric\n const builtinMetric = metrics.builtin[name];\n if (builtinMetric) {\n if (builtinMetric.type === 'histogram') {\n builtinMetric.values.push(value);\n if (builtinMetric.values.length > 1000) {\n builtinMetric.values = builtinMetric.values.slice(-1000);\n }\n } else if (builtinMetric.type === 'counter') {\n builtinMetric.value += value;\n } else if (builtinMetric.type === 'gauge') {\n builtinMetric.values.push(value);\n if (builtinMetric.values.length > 100) {\n builtinMetric.values = builtinMetric.values.slice(-100);\n }\n }\n }\n\n // Check if it's a custom metric\n const customMetric = metrics.custom[name];\n if (customMetric) {\n if (customMetric.type === 'histogram') {\n customMetric.values = customMetric.values || [];\n customMetric.values.push(value);\n if (customMetric.values.length > 1000) {\n customMetric.values = customMetric.values.slice(-1000);\n }\n } else if (customMetric.type === 'counter') {\n customMetric.value = (customMetric.value || 0) + value;\n } else if (customMetric.type === 'gauge') {\n customMetric.values = customMetric.values || [];\n customMetric.values.push(value);\n if (customMetric.values.length > 100) {\n customMetric.values = customMetric.values.slice(-100);\n }\n }\n\n // Check threshold\n if (customMetric.threshold) {\n const currentValue = customMetric.type === 'histogram' || customMetric.type === 'gauge'\n ? customMetric.values[customMetric.values.length - 1]\n : customMetric.value;\n\n if (currentValue > customMetric.threshold) {\n checkAlerts(name, currentValue);\n }\n }\n }\n\n // Add to batch if enabled\n if (opts.reporting.enabled && opts.reporting.batch.enabled) {\n reportingState.batch.push({\n metric: name,\n value,\n metadata,\n timestamp: Date.now()\n });\n\n if (reportingState.batch.length >= opts.reporting.batch.maxSize) {\n flushBatch();\n }\n }\n\n // Check alerts\n checkAlerts(name, value);\n }\n\n /**\n * Check alert rules\n */\n function checkAlerts(metric, value) {\n if (!opts.alerts.enabled) return;\n\n opts.alerts.rules.forEach(rule => {\n if (rule.metric !== metric) return;\n\n let triggered = false;\n\n if (rule.condition === 'exceeds' && value > rule.threshold) {\n triggered = true;\n } else if (rule.condition === 'below' && value < rule.threshold) {\n triggered = true;\n } else if (rule.condition === 'equals' && value === rule.threshold) {\n triggered = true;\n }\n\n if (triggered) {\n const alertKey = `${rule.metric}-${rule.condition}-${rule.threshold}`;\n const lastTriggered = alertState.triggered.get(alertKey);\n const now = Date.now();\n\n // Debounce alerts (don't trigger same alert within 5 seconds)\n if (!lastTriggered || now - lastTriggered > 5000) {\n alertState.triggered.set(alertKey, now);\n alertState.history.push({\n rule,\n value,\n timestamp: now\n });\n stats.alertsTriggered++;\n\n if (rule.action) {\n rule.action(value, rule);\n }\n }\n }\n });\n }\n\n /**\n * Flush batch of metrics\n */\n function flushBatch() {\n if (reportingState.batch.length === 0) return;\n\n const batch = [...reportingState.batch];\n reportingState.batch = [];\n\n if (opts.reporting.onReport) {\n opts.reporting.onReport({ type: 'batch', data: batch });\n }\n }\n\n /**\n * Generate a performance report\n */\n function generateReport() {\n const report = {\n timestamp: Date.now(),\n statistics: { ...stats },\n metrics: {}\n };\n\n // Built-in metrics\n Object.entries(metrics.builtin).forEach(([name, metric]) => {\n if (metric.type === 'histogram') {\n report.metrics[name] = {\n type: 'histogram',\n unit: metric.unit,\n count: metric.values.length,\n min: metric.values.length > 0 ? Math.min(...metric.values) : 0,\n max: metric.values.length > 0 ? Math.max(...metric.values) : 0,\n avg: metric.values.length > 0\n ? metric.values.reduce((a, b) => a + b, 0) / metric.values.length\n : 0,\n p50: percentile(metric.values, 0.5),\n p95: percentile(metric.values, 0.95),\n p99: percentile(metric.values, 0.99)\n };\n } else if (metric.type === 'counter') {\n report.metrics[name] = {\n type: 'counter',\n unit: metric.unit,\n value: metric.value\n };\n } else if (metric.type === 'gauge') {\n report.metrics[name] = {\n type: 'gauge',\n unit: metric.unit,\n current: metric.values.length > 0 ? metric.values[metric.values.length - 1] : 0,\n avg: metric.values.length > 0\n ? metric.values.reduce((a, b) => a + b, 0) / metric.values.length\n : 0\n };\n }\n });\n\n // Custom metrics\n Object.entries(metrics.custom).forEach(([name, metric]) => {\n if (metric.type === 'histogram') {\n report.metrics[name] = {\n type: 'histogram',\n unit: metric.unit,\n count: metric.values?.length || 0,\n min: metric.values?.length > 0 ? Math.min(...metric.values) : 0,\n max: metric.values?.length > 0 ? Math.max(...metric.values) : 0,\n avg: metric.values?.length > 0\n ? metric.values.reduce((a, b) => a + b, 0) / metric.values.length\n : 0,\n p95: percentile(metric.values || [], 0.95),\n p99: percentile(metric.values || [], 0.99)\n };\n } else if (metric.type === 'counter') {\n report.metrics[name] = {\n type: 'counter',\n unit: metric.unit,\n value: metric.value || 0\n };\n } else if (metric.type === 'gauge') {\n report.metrics[name] = {\n type: 'gauge',\n unit: metric.unit,\n current: metric.values?.length > 0 ? metric.values[metric.values.length - 1] : 0,\n avg: metric.values?.length > 0\n ? metric.values.reduce((a, b) => a + b, 0) / metric.values.length\n : 0\n };\n }\n });\n\n // Alerts\n report.alerts = {\n total: alertState.history.length,\n recent: alertState.history.slice(-10)\n };\n\n // Resources\n if (opts.resources.enabled) {\n report.resources = {\n samples: resourceState.samples.slice(-20)\n };\n }\n\n stats.reportsGenerated++;\n\n if (opts.reporting.onReport) {\n opts.reporting.onReport({ type: 'report', data: report });\n }\n\n return report;\n }\n\n /**\n * Calculate percentile\n */\n function percentile(values, p) {\n if (values.length === 0) return 0;\n const sorted = [...values].sort((a, b) => a - b);\n const index = Math.ceil(sorted.length * p) - 1;\n return sorted[Math.max(0, index)];\n }\n\n /**\n * Start resource monitoring\n */\n function startResourceMonitoring() {\n if (!opts.resources.enabled) return;\n\n const collectResources = () => {\n const sample = {\n timestamp: Date.now()\n };\n\n if (opts.resources.track.includes('memory')) {\n if (typeof process !== 'undefined' && process.memoryUsage) {\n const mem = process.memoryUsage();\n sample.memory = {\n heapUsed: mem.heapUsed / 1024 / 1024,\n heapTotal: mem.heapTotal / 1024 / 1024,\n external: mem.external / 1024 / 1024,\n rss: mem.rss / 1024 / 1024\n };\n } else if (typeof performance !== 'undefined' && performance.memory) {\n sample.memory = {\n heapUsed: performance.memory.usedJSHeapSize / 1024 / 1024,\n heapTotal: performance.memory.totalJSHeapSize / 1024 / 1024\n };\n }\n }\n\n resourceState.samples.push(sample);\n if (resourceState.samples.length > 100) {\n resourceState.samples = resourceState.samples.slice(-100);\n }\n\n resourceState.timer = setTimeout(collectResources, opts.resources.interval);\n };\n\n collectResources();\n }\n\n /**\n * Stop resource monitoring\n */\n function stopResourceMonitoring() {\n if (resourceState.timer) {\n clearTimeout(resourceState.timer);\n resourceState.timer = null;\n }\n }\n\n /**\n * Start automated reporting\n */\n function startReporting() {\n if (!opts.reporting.enabled) return;\n\n reportingState.reportTimer = setInterval(() => {\n generateReport();\n }, opts.reporting.interval);\n\n if (opts.reporting.batch.enabled) {\n reportingState.flushTimer = setInterval(() => {\n flushBatch();\n }, opts.reporting.batch.flushInterval);\n }\n }\n\n /**\n * Stop automated reporting\n */\n function stopReporting() {\n if (reportingState.reportTimer) {\n clearInterval(reportingState.reportTimer);\n reportingState.reportTimer = null;\n }\n if (reportingState.flushTimer) {\n clearInterval(reportingState.flushTimer);\n reportingState.flushTimer = null;\n }\n flushBatch(); // Flush remaining batch\n }\n\n /**\n * Start profiling\n */\n function startProfiling() {\n if (!opts.profiling.enabled) return;\n // Profiling implementation would hook into render pipeline\n }\n\n /**\n * Record a trace\n */\n function recordTrace(name, duration, metadata = {}) {\n if (!opts.profiling.enabled || !opts.profiling.tracing.enabled) return;\n\n if (Math.random() < opts.profiling.tracing.sampleRate) {\n profilingState.traces.push({\n name,\n duration,\n metadata,\n timestamp: Date.now()\n });\n\n if (profilingState.traces.length > 1000) {\n profilingState.traces = profilingState.traces.slice(-1000);\n }\n }\n }\n\n /**\n * Measure execution time\n */\n function measure(name, fn, metadata = {}) {\n if (!opts.enabled) return fn();\n\n const start = performance.now();\n try {\n const result = fn();\n const duration = performance.now() - start;\n\n recordMetric('renderTime', duration, { name, ...metadata });\n recordTrace(name, duration, metadata);\n\n return result;\n } catch (error) {\n recordMetric('errorCount', 1, { name, error: error.message });\n throw error;\n }\n }\n\n /**\n * Measure async execution time\n */\n async function measureAsync(name, fn, metadata = {}) {\n if (!opts.enabled) return fn();\n\n const start = performance.now();\n try {\n const result = await fn();\n const duration = performance.now() - start;\n\n recordMetric('renderTime', duration, { name, ...metadata });\n recordTrace(name, duration, metadata);\n\n return result;\n } catch (error) {\n recordMetric('errorCount', 1, { name, error: error.message });\n throw error;\n }\n }\n\n /**\n * Add a custom metric\n */\n function addMetric(name, config) {\n metrics.custom[name] = {\n type: config.type || 'counter',\n unit: config.unit || '',\n threshold: config.threshold,\n values: config.type === 'histogram' ? [] : undefined,\n value: config.type === 'counter' || config.type === 'gauge' ? 0 : undefined\n };\n }\n\n /**\n * Add an alert rule\n */\n function addAlertRule(rule) {\n opts.alerts.rules.push(rule);\n }\n\n /**\n * Get current statistics\n */\n function getStats() {\n return {\n ...stats,\n sampleRate: samplingState.adaptiveRate,\n batchSize: reportingState.batch.length,\n resourceSamples: resourceState.samples.length,\n traces: profilingState.traces.length,\n alerts: {\n total: alertState.history.length,\n unique: alertState.triggered.size\n }\n };\n }\n\n /**\n * Reset all metrics\n */\n function reset() {\n // Reset built-in metrics\n Object.values(metrics.builtin).forEach(metric => {\n if (metric.type === 'histogram' || metric.type === 'gauge') {\n metric.values = [];\n } else if (metric.type === 'counter') {\n metric.value = 0;\n }\n });\n\n // Reset custom metrics\n Object.values(metrics.custom).forEach(metric => {\n if (metric.type === 'histogram' || metric.type === 'gauge') {\n metric.values = [];\n } else if (metric.type === 'counter') {\n metric.value = 0;\n }\n });\n\n // Reset state\n samplingState.count = 0;\n samplingState.sampled = 0;\n reportingState.batch = [];\n alertState.history = [];\n alertState.triggered.clear();\n resourceState.samples = [];\n profilingState.traces = [];\n\n // Reset stats\n stats.metricsRecorded = 0;\n stats.reportsGenerated = 0;\n stats.alertsTriggered = 0;\n }\n\n // Start monitoring\n if (opts.enabled) {\n startResourceMonitoring();\n startReporting();\n startProfiling();\n }\n\n return {\n recordMetric,\n measure,\n measureAsync,\n addMetric,\n addAlertRule,\n generateReport,\n getStats,\n reset,\n start() {\n opts.enabled = true;\n startResourceMonitoring();\n startReporting();\n startProfiling();\n },\n stop() {\n opts.enabled = false;\n stopResourceMonitoring();\n stopReporting();\n return generateReport();\n }\n };\n}\n\n// Export default instance\nexport const performanceMonitor = createPerformanceMonitor();\n", "/**\n * Core Object Utilities for Coherent.js\n * Handles object validation, manipulation, and analysis\n */\n\n/**\n * Deep clone an object with optimizations for common patterns\n * Handles circular references, functions, dates, regex, and more\n */\nexport function deepClone(obj, seen = new WeakMap()) {\n // Handle primitives\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n // Handle circular references\n if (seen.has(obj)) {\n return seen.get(obj);\n }\n\n // Handle Date objects\n if (obj instanceof Date) {\n return new Date(obj.getTime());\n }\n\n // Handle RegExp objects\n if (obj instanceof RegExp) {\n return new RegExp(obj.source, obj.flags);\n }\n\n // Handle Array objects\n if (Array.isArray(obj)) {\n const clonedArray = [];\n seen.set(obj, clonedArray);\n\n for (let i = 0; i < obj.length; i++) {\n clonedArray[i] = deepClone(obj[i], seen);\n }\n\n return clonedArray;\n }\n\n // Handle Function objects (preserve reference for performance)\n if (typeof obj === 'function') {\n // For Coherent components, we typically want to preserve function references\n // rather than cloning them, as they represent behavior\n return obj;\n }\n\n // Handle Map objects\n if (obj instanceof Map) {\n const clonedMap = new Map();\n seen.set(obj, clonedMap);\n\n for (const [key, value] of obj) {\n clonedMap.set(deepClone(key, seen), deepClone(value, seen));\n }\n\n return clonedMap;\n }\n\n // Handle Set objects\n if (obj instanceof Set) {\n const clonedSet = new Set();\n seen.set(obj, clonedSet);\n\n for (const value of obj) {\n clonedSet.add(deepClone(value, seen));\n }\n\n return clonedSet;\n }\n\n // Handle WeakMap and WeakSet (cannot be cloned, return new empty instance)\n if (obj instanceof WeakMap) {\n return new WeakMap();\n }\n\n if (obj instanceof WeakSet) {\n return new WeakSet();\n }\n\n // Handle plain objects and other object types\n const clonedObj = {};\n seen.set(obj, clonedObj);\n\n // Handle objects with custom prototypes\n if (obj.constructor && obj.constructor !== Object) {\n try {\n // Attempt to create instance with same constructor\n clonedObj.__proto__ = obj.__proto__;\n } catch {\n // Fallback to Object.create if direct prototype assignment fails\n Object.setPrototypeOf(clonedObj, Object.getPrototypeOf(obj));\n }\n }\n\n // Clone all enumerable properties\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n clonedObj[key] = deepClone(obj[key], seen);\n }\n }\n\n // Clone non-enumerable properties (important for some objects)\n const descriptors = Object.getOwnPropertyDescriptors(obj);\n for (const key of Object.keys(descriptors)) {\n if (!descriptors[key].enumerable && descriptors[key].configurable) {\n try {\n Object.defineProperty(clonedObj, key, {\n ...descriptors[key],\n value: deepClone(descriptors[key].value, seen)\n });\n } catch {\n // Skip properties that can't be cloned\n }\n }\n }\n\n return clonedObj;\n}\n\n/**\n * Shallow clone optimized for Coherent objects\n * Much faster than deep clone when you only need one level\n */\nexport function shallowClone(obj) {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return [...obj];\n }\n\n if (obj instanceof Date) {\n return new Date(obj.getTime());\n }\n\n if (obj instanceof RegExp) {\n return new RegExp(obj.source, obj.flags);\n }\n\n // For objects, spread operator is fastest for shallow clone\n return { ...obj };\n}\n\n/**\n * Smart clone that chooses between shallow and deep based on structure\n * Optimized for Coherent component patterns\n */\nexport function smartClone(obj, maxDepth = 10, currentDepth = 0) {\n // Prevent infinite recursion\n if (currentDepth >= maxDepth) {\n return shallowClone(obj);\n }\n\n // Use shallow clone for simple structures\n if (typeof obj !== 'object' || obj === null) {\n return obj;\n }\n\n // For arrays, check if elements need deep cloning\n if (Array.isArray(obj)) {\n const needsDeepClone = obj.some(item =>\n typeof item === 'object' && item !== null && !isSimpleObject(item)\n );\n\n if (!needsDeepClone && currentDepth < 3) {\n return obj.map(item => smartClone(item, maxDepth, currentDepth + 1));\n } else {\n return obj.map(item => shallowClone(item));\n }\n }\n\n // For Coherent objects, intelligently clone based on content\n if (isCoherentObject(obj)) {\n const cloned = {};\n\n for (const [tag, props] of Object.entries(obj)) {\n if (props && typeof props === 'object') {\n // Deep clone children, shallow clone other props\n if (props.children) {\n cloned[tag] = {\n ...props,\n children: smartClone(props.children, maxDepth, currentDepth + 1)\n };\n } else {\n cloned[tag] = shallowClone(props);\n }\n } else {\n cloned[tag] = props;\n }\n }\n\n return cloned;\n }\n\n // Fallback to shallow clone for other objects\n return shallowClone(obj);\n}\n\n/**\n * Check if object is a simple structure (no nested objects/arrays)\n */\nfunction isSimpleObject(obj) {\n if (typeof obj !== 'object' || obj === null) {\n return true;\n }\n\n if (Array.isArray(obj)) {\n return obj.every(item => typeof item !== 'object' || item === null);\n }\n\n return Object.values(obj).every(value =>\n typeof value !== 'object' || value === null || value instanceof Date || value instanceof RegExp\n );\n}\n\n/**\n * Clone with performance monitoring\n * Useful for debugging clone performance in development\n */\nexport function monitoredClone(obj, options = {}) {\n const {\n method = 'deep',\n logTiming = false,\n maxDepth = 10\n } = options;\n\n const start = performance.now();\n let result;\n\n switch (method) {\n case 'shallow':\n result = shallowClone(obj);\n break;\n case 'smart':\n result = smartClone(obj, maxDepth);\n break;\n case 'deep':\n default:\n result = deepClone(obj);\n break;\n }\n\n const end = performance.now();\n\n if (logTiming) {\n console.log(`\uD83D\uDD04 ${method} clone took ${(end - start).toFixed(2)}ms`);\n }\n\n return result;\n}\n\n// Rest of your existing object-utils.js code...\n\n/**\n * Validate that a component structure is valid for rendering\n */\nexport function validateComponent(component, path = 'root') {\n if (component === null || component === undefined) {\n throw new Error(`Invalid component at ${path}: null or undefined`);\n }\n\n // Allow strings, numbers, booleans as text content\n if (['string', 'number', 'boolean'].includes(typeof component)) {\n return true;\n }\n\n // Allow functions (will be evaluated during render)\n if (typeof component === 'function') {\n return true;\n }\n\n // Handle arrays\n if (Array.isArray(component)) {\n component.forEach((child, index) => {\n validateComponent(child, `${path}[${index}]`);\n });\n return true;\n }\n\n // Handle objects\n if (typeof component === 'object') {\n const keys = Object.keys(component);\n\n if (keys.length === 0) {\n throw new Error(`Empty object at ${path}`);\n }\n\n keys.forEach(key => {\n const value = component[key];\n\n // Validate HTML tag names (basic validation)\n if (!/^[a-zA-Z][a-zA-Z0-9-]*$/.test(key) && key !== 'text') {\n console.warn(`Potentially invalid tag name at ${path}: ${key}`);\n }\n\n // If value is an object, it should be props\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n // Validate children if present\n if (value.children) {\n validateComponent(value.children, `${path}.${key}.children`);\n }\n } else if (value && typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'function') {\n throw new Error(`Invalid value type at ${path}.${key}: ${typeof value}`);\n }\n });\n\n return true;\n }\n\n throw new Error(`Invalid component type at ${path}: ${typeof component}`);\n}\n\n/**\n * Check if an object follows Coherent.js object syntax\n */\nexport function isCoherentObject(obj) {\n if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {\n return false;\n }\n\n const keys = Object.keys(obj);\n\n // Empty objects are not coherent objects\n if (keys.length === 0) {\n return false;\n }\n\n // Check if all keys look like HTML tags or 'text'\n return keys.every(key => {\n // Allow 'text' as a special key\n if (key === 'text') return true;\n\n // Basic HTML tag validation\n return /^[a-zA-Z][a-zA-Z0-9-]*$/.test(key);\n });\n}\n\n/**\n * Extract props from a Coherent object\n */\nexport function extractProps(coherentObj) {\n if (!isCoherentObject(coherentObj)) {\n return {};\n }\n\n const props = {};\n const keys = Object.keys(coherentObj);\n\n keys.forEach(tag => {\n const value = coherentObj[tag];\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n props[tag] = { ...value };\n } else {\n props[tag] = { text: value };\n }\n });\n\n return props;\n}\n\n/**\n * Check if a component has children\n */\nexport function hasChildren(component) {\n if (Array.isArray(component)) {\n return component.length > 0;\n }\n\n if (isCoherentObject(component)) {\n // First check if the component itself has a children property\n if (component.children !== undefined && component.children !== null) {\n return Array.isArray(component.children) ? component.children.length > 0 : true;\n }\n \n // Then check if any of its properties have children\n const keys = Object.keys(component);\n return keys.some(key => {\n const value = component[key];\n return value && typeof value === 'object' && value.children;\n });\n }\n\n return false;\n}\n\n/**\n * Normalize children to a consistent array format\n */\nexport function normalizeChildren(children) {\n if (children === null || children === undefined) {\n return [];\n }\n\n if (Array.isArray(children)) {\n return children.flat().filter(child => child !== null && child !== undefined);\n }\n\n return [children];\n}\n\n/**\n * Get children from a component's props\n */\nexport function getChildren(props) {\n if (!props || typeof props !== 'object') {\n return [];\n }\n\n if (props.children === undefined) {\n return [];\n }\n\n return normalizeChildren(props.children);\n}\n\n/**\n * Merge props objects with conflict resolution\n */\nexport function mergeProps(base = {}, override = {}) {\n const merged = { ...base };\n\n Object.keys(override).forEach(key => {\n if (key === 'children') {\n // Merge children arrays\n const baseChildren = normalizeChildren(base.children);\n const overrideChildren = normalizeChildren(override.children);\n merged.children = [...baseChildren, ...overrideChildren];\n } else if (key === 'className' && base.className) {\n // Merge class names\n merged.className = `${base.className} ${override.className}`;\n } else if (key === 'style' && base.style && typeof base.style === 'object') {\n // Merge style objects\n merged.style = { ...base.style, ...override.style };\n } else {\n // Override other properties\n merged[key] = override[key];\n }\n });\n\n return merged;\n}\n\n/**\n * Get nested value from object using dot notation\n */\nexport function getNestedValue(obj, path) {\n if (!obj || typeof path !== 'string') {\n return undefined;\n }\n\n return path.split('.').reduce((current, key) => {\n return current && current[key] !== undefined ? current[key] : undefined;\n }, obj);\n}\n\n/**\n * Set nested value in object using dot notation\n */\nexport function setNestedValue(obj, path, value) {\n if (!obj || typeof path !== 'string') {\n return obj;\n }\n\n const keys = path.split('.');\n const lastKey = keys.pop();\n\n const target = keys.reduce((current, key) => {\n if (!current[key] || typeof current[key] !== 'object') {\n current[key] = {};\n }\n return current[key];\n }, obj);\n\n target[lastKey] = value;\n return obj;\n}\n\n/**\n * Compare two components for equality (useful for optimization)\n */\nexport function isEqual(a, b, maxDepth = 5, currentDepth = 0) {\n // Prevent deep comparisons that are too expensive\n if (currentDepth > maxDepth) {\n return a === b;\n }\n\n if (a === b) return true;\n if (a === null || b === null || a === undefined || b === undefined) return false;\n if (typeof a !== typeof b) return false;\n\n if (typeof a === 'function') {\n // Functions are compared by reference\n return a === b;\n }\n\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) return false;\n return a.every((item, i) => isEqual(item, b[i], maxDepth, currentDepth + 1));\n }\n\n if (typeof a === 'object') {\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n return keysA.every(key =>\n keysB.includes(key) &&\n isEqual(a[key], b[key], maxDepth, currentDepth + 1)\n );\n }\n\n return false;\n}\n\n/**\n * Create a frozen (immutable) version of a component\n */\nexport function freeze(obj) {\n if (obj && typeof obj === 'object') {\n Object.freeze(obj);\n\n // Recursively freeze nested objects\n Object.values(obj).forEach(value => {\n if (value && typeof value === 'object') {\n freeze(value);\n }\n });\n }\n\n return obj;\n}\n\n/**\n * Check if component tree contains circular references\n */\nexport function hasCircularReferences(obj, seen = new WeakSet()) {\n if (obj && typeof obj === 'object') {\n if (seen.has(obj)) {\n return true;\n }\n\n seen.add(obj);\n\n for (const value of Object.values(obj)) {\n if (hasCircularReferences(value, seen)) {\n return true;\n }\n }\n }\n\n return false;\n}\n\n/**\n * Get memory footprint estimate of a component tree\n */\nexport function getMemoryFootprint(obj, visited = new WeakSet()) {\n if (obj === null || obj === undefined) return 0;\n if (visited.has(obj)) return 0;\n\n let size = 0;\n\n if (typeof obj === 'string') {\n size = obj.length * 2; // Rough estimate: 2 bytes per character\n } else if (typeof obj === 'number') {\n size = 8; // 64-bit number\n } else if (typeof obj === 'boolean') {\n size = 4; // Boolean\n } else if (typeof obj === 'object') {\n visited.add(obj);\n size = 48; // Base object overhead\n\n if (Array.isArray(obj)) {\n size += obj.length * 8; // Array overhead\n obj.forEach(item => {\n size += getMemoryFootprint(item, visited);\n });\n } else {\n Object.keys(obj).forEach(key => {\n size += key.length * 2; // Key string\n size += getMemoryFootprint(obj[key], visited);\n });\n }\n }\n\n return size;\n}\n", "/**\n * Component System for Coherent.js\n * Provides component definition, lifecycle, composition, and state management\n */\n\nimport { deepClone, validateComponent } from '../core/object-utils.js';\nimport { performanceMonitor } from '../performance/monitor.js';\n\n/**\n * Component registry for global component management\n */\nconst COMPONENT_REGISTRY = new Map();\n// eslint-disable-next-line no-unused-vars -- kept for future devtools/features\nconst COMPONENT_INSTANCES = new WeakMap();\nconst COMPONENT_METADATA = new WeakMap();\n\n/**\n * Component lifecycle hooks\n */\n// eslint-disable-next-line no-unused-vars -- lifecycle map kept for planned hooks\nconst LIFECYCLE_HOOKS = {\n beforeCreate: 'beforeCreate',\n created: 'created',\n beforeMount: 'beforeMount',\n mounted: 'mounted',\n beforeUpdate: 'beforeUpdate',\n updated: 'updated',\n beforeDestroy: 'beforeDestroy',\n destroyed: 'destroyed',\n errorCaptured: 'errorCaptured'\n};\n\n/**\n * Component state management class\n * \n * @class ComponentState\n * @description Manages component state with reactive updates and listener notifications.\n * Provides immutable state updates with change detection.\n * \n * @param {Object} [initialState={}] - Initial state object\n * \n * @example\n * const state = new ComponentState({ count: 0 });\n * state.set({ count: 1 });\n * const count = state.get('count'); // 1\n */\nclass ComponentState {\n constructor(initialState = {}) {\n this.state = {...initialState};\n this.listeners = new Set();\n this.isUpdating = false;\n }\n\n /**\n * Get state value by key or entire state\n * \n * @param {string} [key] - State key to retrieve\n * @returns {*} State value or entire state object\n */\n get(key) {\n return key ? this.state[key] : {...this.state};\n }\n\n /**\n * Update state with new values\n * \n * @param {Object} updates - State updates to apply\n * @returns {ComponentState} This instance for chaining\n */\n set(updates) {\n if (this.isUpdating) return this;\n\n const oldState = {...this.state};\n\n if (typeof updates === 'function') {\n updates = updates(oldState);\n }\n\n this.state = {...this.state, ...updates};\n\n // Notify listeners\n this.notifyListeners(oldState, this.state);\n\n return this;\n }\n\n subscribe(listener) {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n notifyListeners(oldState, newState) {\n if (this.listeners.size === 0) return;\n\n this.isUpdating = true;\n\n this.listeners.forEach(listener => {\n try {\n listener(newState, oldState);\n } catch (_error) {\n console.error('State listener _error:', _error);\n }\n });\n\n this.isUpdating = false;\n }\n}\n\n/**\n * Base Component class\n */\nexport class Component {\n constructor(definition = {}) {\n this.definition = definition;\n this.name = definition.name || 'AnonymousComponent';\n this.props = {};\n this.state = new ComponentState(definition.state || {});\n this.children = [];\n this.parent = null;\n this.rendered = null;\n this.isMounted = false;\n this.isDestroyed = false;\n\n // Lifecycle hooks\n this.hooks = {\n beforeCreate: definition.beforeCreate || (() => {\n }),\n created: definition.created || (() => {\n }),\n beforeMount: definition.beforeMount || (() => {\n }),\n mounted: definition.mounted || (() => {\n }),\n beforeUpdate: definition.beforeUpdate || (() => {\n }),\n updated: definition.updated || (() => {\n }),\n beforeDestroy: definition.beforeDestroy || (() => {\n }),\n destroyed: definition.destroyed || (() => {\n }),\n errorCaptured: definition.errorCaptured || (() => {\n })\n };\n\n // Methods\n this.methods = definition.methods || {};\n Object.keys(this.methods).forEach(methodName => {\n if (typeof this.methods[methodName] === 'function') {\n this[methodName] = this.methods[methodName].bind(this);\n }\n });\n\n // Computed properties\n this.computed = definition.computed || {};\n this.computedCache = new Map();\n\n // Watch properties\n this.watchers = definition.watch || {};\n this.setupWatchers();\n\n // Store metadata\n COMPONENT_METADATA.set(this, {\n createdAt: Date.now(),\n updateCount: 0,\n renderCount: 0\n });\n\n // Initialize lifecycle\n this.callHook('beforeCreate');\n this.initialize();\n this.callHook('created');\n }\n\n /**\n * Initialize component\n */\n initialize() {\n // Set up state subscription for re-rendering\n this.unsubscribeState = this.state.subscribe((newState, oldState) => {\n this.onStateChange(newState, oldState);\n });\n\n // Initialize computed properties\n this.initializeComputed();\n }\n\n /**\n * Set up watchers for reactive data\n */\n setupWatchers() {\n Object.keys(this.watchers).forEach(key => {\n const handler = this.watchers[key];\n\n // Watch state changes\n this.state.subscribe((newState, oldState) => {\n if (newState[key] !== oldState[key]) {\n handler.call(this, newState[key], oldState[key]);\n }\n });\n });\n }\n\n /**\n * Initialize computed properties\n */\n initializeComputed() {\n Object.keys(this.computed).forEach(key => {\n Object.defineProperty(this, key, {\n get: () => {\n if (!this.computedCache.has(key)) {\n const value = this.computed[key].call(this);\n this.computedCache.set(key, value);\n }\n return this.computedCache.get(key);\n },\n enumerable: true\n });\n });\n }\n\n /**\n * Handle state changes\n */\n onStateChange() {\n if (this.isDestroyed) return;\n\n // Clear computed cache\n this.computedCache.clear();\n\n // Trigger update if mounted\n if (this.isMounted) {\n this.update();\n }\n }\n\n /**\n * Call lifecycle hook\n */\n callHook(hookName, ...args) {\n try {\n if (this.hooks[hookName]) {\n return this.hooks[hookName].call(this, ...args);\n }\n } catch (_error) {\n this.handleError(_error, `${hookName} hook`);\n }\n }\n\n /**\n * Handle component errors\n */\n handleError(_error) {\n console.error(`Component Error in ${this.name}:`, _error);\n\n // Call _error hook\n this.callHook('errorCaptured', _error);\n\n // Propagate to parent\n if (this.parent && this.parent.handleError) {\n this.parent.handleError(_error, `${this.name} -> ${context}`);\n }\n }\n\n /**\n * Render the component\n */\n render(props = {}) {\n if (this.isDestroyed) {\n console.warn(`Attempting to render destroyed component: ${this.name}`);\n return null;\n }\n\n try {\n // Update metadata\n const metadata = COMPONENT_METADATA.get(this);\n if (metadata) {\n metadata.renderCount++;\n }\n\n // Set props\n this.props = {...props};\n\n // Call render method\n if (typeof this.definition.render === 'function') {\n this.rendered = this.definition.render.call(this, this.props, this.state.get());\n } else if (typeof this.definition.template !== 'undefined') {\n this.rendered = this.processTemplate(this.definition.template, this.props, this.state.get());\n } else {\n throw new Error(`Component ${this.name} must have either render method or template`);\n }\n\n // Validate rendered output\n if (this.rendered !== null) {\n validateComponent(this.rendered, this.name);\n }\n\n return this.rendered;\n\n } catch (_error) {\n this.handleError(_error);\n return {div: {className: 'component-_error', text: `Error in ${this.name}`}};\n }\n }\n\n /**\n * Process template with data\n */\n processTemplate(template, props, state) {\n if (typeof template === 'function') {\n return template.call(this, props, state);\n }\n\n if (typeof template === 'string') {\n // Simple string interpolation\n return template.replace(/\\{\\{(\\w+)\\}\\}/g, (match, key) => {\n return props[key] || state[key] || '';\n });\n }\n\n // Clone template object and process\n const processed = deepClone(template);\n this.interpolateObject(processed, {...props, ...state});\n return processed;\n }\n\n /**\n * Interpolate object with data\n */\n interpolateObject(obj, data) {\n if (typeof obj === 'string') {\n return obj.replace(/\\{\\{(\\w+)\\}\\}/g, (match, key) => data[key] || '');\n }\n\n if (Array.isArray(obj)) {\n return obj.map(item => this.interpolateObject(item, data));\n }\n\n if (obj && typeof obj === 'object') {\n Object.keys(obj).forEach(key => {\n obj[key] = this.interpolateObject(obj[key], data);\n });\n }\n\n return obj;\n }\n\n /**\n * Mount the component\n */\n mount() {\n if (this.isMounted || this.isDestroyed) return this;\n\n this.callHook('beforeMount');\n this.isMounted = true;\n this.callHook('mounted');\n\n return this;\n }\n\n /**\n * Update the component\n */\n update() {\n if (!this.isMounted || this.isDestroyed) return this;\n\n const metadata = COMPONENT_METADATA.get(this);\n if (metadata) {\n metadata.updateCount++;\n }\n\n this.callHook('beforeUpdate');\n // Re-render will happen automatically via state subscription\n this.callHook('updated');\n\n return this;\n }\n\n /**\n * Destroy the component\n */\n destroy() {\n if (this.isDestroyed) return this;\n\n this.callHook('beforeDestroy');\n\n // Cleanup\n if (this.unsubscribeState) {\n this.unsubscribeState();\n }\n\n // Destroy children\n this.children.forEach(child => {\n if (child.destroy) {\n child.destroy();\n }\n });\n\n this.isMounted = false;\n this.isDestroyed = true;\n this.children = [];\n this.parent = null;\n\n this.callHook('destroyed');\n\n return this;\n }\n\n /**\n * Get component metadata\n */\n getMetadata() {\n return COMPONENT_METADATA.get(this) || {};\n }\n\n /**\n * Clone component with new props/state\n */\n clone(overrides = {}) {\n const newDefinition = {...this.definition, ...overrides};\n return new Component(newDefinition);\n }\n}\n\n/**\n * Create a functional component\n */\nexport function createComponent(definition) {\n if (typeof definition === 'function') {\n // Convert function to component definition\n definition = {\n name: definition.name || 'FunctionalComponent',\n render: definition\n };\n }\n\n return new Component(definition);\n}\n\n/**\n * Create a component factory\n */\nexport function defineComponent(definition) {\n const componentFactory = (props) => {\n const component = new Component(definition);\n return component.render(props);\n };\n\n // Add static properties\n componentFactory.componentName = definition.name || 'Component';\n componentFactory.definition = definition;\n\n return componentFactory;\n}\n\n/**\n * Register a global component\n */\nexport function registerComponent(name, definition) {\n if (COMPONENT_REGISTRY.has(name)) {\n console.warn(`Component ${name} is already registered. Overriding.`);\n }\n\n const component = typeof definition === 'function' ?\n defineComponent({name, render: definition}) :\n defineComponent(definition);\n\n COMPONENT_REGISTRY.set(name, component);\n return component;\n}\n\n/**\n * Get a registered component\n */\nexport function getComponent(name) {\n return COMPONENT_REGISTRY.get(name);\n}\n\n/**\n * Get all registered components\n */\nexport function getRegisteredComponents() {\n return new Map(COMPONENT_REGISTRY);\n}\n\n/**\n * Create a higher-order component\n */\nexport function createHOC(enhancer) {\n return (WrappedComponent) => {\n return defineComponent({\n name: `HOC(${WrappedComponent.componentName || 'Component'})`,\n render(props) {\n return enhancer(WrappedComponent, props);\n }\n });\n };\n}\n\n/**\n * Mixin functionality\n */\nexport function createMixin(mixin) {\n return (componentDefinition) => {\n return {\n ...mixin,\n ...componentDefinition,\n\n // Merge methods\n methods: {\n ...mixin.methods,\n ...componentDefinition.methods\n },\n\n // Merge computed\n computed: {\n ...mixin.computed,\n ...componentDefinition.computed\n },\n\n // Merge watchers\n watch: {\n ...mixin.watch,\n ...componentDefinition.watch\n },\n\n // Merge state\n state: {\n ...mixin.state,\n ...componentDefinition.state\n }\n };\n };\n}\n\n/**\n * Component composition utilities\n */\nexport const compose = {\n /**\n * Combine multiple components\n */\n combine: (...components) => {\n return defineComponent({\n name: 'ComposedComponent',\n render(props) {\n return components.map(comp =>\n typeof comp === 'function' ? comp(props) : comp\n );\n }\n });\n },\n\n /**\n * Conditionally render components\n */\n conditional: (condition, trueComponent, falseComponent = null) => {\n return defineComponent({\n name: 'ConditionalComponent',\n render(props) {\n const shouldRender = typeof condition === 'function' ?\n condition(props) : condition;\n\n if (shouldRender) {\n return typeof trueComponent === 'function' ?\n trueComponent(props) : trueComponent;\n } else if (falseComponent) {\n return typeof falseComponent === 'function' ?\n falseComponent(props) : falseComponent;\n }\n\n return null;\n }\n });\n },\n\n /**\n * Loop over data to render components\n */\n loop: (data, itemComponent, keyFn = (item, index) => index) => {\n return defineComponent({\n name: 'LoopComponent',\n render(props) {\n const items = typeof data === 'function' ? data(props) : data;\n\n if (!Array.isArray(items)) {\n console.warn('Loop component expects array data');\n return null;\n }\n\n return items.map((item, index) => {\n const key = keyFn(item, index);\n const itemProps = {...props, item, index, key};\n\n return typeof itemComponent === 'function' ?\n itemComponent(itemProps) : itemComponent;\n });\n }\n });\n }\n};\n\n/**\n * Component utilities\n */\nexport const componentUtils = {\n /**\n * Get component tree information\n */\n getComponentTree: (component) => {\n const tree = {\n name: component.name || 'Unknown',\n props: component.props || {},\n state: component.state ? component.state.get() : {},\n children: [],\n metadata: component.getMetadata ? component.getMetadata() : {}\n };\n\n if (component.children && component.children.length > 0) {\n tree.children = component.children.map(child =>\n componentUtils.getComponentTree(child)\n );\n }\n\n return tree;\n },\n\n /**\n * Find component by name in tree\n */\n findComponent: (component, name) => {\n if (component.name === name) {\n return component;\n }\n\n if (component.children) {\n for (const child of component.children) {\n const found = componentUtils.findComponent(child, name);\n if (found) return found;\n }\n }\n\n return null;\n },\n\n /**\n * Get component performance metrics\n */\n getPerformanceMetrics: (component) => {\n const metadata = component.getMetadata ? component.getMetadata() : {};\n\n return {\n renderCount: metadata.renderCount || 0,\n updateCount: metadata.updateCount || 0,\n createdAt: metadata.createdAt || Date.now(),\n age: Date.now() - (metadata.createdAt || Date.now())\n };\n },\n\n /**\n * Validate component definition\n */\n validateDefinition: (definition) => {\n const errors = [];\n\n if (!definition || typeof definition !== 'object') {\n errors.push('Definition must be an object');\n return errors;\n }\n\n if (!definition.render && !definition.template) {\n errors.push('Component must have either render method or template');\n }\n\n if (definition.render && typeof definition.render !== 'function') {\n errors.push('render must be a function');\n }\n\n if (definition.methods && typeof definition.methods !== 'object') {\n errors.push('methods must be an object');\n }\n\n if (definition.computed && typeof definition.computed !== 'object') {\n errors.push('computed must be an object');\n }\n\n if (definition.watch && typeof definition.watch !== 'object') {\n errors.push('watch must be an object');\n }\n\n return errors;\n }\n};\n\n/**\n * Performance monitoring for components\n */\nif (performanceMonitor) {\n const originalRender = Component.prototype.render;\n\n Component.prototype.render = function(...args) {\n const start = performance.now();\n const result = originalRender.apply(this, args);\n const duration = performance.now() - start;\n\n performanceMonitor.recordMetric('renderTime', duration, {\n type: 'component',\n name: this.name,\n propsSize: JSON.stringify(this.props || {}).length,\n hasState: Object.keys(this.state?.get() || {}).length > 0\n });\n\n return result;\n };\n}\n\n/**\n * Development helpers\n */\nexport const dev = {\n /**\n * Get all component instances\n */\n getAllComponents: () => {\n return Array.from(COMPONENT_REGISTRY.entries()).map(([name, factory]) => ({\n name,\n factory,\n definition: factory.definition\n }));\n },\n\n /**\n * Clear component registry\n */\n clearRegistry: () => {\n COMPONENT_REGISTRY.clear();\n },\n\n /**\n * Get component registry stats\n */\n getRegistryStats: () => ({\n totalComponents: COMPONENT_REGISTRY.size,\n components: Array.from(COMPONENT_REGISTRY.keys())\n })\n};\n\n/**\n * Create lazy-evaluated properties and components\n * Defers computation until actually needed, with optional caching\n */\nexport function lazy(factory, options = {}) {\n const {\n cache = true, // Cache the result after first evaluation\n timeout = null, // Optional timeout for evaluation\n fallback = null, // Fallback value if evaluation fails\n onError = null, // Error handler\n dependencies = [] // Dependencies that invalidate cache\n } = options;\n\n let cached = false;\n let cachedValue = null;\n let isEvaluating = false;\n let lastDependencyHash = null;\n\n const lazyWrapper = {\n // Mark as lazy for identification\n __isLazy: true,\n __factory: factory,\n __options: options,\n\n // Evaluation method\n evaluate(...args) {\n // Prevent recursive evaluation\n if (isEvaluating) {\n console.warn('Lazy evaluation cycle detected, returning fallback');\n return fallback;\n }\n\n // Check dependency changes\n if (cache && dependencies.length > 0) {\n const currentHash = hashDependencies(dependencies);\n if (lastDependencyHash !== null && lastDependencyHash !== currentHash) {\n cached = false;\n cachedValue = null;\n }\n lastDependencyHash = currentHash;\n }\n\n // Return cached value if available\n if (cache && cached) {\n return cachedValue;\n }\n\n isEvaluating = true;\n\n try {\n let result;\n\n // Handle timeout\n if (timeout) {\n result = evaluateWithTimeout(factory, timeout, args, fallback);\n } else {\n result = typeof factory === 'function' ? factory(...args) : factory;\n }\n\n // Handle promises\n if (result && typeof result.then === 'function') {\n return result.catch(_error => {\n if (onError) onError(_error);\n return fallback;\n });\n }\n\n // Cache successful result\n if (cache) {\n cached = true;\n cachedValue = result;\n }\n\n return result;\n\n } catch (_error) {\n if (onError) {\n onError(_error);\n } else {\n console.error('Lazy evaluation _error:', _error);\n }\n return fallback;\n } finally {\n isEvaluating = false;\n }\n },\n\n // Force re-evaluation\n invalidate() {\n cached = false;\n cachedValue = null;\n lastDependencyHash = null;\n return this;\n },\n\n // Check if evaluated\n isEvaluated() {\n return cached;\n },\n\n // Get cached value without evaluation\n getCachedValue() {\n return cachedValue;\n },\n\n // Transform the lazy value\n map(transform) {\n return lazy((...args) => {\n const value = this.evaluate(...args);\n return transform(value);\n }, {...options, cache: false}); // Don't double-cache\n },\n\n // Chain lazy evaluations\n flatMap(transform) {\n return lazy((...args) => {\n const value = this.evaluate(...args);\n const transformed = transform(value);\n\n if (isLazy(transformed)) {\n return transformed.evaluate(...args);\n }\n\n return transformed;\n }, {...options, cache: false});\n },\n\n // Convert to string for debugging\n toString() {\n return `[Lazy${cached ? ' (cached)' : ''}]`;\n },\n\n // JSON serialization\n toJSON() {\n return this.evaluate();\n }\n };\n\n return lazyWrapper;\n}\n\n/**\n * Check if value is lazy\n */\nexport function isLazy(value) {\n return value && typeof value === 'object' && value.__isLazy === true;\n}\n\n/**\n * Evaluate lazy values recursively in an object\n */\nexport function evaluateLazy(obj, ...args) {\n if (isLazy(obj)) {\n return obj.evaluate(...args);\n }\n\n if (Array.isArray(obj)) {\n return obj.map(item => evaluateLazy(item, ...args));\n }\n\n if (obj && typeof obj === 'object') {\n const result = {};\n\n for (const [key, value] of Object.entries(obj)) {\n result[key] = evaluateLazy(value, ...args);\n }\n\n return result;\n }\n\n return obj;\n}\n\n/**\n * Create lazy component\n */\nexport function lazyComponent(componentFactory, options = {}) {\n return lazy(componentFactory, {\n cache: true,\n fallback: {div: {text: 'Loading component...'}},\n ...options\n });\n}\n\n/**\n * Create lazy import for dynamic imports\n */\nexport function lazyImport(importPromise, options = {}) {\n return lazy(async () => {\n const module = await importPromise;\n return module.default || module;\n }, {\n cache: true,\n fallback: {div: {text: 'Loading...'}},\n ...options\n });\n}\n\n/**\n * Create lazy computed property\n */\nexport function lazyComputed(computeFn, dependencies = [], options = {}) {\n return lazy(computeFn, {\n cache: true,\n dependencies,\n ...options\n });\n}\n\n/**\n * Batch evaluate multiple lazy values\n */\nexport function batchEvaluate(lazyValues, ...args) {\n const results = {};\n const promises = [];\n\n Object.entries(lazyValues).forEach(([key, lazyValue]) => {\n if (isLazy(lazyValue)) {\n const result = lazyValue.evaluate(...args);\n\n if (result && typeof result.then === 'function') {\n promises.push(\n result.then(value => ({key, value}))\n .catch(_error => ({key, _error}))\n );\n } else {\n results[key] = result;\n }\n } else {\n results[key] = lazyValue;\n }\n });\n\n if (promises.length === 0) {\n return results;\n }\n\n return Promise.all(promises).then(asyncResults => {\n asyncResults.forEach(({key, value, _error}) => {\n if (_error) {\n console.error(`Batch evaluation _error for ${key}:`, _error);\n results[key] = null;\n } else {\n results[key] = value;\n }\n });\n\n return results;\n });\n}\n\n/**\n * Helper function to hash dependencies\n */\nfunction hashDependencies(dependencies) {\n return dependencies.map(dep => {\n if (typeof dep === 'function') {\n return dep.toString();\n }\n return JSON.stringify(dep);\n }).join('|');\n}\n\n/**\n * Helper function to evaluate with timeout\n */\nfunction evaluateWithTimeout(factory, timeout, args, fallback) {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(new Error(`Lazy evaluation timeout after ${timeout}ms`));\n }, timeout);\n\n try {\n const result = factory(...args);\n\n if (result && typeof result.then === 'function') {\n result\n .then(value => {\n clearTimeout(timer);\n resolve(value);\n })\n .catch(_error => {\n clearTimeout(timer);\n reject(_error);\n });\n } else {\n clearTimeout(timer);\n resolve(result);\n }\n } catch (_error) {\n clearTimeout(timer);\n reject(_error);\n }\n }).catch(() => fallback);\n}\n\n/**\n * Lazy evaluation utilities\n */\nexport const lazyUtils = {\n /**\n * Create a lazy chain of transformations\n */\n chain: (...transformations) => {\n return lazy((initialValue) => {\n return transformations.reduce((value, transform) => {\n if (isLazy(value)) {\n value = value.evaluate();\n }\n return transform(value);\n }, initialValue);\n });\n },\n\n /**\n * Create conditional lazy evaluation\n */\n conditional: (condition, trueFactory, falseFactory) => {\n return lazy((...args) => {\n const shouldEvaluateTrue = typeof condition === 'function' ?\n condition(...args) : condition;\n\n const factory = shouldEvaluateTrue ? trueFactory : falseFactory;\n return typeof factory === 'function' ? factory(...args) : factory;\n });\n },\n\n /**\n * Memoize a function with lazy evaluation\n */\n memoize: (fn, keyFn = (...args) => JSON.stringify(args)) => {\n const cache = new Map();\n\n return lazy((...args) => {\n const key = keyFn(...args);\n\n if (cache.has(key)) {\n return cache.get(key);\n }\n\n const result = fn(...args);\n cache.set(key, result);\n return result;\n }, {cache: false}); // Handle caching internally\n },\n\n /**\n * Create lazy value from async function\n */\n async: (asyncFn, options = {}) => {\n return lazy(asyncFn, {\n cache: true,\n fallback: options.loading || {div: {text: 'Loading...'}},\n onError: options.onError,\n ...options\n });\n },\n\n /**\n * Create lazy array with lazy items\n */\n array: (items = []) => {\n return lazy(() => items.map(item =>\n isLazy(item) ? item.evaluate() : item\n ));\n },\n\n /**\n * Create lazy object with lazy properties\n */\n object: (obj = {}) => {\n return lazy(() => {\n const result = {};\n\n for (const [key, value] of Object.entries(obj)) {\n result[key] = isLazy(value) ? value.evaluate() : value;\n }\n\n return result;\n });\n }\n};\n\n/**\n * Memoization utilities for caching function results and component renders\n */\n\n/**\n * Enhanced memoization with multiple caching strategies\n */\nexport function memo(fn, options = {}) {\n const {\n // Caching strategy\n strategy = 'lru', // 'lru', 'ttl', 'weak', 'simple'\n maxSize = 100, // Maximum cache entries\n ttl = null, // Time to live in milliseconds\n\n // Key generation\n keyFn = null, // Custom key function\n keySerializer = JSON.stringify, // Default serialization\n\n // Comparison\n // eslint-disable-next-line no-unused-vars\n compareFn = null, // Custom equality comparison\n // eslint-disable-next-line no-unused-vars\n shallow = false, // Shallow comparison for objects\n\n // Lifecycle hooks\n onHit = null, // Called on cache hit\n onMiss = null, // Called on cache miss\n onEvict = null, // Called when item evicted\n\n // Performance\n stats = false, // Track hit/miss statistics\n\n // Development\n debug = false // Debug logging\n } = options;\n\n // Choose cache implementation based on strategy\n let cache;\n const stats_data = stats ? {hits: 0, misses: 0, evictions: 0} : null;\n\n switch (strategy) {\n case 'lru':\n cache = new LRUCache(maxSize, {onEvict: onEvict});\n break;\n case 'ttl':\n cache = new TTLCache(ttl, {onEvict: onEvict});\n break;\n case 'weak':\n cache = new WeakMap();\n break;\n default:\n cache = new Map();\n }\n\n // Generate cache key\n const generateKey = keyFn || ((...args) => {\n if (args.length === 0) return '__empty__';\n if (args.length === 1) return keySerializer(args[0]);\n return keySerializer(args);\n });\n\n // Compare values for equality (inline via compareFn or defaults where used)\n\n const memoizedFn = (...args) => {\n const key = generateKey(...args);\n\n // Check cache hit\n if (cache.has(key)) {\n const cached = cache.get(key);\n\n // For TTL cache or custom validation\n if (cached && (!cached.expires || Date.now() < cached.expires)) {\n if (debug) console.log(`Memo cache hit for key: ${key}`);\n if (onHit) onHit(key, cached.value, args);\n if (stats_data) stats_data.hits++;\n\n return cached.value || cached;\n } else {\n // Expired entry\n cache.delete(key);\n }\n }\n\n // Cache miss - compute result\n if (debug) console.log(`Memo cache miss for key: ${key}`);\n if (onMiss) onMiss(key, args);\n if (stats_data) stats_data.misses++;\n\n const result = fn(...args);\n\n // Store in cache\n const cacheEntry = ttl ?\n {value: result, expires: Date.now() + ttl} :\n result;\n\n cache.set(key, cacheEntry);\n\n return result;\n };\n\n // Attach utility methods\n memoizedFn.cache = cache;\n memoizedFn.clear = () => cache.clear();\n memoizedFn.delete = (key) => cache.delete(key);\n memoizedFn.has = (key) => cache.has(key);\n memoizedFn.size = () => cache.size;\n\n if (stats_data) {\n memoizedFn.stats = () => ({...stats_data});\n memoizedFn.resetStats = () => {\n stats_data.hits = 0;\n stats_data.misses = 0;\n stats_data.evictions = 0;\n };\n }\n\n // Force recomputation for specific args\n memoizedFn.refresh = (...args) => {\n const key = generateKey(...args);\n cache.delete(key);\n return memoizedFn(...args);\n };\n\n return memoizedFn;\n}\n\n/**\n * Component-specific memoization\n */\nexport function memoComponent(component, options = {}) {\n const {\n propsEqual = shallowEqual,\n stateEqual = shallowEqual,\n name = component.name || 'AnonymousComponent'\n } = options;\n\n return memo((props = {}, state = {}, context = {}) => {\n return typeof component === 'function' ?\n component(props, state, context) :\n component;\n }, {\n keyFn: (props, state) => {\n // Create key based on props and state\n return `${name}:${JSON.stringify(props)}:${JSON.stringify(state)}`;\n },\n compareFn: (a, b) => {\n // Custom comparison for component args\n return propsEqual(a.props, b.props) &&\n stateEqual(a.state, b.state);\n },\n ...options\n });\n}\n\n/**\n * Async memoization with promise caching\n */\nexport function memoAsync(asyncFn, options = {}) {\n const promiseCache = new Map();\n\n const memoized = memo((...args) => {\n const key = options.keyFn ?\n options.keyFn(...args) :\n JSON.stringify(args);\n\n // Check if promise is already running\n if (promiseCache.has(key)) {\n return promiseCache.get(key);\n }\n\n // Start new async operation\n const promise = asyncFn(...args).catch(_error => {\n // Remove failed promise from cache\n promiseCache.delete(key);\n throw _error;\n });\n\n promiseCache.set(key, promise);\n\n // Clean up resolved promise\n promise.finally(() => {\n setTimeout(() => promiseCache.delete(key), 0);\n });\n\n return promise;\n }, options);\n\n // Clear both caches\n const originalClear = memoized.clear;\n memoized.clear = () => {\n originalClear();\n promiseCache.clear();\n };\n\n return memoized;\n}\n\n/**\n * LRU Cache implementation\n */\nclass LRUCache {\n constructor(maxSize = 100, options = {}) {\n this.maxSize = maxSize;\n this.cache = new Map();\n this.onEvict = options.onEvict;\n }\n\n get(key) {\n if (this.cache.has(key)) {\n // Move to end (most recently used)\n const value = this.cache.get(key);\n this.cache.delete(key);\n this.cache.set(key, value);\n return value;\n }\n return undefined;\n }\n\n set(key, value) {\n if (this.cache.has(key)) {\n // Update existing\n this.cache.delete(key);\n } else if (this.cache.size >= this.maxSize) {\n // Evict least recently used (first entry)\n const firstKey = this.cache.keys().next().value;\n const evicted = this.cache.get(firstKey);\n this.cache.delete(firstKey);\n\n if (this.onEvict) {\n this.onEvict(firstKey, evicted);\n }\n }\n\n this.cache.set(key, value);\n }\n\n has(key) {\n return this.cache.has(key);\n }\n\n delete(key) {\n return this.cache.delete(key);\n }\n\n clear() {\n this.cache.clear();\n }\n\n get size() {\n return this.cache.size;\n }\n}\n\n/**\n * TTL Cache implementation\n */\nclass TTLCache {\n constructor(ttl, options = {}) {\n this.ttl = ttl;\n this.cache = new Map();\n this.timers = new Map();\n this.onEvict = options.onEvict;\n }\n\n get(key) {\n if (this.cache.has(key)) {\n const entry = this.cache.get(key);\n\n if (Date.now() < entry.expires) {\n return entry.value;\n } else {\n // Expired\n this.delete(key);\n }\n }\n return undefined;\n }\n\n set(key, value) {\n // Clear existing timer\n if (this.timers.has(key)) {\n clearTimeout(this.timers.get(key));\n }\n\n const expires = Date.now() + this.ttl;\n this.cache.set(key, {value, expires});\n\n // Set expiration timer\n const timer = setTimeout(() => {\n this.delete(key);\n }, this.ttl);\n\n this.timers.set(key, timer);\n }\n\n has(key) {\n if (this.cache.has(key)) {\n const entry = this.cache.get(key);\n return Date.now() < entry.expires;\n }\n return false;\n }\n\n delete(key) {\n const had = this.cache.has(key);\n\n if (had) {\n const entry = this.cache.get(key);\n this.cache.delete(key);\n\n if (this.timers.has(key)) {\n clearTimeout(this.timers.get(key));\n this.timers.delete(key);\n }\n\n if (this.onEvict) {\n this.onEvict(key, entry.value);\n }\n }\n\n return had;\n }\n\n clear() {\n // Clear all timers\n this.timers.forEach(timer => clearTimeout(timer));\n this.timers.clear();\n this.cache.clear();\n }\n\n get size() {\n return this.cache.size;\n }\n}\n\n/**\n * Shallow equality check for objects\n */\nfunction shallowEqual(a, b) {\n if (a === b) return true;\n if (!a || !b) return false;\n if (typeof a !== typeof b) return false;\n\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false;\n return a.every((item, index) => item === b[index]);\n }\n\n if (typeof a === 'object') {\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n return keysA.every(key => a[key] === b[key]);\n }\n\n return false;\n}\n\n/**\n * Memoization utilities\n */\nexport const memoUtils = {\n /**\n * Create a memo with automatic dependency tracking\n */\n auto: (fn, dependencies = []) => {\n let lastDeps = null;\n let cached = null;\n let hasCached = false;\n\n return (...args) => {\n const currentDeps = dependencies.map(dep =>\n typeof dep === 'function' ? dep() : dep\n );\n\n if (!hasCached || !shallowEqual(lastDeps, currentDeps)) {\n cached = fn(...args);\n lastDeps = currentDeps;\n hasCached = true;\n }\n\n return cached;\n };\n },\n\n /**\n * Memo with size-based eviction\n */\n sized: (fn, maxSize = 50) => memo(fn, {strategy: 'lru', maxSize}),\n\n /**\n * Memo with time-based eviction\n */\n timed: (fn, ttl = 5000) => memo(fn, {strategy: 'ttl', ttl}),\n\n /**\n * Weak memo (garbage collected with keys)\n */\n weak: (fn) => memo(fn, {strategy: 'weak'}),\n\n /**\n * Create multiple memoized variants\n */\n variants: (fn, configs) => {\n const variants = {};\n\n Object.entries(configs).forEach(([name, config]) => {\n variants[name] = memo(fn, config);\n });\n\n return variants;\n },\n\n /**\n * Conditional memoization\n */\n conditional: (fn, shouldMemo = () => true) => {\n const memoized = memo(fn);\n\n return (...args) => {\n if (shouldMemo(...args)) {\n return memoized(...args);\n }\n return fn(...args);\n };\n },\n\n /**\n * Memo with custom storage\n */\n custom: (fn, storage) => {\n return (...args) => {\n const key = JSON.stringify(args);\n\n if (storage.has(key)) {\n return storage.get(key);\n }\n\n const result = fn(...args);\n storage.set(key, result);\n return result;\n };\n }\n};\n\n/**\n * Higher-order function utilities for component composition and prop manipulation\n */\n\n/**\n * Enhanced withProps utility for component prop transformation and injection\n */\nexport function withProps(propsTransform, options = {}) {\n const {\n // Transformation options\n merge = true, // Merge with existing props vs replace\n override = false, // Allow overriding existing props\n validate = null, // Validation function for props\n\n // Caching and performance\n memoize = false, // Memoize the transformation\n memoOptions = {}, // Memoization options\n\n // Error handling\n onError = null, // Error handler for transformation\n fallbackProps = {}, // Fallback props on _error\n\n // Development\n displayName = null, // Component name for debugging\n debug = false, // Debug logging\n\n // Lifecycle\n onPropsChange = null, // Called when props change\n shouldUpdate = null // Custom update logic\n } = options;\n\n return function withPropsHOC(WrappedComponent) {\n // Create the enhanced component\n function WithPropsComponent(originalProps = {}, state = {}, context = {}) {\n try {\n // Transform props\n let transformedProps;\n\n if (typeof propsTransform === 'function') {\n transformedProps = propsTransform(originalProps, state, context);\n } else if (typeof propsTransform === 'object') {\n transformedProps = propsTransform;\n } else {\n transformedProps = {};\n }\n\n // Handle async transformations\n if (transformedProps && typeof transformedProps.then === 'function') {\n return transformedProps.then(resolved => {\n return processProps(resolved, originalProps, WrappedComponent, state, context);\n }).catch(_error => {\n if (onError) onError(_error, originalProps);\n return processProps(fallbackProps, originalProps, WrappedComponent, state, context);\n });\n }\n\n return processProps(transformedProps, originalProps, WrappedComponent, state, context);\n\n } catch (_error) {\n if (debug) console.error('withProps _error:', _error);\n if (onError) onError(_error, originalProps);\n\n // Use fallback props\n return processProps(fallbackProps, originalProps, WrappedComponent, state, context);\n }\n }\n\n // Process and merge props\n function processProps(transformed, original, component, state, context) {\n let finalProps;\n\n if (merge) {\n if (override) {\n finalProps = {...original, ...transformed};\n } else {\n // Don't override existing props\n finalProps = {...transformed, ...original};\n }\n } else {\n finalProps = transformed;\n }\n\n // Validate final props\n if (validate && !validate(finalProps)) {\n if (debug) console.warn('Props validation failed:', finalProps);\n finalProps = {...finalProps, ...fallbackProps};\n }\n\n // Check if should update\n if (shouldUpdate && !shouldUpdate(finalProps, original, state)) {\n return null; // Skip update\n }\n\n // Notify props change\n if (onPropsChange) {\n onPropsChange(finalProps, original, transformed);\n }\n\n if (debug) {\n console.log('withProps transformation:', {\n original,\n transformed,\n final: finalProps\n });\n }\n\n // Render wrapped component\n return typeof component === 'function' ?\n component(finalProps, state, context) :\n component;\n }\n\n // Set display name for debugging\n WithPropsComponent.displayName = displayName ||\n `withProps(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`;\n\n // Add metadata\n WithPropsComponent.__isHOC = true;\n WithPropsComponent.__wrappedComponent = WrappedComponent;\n WithPropsComponent.__transform = propsTransform;\n\n // Apply memoization if requested\n if (memoize) {\n return memo(WithPropsComponent, {\n keyFn: (props, state) => JSON.stringify({props, state}),\n ...memoOptions\n });\n }\n\n return WithPropsComponent;\n };\n}\n\n/**\n * Specialized withProps variants\n */\nexport const withPropsUtils = {\n /**\n * Add static props to component\n */\n static: (staticProps) => withProps(() => staticProps),\n\n /**\n * Transform props based on conditions\n */\n conditional: (condition, trueProps, falseProps = {}) =>\n withProps((props, state, context) => {\n const shouldApply = typeof condition === 'function' ?\n condition(props, state, context) :\n condition;\n\n return shouldApply ? trueProps : falseProps;\n }),\n\n /**\n * Map specific props to new names/values\n */\n map: (mapping) => withProps((props) => {\n const result = {};\n\n Object.entries(mapping).forEach(([newKey, mapper]) => {\n if (typeof mapper === 'string') {\n // Simple property rename\n result[newKey] = props[mapper];\n } else if (typeof mapper === 'function') {\n // Transform function\n result[newKey] = mapper(props);\n } else {\n // Static value\n result[newKey] = mapper;\n }\n });\n\n return result;\n }),\n\n /**\n * Pick only specific props\n */\n pick: (keys) => withProps((props) => {\n const result = {};\n keys.forEach(key => {\n if (props.hasOwnProperty(key)) {\n result[key] = props[key];\n }\n });\n return result;\n }),\n\n /**\n * Omit specific props\n */\n omit: (keys) => withProps((props) => {\n const result = {...props};\n keys.forEach(key => delete result[key]);\n return result;\n }),\n\n /**\n * Default values for missing props\n */\n defaults: (defaultProps) => withProps((props) => ({\n ...defaultProps,\n ...props\n }), {merge: false}),\n\n /**\n * Transform props with validation\n */\n validated: (transform, validator) => withProps(transform, {\n validate: validator,\n onError: (_error) => console.warn('Prop validation failed:', _error)\n }),\n\n /**\n * Async prop transformation\n */\n async: (asyncTransform, loadingProps = {}) => withProps(async (props, state, context) => {\n try {\n return await asyncTransform(props, state, context);\n } catch (_error) {\n console.error('Async prop transform failed:', _error);\n return loadingProps;\n }\n }, {\n fallbackProps: loadingProps\n }),\n\n /**\n * Computed props based on other props\n */\n computed: (computedProps) => withProps((props) => {\n const computed = {};\n\n Object.entries(computedProps).forEach(([key, compute]) => {\n computed[key] = typeof compute === 'function' ?\n compute(props) :\n compute;\n });\n\n return computed;\n }),\n\n /**\n * Props with context injection\n */\n withContext: (contextKeys) => withProps((props, state, context) => {\n const contextProps = {};\n\n contextKeys.forEach(key => {\n if (context && context[key] !== undefined) {\n contextProps[key] = context[key];\n }\n });\n\n return contextProps;\n }),\n\n /**\n * Props with state injection\n */\n withState: (stateMapping) => withProps((props, state) => {\n if (typeof stateMapping === 'function') {\n return stateMapping(state, props);\n }\n\n const stateProps = {};\n Object.entries(stateMapping).forEach(([propKey, stateKey]) => {\n stateProps[propKey] = state[stateKey];\n });\n\n return stateProps;\n }),\n\n /**\n * Memoized prop transformation\n */\n memoized: (transform, memoOptions = {}) => withProps(transform, {\n memoize: true,\n memoOptions: {\n maxSize: 50,\n ...memoOptions\n }\n }),\n\n /**\n * Props with performance measurement\n */\n timed: (transform, name = 'PropTransform') => withProps((props, state, context) => {\n const start = performance.now();\n const result = transform(props, state, context);\n const end = performance.now();\n\n if (end - start > 1) { // Log if > 1ms\n console.log(`${name} took ${(end - start).toFixed(2)}ms`);\n }\n\n return result;\n }),\n\n /**\n * Chain multiple prop transformations\n */\n chain: (...transforms) => withProps((props, state, context) => {\n return transforms.reduce((acc, transform) => {\n if (typeof transform === 'function') {\n return {...acc, ...transform(acc, state, context)};\n }\n return {...acc, ...transform};\n }, props);\n })\n};\n\n/**\n * Create a reusable prop transformer\n */\nexport function createPropTransformer(config) {\n const {\n transforms = [],\n validators = [],\n defaults = {},\n options = {}\n } = config;\n\n return withProps((props, state, context) => {\n let result = {...defaults, ...props};\n\n // Apply transforms in sequence\n for (const transform of transforms) {\n if (typeof transform === 'function') {\n result = {...result, ...transform(result, state, context)};\n } else {\n result = {...result, ...transform};\n }\n }\n\n // Run validators\n for (const validator of validators) {\n if (!validator(result)) {\n throw new Error('Prop validation failed');\n }\n }\n\n return result;\n }, options);\n}\n\n/**\n * Props debugging utility\n */\nexport function withPropsDebug(component, debugOptions = {}) {\n const {\n logProps = true,\n logChanges = true,\n breakOnError = false\n } = debugOptions;\n\n return withProps((props, state, context) => {\n if (logProps) {\n console.group(`Props Debug: ${component.name || 'Component'}`);\n console.log('Props:', props);\n console.log('State:', state);\n console.log('Context:', context);\n console.groupEnd();\n }\n\n return props;\n }, {\n debug: true,\n onError: breakOnError ? () => {\n // eslint-disable-next-line no-debugger\n debugger;\n } : undefined,\n onPropsChange: logChanges ? (finalProps, original) => {\n console.log('Props changed:', {from: original, to: finalProps});\n } : undefined\n })(component);\n}\n\n/**\n * State management utilities for component state injection and management\n */\n\n/**\n * Enhanced withState utility for component state management and injection\n */\nexport function withState(initialState = {}, options = {}) {\n const {\n // State options\n persistent = false, // Persist state across component unmounts\n storageKey = null, // Key for persistent storage\n storage = (typeof window !== 'undefined' && typeof window.localStorage !== 'undefined') ? window.localStorage : {\n // Fallback storage for Node.js environments\n _data: new Map(),\n setItem(key, value) { this._data.set(key, value); },\n getItem(key) { return this._data.get(key) || null; },\n removeItem(key) { this._data.delete(key); },\n clear() { this._data.clear(); }\n }, // Storage mechanism\n\n // State transformation\n stateTransform = null, // Transform state before injection\n propName = 'state', // Prop name for state injection\n actionsName = 'actions', // Prop name for action injection\n\n // Reducers and actions\n reducer = null, // State reducer function\n actions = {}, // Action creators\n middleware = [], // State middleware\n\n // Performance\n memoizeState = false, // Memoize state transformations\n // eslint-disable-next-line no-unused-vars\n shallow = false, // Shallow state comparison\n\n // Development\n // eslint-disable-next-line no-unused-vars\n devTools = false, // Connect to dev tools\n debug = false, // Debug logging\n displayName = null, // Component name for debugging\n\n // Lifecycle hooks\n onStateChange = null, // Called when state changes\n onMount = null, // Called when component mounts\n onUnmount = null, // Called when component unmounts\n\n // Validation\n validator = null, // State validator function\n\n // Async state\n supportAsync = false // Support async state updates\n } = options;\n\n return function withStateHOC(WrappedComponent) {\n // Create state container\n const stateContainer = createStateContainer(initialState, {\n persistent,\n storageKey: storageKey || `${getComponentName(WrappedComponent)}_state`,\n storage,\n reducer,\n middleware,\n validator,\n onStateChange,\n debug\n });\n\n function WithStateComponent(props = {}, globalState = {}, context = {}) {\n // Initialize component state if not exists\n if (!stateContainer.initialized) {\n stateContainer.initialize();\n\n if (onMount) {\n onMount(stateContainer.getState(), props, context);\n }\n }\n\n // Get current state\n const currentState = stateContainer.getState();\n\n // Transform state if needed\n let transformedState = currentState;\n if (stateTransform) {\n transformedState = stateTransform(currentState, props, context);\n }\n\n // Create actions bound to this state container\n const boundActions = createBoundActions(actions, stateContainer, {\n props,\n context,\n supportAsync,\n debug\n });\n\n // Create state management utilities\n const stateUtils = {\n // Basic state operations\n setState: stateContainer.setState.bind(stateContainer),\n getState: stateContainer.getState.bind(stateContainer),\n resetState: () => stateContainer.setState(initialState),\n\n // Advanced operations\n updateState: (updater) => {\n const current = stateContainer.getState();\n const next = typeof updater === 'function' ? updater(current) : updater;\n stateContainer.setState(next);\n },\n\n // Batch updates\n batchUpdate: (updates) => {\n stateContainer.batch(() => {\n updates.forEach(update => {\n if (typeof update === 'function') {\n update(stateContainer);\n } else {\n stateContainer.setState(update);\n }\n });\n });\n },\n\n // Computed state\n computed: (computeFn) => {\n return memoizeState ?\n memo(computeFn)(transformedState) :\n computeFn(transformedState);\n },\n\n // State subscription\n subscribe: stateContainer.subscribe.bind(stateContainer),\n unsubscribe: stateContainer.unsubscribe.bind(stateContainer),\n\n // Async state operations\n ...(supportAsync && {\n setStateAsync: async (stateOrPromise) => {\n const resolved = await Promise.resolve(stateOrPromise);\n stateContainer.setState(resolved);\n },\n\n updateStateAsync: async (asyncUpdater) => {\n const current = stateContainer.getState();\n const next = await Promise.resolve(asyncUpdater(current));\n stateContainer.setState(next);\n }\n })\n };\n\n // Prepare enhanced props\n const enhancedProps = {\n ...props,\n [propName]: transformedState,\n [actionsName]: boundActions,\n stateUtils\n };\n\n if (debug) {\n console.log('withState render:', {\n component: getComponentName(WrappedComponent),\n state: transformedState,\n props: enhancedProps\n });\n }\n\n // Render wrapped component\n return typeof WrappedComponent === 'function' ?\n WrappedComponent(enhancedProps, globalState, context) :\n WrappedComponent;\n }\n\n // Set display name\n WithStateComponent.displayName = displayName ||\n `withState(${getComponentName(WrappedComponent)})`;\n\n // Add metadata\n WithStateComponent.__isHOC = true;\n WithStateComponent.__hasState = true;\n WithStateComponent.__stateContainer = stateContainer;\n WithStateComponent.__wrappedComponent = WrappedComponent;\n\n // Cleanup on unmount\n WithStateComponent.cleanup = () => {\n if (onUnmount) {\n onUnmount(stateContainer.getState());\n }\n\n if (!persistent) {\n stateContainer.destroy();\n }\n };\n\n return WithStateComponent;\n };\n}\n\n/**\n * Create a centralized state container\n */\nfunction createStateContainer(initialState, options) {\n const {\n persistent,\n storageKey,\n storage,\n reducer,\n middleware,\n validator,\n onStateChange,\n debug\n } = options;\n\n let state = deepClone(initialState);\n let listeners = new Set();\n const middlewareStack = [...middleware];\n\n const container = {\n initialized: false,\n\n initialize() {\n // Load persisted state\n if (persistent && storageKey) {\n try {\n const saved = storage.getItem(storageKey);\n if (saved) {\n const parsed = JSON.parse(saved);\n state = {...state, ...parsed};\n }\n } catch (_error) {\n if (debug) console.warn('Failed to load persisted state:', _error);\n }\n }\n\n container.initialized = true;\n },\n\n getState() {\n return deepClone(state);\n },\n\n setState(newState) {\n const prevState = state;\n\n // Apply reducer if provided\n if (reducer) {\n state = reducer(state, {type: 'SET_STATE', payload: newState});\n } else {\n state = typeof newState === 'function' ?\n newState(state) :\n {...state, ...newState};\n }\n\n // Validate state\n if (validator && !validator(state)) {\n if (debug) console.warn('State validation failed, reverting:', state);\n state = prevState;\n return false;\n }\n\n // Apply middleware\n state = middlewareStack.reduce((acc, middleware) =>\n middleware(acc, prevState) || acc, state\n );\n\n // Persist state\n if (persistent && storageKey) {\n try {\n storage.setItem(storageKey, JSON.stringify(state));\n } catch (_error) {\n if (debug) console.warn('Failed to persist state:', _error);\n }\n }\n\n // Notify listeners\n if (state !== prevState) {\n listeners.forEach(listener => {\n try {\n listener(state, prevState);\n } catch (_error) {\n if (debug) console.error('State listener _error:', _error);\n }\n });\n\n if (onStateChange) {\n onStateChange(state, prevState);\n }\n }\n\n return true;\n },\n\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n\n unsubscribe(listener) {\n return listeners.delete(listener);\n },\n\n batch(batchFn) {\n const originalListeners = listeners;\n listeners = new Set(); // Temporarily disable listeners\n\n try {\n batchFn();\n } finally {\n listeners = originalListeners;\n // Notify once after batch\n listeners.forEach(listener => listener(state));\n }\n },\n\n destroy() {\n listeners.clear();\n if (persistent && storageKey) {\n try {\n storage.removeItem(storageKey);\n } catch (_error) {\n if (debug) console.warn('Failed to remove persisted state:', _error);\n }\n }\n }\n };\n\n return container;\n}\n\n/**\n * Create bound action creators\n */\nfunction createBoundActions(actions, stateContainer, options) {\n const {props, context, supportAsync, debug} = options;\n const boundActions = {};\n\n Object.entries(actions).forEach(([actionName, actionCreator]) => {\n boundActions[actionName] = (...args) => {\n try {\n const result = actionCreator(\n stateContainer.getState(),\n stateContainer.setState.bind(stateContainer),\n {props, context, args}\n );\n\n // Handle async actions\n if (supportAsync && result && typeof result.then === 'function') {\n return result.catch(_error => {\n if (debug) console.error(`Async action ${actionName} failed:`, _error);\n throw _error;\n });\n }\n\n return result;\n } catch (_error) {\n if (debug) console.error(`Action ${actionName} failed:`, _error);\n throw _error;\n }\n };\n });\n\n return boundActions;\n}\n\n/**\n * Specialized withState variants\n */\nexport const withStateUtils = {\n /**\n * Simple local state\n */\n local: (initialState) => withState(initialState),\n\n /**\n * Persistent state with localStorage\n */\n persistent: (initialState, key) => withState(initialState, {\n persistent: true,\n storageKey: key\n }),\n\n /**\n * State with reducer pattern\n */\n reducer: (initialState, reducer, actions = {}) => withState(initialState, {\n reducer,\n actions\n }),\n\n /**\n * Async state management\n */\n async: (initialState, asyncActions = {}) => withState(initialState, {\n supportAsync: true,\n actions: asyncActions\n }),\n\n /**\n * State with validation\n */\n validated: (initialState, validator) => withState(initialState, {\n validator,\n debug: true\n }),\n\n /**\n * Shared state across components\n */\n shared: (initialState, sharedKey) => {\n const sharedStates = withStateUtils._shared || (withStateUtils._shared = new Map());\n\n if (!sharedStates.has(sharedKey)) {\n sharedStates.set(sharedKey, createStateContainer(initialState, {}));\n }\n\n return (WrappedComponent) => {\n const sharedContainer = sharedStates.get(sharedKey);\n\n function SharedStateComponent(props, globalState, context) {\n const currentState = sharedContainer.getState();\n\n const enhancedProps = {\n ...props,\n state: currentState,\n setState: sharedContainer.setState.bind(sharedContainer),\n subscribe: sharedContainer.subscribe.bind(sharedContainer)\n };\n\n return typeof WrappedComponent === 'function' ?\n WrappedComponent(enhancedProps, globalState, context) :\n WrappedComponent;\n }\n\n SharedStateComponent.displayName = `withSharedState(${getComponentName(WrappedComponent)})`;\n return SharedStateComponent;\n };\n },\n\n /**\n * State with form utilities\n */\n form: (initialFormState) => withState(initialFormState, {\n actions: {\n updateField: (state, setState, {args: [field, value]}) => {\n setState({[field]: value});\n },\n\n updateMultiple: (state, setState, {args: [updates]}) => {\n setState(updates);\n },\n\n resetForm: (state, setState) => {\n setState(initialFormState);\n },\n\n validateForm: (state, setState, {args: [validator]}) => {\n const errors = validator(state);\n setState({_errors: errors});\n return Object.keys(errors).length === 0;\n }\n }\n }),\n\n /**\n * State with loading/_error handling\n */\n withLoading: async (initialState) => withState({\n ...initialState,\n _loading: false,\n _error: null\n }, {\n supportAsync: true,\n actions: {\n setLoading: (state, setState, {args: [loading]}) => {\n setState({_loading: loading});\n },\n\n setError: (state, setState, {args: [_error]}) => {\n setState({_error: _error, _loading: false});\n },\n\n clearError: (state, setState) => {\n setState({_error: null});\n },\n\n asyncAction: async (state, setState, {args: [asyncFn]}) => {\n setState({_loading: true, _error: null});\n try {\n const result = await asyncFn(state);\n setState({_loading: false});\n return result;\n } catch (_error) {\n setState({_loading: false, _error: _error});\n throw _error;\n }\n }\n }\n }),\n\n /**\n * State with undo/redo functionality\n */\n withHistory: (initialState, maxHistory = 10) => {\n const historyState = {\n present: initialState,\n past: [],\n future: []\n };\n\n return withState(historyState, {\n actions: {\n undo: (state, setState) => {\n if (state.past.length === 0) return;\n\n const previous = state.past[state.past.length - 1];\n const newPast = state.past.slice(0, state.past.length - 1);\n\n setState({\n past: newPast,\n present: previous,\n future: [state.present, ...state.future]\n });\n },\n\n redo: (state, setState) => {\n if (state.future.length === 0) return;\n\n const next = state.future[0];\n const newFuture = state.future.slice(1);\n\n setState({\n past: [...state.past, state.present],\n present: next,\n future: newFuture\n });\n },\n\n updatePresent: (state, setState, {args: [newPresent]}) => {\n setState({\n past: [...state.past, state.present].slice(-maxHistory),\n present: newPresent,\n future: []\n });\n },\n\n canUndo: (state) => state.past.length > 0,\n canRedo: (state) => state.future.length > 0\n }\n });\n },\n\n /**\n * Computed state properties\n */\n computed: (initialState, computedProps) => withState(initialState, {\n stateTransform: (state) => {\n const computed = {};\n Object.entries(computedProps).forEach(([key, computeFn]) => {\n computed[key] = computeFn(state);\n });\n return {...state, ...computed};\n },\n memoizeState: true\n })\n};\n\n/**\n * Create a compound state manager\n */\nexport function createStateManager(config) {\n const {\n initialState = {},\n reducers = {},\n actions = {},\n middleware = [],\n plugins = []\n } = config;\n\n // Combine reducers\n const rootReducer = (state, action) => {\n let nextState = state;\n\n Object.entries(reducers).forEach(([key, reducer]) => {\n nextState = {\n ...nextState,\n [key]: reducer(nextState[key], action)\n };\n });\n\n return nextState;\n };\n\n // Apply plugins\n const enhancedConfig = plugins.reduce(\n (acc, plugin) => plugin(acc),\n {initialState, reducer: rootReducer, actions, middleware}\n );\n\n return withState(enhancedConfig.initialState, {\n reducer: enhancedConfig.reducer,\n actions: enhancedConfig.actions,\n middleware: enhancedConfig.middleware\n });\n}\n\n// Utility to get component name\nfunction getComponentName(component) {\n if (!component) return 'Component';\n return component.displayName ||\n component.name ||\n component.constructor?.name ||\n 'Component';\n}\n\nexport default {\n Component,\n createComponent,\n defineComponent,\n registerComponent,\n getComponent,\n getRegisteredComponents,\n createHOC,\n createMixin,\n compose,\n componentUtils,\n dev,\n lazy,\n lazyUtils,\n evaluateLazy,\n evaluateWithTimeout,\n batchEvaluate,\n hashDependencies,\n memo,\n memoUtils,\n withProps,\n withPropsUtils,\n withPropsDebug,\n withState,\n createStateManager,\n getComponentName,\n withStateUtils\n};\n", "/**\n * Enhanced Error Handling System for Coherent.js\n * Provides detailed _error messages and debugging context\n */\n\n/**\n * Custom _error types for better debugging\n */\nexport class CoherentError extends Error {\n constructor(message, options = {}) {\n super(message);\n this.name = 'CoherentError';\n this.type = options.type || 'generic';\n this.component = options.component;\n this.context = options.context;\n this.suggestions = options.suggestions || [];\n this.timestamp = Date.now();\n \n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, CoherentError);\n }\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n type: this.type,\n component: this.component,\n context: this.context,\n suggestions: this.suggestions,\n timestamp: this.timestamp,\n stack: this.stack\n };\n }\n}\n\nexport class ComponentValidationError extends CoherentError {\n constructor(message, component, suggestions = []) {\n super(message, {\n type: 'validation',\n component,\n suggestions: [\n 'Check component structure and syntax',\n 'Ensure all required properties are present',\n 'Validate prop types and values',\n ...suggestions\n ]\n });\n this.name = 'ComponentValidationError';\n }\n}\n\nexport class RenderingError extends CoherentError {\n constructor(message, component, context, suggestions = []) {\n super(message, {\n type: 'rendering',\n component,\n context,\n suggestions: [\n 'Check for circular references',\n 'Validate component depth',\n 'Ensure all functions return valid components',\n ...suggestions\n ]\n });\n this.name = 'RenderingError';\n }\n}\n\nexport class PerformanceError extends CoherentError {\n constructor(message, metrics, suggestions = []) {\n super(message, {\n type: 'performance',\n context: metrics,\n suggestions: [\n 'Consider component memoization',\n 'Reduce component complexity',\n 'Enable caching',\n ...suggestions\n ]\n });\n this.name = 'PerformanceError';\n }\n}\n\nexport class StateError extends CoherentError {\n constructor(message, state, suggestions = []) {\n super(message, {\n type: 'state',\n context: state,\n suggestions: [\n 'Check state mutations',\n 'Ensure proper state initialization',\n 'Validate state transitions',\n ...suggestions\n ]\n });\n this.name = 'StateError';\n }\n}\n\n/**\n * Error handler with context-aware reporting\n */\nexport class ErrorHandler {\n constructor(options = {}) {\n this.options = {\n enableStackTrace: options.enableStackTrace !== false,\n enableSuggestions: options.enableSuggestions !== false,\n enableLogging: options.enableLogging !== false,\n logLevel: options.logLevel || '_error',\n maxErrorHistory: options.maxErrorHistory || 100,\n ...options\n };\n\n this.errorHistory = [];\n this.errorCounts = new Map();\n this.suppressedErrors = new Set();\n }\n\n /**\n * Handle and report errors with detailed context\n */\n handle(_error, context = {}) {\n // Create enhanced _error if it's not already a CoherentError\n const enhancedError = this.enhanceError(_error, context);\n\n // Add to history\n this.addToHistory(enhancedError);\n\n // Log if enabled\n if (this.options.enableLogging) {\n this.logError(enhancedError);\n }\n\n // Return enhanced _error for potential re-throwing\n return enhancedError;\n }\n\n /**\n * Enhance existing errors with more context\n */\n enhanceError(_error, context = {}) {\n if (_error instanceof CoherentError) {\n return _error;\n }\n\n // Determine _error type from context\n const errorType = this.classifyError(_error, context);\n \n // Create appropriate _error type\n switch (errorType) {\n case 'validation':\n return new ComponentValidationError(\n _error.message,\n context.component,\n this.generateSuggestions(_error, context)\n );\n\n case 'rendering':\n return new RenderingError(\n _error.message,\n context.component,\n context.renderContext,\n this.generateSuggestions(_error, context)\n );\n\n case 'performance':\n return new PerformanceError(\n _error.message,\n context.metrics,\n this.generateSuggestions(_error, context)\n );\n\n case 'state':\n return new StateError(\n _error.message,\n context.state,\n this.generateSuggestions(_error, context)\n );\n\n default:\n return new CoherentError(_error.message, {\n type: errorType,\n component: context.component,\n context: context.context,\n suggestions: this.generateSuggestions(_error, context)\n });\n }\n }\n\n /**\n * Classify _error type based on message and context\n */\n classifyError(_error, context) {\n const message = _error.message.toLowerCase();\n\n // Validation errors\n if (message.includes('invalid') || message.includes('validation') || \n message.includes('required') || message.includes('type')) {\n return 'validation';\n }\n\n // Rendering errors\n if (message.includes('render') || message.includes('circular') ||\n message.includes('depth') || message.includes('cannot render')) {\n return 'rendering';\n }\n\n // Performance errors\n if (message.includes('slow') || message.includes('memory') ||\n message.includes('performance') || message.includes('timeout')) {\n return 'performance';\n }\n\n // State errors\n if (message.includes('state') || message.includes('mutation') ||\n message.includes('store') || context.state) {\n return 'state';\n }\n\n // Check context for type hints\n if (context.component) return 'validation';\n if (context.renderContext) return 'rendering';\n if (context.metrics) return 'performance';\n\n return 'generic';\n }\n\n /**\n * Generate helpful suggestions based on _error\n */\n generateSuggestions(_error, context = {}) {\n const suggestions = [];\n const message = _error.message.toLowerCase();\n\n // Common patterns and suggestions\n const patterns = [\n {\n pattern: /cannot render|render.*failed/,\n suggestions: [\n 'Check if component returns a valid object structure',\n 'Ensure all properties are properly defined',\n 'Look for undefined variables or null references'\n ]\n },\n {\n pattern: /circular.*reference/,\n suggestions: [\n 'Remove circular references between components',\n 'Use lazy loading or memoization to break cycles',\n 'Check for self-referencing components'\n ]\n },\n {\n pattern: /maximum.*depth/,\n suggestions: [\n 'Reduce component nesting depth',\n 'Break complex components into smaller parts',\n 'Check for infinite recursion in component functions'\n ]\n },\n {\n pattern: /invalid.*component/,\n suggestions: [\n 'Ensure component follows the expected object structure',\n 'Check property names and values for typos',\n 'Verify component is not null or undefined'\n ]\n },\n {\n pattern: /performance|slow|timeout/,\n suggestions: [\n 'Enable component caching',\n 'Use memoization for expensive operations',\n 'Reduce component complexity',\n 'Consider lazy loading for large components'\n ]\n }\n ];\n\n // Match patterns and add suggestions\n patterns.forEach(({ pattern, suggestions: patternSuggestions }) => {\n if (pattern.test(message)) {\n suggestions.push(...patternSuggestions);\n }\n });\n\n // Context-specific suggestions\n if (context.component) {\n const componentType = typeof context.component;\n if (componentType === 'function') {\n suggestions.push('Check function component return value');\n } else if (componentType === 'object' && context.component === null) {\n suggestions.push('Component is null - ensure proper initialization');\n } else if (Array.isArray(context.component)) {\n suggestions.push('Arrays should contain valid component objects');\n }\n }\n\n // Add debugging tips\n if (suggestions.length === 0) {\n suggestions.push(\n 'Enable development tools for more detailed debugging',\n 'Check browser console for additional _error details',\n 'Use component validation tools to identify issues'\n );\n }\n\n return [...new Set(suggestions)]; // Remove duplicates\n }\n\n /**\n * Add _error to history with deduplication\n */\n addToHistory(_error) {\n const errorKey = `${_error.name}:${_error.message}`;\n \n // Update count\n this.errorCounts.set(errorKey, (this.errorCounts.get(errorKey) || 0) + 1);\n\n // Add to history\n const historyEntry = {\n ..._error.toJSON(),\n count: this.errorCounts.get(errorKey),\n firstSeen: this.errorHistory.find(e => e.key === errorKey)?.firstSeen || _error.timestamp,\n key: errorKey\n };\n\n // Remove old entry if exists\n this.errorHistory = this.errorHistory.filter(e => e.key !== errorKey);\n \n // Add new entry\n this.errorHistory.unshift(historyEntry);\n\n // Limit history size\n if (this.errorHistory.length > this.options.maxErrorHistory) {\n this.errorHistory = this.errorHistory.slice(0, this.options.maxErrorHistory);\n }\n }\n\n /**\n * Log _error with enhanced formatting\n */\n logError(_error) {\n if (this.suppressedErrors.has(`${_error.name }:${ _error.message}`)) {\n return;\n }\n\n const isRepeated = this.errorCounts.get(`${_error.name}:${_error.message}`) > 1;\n \n // Format _error for console\n const errorGroup = `\uD83D\uDEA8 ${_error.name}${isRepeated ? ` (\u00D7${this.errorCounts.get(`${_error.name }:${ _error.message}`)})` : ''}`;\n \n console.group(errorGroup);\n \n // Main _error message\n console.error(`\u274C ${_error.message}`);\n \n // Component context if available\n if (_error.component) {\n console.log('\uD83D\uDD0D Component:', this.formatComponent(_error.component));\n }\n \n // Additional context\n if (_error.context) {\n console.log('\uD83D\uDCCB Context:', _error.context);\n }\n \n // Suggestions\n if (this.options.enableSuggestions && _error.suggestions.length > 0) {\n console.group('\uD83D\uDCA1 Suggestions:');\n _error.suggestions.forEach((suggestion, index) => {\n console.log(`${index + 1}. ${suggestion}`);\n });\n console.groupEnd();\n }\n \n // Stack trace\n if (this.options.enableStackTrace && _error.stack) {\n console.log('\uD83D\uDCDA Stack trace:', _error.stack);\n }\n \n console.groupEnd();\n }\n\n /**\n * Format component for logging\n */\n formatComponent(component, maxDepth = 2, currentDepth = 0) {\n if (currentDepth > maxDepth) {\n return '[...deep]';\n }\n\n if (typeof component === 'function') {\n return `[Function: ${component.name || 'anonymous'}]`;\n }\n\n if (Array.isArray(component)) {\n return component.slice(0, 3).map(item => \n this.formatComponent(item, maxDepth, currentDepth + 1)\n );\n }\n\n if (component && typeof component === 'object') {\n const formatted = {};\n const keys = Object.keys(component).slice(0, 5);\n \n for (const key of keys) {\n if (key === 'children' && component[key]) {\n formatted[key] = this.formatComponent(component[key], maxDepth, currentDepth + 1);\n } else {\n formatted[key] = component[key];\n }\n }\n\n if (Object.keys(component).length > 5) {\n formatted['...'] = `(${Object.keys(component).length - 5} more)`;\n }\n\n return formatted;\n }\n\n return component;\n }\n\n /**\n * Suppress specific _error types\n */\n suppress(errorPattern) {\n this.suppressedErrors.add(errorPattern);\n }\n\n /**\n * Clear _error history\n */\n clearHistory() {\n this.errorHistory = [];\n this.errorCounts.clear();\n }\n\n /**\n * Get _error statistics\n */\n getStats() {\n const errorsByType = {};\n const errorsByTime = {};\n\n this.errorHistory.forEach(_error => {\n // Count by type\n errorsByType[_error.type] = (errorsByType[_error.type] || 0) + _error.count;\n\n // Count by hour\n const hour = new Date(_error.timestamp).toISOString().slice(0, 13);\n errorsByTime[hour] = (errorsByTime[hour] || 0) + _error.count;\n });\n\n return {\n totalErrors: this.errorHistory.reduce((sum, e) => sum + e.count, 0),\n uniqueErrors: this.errorHistory.length,\n errorsByType,\n errorsByTime,\n mostCommonErrors: this.getMostCommonErrors(5),\n recentErrors: this.errorHistory.slice(0, 10)\n };\n }\n\n /**\n * Get most common errors\n */\n getMostCommonErrors(limit = 10) {\n return this.errorHistory\n .sort((a, b) => b.count - a.count)\n .slice(0, limit)\n .map(({ name, message, count, type }) => ({\n name,\n message,\n count,\n type\n }));\n }\n}\n\n/**\n * Global _error handler instance\n */\nexport const globalErrorHandler = new ErrorHandler();\n\n/**\n * Convenience functions for common _error types\n */\nexport function throwValidationError(message, component, suggestions = []) {\n throw new ComponentValidationError(message, component, suggestions);\n}\n\nexport function throwRenderingError(message, component, context, suggestions = []) {\n throw new RenderingError(message, component, context, suggestions);\n}\n\nexport function throwPerformanceError(message, metrics, suggestions = []) {\n throw new PerformanceError(message, metrics, suggestions);\n}\n\nexport function throwStateError(message, state, suggestions = []) {\n throw new StateError(message, state, suggestions);\n}\n\n/**\n * Try-catch wrapper with enhanced _error handling\n */\nexport function safeExecute(fn, context = {}, fallback = null) {\n try {\n return fn();\n } catch (_error) {\n const enhancedError = globalErrorHandler.handle(_error, context);\n \n if (fallback !== null) {\n return typeof fallback === 'function' ? fallback(enhancedError) : fallback;\n }\n \n throw enhancedError;\n }\n}\n\n/**\n * Async try-catch wrapper\n */\nexport async function safeExecuteAsync(fn, context = {}, fallback = null) {\n try {\n return await fn();\n } catch (_error) {\n const enhancedError = globalErrorHandler.handle(_error, context);\n \n if (fallback !== null) {\n return typeof fallback === 'function' ? fallback(enhancedError) : fallback;\n }\n \n throw enhancedError;\n }\n}\n\n/**\n * Factory function to create an ErrorHandler instance\n * \n * @param {Object} options - ErrorHandler configuration\n * @returns {ErrorHandler} ErrorHandler instance\n * \n * @example\n * const errorHandler = createErrorHandler({\n * enableTracing: true,\n * enableSuggestions: true\n * });\n */\nexport function createErrorHandler(options = {}) {\n return new ErrorHandler(options);\n}\n\nexport default ErrorHandler;", "/**\n * Component Lifecycle System for Coherent.js\n * Provides hooks and events for component lifecycle management\n */\n\nimport { globalErrorHandler } from '../utils/error-handler.js';\n// Note: ReactiveState moved to @coherent.js/state package\n// Lifecycle hooks are SSR-compatible and don't require reactive state\n\n/**\n * Lifecycle phases\n */\nexport const LIFECYCLE_PHASES = {\n BEFORE_CREATE: 'beforeCreate',\n CREATED: 'created',\n BEFORE_MOUNT: 'beforeMount',\n MOUNTED: 'mounted',\n BEFORE_UPDATE: 'beforeUpdate',\n UPDATED: 'updated',\n BEFORE_UNMOUNT: 'beforeUnmount',\n UNMOUNTED: 'unmounted',\n ERROR: '_error'\n};\n\n/**\n * Component instance tracker\n */\nconst componentInstances = new WeakMap();\nconst componentRegistry = new Map();\n\n/**\n * Component lifecycle manager\n */\nexport class ComponentLifecycle {\n constructor(component, options = {}) {\n this.component = component;\n this.id = this.generateId();\n this.options = options;\n this.phase = null;\n this.hooks = new Map();\n this.state = new Map(); // Simple Map for SSR compatibility\n this.props = {};\n this.context = {};\n this.isMounted = false;\n this.isDestroyed = false;\n this.children = new Set();\n this.parent = null;\n this.eventHandlers = new Map();\n this.timers = new Set();\n this.subscriptions = new Set();\n\n // Register instance\n componentInstances.set(component, this);\n componentRegistry.set(this.id, this);\n\n // Initialize lifecycle\n this.executeHook(LIFECYCLE_PHASES.BEFORE_CREATE);\n this.executeHook(LIFECYCLE_PHASES.CREATED);\n }\n\n /**\n * Generate unique component ID\n */\n generateId() {\n return `comp_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n }\n\n /**\n * Add lifecycle hook\n */\n hook(phase, callback) {\n if (typeof callback !== 'function') {\n throw new Error(`Hook callback must be a function for phase: ${phase}`);\n }\n\n if (!this.hooks.has(phase)) {\n this.hooks.set(phase, []);\n }\n\n this.hooks.get(phase).push(callback);\n return this;\n }\n\n /**\n * Execute hooks for a specific phase\n */\n async executeHook(phase, ...args) {\n if (this.isDestroyed) {\n return;\n }\n\n this.phase = phase;\n const hooks = this.hooks.get(phase) || [];\n\n for (const hook of hooks) {\n try {\n await hook.call(this, ...args);\n } catch (_error) {\n this.handleError(_error, phase);\n }\n }\n }\n\n /**\n * Handle component errors\n */\n handleError(_error, phase) {\n const enhancedError = globalErrorHandler.handle(_error, {\n component: this.component,\n context: {\n phase,\n componentId: this.id,\n props: this.props,\n state: this.state.toObject()\n }\n });\n\n this.executeHook(LIFECYCLE_PHASES.ERROR, enhancedError);\n }\n\n /**\n * Mount component\n */\n async mount(container, props = {}) {\n if (this.isMounted) {\n console.warn(`Component ${this.id} is already mounted`);\n return;\n }\n\n this.props = props;\n this.container = container;\n\n await this.executeHook(LIFECYCLE_PHASES.BEFORE_MOUNT, container, props);\n\n try {\n // Actual mounting logic would be handled by the renderer\n this.isMounted = true;\n await this.executeHook(LIFECYCLE_PHASES.MOUNTED, container);\n } catch (_error) {\n this.handleError(_error, 'mount');\n }\n }\n\n /**\n * Update component\n */\n async update(newProps = {}) {\n if (!this.isMounted || this.isDestroyed) {\n return;\n }\n\n const oldProps = this.props;\n this.props = { ...this.props, ...newProps };\n\n await this.executeHook(LIFECYCLE_PHASES.BEFORE_UPDATE, newProps, oldProps);\n\n try {\n // Update logic would be handled by the renderer\n await this.executeHook(LIFECYCLE_PHASES.UPDATED, this.props, oldProps);\n } catch (_error) {\n this.handleError(_error, 'update');\n }\n }\n\n /**\n * Unmount component\n */\n async unmount() {\n if (!this.isMounted || this.isDestroyed) {\n return;\n }\n\n await this.executeHook(LIFECYCLE_PHASES.BEFORE_UNMOUNT);\n\n try {\n // Cleanup children\n for (const child of this.children) {\n await child.unmount();\n }\n\n // Cleanup subscriptions\n this.subscriptions.forEach(unsub => {\n try {\n unsub();\n } catch (_error) {\n console.warn('Error cleaning up subscription:', _error);\n }\n });\n\n // Clear timers\n this.timers.forEach(timer => {\n clearTimeout(timer);\n clearInterval(timer);\n });\n\n // Remove event handlers\n this.eventHandlers.forEach((handler, element) => {\n handler.events.forEach((listeners, event) => {\n listeners.forEach(listener => {\n element.removeEventListener(event, listener);\n });\n });\n });\n\n // Cleanup state\n this.state.destroy();\n\n this.isMounted = false;\n this.isDestroyed = true;\n\n await this.executeHook(LIFECYCLE_PHASES.UNMOUNTED);\n\n // Unregister\n componentRegistry.delete(this.id);\n\n } catch (_error) {\n this.handleError(_error, 'unmount');\n }\n }\n\n /**\n * Add child component\n */\n addChild(child) {\n child.parent = this;\n this.children.add(child);\n }\n\n /**\n * Remove child component\n */\n removeChild(child) {\n child.parent = null;\n this.children.delete(child);\n }\n\n /**\n * Add event listener with automatic cleanup\n */\n addEventListener(element, event, listener, options = {}) {\n if (!this.eventHandlers.has(element)) {\n this.eventHandlers.set(element, {\n events: new Map()\n });\n }\n\n const handler = this.eventHandlers.get(element);\n\n if (!handler.events.has(event)) {\n handler.events.set(event, new Set());\n }\n\n handler.events.get(event).add(listener);\n element.addEventListener(event, listener, options);\n\n // Return cleanup function\n return () => {\n handler.events.get(event).delete(listener);\n element.removeEventListener(event, listener);\n };\n }\n\n /**\n * Add subscription with automatic cleanup\n */\n addSubscription(unsubscribe) {\n this.subscriptions.add(unsubscribe);\n return unsubscribe;\n }\n\n /**\n * Set timer with automatic cleanup\n */\n setTimeout(callback, delay) {\n const timer = setTimeout(() => {\n this.timers.delete(timer);\n callback();\n }, delay);\n\n this.timers.add(timer);\n return timer;\n }\n\n setInterval(callback, interval) {\n const timer = setInterval(callback, interval);\n this.timers.add(timer);\n return timer;\n }\n\n /**\n * Get component statistics\n */\n getStats() {\n return {\n id: this.id,\n phase: this.phase,\n isMounted: this.isMounted,\n isDestroyed: this.isDestroyed,\n childCount: this.children.size,\n eventHandlers: this.eventHandlers.size,\n subscriptions: this.subscriptions.size,\n timers: this.timers.size,\n state: this.state.getStats()\n };\n }\n}\n\n/**\n * Event system for components\n */\nexport class ComponentEventSystem {\n constructor() {\n this.events = new Map();\n this.globalHandlers = new Map();\n }\n\n /**\n * Emit event to component or globally\n */\n emit(eventName, data = {}, target = null) {\n const event = {\n name: eventName,\n data,\n target,\n timestamp: Date.now(),\n stopped: false,\n preventDefault: false\n };\n\n // Target specific component\n if (target) {\n const instance = componentInstances.get(target);\n if (instance) {\n this._notifyHandlers(instance.id, event);\n }\n } else {\n // Global event\n this._notifyGlobalHandlers(event);\n }\n\n return event;\n }\n\n /**\n * Listen for events on component or globally\n */\n on(eventName, handler, componentId = null) {\n if (componentId) {\n // Component-specific event\n if (!this.events.has(componentId)) {\n this.events.set(componentId, new Map());\n }\n\n const componentEvents = this.events.get(componentId);\n if (!componentEvents.has(eventName)) {\n componentEvents.set(eventName, new Set());\n }\n\n componentEvents.get(eventName).add(handler);\n } else {\n // Global event\n if (!this.globalHandlers.has(eventName)) {\n this.globalHandlers.set(eventName, new Set());\n }\n\n this.globalHandlers.get(eventName).add(handler);\n }\n\n // Return unsubscribe function\n return () => this.off(eventName, handler, componentId);\n }\n\n /**\n * Remove event handler\n */\n off(eventName, handler, componentId = null) {\n if (componentId) {\n const componentEvents = this.events.get(componentId);\n if (componentEvents && componentEvents.has(eventName)) {\n componentEvents.get(eventName).delete(handler);\n\n // Cleanup empty sets\n if (componentEvents.get(eventName).size === 0) {\n componentEvents.delete(eventName);\n if (componentEvents.size === 0) {\n this.events.delete(componentId);\n }\n }\n }\n } else {\n const handlers = this.globalHandlers.get(eventName);\n if (handlers) {\n handlers.delete(handler);\n if (handlers.size === 0) {\n this.globalHandlers.delete(eventName);\n }\n }\n }\n }\n\n /**\n * Listen once\n */\n once(eventName, handler, componentId = null) {\n const onceHandler = (event) => {\n handler(event);\n this.off(eventName, onceHandler, componentId);\n };\n\n return this.on(eventName, onceHandler, componentId);\n }\n\n /**\n * Notify component handlers\n */\n _notifyHandlers(componentId, event) {\n const componentEvents = this.events.get(componentId);\n if (componentEvents && componentEvents.has(event.name)) {\n const handlers = componentEvents.get(event.name);\n for (const handler of handlers) {\n if (event.stopped) break;\n\n try {\n handler(event);\n } catch (_error) {\n globalErrorHandler.handle(_error, {\n type: 'event-handler-_error',\n context: { event, handler: handler.toString() }\n });\n }\n }\n }\n }\n\n /**\n * Notify global handlers\n */\n _notifyGlobalHandlers(event) {\n const handlers = this.globalHandlers.get(event.name);\n if (handlers) {\n for (const handler of handlers) {\n if (event.stopped) break;\n\n try {\n handler(event);\n } catch (_error) {\n globalErrorHandler.handle(_error, {\n type: 'global-event-handler-_error',\n context: { event, handler: handler.toString() }\n });\n }\n }\n }\n }\n\n /**\n * Clean up events for a component\n */\n cleanup(componentId) {\n this.events.delete(componentId);\n }\n\n /**\n * Get event statistics\n */\n getStats() {\n return {\n componentEvents: this.events.size,\n globalEvents: this.globalHandlers.size,\n totalHandlers: Array.from(this.events.values()).reduce((sum, events) => {\n return sum + Array.from(events.values()).reduce((eventSum, handlers) => {\n return eventSum + handlers.size;\n }, 0);\n }, 0) + Array.from(this.globalHandlers.values()).reduce((sum, handlers) => {\n return sum + handlers.size;\n }, 0)\n };\n }\n}\n\n/**\n * Global event system instance\n */\nexport const eventSystem = new ComponentEventSystem();\n\n/**\n * Lifecycle hooks factory\n */\nexport function createLifecycleHooks() {\n const hooks = {};\n\n Object.values(LIFECYCLE_PHASES).forEach(phase => {\n hooks[phase] = (callback) => {\n // This would be called during component creation\n const instance = getCurrentInstance();\n if (instance) {\n instance.hook(phase, callback);\n }\n };\n });\n\n return hooks;\n}\n\n/**\n * Get current component instance (context-based)\n */\nlet currentInstance = null;\n\nexport function getCurrentInstance() {\n return currentInstance;\n}\n\nexport function setCurrentInstance(instance) {\n currentInstance = instance;\n}\n\n/**\n * Lifecycle hooks for direct use\n */\nexport const useHooks = createLifecycleHooks();\n\n/**\n * Utility functions for component management\n */\nexport const componentUtils = {\n /**\n * Get component lifecycle instance\n */\n getLifecycle(component) {\n return componentInstances.get(component);\n },\n\n /**\n * Create component with lifecycle\n */\n createWithLifecycle(component, options = {}) {\n const lifecycle = new ComponentLifecycle(component, options);\n return {\n component,\n lifecycle,\n mount: lifecycle.mount.bind(lifecycle),\n unmount: lifecycle.unmount.bind(lifecycle),\n update: lifecycle.update.bind(lifecycle)\n };\n },\n\n /**\n * Get all component instances\n */\n getAllInstances() {\n return Array.from(componentRegistry.values());\n },\n\n /**\n * Find component by ID\n */\n findById(id) {\n return componentRegistry.get(id);\n },\n\n /**\n * Emit event to component\n */\n emit(component, eventName, data) {\n return eventSystem.emit(eventName, data, component);\n },\n\n /**\n * Listen to component events\n */\n listen(component, eventName, handler) {\n const lifecycle = componentInstances.get(component);\n return eventSystem.on(eventName, handler, lifecycle?.id);\n }\n};\n\n/**\n * Component decorator for automatic lifecycle management\n */\nexport function withLifecycle(component, options = {}) {\n return function LifecycleComponent(props = {}) {\n const instance = componentUtils.getLifecycle(component);\n\n if (!instance) {\n const lifecycle = new ComponentLifecycle(component, options);\n setCurrentInstance(lifecycle);\n }\n\n const result = typeof component === 'function' ? component(props) : component;\n\n setCurrentInstance(null);\n\n return result;\n };\n}\n\nexport default ComponentLifecycle;\n", "/**\n * Enhanced Event Bus System for Coherent.js\n * Adds priority, throttling, filtering, and advanced features\n */\n\n// Performance monitor available for future use\n// import { performanceMonitor } from '../performance/monitor.js';\n\n/**\n * Throttle helper\n */\nfunction throttle(func, delay) {\n let lastCall = 0;\n let timeoutId = null;\n \n return function throttled(...args) {\n const now = Date.now();\n const timeSinceLastCall = now - lastCall;\n \n if (timeSinceLastCall >= delay) {\n lastCall = now;\n return func.apply(this, args);\n } else {\n if (timeoutId) clearTimeout(timeoutId);\n timeoutId = setTimeout(() => {\n lastCall = Date.now();\n func.apply(this, args);\n }, delay - timeSinceLastCall);\n }\n };\n}\n\n/**\n * Debounce helper (available for future use)\n */\n// function debounce(func, delay) {\n// let timeoutId = null;\n// \n// return function debounced(...args) {\n// if (timeoutId) clearTimeout(timeoutId);\n// timeoutId = setTimeout(() => {\n// func.apply(this, args);\n// }, delay);\n// };\n// }\n\n/**\n * Event Bus with advanced features (backward compatible)\n */\nexport class EventBus {\n constructor(options = {}) {\n this.listeners = new Map(); // event -> Array of {listener, priority, options}\n this.handlers = new Map();\n this.actionHandlers = new Map();\n this.middleware = [];\n this.throttledEmitters = new Map();\n this.debouncedEmitters = new Map();\n \n this.options = {\n debug: false,\n performance: true,\n maxListeners: 100,\n enableWildcards: true,\n enableAsync: true,\n wildcardSeparator: ':',\n enablePriority: true,\n defaultPriority: 0,\n errorHandler: null,\n filters: {\n allowList: null, // null means allow all\n blockList: []\n },\n throttle: {\n enabled: false,\n defaultDelay: 100,\n events: {}\n },\n batching: {\n enabled: false,\n maxBatchSize: 10,\n flushInterval: 16\n },\n ...options\n };\n\n // Performance tracking\n this.stats = {\n eventsEmitted: 0,\n listenersExecuted: 0,\n errorsOccurred: 0,\n averageEmitTime: 0,\n throttledEvents: 0,\n filteredEvents: 0\n };\n\n // Batching queue\n if (this.options.batching.enabled) {\n this.batchQueue = [];\n this.batchTimer = null;\n }\n\n // Debug middleware\n if (this.options.debug) {\n this.use((event, data, next) => {\n console.log(`[EventBus] ${event}:`, data);\n next();\n });\n }\n }\n\n /**\n * Add middleware\n */\n use(middleware) {\n if (typeof middleware !== 'function') {\n throw new Error('Middleware must be a function');\n }\n this.middleware.push(middleware);\n return this;\n }\n\n /**\n * Check if event passes filters\n */\n passesFilters(event) {\n const { allowList, blockList } = this.options.filters;\n \n // Check block list first\n if (blockList && blockList.length > 0) {\n for (const pattern of blockList) {\n if (this.matchPattern(pattern, event)) {\n this.stats.filteredEvents++;\n return false;\n }\n }\n }\n \n // Check allow list if it exists\n if (allowList && allowList.length > 0) {\n for (const pattern of allowList) {\n if (this.matchPattern(pattern, event)) {\n return true;\n }\n }\n this.stats.filteredEvents++;\n return false;\n }\n \n return true;\n }\n\n /**\n * Match event against pattern\n */\n matchPattern(pattern, event) {\n const sep = this.options.wildcardSeparator;\n const patternParts = pattern.split(sep);\n const eventParts = event.split(sep);\n \n if (pattern.includes('*')) {\n if (patternParts.length !== eventParts.length) {\n return false;\n }\n return patternParts.every((part, i) => part === '*' || part === eventParts[i]);\n }\n \n return pattern === event;\n }\n\n /**\n * Emit an event\n */\n async emit(event, data = null) {\n // Check filters\n if (!this.passesFilters(event)) {\n if (this.options.debug) {\n console.warn(`[EventBus] Event filtered: ${event}`);\n }\n return;\n }\n\n // Handle batching\n if (this.options.batching.enabled) {\n return this.addToBatch(event, data);\n }\n\n // Handle throttling\n if (this.options.throttle.enabled) {\n const throttleDelay = (this.options.throttle.events && this.options.throttle.events[event]) || this.options.throttle.defaultDelay;\n if (throttleDelay > 0) {\n return this.emitThrottled(event, data, throttleDelay);\n }\n }\n\n return this.emitImmediate(event, data);\n }\n\n /**\n * Emit immediately without throttling\n */\n async emitImmediate(event, data = null) {\n const startTime = this.options.performance ? performance.now() : 0;\n\n try {\n // Run middleware\n await this.runMiddleware(event, data);\n\n // Get listeners (sorted by priority if enabled)\n const listeners = this.getEventListeners(event);\n\n if (listeners.length === 0) {\n if (this.options.debug) {\n console.warn(`[EventBus] No listeners for event: ${event}`);\n }\n return;\n }\n\n // Execute listeners\n const promises = listeners.map(listenerObj =>\n this.executeListener(listenerObj.listener, event, data, listenerObj.options)\n );\n\n if (this.options.enableAsync) {\n await Promise.allSettled(promises);\n } else {\n for (const promise of promises) {\n await promise;\n }\n }\n\n this.stats.eventsEmitted++;\n this.stats.listenersExecuted += listeners.length;\n\n } catch (error) {\n this.stats.errorsOccurred++;\n this.handleError(error, event, data);\n } finally {\n if (this.options.performance) {\n const duration = performance.now() - startTime;\n this.updatePerformanceStats(duration);\n }\n }\n }\n\n /**\n * Emit with throttling\n */\n emitThrottled(event, data, delay) {\n if (!this.throttledEmitters.has(event)) {\n const throttled = throttle((evt, d) => this.emitImmediate(evt, d), delay);\n this.throttledEmitters.set(event, throttled);\n }\n \n this.stats.throttledEvents++;\n return this.throttledEmitters.get(event)(event, data);\n }\n\n /**\n * Add event to batch queue\n */\n addToBatch(event, data) {\n this.batchQueue.push({ event, data, timestamp: Date.now() });\n \n if (this.batchQueue.length >= this.options.batching.maxBatchSize) {\n this.flushBatch();\n } else if (!this.batchTimer) {\n this.batchTimer = setTimeout(() => {\n this.flushBatch();\n }, this.options.batching.flushInterval);\n }\n }\n\n /**\n * Flush batch queue\n */\n async flushBatch() {\n if (this.batchTimer) {\n clearTimeout(this.batchTimer);\n this.batchTimer = null;\n }\n \n const batch = this.batchQueue.splice(0);\n \n for (const { event, data } of batch) {\n await this.emitImmediate(event, data);\n }\n }\n\n /**\n * Register event listener with options\n */\n on(event, listener, options = {}) {\n if (typeof listener !== 'function') {\n throw new Error('Listener must be a function');\n }\n\n if (!this.listeners.has(event)) {\n this.listeners.set(event, []);\n }\n\n const listeners = this.listeners.get(event);\n\n // Check max listeners\n if (listeners.length >= this.options.maxListeners) {\n console.warn(`[EventBus] Max listeners (${this.options.maxListeners}) reached for event: ${event}`);\n }\n\n // Create listener object\n const listenerId = this.generateListenerId(event);\n const listenerObj = {\n listener,\n listenerId,\n priority: options.priority !== undefined ? options.priority : this.options.defaultPriority,\n condition: options.condition || null,\n timeout: options.timeout || null,\n options\n };\n\n listener.__listenerId = listenerId;\n listener.__event = event;\n\n // Insert listener in priority order\n if (this.options.enablePriority) {\n const insertIndex = listeners.findIndex(l => l.priority < listenerObj.priority);\n if (insertIndex === -1) {\n listeners.push(listenerObj);\n } else {\n listeners.splice(insertIndex, 0, listenerObj);\n }\n } else {\n listeners.push(listenerObj);\n }\n\n return listenerId;\n }\n\n /**\n * Register one-time listener\n */\n once(event, listener, options = {}) {\n const onceListener = (...args) => {\n this.off(event, onceListener.__listenerId);\n return listener.call(this, ...args);\n };\n\n // Handle timeout for once listeners\n if (options.timeout) {\n const timeoutId = setTimeout(() => {\n this.off(event, onceListener.__listenerId);\n if (this.options.debug) {\n console.warn(`[EventBus] Listener timeout for event: ${event}`);\n }\n }, options.timeout);\n \n onceListener.__cleanup = () => clearTimeout(timeoutId);\n }\n\n return this.on(event, onceListener, options);\n }\n\n /**\n * Remove listener\n */\n off(event, listenerId) {\n if (!this.listeners.has(event)) {\n return false;\n }\n\n const listeners = this.listeners.get(event);\n const index = listeners.findIndex(l => l.listenerId === listenerId);\n \n if (index !== -1) {\n const listenerObj = listeners[index];\n if (listenerObj.listener.__cleanup) {\n listenerObj.listener.__cleanup();\n }\n listeners.splice(index, 1);\n \n if (listeners.length === 0) {\n this.listeners.delete(event);\n }\n \n return true;\n }\n\n return false;\n }\n\n /**\n * Remove all listeners for an event\n */\n removeAllListeners(event) {\n if (event) {\n this.listeners.delete(event);\n } else {\n this.listeners.clear();\n }\n }\n\n /**\n * Get event listeners with wildcard support\n */\n getEventListeners(event) {\n const listeners = [];\n\n // Direct listeners\n if (this.listeners.has(event)) {\n listeners.push(...this.listeners.get(event));\n }\n\n // Wildcard listeners\n if (this.options.enableWildcards) {\n for (const [pattern, patternListeners] of this.listeners) {\n if (pattern.includes('*') && this.matchPattern(pattern, event)) {\n listeners.push(...patternListeners);\n }\n }\n }\n\n // Sort by priority if enabled\n if (this.options.enablePriority) {\n listeners.sort((a, b) => b.priority - a.priority);\n }\n\n return listeners;\n }\n\n /**\n * Execute listener with options\n */\n async executeListener(listener, event, data, options = {}) {\n try {\n // Check condition\n if (options.condition && !options.condition(data)) {\n return;\n }\n\n const result = listener.call(this, data, event);\n\n if (result && typeof result.then === 'function') {\n await result;\n }\n\n return result;\n } catch (error) {\n this.handleError(error, event, data);\n }\n }\n\n /**\n * Run middleware chain\n */\n async runMiddleware(event, data) {\n if (this.middleware.length === 0) return;\n\n let index = 0;\n\n const next = async () => {\n if (index < this.middleware.length) {\n const middleware = this.middleware[index++];\n await middleware(event, data, next);\n }\n };\n\n await next();\n }\n\n /**\n * Handle errors\n */\n handleError(error, event, data) {\n if (this.options.errorHandler) {\n this.options.errorHandler(error, event, data);\n } else if (this.options.debug) {\n console.error(`[EventBus] Error in event ${event}:`, error, data);\n }\n\n // Emit error event\n this.emitSync('eventbus:error', { error, event, data });\n }\n\n /**\n * Synchronous emit\n */\n emitSync(event, data = null) {\n try {\n const listeners = this.getEventListeners(event);\n\n listeners.forEach(listenerObj => {\n try {\n if (!listenerObj.options.condition || listenerObj.options.condition(data)) {\n listenerObj.listener.call(this, data, event);\n }\n } catch (error) {\n this.handleError(error, event, data);\n }\n });\n\n this.stats.eventsEmitted++;\n this.stats.listenersExecuted += listeners.length;\n\n } catch (error) {\n this.stats.errorsOccurred++;\n this.handleError(error, event, data);\n }\n }\n\n /**\n * Register action handler\n */\n registerAction(action, handler) {\n if (typeof handler !== 'function') {\n throw new Error('Action handler must be a function');\n }\n\n this.actionHandlers.set(action, handler);\n\n if (this.options.debug) {\n console.log(`[EventBus] Registered action: ${action}`);\n }\n }\n\n /**\n * Register multiple actions\n */\n registerActions(actions) {\n Object.entries(actions).forEach(([action, handler]) => {\n this.registerAction(action, handler);\n });\n }\n\n /**\n * Get registered actions\n */\n getRegisteredActions() {\n return Array.from(this.actionHandlers.keys());\n }\n\n /**\n * Handle action event (called by DOM integration)\n */\n handleAction(action, element, event, data) {\n const handler = this.actionHandlers.get(action);\n \n if (!handler) {\n if (this.options.debug) {\n console.warn(`[EventBus] No handler registered for action: ${action}`);\n }\n return;\n }\n\n try {\n handler.call(element, {\n element,\n event,\n data,\n emit: this.emit.bind(this),\n emitSync: this.emitSync.bind(this)\n });\n } catch (error) {\n this.handleError(error, `action:${action}`, { element, event, data });\n }\n }\n\n /**\n * Generate unique listener ID\n */\n generateListenerId(event) {\n return `${event}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n }\n\n /**\n * Update performance stats\n */\n updatePerformanceStats(duration) {\n const count = this.stats.eventsEmitted;\n this.stats.averageEmitTime = (this.stats.averageEmitTime * (count - 1) + duration) / count;\n }\n\n /**\n * Get statistics\n */\n getStats() {\n return { ...this.stats };\n }\n\n /**\n * Reset statistics\n */\n resetStats() {\n this.stats = {\n eventsEmitted: 0,\n listenersExecuted: 0,\n errorsOccurred: 0,\n averageEmitTime: 0,\n throttledEvents: 0,\n filteredEvents: 0\n };\n }\n\n /**\n * Destroy event bus\n */\n destroy() {\n this.removeAllListeners();\n this.actionHandlers.clear();\n this.handlers.clear();\n this.middleware = [];\n this.throttledEmitters.clear();\n this.debouncedEmitters.clear();\n \n if (this.batchTimer) {\n clearTimeout(this.batchTimer);\n }\n }\n}\n\n/**\n * Create event bus instance\n */\nexport function createEventBus(options = {}) {\n return new EventBus(options);\n}\n\n/**\n * Global event bus instance\n */\nexport const globalEventBus = createEventBus();\n\n/**\n * Quick access functions for global event bus\n */\nexport const emit = globalEventBus.emit.bind(globalEventBus);\nexport const emitSync = globalEventBus.emitSync.bind(globalEventBus);\nexport const on = globalEventBus.on.bind(globalEventBus);\nexport const once = globalEventBus.once.bind(globalEventBus);\nexport const off = globalEventBus.off.bind(globalEventBus);\nexport const registerAction = globalEventBus.registerAction.bind(globalEventBus);\nexport const handleAction = globalEventBus.handleAction.bind(globalEventBus);\n\nexport default EventBus;\n", "/**\n * DOM Integration for Coherent.js Event Bus\n *\n * Provides seamless integration between DOM events, data attributes,\n * and the event bus system. Enables declarative event handling in HTML.\n */\n\nimport { globalEventBus } from './event-bus.js';\n\n/**\n * DOM Event Integration Class\n * Manages DOM event listeners and data-action attribute handling\n */\nexport class DOMEventIntegration {\n constructor(eventBus = globalEventBus, options = {}) {\n this.eventBus = eventBus;\n this.options = {\n debug: false,\n debounceDelay: 150,\n throttleDelay: 100,\n enableDelegation: true,\n enableDebounce: true,\n enableThrottle: false,\n ...options\n };\n\n this.boundHandlers = new Map();\n this.activeElement = null;\n this.isInitialized = false;\n\n // Bind context for event handlers\n this.handleClick = this.handleClick.bind(this);\n this.handleChange = this.handleChange.bind(this);\n this.handleInput = this.handleInput.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n this.handleKeydown = this.handleKeydown.bind(this);\n this.handleFocus = this.handleFocus.bind(this);\n this.handleBlur = this.handleBlur.bind(this);\n }\n\n /**\n * Initialize DOM event listeners\n * @param {HTMLElement} rootElement - Root element to attach listeners to (default: document)\n */\n initialize(rootElement = document) {\n if (this.isInitialized) {\n console.warn('[DOMEventIntegration] Already initialized');\n return;\n }\n\n if (typeof window === 'undefined' || !rootElement) {\n console.warn('[DOMEventIntegration] Cannot initialize: no DOM environment');\n return;\n }\n\n this.rootElement = rootElement;\n this.setupDOMEventListeners();\n this.isInitialized = true;\n\n if (this.options.debug) {\n console.log('[DOMEventIntegration] Initialized with options:', this.options);\n }\n }\n\n /**\n * Set up delegated DOM event listeners\n * @private\n */\n setupDOMEventListeners() {\n // Click events\n const clickHandler = this.createDelegatedHandler('click', this.handleClick);\n this.rootElement.addEventListener('click', clickHandler, { passive: false });\n this.boundHandlers.set('click', clickHandler);\n\n // Change events (with debouncing)\n const changeHandler = this.options.enableDebounce\n ? this.debounce(this.createDelegatedHandler('change', this.handleChange), this.options.debounceDelay)\n : this.createDelegatedHandler('change', this.handleChange);\n this.rootElement.addEventListener('change', changeHandler, { passive: true });\n this.boundHandlers.set('change', changeHandler);\n\n // Input events (with debouncing)\n const inputHandler = this.options.enableDebounce\n ? this.debounce(this.createDelegatedHandler('input', this.handleInput), this.options.debounceDelay)\n : this.createDelegatedHandler('input', this.handleInput);\n this.rootElement.addEventListener('input', inputHandler, { passive: true });\n this.boundHandlers.set('input', inputHandler);\n\n // Submit events\n const submitHandler = this.createDelegatedHandler('submit', this.handleSubmit);\n this.rootElement.addEventListener('submit', submitHandler, { passive: false });\n this.boundHandlers.set('submit', submitHandler);\n\n // Keyboard events\n const keydownHandler = this.createDelegatedHandler('keydown', this.handleKeydown);\n this.rootElement.addEventListener('keydown', keydownHandler, { passive: false });\n this.boundHandlers.set('keydown', keydownHandler);\n\n // Focus events\n const focusHandler = this.createDelegatedHandler('focus', this.handleFocus);\n this.rootElement.addEventListener('focus', focusHandler, { passive: true, capture: true });\n this.boundHandlers.set('focus', focusHandler);\n\n // Blur events\n const blurHandler = this.createDelegatedHandler('blur', this.handleBlur);\n this.rootElement.addEventListener('blur', blurHandler, { passive: true, capture: true });\n this.boundHandlers.set('blur', blurHandler);\n }\n\n /**\n * Create a delegated event handler\n * @private\n */\n createDelegatedHandler(eventType, handler) {\n return (event) => {\n const target = event.target;\n if (!target) return;\n\n // Find the closest element with data-action\n const actionElement = this.options.enableDelegation\n ? target.closest('[data-action]')\n : (target.hasAttribute?.('data-action') ? target : null);\n\n if (actionElement) {\n handler(actionElement, event);\n } else {\n // Also handle direct handler calls for elements without data-action\n handler(target, event);\n }\n };\n }\n\n /**\n * Handle click events\n * @private\n */\n handleClick(element, event) {\n const action = element.getAttribute?.('data-action');\n\n if (action) {\n this.handleDataAction(element, event, action);\n }\n\n // Emit generic DOM event\n this.eventBus.emitSync('dom:click', {\n element,\n event,\n action,\n data: this.parseDataAttributes(element)\n });\n }\n\n /**\n * Handle change events\n * @private\n */\n handleChange(element, event) {\n const action = element.getAttribute?.('data-action');\n\n if (action) {\n this.handleDataAction(element, event, action);\n }\n\n // Emit form change event\n this.eventBus.emitSync('dom:change', {\n element,\n event,\n value: element.value,\n action,\n data: this.parseDataAttributes(element)\n });\n }\n\n /**\n * Handle input events\n * @private\n */\n handleInput(element, event) {\n const action = element.getAttribute?.('data-action');\n\n if (action) {\n this.handleDataAction(element, event, action);\n }\n\n // Emit input event\n this.eventBus.emitSync('dom:input', {\n element,\n event,\n value: element.value,\n action,\n data: this.parseDataAttributes(element)\n });\n }\n\n /**\n * Handle submit events\n * @private\n */\n handleSubmit(element, event) {\n const action = element.getAttribute?.('data-action');\n\n if (action) {\n event.preventDefault(); // Prevent default form submission\n this.handleDataAction(element, event, action);\n }\n\n // Emit form submit event\n this.eventBus.emitSync('dom:submit', {\n element,\n event,\n action,\n formData: this.extractFormData(element),\n data: this.parseDataAttributes(element)\n });\n }\n\n /**\n * Handle keydown events\n * @private\n */\n handleKeydown(element, event) {\n const action = element.getAttribute?.('data-action');\n const keyAction = element.getAttribute?.(`data-key-${event.key.toLowerCase()}`);\n\n if (action && this.shouldTriggerKeyAction(event)) {\n this.handleDataAction(element, event, action);\n }\n\n if (keyAction) {\n this.handleDataAction(element, event, keyAction);\n }\n\n // Emit keyboard event\n this.eventBus.emitSync('dom:keydown', {\n element,\n event,\n key: event.key,\n code: event.code,\n action,\n keyAction,\n data: this.parseDataAttributes(element)\n });\n }\n\n /**\n * Handle focus events\n * @private\n */\n handleFocus(element, event) {\n this.activeElement = element;\n\n this.eventBus.emitSync('dom:focus', {\n element,\n event,\n data: this.parseDataAttributes(element)\n });\n }\n\n /**\n * Handle blur events\n * @private\n */\n handleBlur(element, event) {\n if (this.activeElement === element) {\n this.activeElement = null;\n }\n\n this.eventBus.emitSync('dom:blur', {\n element,\n event,\n data: this.parseDataAttributes(element)\n });\n }\n\n /**\n * Handle data-action attributes\n * @private\n */\n handleDataAction(element, event, action) {\n if (!action) return;\n\n // Parse additional data from element\n const data = this.parseDataAttributes(element);\n\n // Emit generic action event\n this.eventBus.emitSync('dom:action', {\n action,\n element,\n event,\n data\n });\n\n // Let the event bus handle the specific action\n this.eventBus.handleAction(action, element, event, data);\n\n if (this.options.debug) {\n console.log(`[DOMEventIntegration] Action triggered: ${action}`, {\n element,\n event: event.type,\n data\n });\n }\n }\n\n /**\n * Parse data attributes from an element\n * @private\n */\n parseDataAttributes(element) {\n if (!element?.attributes) return {};\n\n const data = {};\n\n Array.from(element.attributes).forEach(attr => {\n if (attr.name.startsWith('data-') && attr.name !== 'data-action') {\n // Convert kebab-case to camelCase\n const key = attr.name\n .slice(5) // Remove 'data-' prefix\n .replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());\n\n // Try to parse as JSON, fall back to string\n let value = attr.value;\n try {\n // Attempt to parse numbers, booleans, and JSON\n if (value === 'true') value = true;\n else if (value === 'false') value = false;\n else if (value === 'null') value = null;\n else if (value === 'undefined') value = undefined;\n else if (/^\\d+$/.test(value)) value = parseInt(value, 10);\n else if (/^\\d*\\.\\d+$/.test(value)) value = parseFloat(value);\n else if ((value.startsWith('{') && value.endsWith('}')) ||\n (value.startsWith('[') && value.endsWith(']'))) {\n value = JSON.parse(value);\n }\n } catch {\n // Keep as string if parsing fails\n }\n\n data[key] = value;\n }\n });\n\n return data;\n }\n\n /**\n * Extract form data from a form element\n * @private\n */\n extractFormData(formElement) {\n if (!formElement || formElement.tagName !== 'FORM') {\n return {};\n }\n\n const formData = new FormData(formElement);\n const data = {};\n\n for (const [key, value] of formData.entries()) {\n // Handle multiple values (checkboxes, multiple selects)\n if (data[key]) {\n if (Array.isArray(data[key])) {\n data[key].push(value);\n } else {\n data[key] = [data[key], value];\n }\n } else {\n data[key] = value;\n }\n }\n\n return data;\n }\n\n /**\n * Check if a key event should trigger an action\n * @private\n */\n shouldTriggerKeyAction(event) {\n // Common keys that should trigger actions\n const triggerKeys = ['Enter', 'Space', 'Escape'];\n return triggerKeys.includes(event.key);\n }\n\n /**\n * Debounce utility function\n * @private\n */\n debounce(func, wait) {\n let timeout;\n return function executedFunction(...args) {\n const later = () => {\n clearTimeout(timeout);\n func.apply(this, args);\n };\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n };\n }\n\n /**\n * Throttle utility function\n * @private\n */\n throttle(func, limit) {\n let inThrottle;\n return function executedFunction(...args) {\n if (!inThrottle) {\n func.apply(this, args);\n inThrottle = true;\n setTimeout(() => inThrottle = false, limit);\n }\n };\n }\n\n /**\n * Add custom event listener\n * @param {string} eventType - Event type\n * @param {Function} handler - Event handler\n * @param {Object} options - Event listener options\n */\n addCustomListener(eventType, handler, options = {}) {\n const wrappedHandler = this.createDelegatedHandler(eventType, handler);\n this.rootElement.addEventListener(eventType, wrappedHandler, options);\n this.boundHandlers.set(`custom:${eventType}`, wrappedHandler);\n }\n\n /**\n * Remove custom event listener\n * @param {string} eventType - Event type\n */\n removeCustomListener(eventType) {\n const handler = this.boundHandlers.get(`custom:${eventType}`);\n if (handler) {\n this.rootElement.removeEventListener(eventType, handler);\n this.boundHandlers.delete(`custom:${eventType}`);\n }\n }\n\n /**\n * Register action handlers in bulk\n * @param {Object} actions - Object mapping action names to handlers\n */\n registerActions(actions) {\n this.eventBus.registerActions(actions);\n }\n\n /**\n * Get the currently active (focused) element\n * @returns {HTMLElement|null}\n */\n getActiveElement() {\n return this.activeElement;\n }\n\n /**\n * Trigger an action programmatically\n * @param {string} action - Action name\n * @param {HTMLElement} element - Target element\n * @param {Object} data - Additional data\n */\n triggerAction(action, element, data = {}) {\n const syntheticEvent = new CustomEvent('synthetic', {\n bubbles: true,\n cancelable: true,\n detail: data\n });\n\n this.eventBus.handleAction(action, element, syntheticEvent, data);\n }\n\n /**\n * Clean up event listeners\n */\n destroy() {\n if (!this.isInitialized) return;\n\n this.boundHandlers.forEach((handler, eventType) => {\n this.rootElement.removeEventListener(\n eventType.replace('custom:', ''),\n handler\n );\n });\n\n this.boundHandlers.clear();\n this.activeElement = null;\n this.isInitialized = false;\n\n if (this.options.debug) {\n console.log('[DOMEventIntegration] Destroyed');\n }\n }\n}\n\n/**\n * Global DOM integration instance\n */\nexport const globalDOMIntegration = new DOMEventIntegration(globalEventBus, {\n debug: typeof process !== 'undefined' && process.env?.NODE_ENV === 'development'\n});\n\n/**\n * Initialize DOM integration with auto-start\n * @param {Object} options - Configuration options\n * @returns {DOMEventIntegration} DOM integration instance\n */\nexport function initializeDOMIntegration(options = {}) {\n const integration = new DOMEventIntegration(globalEventBus, options);\n\n // Auto-initialize when DOM is ready\n if (typeof window !== 'undefined') {\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', () => {\n integration.initialize();\n });\n } else {\n integration.initialize();\n }\n }\n\n return integration;\n}\n\n/**\n * Auto-initialize global DOM integration\n */\nif (typeof window !== 'undefined') {\n // Auto-start the global integration\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', () => {\n globalDOMIntegration.initialize();\n });\n } else {\n globalDOMIntegration.initialize();\n }\n}\n\nexport default globalDOMIntegration;", "/**\n * Coherent.js Event Bus System\n *\n * A comprehensive event-driven architecture for Coherent.js applications.\n * Provides centralized event management, DOM integration, and component utilities.\n */\n\n// Core event bus\nexport {\n EventBus,\n createEventBus,\n globalEventBus,\n emit,\n emitSync,\n on,\n once,\n off,\n registerAction,\n handleAction\n} from './event-bus.js';\n\n// DOM integration\nexport {\n DOMEventIntegration,\n globalDOMIntegration,\n initializeDOMIntegration\n} from './dom-integration.js';\n\n// Component integration\nexport {\n withEventBus,\n withEventState,\n createActionHandlers,\n createEventHandlers,\n createEventComponent,\n emitEvent\n} from './component-integration.js';\n\n// Re-export for convenience\nimport { globalEventBus } from './event-bus.js';\nimport { globalDOMIntegration } from './dom-integration.js';\n\n/**\n * Default export with all event system functionality\n */\nconst eventSystem = {\n // Core bus\n bus: globalEventBus,\n dom: globalDOMIntegration,\n\n // Quick access methods\n emit: globalEventBus.emit.bind(globalEventBus),\n emitSync: globalEventBus.emitSync.bind(globalEventBus),\n on: globalEventBus.on.bind(globalEventBus),\n once: globalEventBus.once.bind(globalEventBus),\n off: globalEventBus.off.bind(globalEventBus),\n\n // Action methods\n registerAction: globalEventBus.registerAction.bind(globalEventBus),\n registerActions: globalEventBus.registerActions.bind(globalEventBus),\n handleAction: globalEventBus.handleAction.bind(globalEventBus),\n\n // Statistics and debugging\n getStats: globalEventBus.getStats.bind(globalEventBus),\n resetStats: globalEventBus.resetStats.bind(globalEventBus),\n\n // Lifecycle\n destroy() {\n globalEventBus.destroy();\n globalDOMIntegration.destroy();\n }\n};\n\nexport default eventSystem;", "/**\n * Coherent.js - Object-Based Rendering Framework\n * A pure JavaScript framework for server-side rendering using natural object syntax\n *\n * @version 2.0.0\n * @author Coherent Framework Team\n * @license MIT\n */\n\n// Performance monitoring\nimport { performanceMonitor } from './performance/monitor.js';\n\n// Component system imports\nimport {\n withState,\n withStateUtils,\n createStateManager,\n createComponent,\n defineComponent,\n registerComponent,\n getComponent,\n getRegisteredComponents,\n lazy,\n isLazy,\n evaluateLazy\n} from './components/component-system.js';\n\n// Component lifecycle imports\nimport {\n ComponentLifecycle,\n LIFECYCLE_PHASES,\n withLifecycle,\n createLifecycleHooks,\n useHooks,\n componentUtils as lifecycleUtils\n} from './components/lifecycle.js';\n\n// Object factory imports\nimport {\n createElement,\n createTextNode,\n h\n} from './core/object-factory.js';\n\n// Component cache imports\nimport {\n ComponentCache,\n createComponentCache,\n memoize\n} from './performance/component-cache.js';\n\n// Error boundary imports\nimport {\n createErrorBoundary,\n createErrorFallback,\n withErrorBoundary,\n createAsyncErrorBoundary,\n GlobalErrorHandler,\n createGlobalErrorHandler\n} from './components/error-boundary.js';\n\n// CSS Scoping System (similar to Angular View Encapsulation)\nconst scopeCounter = { value: 0 };\n\nfunction generateScopeId() {\n return `coh-${scopeCounter.value++}`;\n}\n\nfunction scopeCSS(css, scopeId) {\n if (!css || typeof css !== 'string') return css;\n\n // Add scope attribute to all selectors\n return css\n .replace(/([^{}]*)\\s*{/g, (match, selector) => {\n // Handle multiple selectors separated by commas\n const selectors = selector.split(',').map(s => {\n const trimmed = s.trim();\n if (!trimmed) return s;\n\n // Handle pseudo-selectors and complex selectors\n if (trimmed.includes(':')) {\n return trimmed.replace(/([^:]+)(:.*)?/, `$1[${scopeId}]$2`);\n }\n\n // Simple selector scoping\n return `${trimmed}[${scopeId}]`;\n });\n\n return `${selectors.join(', ')} {`;\n });\n}\n\nfunction applyScopeToElement(element, scopeId) {\n if (typeof element === 'string' || typeof element === 'number' || !element) {\n return element;\n }\n\n if (Array.isArray(element)) {\n return element.map(item => applyScopeToElement(item, scopeId));\n }\n\n if (typeof element === 'object') {\n const scoped = {};\n\n for (const [tagName, props] of Object.entries(element)) {\n if (typeof props === 'object' && props !== null) {\n const scopedProps = { ...props };\n\n // Add scope attribute to the element\n scopedProps[scopeId] = '';\n\n // Recursively scope children\n if (scopedProps.children) {\n scopedProps.children = applyScopeToElement(scopedProps.children, scopeId);\n }\n\n scoped[tagName] = scopedProps;\n } else {\n // For simple text content elements, keep them as is\n // Don't add scope attributes to text-only elements\n scoped[tagName] = props;\n }\n }\n\n return scoped;\n }\n\n return element;\n}\n\n// Core HTML utilities\nfunction escapeHtml(text) {\n if (typeof text !== 'string') return text;\n return text\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\n/**\n * Mark content as safe/trusted to skip HTML escaping\n * USE WITH EXTREME CAUTION - only for developer-controlled content\n * NEVER use with user input!\n *\n * @param {string} content - Trusted content (e.g., inline scripts/styles)\n * @returns {Object} Marked safe content\n */\nexport function dangerouslySetInnerContent(content) {\n return {\n __html: content,\n __trusted: true\n };\n}\n\n/**\n * Check if content is marked as safe\n */\nfunction isTrustedContent(value) {\n return value && typeof value === 'object' && value.__trusted === true && typeof value.__html === 'string';\n}\n\nfunction isVoidElement(tagName) {\n const voidElements = new Set([\n 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',\n 'link', 'meta', 'param', 'source', 'track', 'wbr'\n ]);\n return voidElements.has(tagName.toLowerCase());\n}\n\nfunction formatAttributes(attrs) {\n if (!attrs || typeof attrs !== 'object') return '';\n\n return Object.entries(attrs)\n .filter(([, value]) => value !== null && value !== undefined && value !== false)\n .map(([key, value]) => {\n // Execute functions to get the actual value\n if (typeof value === 'function') {\n value = value();\n }\n\n // Convert className to class\n const attrName = key === 'className' ? 'class' : key;\n if (value === true) return attrName;\n return `${attrName}=\"${escapeHtml(String(value))}\"`;\n })\n .join(' ');\n}\n\n// Internal raw rendering (no encapsulation) - used by scoped renderer\nfunction renderRaw(obj) {\n if (obj === null || obj === undefined) return '';\n if (typeof obj === 'string' || typeof obj === 'number') return escapeHtml(String(obj));\n if (Array.isArray(obj)) return obj.map(renderRaw).join('');\n\n // Handle functions (like context providers)\n if (typeof obj === 'function') {\n const result = obj(renderRaw);\n return renderRaw(result);\n }\n\n if (typeof obj !== 'object') return escapeHtml(String(obj));\n\n // Handle text content\n if (obj.text !== undefined) {\n return escapeHtml(String(obj.text));\n }\n\n // Handle HTML elements\n for (const [tagName, props] of Object.entries(obj)) {\n if (typeof props === 'object' && props !== null) {\n const { children, text, ...attributes } = props;\n const attrsStr = formatAttributes(attributes);\n const openTag = attrsStr ? `<${tagName} ${attrsStr}>` : `<${tagName}>`;\n\n if (isVoidElement(tagName)) {\n return openTag.replace('>', ' />');\n }\n\n let content = '';\n if (text !== undefined) {\n // Check if content is explicitly marked as trusted\n if (isTrustedContent(text)) {\n content = text.__html;\n } else {\n content = escapeHtml(String(text));\n }\n } else if (children) {\n content = renderRaw(children);\n }\n\n return `${openTag}${content}</${tagName}>`;\n } else if (typeof props === 'string') {\n // Simple text content - always escape unless explicitly marked as trusted\n const content = isTrustedContent(props) ? props.__html : escapeHtml(props);\n return isVoidElement(tagName) ? `<${tagName} />` : `<${tagName}>${content}</${tagName}>`;\n }\n }\n\n return '';\n}\n\n// Main rendering function\nexport function render(obj, options = {}) {\n const { scoped = false } = options;\n\n // Scoped mode - use CSS encapsulation\n if (scoped) {\n return renderScopedComponent(obj);\n }\n\n // Default: unscoped rendering\n return renderRaw(obj);\n}\n\n// Internal: Scoped rendering with CSS encapsulation\nfunction renderScopedComponent(component) {\n const scopeId = generateScopeId();\n\n // Handle style elements specially\n function processScopedElement(element) {\n if (!element || typeof element !== 'object') {\n return element;\n }\n\n if (Array.isArray(element)) {\n return element.map(processScopedElement);\n }\n\n const result = {};\n\n for (const [tagName, props] of Object.entries(element)) {\n if (tagName === 'style' && typeof props === 'object' && props.text) {\n // Scope CSS within style tags\n result[tagName] = {\n ...props,\n text: scopeCSS(props.text, scopeId)\n };\n } else if (typeof props === 'object' && props !== null) {\n // Recursively process children\n const scopedProps = { ...props };\n if (scopedProps.children) {\n scopedProps.children = processScopedElement(scopedProps.children);\n }\n result[tagName] = scopedProps;\n } else {\n result[tagName] = props;\n }\n }\n\n return result;\n }\n\n // First process styles, then apply scope attributes\n const processedComponent = processScopedElement(component);\n const scopedComponent = applyScopeToElement(processedComponent, scopeId);\n\n return renderRaw(scopedComponent);\n}\n\n// Component system - Re-export from component-system for unified API\nexport {\n withState,\n withStateUtils,\n createStateManager,\n createComponent,\n defineComponent,\n registerComponent,\n getComponent,\n getRegisteredComponents,\n lazy,\n isLazy,\n evaluateLazy\n} from './components/component-system.js';\n\n// Component lifecycle exports\nexport {\n ComponentLifecycle,\n LIFECYCLE_PHASES,\n withLifecycle,\n createLifecycleHooks,\n useHooks,\n componentUtils as lifecycleUtils\n} from './components/lifecycle.js';\n\n// Object factory exports\nexport {\n createElement,\n createTextNode,\n h\n} from './core/object-factory.js';\n\n// Component cache exports\nexport {\n ComponentCache,\n createComponentCache,\n memoize\n} from './performance/component-cache.js';\n\n// Error boundaries\nexport {\n createErrorBoundary,\n createErrorFallback,\n withErrorBoundary,\n createAsyncErrorBoundary,\n GlobalErrorHandler,\n createGlobalErrorHandler\n} from './components/error-boundary.js';\n\n// Simple memoization\nconst memoCache = new Map();\n\nexport function memo(component, keyGenerator) {\n return function MemoizedComponent(props = {}) {\n const key = keyGenerator ? keyGenerator(props) : JSON.stringify(props);\n\n if (memoCache.has(key)) {\n return memoCache.get(key);\n }\n\n const result = component(props);\n memoCache.set(key, result);\n\n // Simple cache cleanup - keep only last 100 items\n if (memoCache.size > 100) {\n const firstKey = memoCache.keys().next().value;\n memoCache.delete(firstKey);\n }\n\n return result;\n };\n}\n\n// Utility functions\nexport function validateComponent(obj) {\n if (!obj || typeof obj !== 'object') {\n throw new Error('Component must be an object');\n }\n return true;\n}\n\nexport function isCoherentObject(obj) {\n return obj && typeof obj === 'object' && !Array.isArray(obj);\n}\n\nexport function deepClone(obj) {\n if (obj === null || typeof obj !== 'object') return obj;\n if (obj instanceof Date) return new Date(obj);\n if (Array.isArray(obj)) return obj.map(deepClone);\n\n const cloned = {};\n for (const [key, value] of Object.entries(obj)) {\n cloned[key] = deepClone(value);\n }\n return cloned;\n}\n\n// Version info\nexport const VERSION = '2.0.0';\n\n// Performance monitoring export\nexport { performanceMonitor };\n\n// Shadow DOM exports\nexport { shadowDOM };\n\n// Import Shadow DOM functionality\nimport * as shadowDOM from './shadow-dom.js';\n\n// Event system imports and exports\nimport eventSystemDefault, {\n EventBus,\n createEventBus,\n globalEventBus,\n emit,\n emitSync,\n on,\n once,\n off,\n registerAction,\n handleAction,\n DOMEventIntegration,\n globalDOMIntegration,\n initializeDOMIntegration,\n withEventBus,\n withEventState,\n createActionHandlers,\n createEventHandlers,\n createEventComponent\n} from './events/index.js';\n\nexport {\n eventSystemDefault as eventSystem,\n EventBus,\n createEventBus,\n globalEventBus,\n emit,\n emitSync,\n on,\n once,\n off,\n registerAction,\n handleAction,\n DOMEventIntegration,\n globalDOMIntegration,\n initializeDOMIntegration,\n withEventBus,\n withEventState,\n createActionHandlers,\n createEventHandlers,\n createEventComponent\n};\n\n// Note: Forms have been moved to @coherent.js/forms package\n\n// Default export\nconst coherent = {\n // Core rendering\n render,\n\n // Shadow DOM (client-side only)\n shadowDOM,\n\n // Component system\n createComponent,\n defineComponent,\n registerComponent,\n getComponent,\n getRegisteredComponents,\n lazy,\n isLazy,\n evaluateLazy,\n\n // Component lifecycle\n ComponentLifecycle,\n LIFECYCLE_PHASES,\n withLifecycle,\n createLifecycleHooks,\n useHooks,\n lifecycleUtils,\n\n // Object factory\n createElement,\n createTextNode,\n h,\n\n // Component cache\n ComponentCache,\n createComponentCache,\n memoize,\n\n // State management\n withState,\n withStateUtils,\n createStateManager,\n memo,\n\n // Error boundaries\n createErrorBoundary,\n createErrorFallback,\n withErrorBoundary,\n createAsyncErrorBoundary,\n GlobalErrorHandler,\n createGlobalErrorHandler,\n\n // Event system\n eventSystem: eventSystemDefault,\n emit,\n emitSync,\n on,\n once,\n off,\n registerAction,\n handleAction,\n withEventBus,\n withEventState,\n\n // Utilities\n validateComponent,\n isCoherentObject,\n deepClone,\n escapeHtml,\n performanceMonitor,\n VERSION\n};\n\nexport default coherent;\n", "// src/express/index.js\nimport { render } from '../../core/src/index.js';\n\nexport function expressEngine() {\n return (filePath, options, callback) => {\n try {\n // options contains the Coherent object structure\n const html = render(options);\n callback(null, html);\n } catch (_error) {\n callback(_error);\n }\n };\n}\n\n// Helper for Express apps\nexport function setupCoherent(app) {\n app.engine('coherent', expressEngine());\n app.set('view engine', 'coherent');\n}\n"],
|
|
5
|
-
"mappings": ";AAyBO,SAAS,yBAAyB,UAAU,CAAC,GAAG;AACrD,QAAM,OAAO;AAAA,IACX,SAAS;AAAA,IACT,SAAS;AAAA,MACP,QAAQ,CAAC;AAAA,IACX;AAAA,IACA,UAAU;AAAA,MACR,SAAS;AAAA,MACT,MAAM;AAAA,MACN,UAAU;AAAA,IACZ;AAAA,IACA,WAAW;AAAA,MACT,SAAS;AAAA,MACT,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,OAAO;AAAA,QACL,SAAS;AAAA,QACT,SAAS;AAAA,QACT,eAAe;AAAA,MACjB;AAAA,MACA,UAAU;AAAA,IACZ;AAAA,IACA,QAAQ;AAAA,MACN,SAAS;AAAA,MACT,OAAO,CAAC;AAAA,IACV;AAAA,IACA,WAAW;AAAA,MACT,SAAS;AAAA,MACT,OAAO,CAAC,QAAQ;AAAA,MAChB,UAAU;AAAA,IACZ;AAAA,IACA,WAAW;AAAA,MACT,SAAS;AAAA,MACT,MAAM;AAAA,MACN,YAAY;AAAA,MACZ,SAAS;AAAA,QACP,SAAS;AAAA,QACT,YAAY;AAAA,MACd;AAAA,IACF;AAAA,IACA,GAAG;AAAA,EACL;AAGA,OAAK,UAAU,QAAQ;AAAA,IACrB,SAAS;AAAA,IACT,SAAS;AAAA,IACT,eAAe;AAAA,IACf,GAAI,QAAQ,WAAW,SAAS,CAAC;AAAA,EACnC;AAGA,QAAM,UAAU;AAAA,IACd,SAAS;AAAA,MACP,YAAY,EAAE,MAAM,aAAa,MAAM,MAAM,QAAQ,CAAC,EAAE;AAAA,MACxD,gBAAgB,EAAE,MAAM,WAAW,MAAM,WAAW,OAAO,EAAE;AAAA,MAC7D,YAAY,EAAE,MAAM,WAAW,MAA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GAAG,MAAM;AAC/B,YAAI,YAAY,UAAU;AACxB,sBAAY,WAAW,qBAAqB,YAAY,QAAQ;AAAA,QAClE;AACA,eAAO,OAAO,IAAI;AAAA,MACpB,OAAO;AACL,eAAO,OAAO,IAAI;AAAA,MACpB;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAGA,QAAM,qBAAqB,qBAAqB,SAAS;AACzD,QAAM,kBAAkB,oBAAoB,oBAAoB,OAAO;AAEvE,SAAO,UAAU,eAAe;AAClC;;;ACxSO,SAAS,gBAAgB;AAC5B,SAAO,CAAC,UAAU,SAAS,aAAa;AACpC,QAAI;AAEA,YAAM,OAAO,OAAO,OAAO;AAC3B,eAAS,MAAM,IAAI;AAAA,IACvB,SAAS,QAAQ;AACb,eAAS,MAAM;AAAA,IACnB;AAAA,EACJ;AACJ;AAGO,SAAS,cAAc,KAAK;AAC/B,MAAI,OAAO,YAAY,cAAc,CAAC;AACtC,MAAI,IAAI,eAAe,UAAU;AACrC;",
|
|
6
|
-
"names": [
|
|
3
|
+
"sources": ["../../core/src/index.js", "../src/index.js"],
|
|
4
|
+
"sourcesContent": ["/**\n * Coherent.js - Object-Based Rendering Framework\n * A pure JavaScript framework for server-side rendering using natural object syntax\n *\n * @version 2.0.0\n * @author Coherent Framework Team\n * @license MIT\n */\n\n// Performance monitoring\nimport { performanceMonitor } from './performance/monitor.js';\n\n// Component system imports\nimport {\n withState,\n withStateUtils,\n createStateManager,\n createComponent,\n defineComponent,\n registerComponent,\n getComponent,\n getRegisteredComponents,\n lazy,\n isLazy,\n evaluateLazy\n} from './components/component-system.js';\n\n// Component lifecycle imports\nimport {\n ComponentLifecycle,\n LIFECYCLE_PHASES,\n withLifecycle,\n createLifecycleHooks,\n useHooks,\n componentUtils as lifecycleUtils\n} from './components/lifecycle.js';\n\n// Object factory imports\nimport {\n createElement,\n createTextNode,\n h\n} from './core/object-factory.js';\n\n// Component cache imports\nimport {\n ComponentCache,\n createComponentCache,\n memoize\n} from './performance/component-cache.js';\n\n// Error boundary imports\nimport {\n createErrorBoundary,\n createErrorFallback,\n withErrorBoundary,\n createAsyncErrorBoundary,\n GlobalErrorHandler,\n createGlobalErrorHandler\n} from './components/error-boundary.js';\n\n// CSS Scoping System (similar to Angular View Encapsulation)\nconst scopeCounter = { value: 0 };\n\nfunction generateScopeId() {\n return `coh-${scopeCounter.value++}`;\n}\n\nfunction scopeCSS(css, scopeId) {\n if (!css || typeof css !== 'string') return css;\n\n // Add scope attribute to all selectors\n return css\n .replace(/([^{}]*)\\s*{/g, (match, selector) => {\n // Handle multiple selectors separated by commas\n const selectors = selector.split(',').map(s => {\n const trimmed = s.trim();\n if (!trimmed) return s;\n\n // Handle pseudo-selectors and complex selectors\n if (trimmed.includes(':')) {\n return trimmed.replace(/([^:]+)(:.*)?/, `$1[${scopeId}]$2`);\n }\n\n // Simple selector scoping\n return `${trimmed}[${scopeId}]`;\n });\n\n return `${selectors.join(', ')} {`;\n });\n}\n\nfunction applyScopeToElement(element, scopeId) {\n if (typeof element === 'string' || typeof element === 'number' || !element) {\n return element;\n }\n\n if (Array.isArray(element)) {\n return element.map(item => applyScopeToElement(item, scopeId));\n }\n\n if (typeof element === 'object') {\n const scoped = {};\n\n for (const [tagName, props] of Object.entries(element)) {\n if (typeof props === 'object' && props !== null) {\n const scopedProps = { ...props };\n\n // Add scope attribute to the element\n scopedProps[scopeId] = '';\n\n // Recursively scope children\n if (scopedProps.children) {\n scopedProps.children = applyScopeToElement(scopedProps.children, scopeId);\n }\n\n scoped[tagName] = scopedProps;\n } else {\n // For simple text content elements, keep them as is\n // Don't add scope attributes to text-only elements\n scoped[tagName] = props;\n }\n }\n\n return scoped;\n }\n\n return element;\n}\n\n// Core HTML utilities\nfunction escapeHtml(text) {\n if (typeof text !== 'string') return text;\n return text\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\n/**\n * Mark content as safe/trusted to skip HTML escaping\n * USE WITH EXTREME CAUTION - only for developer-controlled content\n * NEVER use with user input!\n *\n * @param {string} content - Trusted content (e.g., inline scripts/styles)\n * @returns {Object} Marked safe content\n */\nexport function dangerouslySetInnerContent(content) {\n return {\n __html: content,\n __trusted: true\n };\n}\n\n/**\n * Check if content is marked as safe\n */\nfunction isTrustedContent(value) {\n return value && typeof value === 'object' && value.__trusted === true && typeof value.__html === 'string';\n}\n\nfunction isVoidElement(tagName) {\n const voidElements = new Set([\n 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',\n 'link', 'meta', 'param', 'source', 'track', 'wbr'\n ]);\n return voidElements.has(tagName.toLowerCase());\n}\n\nfunction formatAttributes(attrs) {\n if (!attrs || typeof attrs !== 'object') return '';\n\n return Object.entries(attrs)\n .filter(([, value]) => value !== null && value !== undefined && value !== false)\n .map(([key, value]) => {\n // Execute functions to get the actual value\n if (typeof value === 'function') {\n value = value();\n }\n\n // Convert className to class\n const attrName = key === 'className' ? 'class' : key;\n if (value === true) return attrName;\n return `${attrName}=\"${escapeHtml(String(value))}\"`;\n })\n .join(' ');\n}\n\n// Internal raw rendering (no encapsulation) - used by scoped renderer\nfunction renderRaw(obj) {\n if (obj === null || obj === undefined) return '';\n if (typeof obj === 'string' || typeof obj === 'number') return escapeHtml(String(obj));\n if (Array.isArray(obj)) return obj.map(renderRaw).join('');\n\n // Handle functions (like context providers)\n if (typeof obj === 'function') {\n const result = obj(renderRaw);\n return renderRaw(result);\n }\n\n if (typeof obj !== 'object') return escapeHtml(String(obj));\n\n // Handle text content\n if (obj.text !== undefined) {\n return escapeHtml(String(obj.text));\n }\n\n // Handle HTML elements\n for (const [tagName, props] of Object.entries(obj)) {\n if (typeof props === 'object' && props !== null) {\n const { children, text, ...attributes } = props;\n const attrsStr = formatAttributes(attributes);\n const openTag = attrsStr ? `<${tagName} ${attrsStr}>` : `<${tagName}>`;\n\n if (isVoidElement(tagName)) {\n return openTag.replace('>', ' />');\n }\n\n let content = '';\n if (text !== undefined) {\n // Check if content is explicitly marked as trusted\n if (isTrustedContent(text)) {\n content = text.__html;\n } else {\n content = escapeHtml(String(text));\n }\n } else if (children) {\n content = renderRaw(children);\n }\n\n return `${openTag}${content}</${tagName}>`;\n } else if (typeof props === 'string') {\n // Simple text content - always escape unless explicitly marked as trusted\n const content = isTrustedContent(props) ? props.__html : escapeHtml(props);\n return isVoidElement(tagName) ? `<${tagName} />` : `<${tagName}>${content}</${tagName}>`;\n }\n }\n\n return '';\n}\n\n// Main rendering function\nexport function render(obj, options = {}) {\n const { scoped = false } = options;\n\n // Scoped mode - use CSS encapsulation\n if (scoped) {\n return renderScopedComponent(obj);\n }\n\n // Default: unscoped rendering\n return renderRaw(obj);\n}\n\n// Internal: Scoped rendering with CSS encapsulation\nfunction renderScopedComponent(component) {\n const scopeId = generateScopeId();\n\n // Handle style elements specially\n function processScopedElement(element) {\n if (!element || typeof element !== 'object') {\n return element;\n }\n\n if (Array.isArray(element)) {\n return element.map(processScopedElement);\n }\n\n const result = {};\n\n for (const [tagName, props] of Object.entries(element)) {\n if (tagName === 'style' && typeof props === 'object' && props.text) {\n // Scope CSS within style tags\n result[tagName] = {\n ...props,\n text: scopeCSS(props.text, scopeId)\n };\n } else if (typeof props === 'object' && props !== null) {\n // Recursively process children\n const scopedProps = { ...props };\n if (scopedProps.children) {\n scopedProps.children = processScopedElement(scopedProps.children);\n }\n result[tagName] = scopedProps;\n } else {\n result[tagName] = props;\n }\n }\n\n return result;\n }\n\n // First process styles, then apply scope attributes\n const processedComponent = processScopedElement(component);\n const scopedComponent = applyScopeToElement(processedComponent, scopeId);\n\n return renderRaw(scopedComponent);\n}\n\n// Component system - Re-export from component-system for unified API\nexport {\n withState,\n withStateUtils,\n createStateManager,\n createComponent,\n defineComponent,\n registerComponent,\n getComponent,\n getRegisteredComponents,\n lazy,\n isLazy,\n evaluateLazy\n} from './components/component-system.js';\n\n// Component lifecycle exports\nexport {\n ComponentLifecycle,\n LIFECYCLE_PHASES,\n withLifecycle,\n createLifecycleHooks,\n useHooks,\n componentUtils as lifecycleUtils\n} from './components/lifecycle.js';\n\n// Object factory exports\nexport {\n createElement,\n createTextNode,\n h\n} from './core/object-factory.js';\n\n// Component cache exports\nexport {\n ComponentCache,\n createComponentCache,\n memoize\n} from './performance/component-cache.js';\n\n// Error boundaries\nexport {\n createErrorBoundary,\n createErrorFallback,\n withErrorBoundary,\n createAsyncErrorBoundary,\n GlobalErrorHandler,\n createGlobalErrorHandler\n} from './components/error-boundary.js';\n\n// Simple memoization\nconst memoCache = new Map();\n\nexport function memo(component, keyGenerator) {\n return function MemoizedComponent(props = {}) {\n const key = keyGenerator ? keyGenerator(props) : JSON.stringify(props);\n\n if (memoCache.has(key)) {\n return memoCache.get(key);\n }\n\n const result = component(props);\n memoCache.set(key, result);\n\n // Simple cache cleanup - keep only last 100 items\n if (memoCache.size > 100) {\n const firstKey = memoCache.keys().next().value;\n memoCache.delete(firstKey);\n }\n\n return result;\n };\n}\n\n// Utility functions\nexport function validateComponent(obj) {\n if (!obj || typeof obj !== 'object') {\n throw new Error('Component must be an object');\n }\n return true;\n}\n\nexport function isCoherentObject(obj) {\n return obj && typeof obj === 'object' && !Array.isArray(obj);\n}\n\nexport function deepClone(obj) {\n if (obj === null || typeof obj !== 'object') return obj;\n if (obj instanceof Date) return new Date(obj);\n if (Array.isArray(obj)) return obj.map(deepClone);\n\n const cloned = {};\n for (const [key, value] of Object.entries(obj)) {\n cloned[key] = deepClone(value);\n }\n return cloned;\n}\n\n// Version info\nexport const VERSION = '2.0.0';\n\n// Performance monitoring export\nexport { performanceMonitor };\n\n// Shadow DOM exports\nexport { shadowDOM };\n\n// Import Shadow DOM functionality\nimport * as shadowDOM from './shadow-dom.js';\n\n// Event system imports and exports\nimport eventSystemDefault, {\n EventBus,\n createEventBus,\n globalEventBus,\n emit,\n emitSync,\n on,\n once,\n off,\n registerAction,\n handleAction,\n DOMEventIntegration,\n globalDOMIntegration,\n initializeDOMIntegration,\n withEventBus,\n withEventState,\n createActionHandlers,\n createEventHandlers,\n createEventComponent\n} from './events/index.js';\n\nexport {\n eventSystemDefault as eventSystem,\n EventBus,\n createEventBus,\n globalEventBus,\n emit,\n emitSync,\n on,\n once,\n off,\n registerAction,\n handleAction,\n DOMEventIntegration,\n globalDOMIntegration,\n initializeDOMIntegration,\n withEventBus,\n withEventState,\n createActionHandlers,\n createEventHandlers,\n createEventComponent\n};\n\n// Note: Forms have been moved to @coherent.js/forms package\n\n// Default export\nconst coherent = {\n // Core rendering\n render,\n\n // Shadow DOM (client-side only)\n shadowDOM,\n\n // Component system\n createComponent,\n defineComponent,\n registerComponent,\n getComponent,\n getRegisteredComponents,\n lazy,\n isLazy,\n evaluateLazy,\n\n // Component lifecycle\n ComponentLifecycle,\n LIFECYCLE_PHASES,\n withLifecycle,\n createLifecycleHooks,\n useHooks,\n lifecycleUtils,\n\n // Object factory\n createElement,\n createTextNode,\n h,\n\n // Component cache\n ComponentCache,\n createComponentCache,\n memoize,\n\n // State management\n withState,\n withStateUtils,\n createStateManager,\n memo,\n\n // Error boundaries\n createErrorBoundary,\n createErrorFallback,\n withErrorBoundary,\n createAsyncErrorBoundary,\n GlobalErrorHandler,\n createGlobalErrorHandler,\n\n // Event system\n eventSystem: eventSystemDefault,\n emit,\n emitSync,\n on,\n once,\n off,\n registerAction,\n handleAction,\n withEventBus,\n withEventState,\n\n // Utilities\n validateComponent,\n isCoherentObject,\n deepClone,\n escapeHtml,\n performanceMonitor,\n VERSION\n};\n\nexport default coherent;\n", "// src/express/index.js\nimport { render } from '../../core/src/index.js';\n\nexport function expressEngine() {\n return (filePath, options, callback) => {\n try {\n // options contains the Coherent object structure\n const html = render(options);\n callback(null, html);\n } catch (_error) {\n callback(_error);\n }\n };\n}\n\n// Helper for Express apps\nexport function setupCoherent(app) {\n app.engine('coherent', expressEngine());\n app.set('view engine', 'coherent');\n}\n"],
|
|
5
|
+
"mappings": ";AA8DA,IAAM,eAAe,EAAE,OAAO,EAAE;AAEhC,SAAS,kBAAkB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