@coherent.js/core 1.0.0-beta.6 → 1.0.0-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/dist/coherent.d.ts +150 -10
  2. package/dist/coherent.d.ts.map +1 -1
  3. package/dist/coherent.js +166 -33
  4. package/dist/coherent.js.map +1 -1
  5. package/dist/components/component-system.js +109 -109
  6. package/dist/components/lifecycle.d.ts +212 -0
  7. package/dist/components/lifecycle.d.ts.map +1 -0
  8. package/dist/components/lifecycle.js +525 -0
  9. package/dist/components/lifecycle.js.map +1 -0
  10. package/dist/core/html-utils.js +5 -5
  11. package/dist/core/object-factory.js +21 -21
  12. package/dist/core/object-utils.js +2 -2
  13. package/dist/dev/dev-tools.d.ts +1 -1
  14. package/dist/dev/dev-tools.js +28 -28
  15. package/dist/forms/validation.d.ts +271 -0
  16. package/dist/forms/validation.d.ts.map +1 -0
  17. package/dist/forms/validation.js +573 -0
  18. package/dist/forms/validation.js.map +1 -0
  19. package/dist/index.cjs +157 -4
  20. package/dist/index.cjs.map +4 -4
  21. package/dist/index.js +153 -4
  22. package/dist/index.js.map +4 -4
  23. package/dist/performance/bundle-optimizer.js +11 -11
  24. package/dist/performance/cache-manager.js +6 -6
  25. package/dist/performance/component-cache.d.ts +120 -0
  26. package/dist/performance/component-cache.d.ts.map +1 -0
  27. package/dist/performance/component-cache.js +364 -0
  28. package/dist/performance/component-cache.js.map +1 -0
  29. package/dist/performance/monitor.js +10 -10
  30. package/dist/performance/monitor.js.map +1 -1
  31. package/dist/rendering/base-renderer.js +13 -13
  32. package/dist/rendering/css-manager.d.ts +73 -0
  33. package/dist/rendering/css-manager.d.ts.map +1 -0
  34. package/dist/rendering/css-manager.js +176 -0
  35. package/dist/rendering/css-manager.js.map +1 -0
  36. package/dist/rendering/dom-renderer.d.ts +23 -0
  37. package/dist/rendering/dom-renderer.d.ts.map +1 -1
  38. package/dist/rendering/dom-renderer.js +77 -9
  39. package/dist/rendering/dom-renderer.js.map +1 -1
  40. package/dist/rendering/html-renderer.d.ts +15 -0
  41. package/dist/rendering/html-renderer.d.ts.map +1 -1
  42. package/dist/rendering/html-renderer.js +85 -4
  43. package/dist/rendering/html-renderer.js.map +1 -1
  44. package/dist/rendering/streaming-renderer.js +12 -12
  45. package/dist/rendering/vdom-diff.d.ts +47 -0
  46. package/dist/rendering/vdom-diff.d.ts.map +1 -0
  47. package/dist/rendering/vdom-diff.js +416 -0
  48. package/dist/rendering/vdom-diff.js.map +1 -0
  49. package/dist/routing/router.d.ts +241 -0
  50. package/dist/routing/router.d.ts.map +1 -0
  51. package/dist/routing/router.js +648 -0
  52. package/dist/routing/router.js.map +1 -0
  53. package/dist/state/reactive-state.d.ts +166 -0
  54. package/dist/state/reactive-state.d.ts.map +1 -0
  55. package/dist/state/reactive-state.js +546 -0
  56. package/dist/state/reactive-state.js.map +1 -0
  57. package/dist/utils/dependency-utils.js +2 -2
  58. package/dist/utils/error-handler.d.ts +148 -0
  59. package/dist/utils/error-handler.d.ts.map +1 -0
  60. package/dist/utils/error-handler.js +468 -0
  61. package/dist/utils/error-handler.js.map +1 -0
  62. package/dist/utils/normalization.js +1 -1
  63. package/dist/utils/validation.js +1 -1
  64. package/package.json +5 -1
  65. package/dist/database/adapters/mongodb.d.ts +0 -15
  66. package/dist/database/adapters/mongodb.d.ts.map +0 -1
  67. package/dist/database/adapters/mongodb.js +0 -216
  68. package/dist/database/adapters/mongodb.js.map +0 -1
  69. package/dist/database/adapters/mysql.d.ts +0 -12
  70. package/dist/database/adapters/mysql.d.ts.map +0 -1
  71. package/dist/database/adapters/mysql.js +0 -171
  72. package/dist/database/adapters/mysql.js.map +0 -1
  73. package/dist/database/adapters/postgresql.d.ts +0 -12
  74. package/dist/database/adapters/postgresql.d.ts.map +0 -1
  75. package/dist/database/adapters/postgresql.js +0 -177
  76. package/dist/database/adapters/postgresql.js.map +0 -1
  77. package/dist/database/adapters/sqlite.d.ts +0 -15
  78. package/dist/database/adapters/sqlite.d.ts.map +0 -1
  79. package/dist/database/adapters/sqlite.js +0 -241
  80. package/dist/database/adapters/sqlite.js.map +0 -1
  81. package/dist/database/connection-manager.d.ts +0 -135
  82. package/dist/database/connection-manager.d.ts.map +0 -1
  83. package/dist/database/connection-manager.js +0 -362
  84. package/dist/database/connection-manager.js.map +0 -1
  85. package/dist/database/index.d.ts +0 -38
  86. package/dist/database/index.d.ts.map +0 -1
  87. package/dist/database/index.js +0 -60
  88. package/dist/database/index.js.map +0 -1
  89. package/dist/database/middleware.d.ts +0 -122
  90. package/dist/database/middleware.d.ts.map +0 -1
  91. package/dist/database/middleware.js +0 -390
  92. package/dist/database/middleware.js.map +0 -1
  93. package/dist/database/migration.d.ts +0 -62
  94. package/dist/database/migration.d.ts.map +0 -1
  95. package/dist/database/migration.js +0 -423
  96. package/dist/database/migration.js.map +0 -1
  97. package/dist/database/model.d.ts +0 -8
  98. package/dist/database/model.d.ts.map +0 -1
  99. package/dist/database/model.js +0 -167
  100. package/dist/database/model.js.map +0 -1
  101. package/dist/database/query-builder.d.ts +0 -111
  102. package/dist/database/query-builder.d.ts.map +0 -1
  103. package/dist/database/query-builder.js +0 -187
  104. package/dist/database/query-builder.js.map +0 -1
  105. package/dist/database/utils.d.ts +0 -196
  106. package/dist/database/utils.d.ts.map +0 -1
  107. package/dist/database/utils.js +0 -372
  108. package/dist/database/utils.js.map +0 -1
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/index.js", "../src/performance/monitor.js", "../src/core/object-utils.js", "../src/rendering/base-renderer.js", "../src/core/html-nesting-rules.js", "../src/core/html-utils.js", "../src/performance/cache-manager.js", "../src/utils/error-handler.js", "../src/rendering/html-renderer.js", "../src/components/component-system.js", "../src/components/lifecycle.js", "../src/types/constants.js", "../src/core/object-factory.js", "../src/performance/component-cache.js", "../src/components/error-boundary.js", "../src/utils/render-utils.js", "../src/utils/dependency-utils.js", "../src/shadow-dom.js", "../src/events/event-bus.js", "../src/events/dom-integration.js", "../src/events/component-integration.js", "../src/events/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 1.0.0-beta.6\n * @author Coherent Framework Team\n * @license MIT\n */\n\nimport { readFileSync } from 'node:fs';\n\n// Performance monitoring\nimport { performanceMonitor } from './performance/monitor.js';\n\n// Unified HTML renderer\nimport { render as renderWithHtmlRenderer } from './rendering/html-renderer.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, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#x27;');\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// Main rendering function\nexport function render(obj, options = {}) {\n const scoped = options.scoped ?? options.encapsulate ?? false;\n\n const { scoped: _scoped, encapsulate: _encapsulate, ...rendererOptions } = options;\n\n const component = scoped ? renderScopedComponent(obj) : obj;\n return renderWithHtmlRenderer(component, rendererOptions);\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 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};\n\nexport {\n renderWithMonitoring,\n renderWithTemplate,\n renderComponentFactory,\n isCoherentComponent,\n createErrorResponse\n} from './utils/render-utils.js';\n\nexport {\n isPeerDependencyAvailable,\n importPeerDependency,\n createLazyIntegration,\n checkPeerDependencies\n} from './utils/dependency-utils.js';\n\nexport {\n hasChildren,\n normalizeChildren\n} from './core/object-utils.js';\n\n// HTML nesting validation exports\nexport {\n validateNesting,\n FORBIDDEN_CHILDREN,\n HTMLNestingError\n} from './core/html-nesting-rules.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 if (memoCache.has(key)) {\n return memoCache.get(key);\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\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\nconst _corePackageJson = JSON.parse(\n readFileSync(new URL('../package.json', import.meta.url), 'utf-8')\n);\nexport const VERSION = _corePackageJson.version;\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", "/**\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 debounceMs: 5000,\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 debounceMs period)\n if (!lastTriggered || now - lastTriggered > opts.alerts.debounceMs) {\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 * Validate component without throwing - returns { valid: boolean, reason?: string, path?: string }\n * Use this in render contexts where graceful degradation is preferred\n */\nexport function validateComponentGraceful(component, path = 'root') {\n if (component === null || component === undefined) {\n return { valid: false, reason: 'Component is null or undefined', path };\n }\n\n // Allow strings, numbers, booleans as text content\n if (['string', 'number', 'boolean'].includes(typeof component)) {\n return { valid: true };\n }\n\n // Allow functions (will be evaluated during render)\n if (typeof component === 'function') {\n return { valid: true };\n }\n\n // Handle arrays\n if (Array.isArray(component)) {\n for (let i = 0; i < component.length; i++) {\n const result = validateComponentGraceful(component[i], `${path}[${i}]`);\n if (!result.valid) return result;\n }\n return { valid: true };\n }\n\n // Handle objects\n if (typeof component === 'object') {\n const keys = Object.keys(component);\n if (keys.length === 0) {\n return { valid: false, reason: 'Empty object', path };\n }\n return { valid: true };\n }\n\n return { valid: false, reason: `Invalid type: ${typeof component}`, path };\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 * Base Renderer Class\n * Provides common functionality shared across all Coherent.js renderers\n * Reduces code duplication and ensures consistent behavior\n */\n\nimport {\n validateComponent,\n isCoherentObject,\n extractProps,\n hasChildren,\n normalizeChildren,\n} from '../core/object-utils.js';\n\nimport { performanceMonitor } from '../performance/monitor.js';\n\n/**\n * Unified configuration for all Coherent.js renderers\n * Includes options for HTML, Streaming, and DOM renderers\n */\nexport const DEFAULT_RENDERER_CONFIG = {\n // Core rendering options\n maxDepth: 100,\n enableValidation: true,\n enableMonitoring: false,\n validateInput: true,\n\n // HTML Renderer specific options\n enableCache: true,\n minify: false,\n cacheSize: 1000,\n cacheTTL: 300000, // 5 minutes\n\n // Streaming Renderer specific options\n chunkSize: 1024, // Size of each chunk in bytes\n bufferSize: 4096, // Internal buffer size\n enableMetrics: false, // Track streaming metrics\n yieldThreshold: 100, // Yield control after N elements\n encoding: 'utf8', // Output encoding\n\n // DOM Renderer specific options\n enableHydration: true, // Enable hydration support\n namespace: null, // SVG namespace support\n\n // Performance options\n enablePerformanceTracking: false,\n performanceThreshold: 10, // ms threshold for slow renders\n\n // Development options\n enableDevWarnings: typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'development',\n enableDebugLogging: false,\n\n // Error handling options\n errorFallback: '', // Fallback content on errors\n throwOnError: true, // Whether to throw or return fallback\n};\n\n/**\n * Base renderer class with common functionality\n */\nexport class BaseRenderer {\n constructor(options = {}) {\n this.config = this.validateAndMergeConfig(options);\n this.metrics = {\n startTime: null,\n endTime: null,\n elementsProcessed: 0\n };\n }\n\n /**\n * Validate and merge configuration options\n */\n validateAndMergeConfig(options) {\n const config = { ...DEFAULT_RENDERER_CONFIG, ...options };\n \n // Validate critical options\n if (typeof config.maxDepth !== 'number') {\n throw new Error('maxDepth must be a number');\n }\n if (config.maxDepth <= 0) {\n throw new Error('maxDepth must be a positive number');\n }\n \n if (typeof config.chunkSize !== 'number') {\n throw new Error('chunkSize must be a number');\n }\n if (config.chunkSize <= 0) {\n throw new Error('chunkSize must be a positive number');\n }\n \n if (typeof config.yieldThreshold !== 'number') {\n throw new Error('yieldThreshold must be a number');\n }\n if (config.yieldThreshold <= 0) {\n throw new Error('yieldThreshold must be a positive number');\n }\n \n // Warn about potentially problematic configurations\n if (config.enableDevWarnings) {\n if (config.maxDepth > 1000) {\n console.warn('Coherent.js: maxDepth > 1000 may cause performance issues');\n }\n \n if (config.chunkSize > 16384) {\n console.warn('Coherent.js: Large chunkSize may increase memory usage');\n }\n }\n \n return config;\n }\n\n /**\n * Get configuration for specific renderer type\n */\n getRendererConfig(rendererType) {\n const baseConfig = { ...this.config };\n \n switch (rendererType) {\n case 'html':\n return {\n ...baseConfig,\n // HTML-specific defaults\n enableCache: baseConfig.enableCache !== false,\n enableMonitoring: baseConfig.enableMonitoring !== false\n };\n \n case 'streaming':\n return {\n ...baseConfig,\n // Streaming-specific defaults\n enableMetrics: baseConfig.enableMetrics ?? false,\n maxDepth: baseConfig.maxDepth ?? 1000 // Higher default for streaming\n };\n \n case 'dom':\n return {\n ...baseConfig,\n // DOM-specific defaults\n enableHydration: baseConfig.enableHydration !== false\n };\n \n default:\n return baseConfig;\n }\n }\n\n /**\n * Validate component structure\n */\n validateComponent(component) {\n if (this.config.validateInput !== false) {\n return validateComponent(component);\n }\n return true;\n }\n\n /**\n * Check if component is valid for rendering\n */\n isValidComponent(component) {\n if (component === null || component === undefined) return true;\n if (typeof component === 'string' || typeof component === 'number') return true;\n if (typeof component === 'function') return true;\n if (Array.isArray(component)) return component.every(child => this.isValidComponent(child));\n if (isCoherentObject(component)) return true;\n return false;\n }\n\n /**\n * Validate rendering depth to prevent stack overflow\n */\n validateDepth(depth) {\n if (depth > this.config.maxDepth) {\n throw new Error(`Maximum render depth (${this.config.maxDepth}) exceeded`);\n }\n }\n\n /**\n * Handle different component types with consistent logic\n */\n processComponentType(component) {\n // Null/undefined\n if (component === null || component === undefined) {\n return { type: 'empty', value: '' };\n }\n\n // String\n if (typeof component === 'string') {\n return { type: 'text', value: component };\n }\n\n // Number/Boolean\n if (typeof component === 'number' || typeof component === 'boolean') {\n return { type: 'text', value: String(component) };\n }\n\n // Function\n if (typeof component === 'function') {\n return { type: 'function', value: component };\n }\n\n // Array\n if (Array.isArray(component)) {\n return { type: 'array', value: component };\n }\n\n // Object (Coherent element)\n if (isCoherentObject(component)) {\n return { type: 'element', value: component };\n }\n\n // Unknown type\n return { type: 'unknown', value: component };\n }\n\n /**\n * Execute function components with _error handling\n */\n executeFunctionComponent(func, depth = 0) {\n try {\n // Check if this is a context provider by checking function arity or a marker\n const isContextProvider = func.length > 0 || func.isContextProvider;\n \n let result;\n if (isContextProvider) {\n // Call with render function for context providers\n result = func((children) => {\n return this.renderComponent(children, this.config, depth + 1);\n });\n } else {\n // Regular function component\n result = func();\n }\n \n // Handle case where function returns another function\n if (typeof result === 'function') {\n return this.executeFunctionComponent(result, depth);\n }\n \n return result;\n } catch (_error) {\n if (this.config.enableMonitoring) {\n performanceMonitor.recordError('functionComponent', _error);\n }\n \n // In development, provide detailed _error info\n if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'development') {\n console.warn('Coherent.js Function Component Error:', _error.message);\n }\n \n return null;\n }\n }\n\n /**\n * Process element children consistently\n */\n processChildren(children, options, depth) {\n if (!hasChildren({ children })) {\n return [];\n }\n\n const normalizedChildren = normalizeChildren(children);\n return normalizedChildren.map(child => \n this.renderComponent(child, options, depth + 1)\n );\n }\n\n /**\n * Extract and process element attributes\n */\n extractElementAttributes(props) {\n if (!props || typeof props !== 'object') return {};\n\n const attributes = { ...props };\n delete attributes.children;\n delete attributes.text;\n return attributes;\n }\n\n /**\n * Record performance metrics\n */\n recordPerformance(operation, startTime, fromCache = false, metadata = {}) {\n if (this.config.enableMonitoring) {\n performanceMonitor.recordRender(\n operation,\n this.getCurrentTime() - startTime,\n fromCache,\n metadata\n );\n }\n }\n\n /**\n * Record _error for monitoring\n */\n recordError(operation, _error, metadata = {}) {\n if (this.config.enableMonitoring) {\n performanceMonitor.recordError(operation, _error, metadata);\n }\n }\n\n /**\n * Get current timestamp with fallback\n */\n getCurrentTime() {\n if (typeof performance !== 'undefined' && performance.now) {\n return performance.now();\n }\n return Date.now();\n }\n\n /**\n * Start performance timing\n */\n startTiming() {\n this.metrics.startTime = this.getCurrentTime();\n }\n\n /**\n * End performance timing\n */\n endTiming() {\n this.metrics.endTime = this.getCurrentTime();\n }\n\n /**\n * Get performance metrics\n */\n getMetrics() {\n const duration = this.metrics.endTime ? \n this.metrics.endTime - this.metrics.startTime :\n this.getCurrentTime() - this.metrics.startTime;\n\n return {\n ...this.metrics,\n duration,\n elementsPerSecond: this.metrics.elementsProcessed / (duration / 1000)\n };\n }\n\n /**\n * Reset metrics for new render\n */\n resetMetrics() {\n this.metrics = {\n startTime: null,\n endTime: null,\n elementsProcessed: 0\n };\n }\n\n /**\n * Abstract method - must be implemented by subclasses\n */\n renderComponent() {\n throw new Error('renderComponent must be implemented by subclass');\n }\n\n /**\n * Abstract method - must be implemented by subclasses\n */\n render() {\n throw new Error('render must be implemented by subclass');\n }\n}\n\n/**\n * Utility functions for renderer implementations\n */\nexport const RendererUtils = {\n /**\n * Check if element is static (no functions or circular references)\n */\n isStaticElement(element, visited = new WeakSet()) {\n if (!element || typeof element !== 'object') {\n return typeof element === 'string' || typeof element === 'number';\n }\n\n // Handle circular references - treat as non-static (will be caught during render)\n if (visited.has(element)) {\n return false;\n }\n visited.add(element);\n\n // Check if element has any dynamic content\n for (const [_key, value] of Object.entries(element)) {\n if (typeof value === 'function') return false;\n\n // Recursively check arrays (including children)\n if (Array.isArray(value)) {\n const allStatic = value.every(child => RendererUtils.isStaticElement(child, visited));\n if (!allStatic) return false;\n }\n // Recursively check nested objects\n else if (typeof value === 'object' && value !== null) {\n if (!RendererUtils.isStaticElement(value, visited)) return false;\n }\n }\n\n return true;\n },\n\n /**\n * Check if object has functions (for caching decisions)\n */\n hasFunctions(obj, visited = new WeakSet()) {\n if (visited.has(obj)) return false;\n visited.add(obj);\n\n for (const value of Object.values(obj)) {\n if (typeof value === 'function') return true;\n if (typeof value === 'object' && value !== null && RendererUtils.hasFunctions(value, visited)) {\n return true;\n }\n }\n return false;\n },\n\n /**\n * Get element complexity score\n */\n getElementComplexity(element) {\n if (!element || typeof element !== 'object') return 1;\n\n let complexity = Object.keys(element).length;\n\n if (element.children && Array.isArray(element.children)) {\n complexity += element.children.reduce(\n (sum, child) => sum + RendererUtils.getElementComplexity(child),\n 0\n );\n }\n\n return complexity;\n },\n\n /**\n * Generate cache key for element\n */\n generateCacheKey(tagName, element) {\n try {\n // Create a stable cache key for the element\n const keyData = {\n tag: tagName,\n props: extractProps(element),\n hasChildren: hasChildren(element),\n childrenType: Array.isArray(element.children) ? 'array' : typeof element.children\n };\n\n return `element:${JSON.stringify(keyData)}`;\n } catch (_error) {\n // Log _error in development mode\n if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'development') {\n console.warn('Failed to generate cache key:', _error);\n }\n // Return null to indicate uncacheable element\n return null;\n }\n },\n\n /**\n * Check if element is cacheable\n */\n isCacheable(element, options) {\n // Don't cache if caching is disabled\n if (!options.enableCache) return false;\n\n // Don't cache elements with functions (dynamic content)\n if (RendererUtils.hasFunctions(element)) return false;\n\n // Don't cache very large elements (memory consideration)\n if (RendererUtils.getElementComplexity(element) > 1000) return false;\n\n // Don't cache if we can't generate a stable cache key\n const cacheKey = RendererUtils.generateCacheKey(element.tagName || 'unknown', element);\n if (!cacheKey) return false;\n\n return true;\n }\n};\n\nexport default BaseRenderer;\n", "/**\n * HTML Nesting Validation Rules\n * Prevents invalid HTML structures that browsers will auto-correct,\n * which causes hydration mismatches between server and client.\n */\n\n/**\n * Map of parent tags to their forbidden child tags.\n * Based on HTML spec content model rules.\n * See: https://html.spec.whatwg.org/multipage/dom.html#content-models\n */\nexport const FORBIDDEN_CHILDREN = {\n // Phrasing content only - cannot contain flow content\n p: new Set([\n 'address', 'article', 'aside', 'blockquote', 'div', 'dl',\n 'fieldset', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',\n 'header', 'hr', 'main', 'nav', 'ol', 'p', 'pre', 'section',\n 'table', 'ul', 'figure', 'figcaption'\n ]),\n // Interactive content restrictions\n a: new Set(['a']), // Links cannot nest\n button: new Set(['button', 'a', 'input', 'select', 'textarea', 'label']),\n label: new Set(['label']),\n // Table structure restrictions\n thead: new Set(['thead', 'tbody', 'tfoot', 'caption', 'colgroup', 'tr']),\n tbody: new Set(['thead', 'tbody', 'tfoot', 'caption', 'colgroup']),\n tfoot: new Set(['thead', 'tbody', 'tfoot', 'caption', 'colgroup']),\n tr: new Set(['tr', 'thead', 'tbody', 'tfoot', 'table']),\n td: new Set(['td', 'th', 'tr', 'thead', 'tbody', 'tfoot', 'table']),\n th: new Set(['td', 'th', 'tr', 'thead', 'tbody', 'tfoot', 'table']),\n // Other common restrictions\n select: new Set(['select', 'input', 'textarea']),\n option: new Set(['option', 'optgroup']),\n};\n\n/**\n * Validate that a child tag is allowed inside a parent tag.\n *\n * @param {string} parentTag - The parent element tag name\n * @param {string} childTag - The child element tag name\n * @param {string} path - The render path for error reporting\n * @param {Object} options - Validation options\n * @param {boolean} options.warn - Whether to emit console warnings (default: true in dev)\n * @param {boolean} options.throwOnError - Whether to throw instead of warn (default: false)\n * @returns {boolean} True if nesting is valid, false otherwise\n */\nexport function validateNesting(parentTag, childTag, path = '', options = {}) {\n if (!parentTag || !childTag) {\n return true; // Can't validate without both tags\n }\n\n const parent = parentTag.toLowerCase();\n const child = childTag.toLowerCase();\n\n const forbidden = FORBIDDEN_CHILDREN[parent];\n if (!forbidden || !forbidden.has(child)) {\n return true; // Nesting is valid\n }\n\n // Invalid nesting detected\n const pathSuffix = path ? ` at ${path}` : '';\n const message = `Invalid HTML nesting: <${child}> cannot be a child of <${parent}>${pathSuffix}. Browsers will auto-correct this, causing potential hydration mismatches.`;\n\n if (options.throwOnError) {\n throw new HTMLNestingError(message, { parent, child, path });\n }\n\n // Only warn in development mode by default\n const shouldWarn = options.warn !== false &&\n (typeof process === 'undefined' ||\n !process.env ||\n process.env.NODE_ENV !== 'production');\n\n if (shouldWarn) {\n console.warn(`[Coherent.js] ${message}`);\n }\n\n return false;\n}\n\n/**\n * Custom error class for HTML nesting violations\n */\nexport class HTMLNestingError extends Error {\n constructor(message, context = {}) {\n super(message);\n this.name = 'HTMLNestingError';\n this.parent = context.parent;\n this.child = context.child;\n this.path = context.path;\n }\n}\n\n/**\n * Check if a tag is a void element (self-closing, no children allowed)\n * Useful for validation - void elements can't have invalid children\n */\nexport const VOID_ELEMENTS = new Set([\n 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',\n 'link', 'meta', 'param', 'source', 'track', 'wbr'\n]);\n\nexport function isVoidElement(tagName) {\n return VOID_ELEMENTS.has(tagName?.toLowerCase());\n}\n", "/**\n * HTML-specific utility functions\n */\n\nexport function escapeHtml(text) {\n if (typeof text !== 'string') return text;\n\n return text\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n}\n\nexport function unescapeHtml(text) {\n if (typeof text !== 'string') return text;\n\n return text\n .replace(/&quot;/g, '\"')\n .replace(/&#39;/g, \"'\")\n .replace(/&gt;/g, '>')\n .replace(/&lt;/g, '<')\n .replace(/&amp;/g, '&');\n}\n\nexport function isVoidElement(tagName) {\n // Ensure tagName is a string before processing\n if (typeof tagName !== 'string') {\n return false;\n }\n\n const voidElements = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n ]);\n return voidElements.has(tagName.toLowerCase());\n}\n\nexport function formatAttributes(props) {\n let formatted = '';\n for (const key in props) {\n if (props.hasOwnProperty(key)) {\n let value = props[key];\n\n // Convert className to class for HTML output\n const attributeName = key === 'className' ? 'class' : key;\n\n // Handle function values - for event handlers, use data-action attributes\n if (typeof value === 'function') {\n // Check if this is an event handler (starts with 'on')\n if (attributeName.startsWith('on')) {\n // For event handlers, create a unique action identifier\n const actionId = `__coherent_action_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n const DEBUG = (typeof process !== 'undefined' && process && process.env && (process.env.COHERENT_DEBUG === '1' || process.env.NODE_ENV === 'development'))\n || (typeof window !== 'undefined' && window && window.COHERENT_DEBUG === true);\n \n // Store the function in a global registry that will be available during hydration\n // Check if we're in Node.js or browser environment\n if (typeof global !== 'undefined') {\n // Server-side, store in global for hydration\n if (!global.__coherentActionRegistry) {\n global.__coherentActionRegistry = {};\n if (DEBUG) console.log('Initialized global action registry');\n }\n global.__coherentActionRegistry[actionId] = value;\n if (DEBUG) console.log(`Added action ${actionId} to global registry, total: ${Object.keys(global.__coherentActionRegistry).length}`);\n if (DEBUG) console.log(`Global registry keys: ${Object.keys(global.__coherentActionRegistry).join(', ')}`);\n \n // Log the global object to see if it's being reset\n if (DEBUG) {\n if (typeof global.__coherentActionRegistryLog === 'undefined') {\n global.__coherentActionRegistryLog = [];\n }\n global.__coherentActionRegistryLog.push({\n action: 'add',\n actionId: actionId,\n timestamp: Date.now(),\n registrySize: Object.keys(global.__coherentActionRegistry).length\n });\n }\n } else if (typeof window !== 'undefined') {\n // Browser-side, store in window\n if (!window.__coherentActionRegistry) {\n window.__coherentActionRegistry = {};\n if (DEBUG) console.log('Initialized window action registry');\n }\n window.__coherentActionRegistry[actionId] = value;\n if (DEBUG) console.log(`Added action ${actionId} to window registry, total: ${Object.keys(window.__coherentActionRegistry).length}`);\n if (DEBUG) console.log(`Window registry keys: ${Object.keys(window.__coherentActionRegistry).join(', ')}`);\n }\n \n // Use data-action and data-event attributes instead of inline JS\n const eventType = attributeName.substring(2); // Remove 'on' prefix\n formatted += ` data-action=\"${actionId}\" data-event=\"${eventType}\"`;\n continue; // Skip normal processing\n } else {\n // For other function attributes, call them to get the value\n try {\n value = value();\n } catch (_error) {\n console.warn(`Error executing function for attribute '${key}':`, {\n _error: _error.message,\n stack: _error.stack,\n attributeKey: key,\n });\n // Consider different fallback strategies based on attribute type\n value = '';\n }\n }\n }\n\n if (value === true) {\n formatted += ` ${attributeName}`;\n } else if (value !== false && value !== null && value !== undefined) {\n formatted += ` ${attributeName}=\"${escapeHtml(String(value))}\"`;\n }\n }\n }\n return formatted.trim();\n}\n\nexport function minifyHtml(html, options = {}) {\n if (!options.minify) return html;\n\n return (\n html\n // Remove comments\n .replace(/<!--[\\s\\S]*?-->/g, '')\n // Remove extra whitespace\n .replace(/\\s+/g, ' ')\n // Remove whitespace around tags\n .replace(/>\\s+</g, '><')\n // Remove leading/trailing whitespace\n .trim()\n );\n}\n\n/**\n * HTML Void Elements - elements that cannot have children\n * These elements are self-closing and don't need closing tags\n */\nexport const voidElements = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n]);\n", "/**\n * Advanced caching system with memory management and smart invalidation for Coherent.js\n * \n * @module @coherent/performance/cache-manager\n * @license MIT\n */\n\n/**\n * @typedef {Object} CacheEntry\n * @property {any} value - The cached value\n * @property {number} timestamp - When the entry was created\n * @property {number} lastAccess - Last access time\n * @property {number} size - Approximate size in bytes\n * @property {Object} metadata - Additional metadata\n * @property {number} accessCount - Number of times accessed\n */\n\n/**\n * @typedef {Object} CacheStats\n * @property {number} hits - Number of cache hits\n * @property {number} misses - Number of cache misses\n * @property {number} size - Current cache size in bytes\n * @property {number} entries - Number of cache entries\n * @property {Record<string, number>} hitRate - Hit rate by cache type\n */\n\n/**\n * @typedef {Object} CacheOptions\n * @property {number} [maxCacheSize=1000] - Maximum number of entries per cache type\n * @property {number} [maxMemoryMB=100] - Maximum memory usage in MB\n * @property {number} [ttlMs=300000] - Default time-to-live in milliseconds (5 minutes)\n * @property {boolean} [enableStatistics=true] - Whether to collect usage statistics\n */\n\n/**\n * Creates a new CacheManager instance\n * @param {CacheOptions} [options] - Configuration options\n * @returns {Object} Cache manager instance\n */\nexport function createCacheManager(options = {}) {\n const {\n maxCacheSize = 1000,\n maxMemoryMB = 100,\n ttlMs = 1000 * 60 * 5, // 5 minutes\n enableStatistics = true\n } = options;\n\n // Internal state\n const caches = {\n static: new Map(), // Never-changing components\n component: new Map(), // Component results with deps\n template: new Map(), // Template strings\n data: new Map() // General purpose data\n };\n\n let memoryUsage = 0;\n const stats = {\n hits: 0,\n misses: 0,\n hitRate: {\n static: 0,\n component: 0,\n template: 0,\n data: 0\n },\n accessCount: {\n static: 0,\n component: 0,\n template: 0,\n data: 0\n }\n };\n\n // Cleanup interval (doesn't keep Node.js process alive)\n let cleanupInterval;\n if (typeof setInterval === 'function') {\n cleanupInterval = setInterval(() => cleanup(), 30000);\n if (cleanupInterval.unref) {\n cleanupInterval.unref();\n }\n }\n\n /**\n * Generate a cache key from component and props\n * @param {any} component - Component or component name\n * @param {Object} [props={}] - Component props\n * @param {Object} [context={}] - Additional context\n * @returns {string} Cache key\n */\n function generateCacheKey(component, props = {}, context = {}) {\n const componentStr = typeof component === 'function'\n ? component.name || component.toString()\n : JSON.stringify(component);\n\n const propsStr = JSON.stringify(props, Object.keys(props).sort());\n const contextStr = JSON.stringify(context);\n const hash = simpleHash(componentStr + propsStr + contextStr);\n \n return `${extractComponentName(component)}_${hash}`;\n }\n\n /**\n * Get a value from the cache\n * @param {string} key - Cache key\n * @param {string} [type='component'] - Cache type\n * @returns {any|null} Cached value or null if not found\n */\n function get(key, type = 'component') {\n const cache = caches[type] || caches.component;\n const entry = cache.get(key);\n\n if (!entry) {\n stats.misses++;\n if (enableStatistics) stats.accessCount[type]++;\n return null;\n }\n\n // Check TTL\n if (Date.now() - entry.timestamp > ttlMs) {\n cache.delete(key);\n updateMemoryUsage(-entry.size);\n stats.misses++;\n if (enableStatistics) stats.accessCount[type]++;\n return null;\n }\n\n // Update access time and stats\n entry.lastAccess = Date.now();\n entry.accessCount++;\n stats.hits++;\n if (enableStatistics) {\n stats.accessCount[type]++;\n stats.hitRate[type] = (stats.hits / (stats.hits + stats.misses)) * 100;\n }\n\n return entry.value;\n }\n\n /**\n * Store a value in the cache\n * @param {string} key - Cache key\n * @param {any} value - Value to cache\n * @param {string} [type='component'] - Cache type\n * @param {Object} [metadata={}] - Additional metadata\n */\n function set(key, value, type = 'component', metadata = {}) {\n const cache = caches[type] || caches.component;\n const size = calculateSize(value);\n\n // Check memory limits\n if (memoryUsage + size > maxMemoryMB * 1024 * 1024) {\n optimize(type, size);\n }\n\n const entry = {\n value,\n timestamp: Date.now(),\n lastAccess: Date.now(),\n size,\n metadata,\n accessCount: 0\n };\n\n // Remove existing entry if it exists\n const existing = cache.get(key);\n if (existing) {\n updateMemoryUsage(-existing.size);\n }\n\n cache.set(key, entry);\n updateMemoryUsage(size);\n\n // Enforce cache size limits\n if (cache.size > maxCacheSize) {\n optimize(type);\n }\n }\n\n /**\n * Remove an entry from the cache\n * @param {string} key - Cache key\n * @param {string} [type] - Cache type (optional, checks all caches if not provided)\n * @returns {boolean} True if an entry was removed\n */\n function remove(key, type) {\n if (type) {\n const cache = caches[type];\n if (!cache) return false;\n \n const entry = cache.get(key);\n if (entry) {\n updateMemoryUsage(-entry.size);\n return cache.delete(key);\n }\n return false;\n }\n\n // Check all caches if no type specified\n for (const [, cache] of Object.entries(caches)) {\n const entry = cache.get(key);\n if (entry) {\n updateMemoryUsage(-entry.size);\n return cache.delete(key);\n }\n }\n return false;\n }\n\n /**\n * Clear all caches or a specific cache type\n * @param {string} [type] - Cache type to clear (optional, clears all if not provided)\n */\n function clear(type) {\n if (type) {\n const cache = caches[type];\n if (cache) {\n cache.clear();\n }\n } else {\n Object.values(caches).forEach(cache => cache.clear());\n }\n memoryUsage = 0;\n }\n\n /**\n * Get cache statistics\n * @returns {CacheStats} Cache statistics\n */\n function getStats() {\n const entries = Object.values(caches).reduce((sum, cache) => sum + cache.size, 0);\n \n return {\n hits: stats.hits,\n misses: stats.misses,\n size: memoryUsage,\n entries,\n hitRate: stats.hitRate,\n accessCount: stats.accessCount\n };\n }\n\n /**\n * Clean up expired entries\n */\n function cleanup() {\n const now = Date.now();\n let freed = 0;\n\n for (const [, cache] of Object.entries(caches)) {\n for (const [key, entry] of cache.entries()) {\n if (now - entry.timestamp > ttlMs) {\n cache.delete(key);\n updateMemoryUsage(-entry.size);\n freed++;\n }\n }\n }\n\n return { freed };\n }\n\n // Internal helper functions\n function calculateSize(value) {\n if (value === null || value === undefined) return 0;\n if (typeof value === 'string') return value.length * 2; // UTF-16\n if (typeof value === 'number') return 8; // 64-bit float\n if (typeof value === 'boolean') return 4;\n if (Array.isArray(value)) {\n return value.reduce((sum, item) => sum + calculateSize(item), 0);\n }\n if (typeof value === 'object') {\n return Object.values(value).reduce((sum, val) => sum + calculateSize(val), 0);\n }\n return 0;\n }\n\n function updateMemoryUsage(delta) {\n memoryUsage = Math.max(0, memoryUsage + delta);\n }\n\n function optimize(type, requiredSpace = 0) {\n const cache = caches[type] || caches.component;\n const entries = Array.from(cache.entries())\n .sort(([, a], [, b]) => a.lastAccess - b.lastAccess);\n\n let freed = 0;\n for (const [key, entry] of entries) {\n if (freed >= requiredSpace) break;\n \n cache.delete(key);\n updateMemoryUsage(-entry.size);\n freed += entry.size;\n }\n\n return { freed };\n }\n\n function simpleHash(str) {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i);\n hash = ((hash << 5) - hash) + char;\n hash = hash & hash; // Convert to 32-bit integer\n }\n return Math.abs(hash).toString(36);\n }\n\n function extractComponentName(component) {\n if (typeof component === 'function') {\n return component.name || 'AnonymousComponent';\n }\n if (component && typeof component === 'object') {\n const keys = Object.keys(component);\n return keys.length > 0 ? keys[0] : 'ObjectComponent';\n }\n return 'UnknownComponent';\n }\n\n // Clean up on destroy\n function destroy() {\n if (cleanupInterval) {\n clearInterval(cleanupInterval);\n }\n clear();\n }\n\n // Public API\n return {\n get,\n set,\n remove,\n clear,\n getStats,\n cleanup,\n destroy,\n generateCacheKey,\n get memoryUsage() {\n return memoryUsage;\n },\n get maxMemory() {\n return maxMemoryMB * 1024 * 1024;\n }\n };\n}\n\n// Create a default instance for convenience\nexport const cacheManager = createCacheManager();\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.code = options.code || `COHERENT_${String(this.type).toUpperCase()}`;\n this.docsUrl = options.docsUrl || `/docs/core/errors#${this.code}`;\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 code: this.code,\n docsUrl: this.docsUrl,\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 // Add renderPath for debugging if available in context\n if (context && context.path) {\n this.renderPath = context.path;\n }\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 const isDev = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'development';\n const envForceSilent = typeof process !== 'undefined' && process.env && process.env.COHERENT_SILENT === '1';\n const envForceDebug = typeof process !== 'undefined' && process.env && process.env.COHERENT_DEBUG === '1';\n const defaultEnableLogging = envForceSilent ? false : (envForceDebug ? true : isDev);\n\n this.options = {\n enableStackTrace: options.enableStackTrace !== false,\n enableSuggestions: options.enableSuggestions !== false,\n enableLogging: options.enableLogging ?? defaultEnableLogging,\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 if (_error.code) {\n console.log('\uD83C\uDFF7\uFE0F Code:', _error.code);\n }\n\n if (_error.docsUrl) {\n console.log('\uD83D\uDCD6 Docs:', _error.docsUrl);\n }\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 if (_error.context && typeof _error.context === 'object' && _error.context.path) {\n console.log('\uD83D\uDCCD Path:', _error.context.path);\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", "/**\n * High-performance HTML renderer with caching, monitoring, and streaming support\n * Converts object-based components to HTML strings with advanced optimizations\n */\n\nimport { BaseRenderer, RendererUtils } from './base-renderer.js';\nimport {\n hasChildren,\n normalizeChildren,\n} from '../core/object-utils.js';\n\nimport { validateNesting } from '../core/html-nesting-rules.js';\n\nimport {\n escapeHtml,\n isVoidElement,\n formatAttributes,\n minifyHtml\n} from '../core/html-utils.js';\n\nimport { performanceMonitor } from '../performance/monitor.js';\nimport { createCacheManager } from '../performance/cache-manager.js';\nimport { cssUtils, defaultCSSManager } from './css-manager.js';\nimport { CoherentError, RenderingError, globalErrorHandler } from '../utils/error-handler.js';\n\n// Create a global cache instance for the renderer\nconst rendererCache = createCacheManager({\n maxSize: 1000,\n ttlMs: 300000 // 5 minutes\n});\n\nfunction formatRenderPath(path) {\n if (!path || path.length === 0) return 'root';\n\n let rendered = 'root';\n for (const segment of path) {\n if (typeof segment !== 'string' || segment.length === 0) continue;\n if (segment.startsWith('[')) {\n rendered += segment;\n } else {\n rendered += `.${segment}`;\n }\n }\n return rendered;\n}\n\n/**\n * HTML Renderer Class extending BaseRenderer\n *\n * @class HTMLRenderer\n * @extends BaseRenderer\n * @description High-performance HTML renderer with caching, monitoring, and streaming support.\n * Converts object-based components to HTML strings with advanced optimizations.\n *\n * @param {Object} [options={}] - Renderer configuration options\n * @param {boolean} [options.enableCache=true] - Enable component caching\n * @param {boolean} [options.enableMonitoring=true] - Enable performance monitoring\n * @param {boolean} [options.minify=false] - Enable HTML minification\n * @param {boolean} [options.streaming=false] - Enable streaming mode\n * @param {number} [options.maxDepth=100] - Maximum rendering depth\n * @param {number} [options.cacheSize=1000] - Cache size limit\n * @param {number} [options.cacheTTL=300000] - Cache TTL in milliseconds\n *\n * @example\n * const renderer = new HTMLRenderer({\n * enableCache: true,\n * enableMonitoring: true,\n * minify: true\n * });\n *\n * const html = renderer.render({ div: { text: 'Hello World' } });\n */\nclass HTMLRenderer extends BaseRenderer {\n constructor(options = {}) {\n super({\n enableCache: options.enableCache !== false,\n enableMonitoring: options.enableMonitoring !== false,\n minify: options.minify || false,\n streaming: options.streaming || false,\n maxDepth: options.maxDepth || 100,\n ...options\n });\n\n // Initialize cache if enabled\n if (this.config.enableCache && !this.cache) {\n this.cache = rendererCache;\n }\n }\n\n /**\n * Main render method - converts components to HTML string\n *\n * @param {Object|Array|string|Function} component - Component to render\n * @param {Object} [options={}] - Rendering options\n * @param {Object} [options.context] - Rendering context\n * @param {boolean} [options.enableCache] - Override cache setting\n * @param {number} [options.depth=0] - Current rendering depth\n * @returns {string} Rendered HTML string\n *\n * @example\n * const html = renderer.render({\n * div: {\n * className: 'container',\n * children: [\n * { h1: { text: 'Title' } },\n * { p: { text: 'Content' } }\n * ]\n * }\n * });\n */\n render(component, options = {}) {\n const config = { ...this.config, ...options };\n this.startTiming();\n\n try {\n // Input validation\n if (config.validateInput && !this.isValidComponent(component)) {\n throw new Error('Invalid component structure');\n }\n\n // Initialize seenObjects for circular reference detection\n const renderOptions = {\n ...config,\n seenObjects: new WeakSet()\n };\n\n // Main rendering logic\n const html = this.renderComponent(component, renderOptions, 0, []);\n const finalHtml = config.minify ? minifyHtml(html, config) : html;\n\n // Performance monitoring\n this.endTiming();\n this.recordPerformance('render', this.metrics.startTime, false, {\n cacheEnabled: config.enableCache\n });\n\n return finalHtml;\n\n } catch (_error) {\n this.recordError('render', _error);\n const enhancedError = globalErrorHandler.handle(_error, {\n renderContext: { path: 'root', renderer: 'html' }\n });\n\n if (config.throwOnError === false) {\n return config.errorFallback;\n }\n\n throw enhancedError;\n }\n }\n\n /**\n * Render a single component with full optimization pipeline\n */\n renderComponent(component, options, depth = 0, path = []) {\n // Handle nullish and empty inputs immediately\n if (component === null || component === undefined) {\n return '';\n }\n if (Array.isArray(component) && component.length === 0) {\n return '';\n }\n\n // Detect circular references (objects only)\n if (typeof component === 'object' && component !== null && !Array.isArray(component)) {\n if (options.seenObjects && options.seenObjects.has(component)) {\n throw new RenderingError(\n 'Circular reference detected in component tree',\n component,\n { path: formatRenderPath(path) },\n ['Remove the circular reference', 'Use lazy loading to break the cycle']\n );\n }\n if (options.seenObjects) {\n options.seenObjects.add(component);\n }\n }\n\n // Use base class depth validation\n this.validateDepth(depth);\n\n try {\n // Use base class component type processing\n const { type, value } = this.processComponentType(component);\n\n switch (type) {\n case 'empty':\n return '';\n case 'text':\n return escapeHtml(value);\n case 'function':\n {\n const result = this.executeFunctionComponent(value, depth);\n return this.renderComponent(result, options, depth + 1, [...path, '()']);\n }\n case 'array':\n // Development mode warning for missing keys\n if (typeof process !== 'undefined' &&\n process.env &&\n process.env.NODE_ENV !== 'production' &&\n value.length > 1) {\n\n const missingKeyCount = value.filter((child) => {\n if (child && typeof child === 'object' && !Array.isArray(child)) {\n const tagName = Object.keys(child)[0];\n const props = child[tagName];\n return props && typeof props === 'object' && props.key === undefined;\n }\n return false; // primitives don't need keys\n }).length;\n\n if (missingKeyCount > 0) {\n console.warn(\n `[Coherent.js] Array of ${value.length} elements at ${formatRenderPath(path)} ` +\n `has ${missingKeyCount} items missing \"key\" props. ` +\n `Keys help identify which items changed for efficient updates. ` +\n `Add unique key props like: { div: { key: 'unique-id', ... } }`\n );\n }\n }\n return value.map((child, index) => this.renderComponent(child, options, depth + 1, [...path, `[${index}]`])).join('');\n case 'element':\n {\n // Process object-based component\n const tagName = Object.keys(value)[0];\n const elementContent = value[tagName];\n return this.renderElement(tagName, elementContent, options, depth, [...path, tagName]);\n }\n default:\n this.recordError('renderComponent', new Error(`Unknown component type: ${type}`));\n return '';\n }\n } catch (_error) {\n const renderPath = formatRenderPath(path);\n\n if (_error instanceof CoherentError) {\n if (!_error.context || typeof _error.context !== 'object') {\n _error.context = { path: renderPath };\n } else if (!_error.context.path) {\n _error.context = { ..._error.context, path: renderPath };\n }\n throw _error;\n }\n\n throw new RenderingError(_error.message, undefined, { path: renderPath, renderer: 'html' });\n }\n }\n\n /**\n * Render an HTML element with advanced caching and optimization\n */\n renderElement(tagName, element, options, depth = 0, path = []) {\n const startTime = performance.now();\n\n // Check for circular references in element props\n if (element && typeof element === 'object' && !Array.isArray(element)) {\n if (options.seenObjects && options.seenObjects.has(element)) {\n throw new RenderingError(\n 'Circular reference detected in component tree',\n element,\n { path: formatRenderPath(path) },\n ['Remove the circular reference', 'Use lazy loading to break the cycle']\n );\n }\n if (options.seenObjects) {\n options.seenObjects.add(element);\n }\n }\n\n // Track element usage for performance analysis (via stats in the new cache manager)\n if (options.enableMonitoring && this.cache) {\n // The new cache manager tracks usage automatically via get/set operations\n }\n\n // Check cache first for static elements\n if (options.enableCache && this.cache && RendererUtils.isStaticElement(element)) {\n try {\n const cacheKey = `static:${tagName}:${JSON.stringify(element)}`;\n const cached = this.cache.get('static', cacheKey);\n if (cached) {\n this.recordPerformance(tagName, startTime, true);\n return cached.value; // Return the cached HTML\n }\n } catch {\n // Circular reference in element - skip caching and continue with rendering\n // The circular reference will be detected and properly reported during render\n }\n }\n\n // Handle text-only elements including booleans\n if (typeof element === 'string' || typeof element === 'number' || typeof element === 'boolean') {\n const html = isVoidElement(tagName)\n ? `<${tagName}>`\n : `<${tagName}>${escapeHtml(String(element))}</${tagName}>`;\n\n this.cacheIfStatic(tagName, element, html, options);\n this.recordPerformance(tagName, startTime, false);\n return html;\n }\n\n // Handle function elements\n if (typeof element === 'function') {\n const result = this.executeFunctionComponent(element, depth);\n return this.renderElement(tagName, result, options, depth, [...path, '()']);\n }\n\n // Handle object elements (complex elements with props and children)\n if (element && typeof element === 'object') {\n return this.renderObjectElement(tagName, element, options, depth, path);\n }\n\n // Handle null and undefined by returning empty tags\n if (element === null || element === undefined) {\n const html = isVoidElement(tagName)\n ? `<${tagName}>`\n : `<${tagName}></${tagName}>`;\n this.recordPerformance(tagName, startTime, false);\n return html;\n }\n\n // Fallback for any other types\n const html = `<${tagName}>${escapeHtml(String(element))}</${tagName}>`;\n this.recordPerformance(tagName, startTime, false);\n return html;\n }\n\n /**\n * Cache element if it's static\n */\n cacheIfStatic(tagName, element, html) {\n if (this.config.enableCache && this.cache && RendererUtils.isStaticElement(element)) {\n try {\n const cacheKey = `static:${tagName}:${JSON.stringify(element)}`;\n this.cache.set('static', cacheKey, html, {\n ttlMs: this.config.cacheTTL || 5 * 60 * 1000, // 5 minutes default\n size: html.length // Approximate size\n });\n } catch {\n // Circular reference - skip caching\n }\n }\n }\n\n /**\n * Render complex object elements with attributes and children\n */\n renderObjectElement(tagName, element, options, depth = 0, path = []) {\n const startTime = performance.now();\n\n // Check component-level cache\n if (options.enableCache && this.cache) {\n const cacheKey = RendererUtils.generateCacheKey(tagName, element);\n if (cacheKey) {\n const cached = this.cache.get(cacheKey);\n if (cached) {\n this.recordPerformance(tagName, startTime, true);\n return cached;\n }\n }\n }\n\n // Extract props and children directly from element content\n // Note: key is extracted but NOT rendered as an HTML attribute\n // It's used for reconciliation identity, not DOM output\n // html prop is extracted to prevent it from being rendered as an attribute\n const { children, text, key: _key, html: _rawHtml, ...attributes } = element || {};\n\n // Build opening tag with attributes\n const attributeString = formatAttributes(attributes);\n const openingTag = attributeString\n ? `<${tagName} ${attributeString}>`\n : `<${tagName}>`;\n\n // Handle text content\n let textContent = '';\n if (text !== undefined) {\n const isScript = tagName === 'script';\n const isStyle = tagName === 'style';\n const isRawTag = isScript || isStyle;\n const raw = typeof text === 'function' ? String(text()) : String(text);\n if (isRawTag) {\n // Prevent </script> or </style> early-terminating the tag\n const safe = raw\n .replace(/<\\/(script)/gi, '<\\\\/$1')\n .replace(/<\\/(style)/gi, '<\\\\/$1')\n // Escape problematic Unicode line separators in JS\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029');\n textContent = safe;\n } else {\n textContent = escapeHtml(raw);\n }\n }\n\n // Handle children\n let childrenHtml = '';\n if (hasChildren(element)) {\n const normalizedChildren = normalizeChildren(children);\n childrenHtml = normalizedChildren\n .map((child, index) => {\n // Validate HTML nesting before rendering child\n if (child && typeof child === 'object' && !Array.isArray(child)) {\n const childTagName = Object.keys(child)[0];\n if (childTagName) {\n validateNesting(tagName, childTagName, formatRenderPath([...path, `children[${index}]`]));\n }\n }\n return this.renderComponent(child, options, depth + 1, [...path, `children[${index}]`]);\n })\n .join('');\n }\n\n // Build complete HTML\n const html = `${openingTag}${textContent}${childrenHtml}</${tagName}>`;\n\n // Cache the result if appropriate\n if (options.enableCache && this.cache && RendererUtils.isCacheable(element, options)) {\n const cacheKey = RendererUtils.generateCacheKey(tagName, element);\n if (cacheKey) {\n this.cache.set(cacheKey, html);\n }\n }\n\n this.recordPerformance(tagName, startTime, false);\n return html;\n }\n}\n\n// Note: globalCache is now imported from cache-manager.js\n\n/**\n * Main render function - converts object components to HTML\n */\nexport function render(component, options = {}) {\n // Merge default options with provided options\n const mergedOptions = {\n enableCache: true,\n enableMonitoring: false,\n ...options\n };\n\n const renderer = new HTMLRenderer(mergedOptions);\n return renderer.render(component, mergedOptions);\n}\n\n/**\n * Renders component to complete HTML document with DOCTYPE\n * Better alternative to manual DOCTYPE concatenation\n * Supports CSS file inclusion and inline styles\n */\nexport async function renderHTML(component, options = {}) {\n const htmlContent = render(component, options);\n\n // Process CSS options\n const cssOptions = cssUtils.processCSSOptions(options);\n\n // Generate CSS HTML if any CSS is specified\n let cssHtml = '';\n if (cssOptions.files.length > 0 || cssOptions.links.length > 0 || cssOptions.inline) {\n cssHtml = await cssUtils.generateCSSHtml(cssOptions, defaultCSSManager);\n }\n\n // If the component includes a head tag, inject CSS into it\n if (cssHtml && htmlContent.includes('<head>')) {\n const htmlWithCSS = htmlContent.replace(\n '</head>',\n `${cssHtml}\\n</head>`\n );\n return `<!DOCTYPE html>\\n${htmlWithCSS}`;\n }\n\n // If there's CSS but no head tag, wrap the component with a basic HTML structure\n if (cssHtml) {\n return `<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n${cssHtml}\n</head>\n<body>\n${htmlContent}\n</body>\n</html>`;\n }\n\n return `<!DOCTYPE html>\\n${htmlContent}`;\n}\n\n/**\n * Synchronous version of render for cases without CSS files\n * Falls back to async if CSS files are detected\n */\nexport function renderHTMLSync(component, options = {}) {\n const cssOptions = cssUtils.processCSSOptions(options);\n\n // If CSS files are specified, return a promise\n if (cssOptions.files.length > 0) {\n console.warn('CSS files detected, use render() (async) instead of renderSync()');\n return render(component, options);\n }\n\n const htmlContent = render(component, options);\n\n // Handle inline CSS and external links only\n let cssHtml = '';\n if (cssOptions.links.length > 0) {\n cssHtml += defaultCSSManager.generateCSSLinks(cssOptions.links);\n }\n if (cssOptions.inline) {\n cssHtml += `\\n${ defaultCSSManager.generateInlineStyles(cssOptions.inline)}`;\n }\n\n if (cssHtml && htmlContent.includes('<head>')) {\n const htmlWithCSS = htmlContent.replace(\n '</head>',\n `${cssHtml}\\n</head>`\n );\n return `<!DOCTYPE html>\\n${htmlWithCSS}`;\n }\n\n if (cssHtml) {\n return `<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n${cssHtml}\n</head>\n<body>\n${htmlContent}\n</body>\n</html>`;\n }\n\n return `<!DOCTYPE html>\\n${htmlContent}`;\n}\n\n\n// Old functions removed - now part of HTMLRenderer class\n\n// Old helper functions removed - now available in RendererUtils from BaseRenderer\n\n/**\n * Batch rendering for multiple components\n */\nexport function renderBatch(components, options = {}) {\n if (!Array.isArray(components)) {\n throw new Error('renderBatch expects an array of components');\n }\n\n // Merge default options with provided options\n const mergedOptions = {\n enableCache: true,\n enableMonitoring: false,\n ...options\n };\n\n const renderer = new HTMLRenderer(mergedOptions);\n return components.map(component => renderer.render(component, mergedOptions));\n}\n\n/**\n * Real streaming render - yields chunks progressively as HTML is generated\n * Ideal for large component trees or memory-constrained environments\n */\nexport async function* renderToStream(component, options = {}) {\n const config = {\n chunkSize: 8192, // 8KB default chunk size\n maxDepth: 1000,\n yieldThreshold: 100, // Yield control every 100 elements\n encoding: 'utf8',\n ...options\n };\n\n let buffer = '';\n let elementCount = 0;\n\n // Helper to flush buffer when it reaches chunk size\n async function* flushBuffer(force = false) {\n if (force || buffer.length >= config.chunkSize) {\n if (buffer.length > 0) {\n yield buffer;\n buffer = '';\n }\n }\n }\n\n // Helper to add to buffer\n async function* write(text) {\n buffer += text;\n yield* flushBuffer();\n }\n\n // Recursive streaming component renderer\n async function* streamComponent(comp, depth = 0) {\n if (depth > config.maxDepth) {\n throw new Error(`Maximum nesting depth exceeded: ${config.maxDepth}`);\n }\n\n // Handle null/undefined\n if (comp === null || comp === undefined) return;\n\n // Handle primitives\n if (typeof comp === 'string' || typeof comp === 'number') {\n yield* write(escapeHtml(String(comp)));\n return;\n }\n\n // Handle arrays\n if (Array.isArray(comp)) {\n for (const child of comp) {\n yield* streamComponent(child, depth);\n\n // Yield control periodically\n if (elementCount++ % config.yieldThreshold === 0) {\n await new Promise(resolve => setImmediate(resolve));\n }\n }\n return;\n }\n\n // Handle functions\n if (typeof comp === 'function') {\n const result = comp();\n yield* streamComponent(result, depth);\n return;\n }\n\n // Handle objects (HTML elements)\n if (typeof comp === 'object') {\n for (const [tagName, props] of Object.entries(comp)) {\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 yield* write(openTag.replace('>', ' />'));\n elementCount++;\n return;\n }\n\n yield* write(openTag);\n\n if (text !== undefined) {\n yield* write(escapeHtml(String(text)));\n } else if (children) {\n yield* streamComponent(children, depth + 1);\n }\n\n yield* write(`</${tagName}>`);\n elementCount++;\n } else if (typeof props === 'string') {\n const content = escapeHtml(props);\n if (isVoidElement(tagName)) {\n yield* write(`<${tagName} />`);\n } else {\n yield* write(`<${tagName}>${content}</${tagName}>`);\n }\n elementCount++;\n }\n }\n }\n }\n\n // Start streaming\n try {\n yield* streamComponent(component);\n yield* flushBuffer(true); // Force flush remaining buffer\n } catch (error) {\n // Stream error as HTML comment\n yield `<!-- Streaming Error: ${error.message} -->`;\n }\n}\n\n/**\n * Streaming utilities for common use cases\n */\nexport const streamingUtils = {\n /**\n * Collect all chunks into a single string\n */\n async collectChunks(chunkGenerator) {\n let html = '';\n for await (const chunk of chunkGenerator) {\n html += chunk;\n }\n return html;\n },\n\n /**\n * Stream directly to a Node.js response\n */\n async streamToResponse(chunkGenerator, response) {\n let totalBytes = 0;\n response.setHeader('Content-Type', 'text/html; charset=utf-8');\n response.setHeader('Transfer-Encoding', 'chunked');\n\n for await (const chunk of chunkGenerator) {\n response.write(chunk);\n totalBytes += Buffer.byteLength(chunk);\n }\n\n response.end();\n return totalBytes;\n },\n\n /**\n * Stream with progress callback\n */\n async* streamWithProgress(chunkGenerator, onProgress) {\n let totalBytes = 0;\n let chunkCount = 0;\n\n for await (const chunk of chunkGenerator) {\n totalBytes += Buffer.byteLength(chunk);\n chunkCount++;\n\n if (onProgress) {\n onProgress({ chunkCount, totalBytes, chunk });\n }\n\n yield chunk;\n }\n }\n};\n\n/**\n * Render to chunks (legacy - kept for backward compatibility)\n * For true streaming, use renderToStream() instead\n */\nexport function* renderToChunks(component, options = {}) {\n const mergedOptions = {\n enableCache: true,\n enableMonitoring: false,\n ...options,\n chunkSize: options.chunkSize || 1024 // Default 1KB chunks\n };\n\n const html = render(component, mergedOptions);\n\n for (let i = 0; i < html.length; i += mergedOptions.chunkSize) {\n yield html.slice(i, i + mergedOptions.chunkSize);\n }\n}\n\n/**\n * Get global cache instance for external access\n */\nexport function getCache() {\n return rendererCache;\n}\n\n/**\n * Reset cache (useful for testing)\n */\nexport function resetCache() {\n if (rendererCache) {\n rendererCache.clear();\n }\n}\n\n/**\n * Get rendering statistics\n */\nexport function getRenderingStats() {\n return {\n cache: rendererCache ? rendererCache.getStats() : null,\n performance: performanceMonitor.getStats()\n };\n}\n\n/**\n * Precompile static components for maximum performance\n */\nexport function precompileComponent(component, options = {}) {\n if (!isStaticElement(component)) {\n throw new Error('Can only precompile static components');\n }\n\n const html = render(component, { ...options, enableCache: false });\n\n return {\n html,\n isPrecompiled: true,\n render: () => html\n };\n}\n\n/**\n * Development helper - render with detailed timing\n */\nexport function renderWithTiming(component, options = {}) {\n const start = performance.now();\n const html = render(component, { ...options, enableMonitoring: true });\n const end = performance.now();\n\n return {\n html,\n timing: {\n total: end - start,\n breakdown: performanceMonitor.getStats()\n }\n };\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 setState: stateUtils.setState,\n getState: stateUtils.getState,\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 * 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 * Core constants and types for the Coherent framework\n */\n\nexport const CoherentTypes = {\n OBJECT: 'coherent-object',\n COMPONENT: 'coherent-component',\n ELEMENT: 'coherent-element'\n};\n\nexport const HTML_ELEMENTS = new Set([\n 'a', 'abbr', 'address', 'area', 'article', 'aside', 'audio',\n 'b', 'base', 'bdi', 'bdo', 'blockquote', 'body', 'br', 'button',\n 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup',\n 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt',\n 'em', 'embed',\n 'fieldset', 'figcaption', 'figure', 'footer', 'form',\n 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hr', 'html',\n 'i', 'iframe', 'img', 'input', 'ins',\n 'kbd',\n 'label', 'legend', 'li', 'link',\n 'main', 'map', 'mark', 'meta', 'meter',\n 'nav', 'noscript',\n 'object', 'ol', 'optgroup', 'option', 'output',\n 'p', 'param', 'picture', 'pre', 'progress',\n 'q',\n 'rp', 'rt', 'ruby',\n 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup',\n 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track',\n 'u', 'ul',\n 'var', 'video',\n 'wbr'\n]);\n\nexport const VOID_ELEMENTS = new Set([\n 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',\n 'link', 'meta', 'param', 'source', 'track', 'wbr'\n]);\n", "/**\n * Object Factory for Coherent.js\n * @fileoverview Creates Coherent objects with HTML elements and text nodes\n */\n\nimport { HTML_ELEMENTS, CoherentTypes } from '../types/constants.js';\n\n/**\n * Creates a Coherent object with the specified tag and properties\n * @param {string} tag - HTML tag name\n * @param {Object} [props={}] - Properties object\n * @returns {Object} Coherent object with element structure\n * @throws {Error} When invalid HTML element is provided\n */\nexport function createElement(tag, props = {}) {\n if (!HTML_ELEMENTS.has(tag)) {\n throw new Error(`Invalid HTML element: ${tag}`);\n }\n\n // Create the coherent object structure\n const coherentObj = {\n [tag]: {\n ...props,\n _type: CoherentTypes.ELEMENT\n }\n };\n\n return coherentObj;\n}\n\n/**\n * Creates a text node\n * @param {string} text - Text content\n * @returns {Object} Coherent text object\n */\nexport function createTextNode(text) {\n return {\n text: String(text),\n _type: CoherentTypes.OBJECT\n };\n}\n\n/**\n * Helper function to create common elements\n */\nexport const h = {\n div: (props) => createElement('div', props),\n span: (props) => createElement('span', props),\n p: (props) => createElement('p', props),\n h1: (props) => createElement('h1', props),\n h2: (props) => createElement('h2', props),\n h3: (props) => createElement('h3', props),\n h4: (props) => createElement('h4', props),\n h5: (props) => createElement('h5', props),\n h6: (props) => createElement('h6', props),\n a: (props) => createElement('a', props),\n img: (props) => createElement('img', props),\n button: (props) => createElement('button', props),\n input: (props) => createElement('input', props),\n form: (props) => createElement('form', props),\n ul: (props) => createElement('ul', props),\n ol: (props) => createElement('ol', props),\n li: (props) => createElement('li', props),\n table: (props) => createElement('table', props),\n tr: (props) => createElement('tr', props),\n td: (props) => createElement('td', props),\n th: (props) => createElement('th', props)\n};\n", "/**\n * Advanced Component Caching System for Coherent.js\n * Provides intelligent caching with dependency tracking and invalidation\n */\n\nimport { deepClone } from '../core/object-utils.js';\n\n/**\n * Cache entry structure\n */\nclass CacheEntry {\n constructor(key, component, deps = [], options = {}) {\n this.key = key;\n this.component = deepClone(component);\n this.deps = new Set(deps);\n this.createdAt = Date.now();\n this.lastAccessed = Date.now();\n this.accessCount = 1;\n this.ttl = options.ttl || 300000; // 5 minutes default\n this.persistent = options.persistent || false;\n }\n\n isExpired() {\n return !this.persistent && (Date.now() - this.createdAt) > this.ttl;\n }\n\n touch() {\n this.lastAccessed = Date.now();\n this.accessCount++;\n }\n\n hasDependency(dep) {\n return this.deps.has(dep);\n }\n\n addDependency(dep) {\n this.deps.add(dep);\n }\n\n removeDependency(dep) {\n this.deps.delete(dep);\n }\n}\n\n/**\n * Component Cache Manager with intelligent invalidation\n */\nexport class ComponentCache {\n constructor(options = {}) {\n this.options = {\n maxSize: options.maxSize || 1000,\n defaultTTL: options.defaultTTL || 300000,\n cleanupInterval: options.cleanupInterval || 60000, // 1 minute\n enableStats: options.enableStats !== false,\n ...options\n };\n\n this.cache = new Map();\n this.dependencies = new Map(); // dependency -> Set of cache keys\n this.stats = {\n hits: 0,\n misses: 0,\n evictions: 0,\n cleanups: 0,\n invalidations: 0\n };\n\n // Start periodic cleanup\n if (this.options.cleanupInterval > 0) {\n this.cleanupTimer = setInterval(() => {\n this.cleanup();\n }, this.options.cleanupInterval);\n }\n }\n\n /**\n * Generate cache key from component and props\n */\n generateKey(component, props = {}, context = {}) {\n if (typeof component === 'string') {\n return `str:${component}`;\n }\n\n if (typeof component === 'function') {\n return `fn:${component.name || 'anonymous'}:${JSON.stringify(props)}`;\n }\n\n if (typeof component === 'object' && component !== null) {\n const serialized = this.serializeComponent(component);\n const propsHash = Object.keys(props).length > 0 ? `:${JSON.stringify(props)}` : '';\n const contextHash = Object.keys(context).length > 0 ? `:${JSON.stringify(context)}` : '';\n return `obj:${serialized}${propsHash}${contextHash}`;\n }\n\n return `primitive:${String(component)}`;\n }\n\n /**\n * Serialize component for cache key generation\n */\n serializeComponent(component, maxDepth = 3, currentDepth = 0) {\n if (currentDepth > maxDepth) {\n return '[DEEP]';\n }\n\n if (typeof component !== 'object' || component === null) {\n return String(component);\n }\n\n if (Array.isArray(component)) {\n return `[${component.map(item => \n this.serializeComponent(item, maxDepth, currentDepth + 1)\n ).join(',')}]`;\n }\n\n const entries = Object.entries(component);\n if (entries.length === 1) {\n const [key, value] = entries[0];\n const serializedValue = typeof value === 'object' \n ? this.serializeComponent(value, maxDepth, currentDepth + 1)\n : String(value);\n return `${key}:${serializedValue}`;\n }\n\n return '[COMPLEX]';\n }\n\n /**\n * Get component from cache\n */\n get(key, dependencies = []) {\n const entry = this.cache.get(key);\n\n if (!entry) {\n this.stats.misses++;\n return null;\n }\n\n if (entry.isExpired()) {\n this.cache.delete(key);\n this.removeDependencyMappings(key);\n this.stats.misses++;\n return null;\n }\n\n entry.touch();\n this.stats.hits++;\n\n // Update dependency tracking\n dependencies.forEach(dep => {\n if (!entry.hasDependency(dep)) {\n entry.addDependency(dep);\n this.addDependencyMapping(dep, key);\n }\n });\n\n return deepClone(entry.component);\n }\n\n /**\n * Set component in cache\n */\n set(key, component, options = {}) {\n // Enforce size limit\n if (this.cache.size >= this.options.maxSize) {\n this.evictLeastUsed();\n }\n\n const deps = options.dependencies || [];\n const entry = new CacheEntry(key, component, deps, {\n ttl: options.ttl || this.options.defaultTTL,\n persistent: options.persistent || false\n });\n\n this.cache.set(key, entry);\n\n // Update dependency mappings\n deps.forEach(dep => {\n this.addDependencyMapping(dep, key);\n });\n\n return true;\n }\n\n /**\n * Check if component exists in cache\n */\n has(key) {\n const entry = this.cache.get(key);\n return entry && !entry.isExpired();\n }\n\n /**\n * Invalidate cache entries by dependency\n */\n invalidate(dependency) {\n const dependentKeys = this.dependencies.get(dependency);\n if (!dependentKeys) {\n return 0;\n }\n\n let invalidated = 0;\n for (const key of dependentKeys) {\n if (this.cache.delete(key)) {\n invalidated++;\n this.stats.invalidations++;\n }\n }\n\n this.dependencies.delete(dependency);\n return invalidated;\n }\n\n /**\n * Invalidate multiple dependencies\n */\n invalidateMultiple(dependencies) {\n let totalInvalidated = 0;\n dependencies.forEach(dep => {\n totalInvalidated += this.invalidate(dep);\n });\n return totalInvalidated;\n }\n\n /**\n * Clear entire cache\n */\n clear() {\n const size = this.cache.size;\n this.cache.clear();\n this.dependencies.clear();\n return size;\n }\n\n /**\n * Add dependency mapping\n */\n addDependencyMapping(dependency, key) {\n if (!this.dependencies.has(dependency)) {\n this.dependencies.set(dependency, new Set());\n }\n this.dependencies.get(dependency).add(key);\n }\n\n /**\n * Remove dependency mappings for a cache key\n */\n removeDependencyMappings(key) {\n for (const [dep, keys] of this.dependencies.entries()) {\n keys.delete(key);\n if (keys.size === 0) {\n this.dependencies.delete(dep);\n }\n }\n }\n\n /**\n * Evict least recently used entry\n */\n evictLeastUsed() {\n let oldestKey = null;\n let oldestTime = Date.now();\n\n for (const [key, entry] of this.cache.entries()) {\n if (!entry.persistent && entry.lastAccessed < oldestTime) {\n oldestTime = entry.lastAccessed;\n oldestKey = key;\n }\n }\n\n if (oldestKey) {\n this.cache.delete(oldestKey);\n this.removeDependencyMappings(oldestKey);\n this.stats.evictions++;\n }\n }\n\n /**\n * Cleanup expired entries\n */\n cleanup() {\n const before = this.cache.size;\n const expiredKeys = [];\n\n for (const [key, entry] of this.cache.entries()) {\n if (entry.isExpired()) {\n expiredKeys.push(key);\n }\n }\n\n expiredKeys.forEach(key => {\n this.cache.delete(key);\n this.removeDependencyMappings(key);\n });\n\n const cleaned = before - this.cache.size;\n if (cleaned > 0) {\n this.stats.cleanups++;\n }\n\n return cleaned;\n }\n\n /**\n * Get cache statistics\n */\n getStats() {\n const totalRequests = this.stats.hits + this.stats.misses;\n return {\n size: this.cache.size,\n maxSize: this.options.maxSize,\n hits: this.stats.hits,\n misses: this.stats.misses,\n hitRate: totalRequests > 0 ? (this.stats.hits / totalRequests * 100).toFixed(2) : 0,\n evictions: this.stats.evictions,\n cleanups: this.stats.cleanups,\n invalidations: this.stats.invalidations,\n dependencies: this.dependencies.size,\n memoryUsage: this.estimateMemoryUsage()\n };\n }\n\n /**\n * Estimate memory usage (rough approximation)\n */\n estimateMemoryUsage() {\n let totalSize = 0;\n for (const entry of this.cache.values()) {\n // Rough estimate: 1KB per component + overhead\n totalSize += JSON.stringify(entry.component).length + 500;\n }\n return Math.round(totalSize / 1024); // Return in KB\n }\n\n /**\n * Get hot path components (most accessed)\n */\n getHotComponents(limit = 10) {\n const entries = Array.from(this.cache.entries());\n return entries\n .sort((a, b) => b[1].accessCount - a[1].accessCount)\n .slice(0, limit)\n .map(([key, entry]) => ({\n key,\n accessCount: entry.accessCount,\n component: entry.component,\n dependencies: Array.from(entry.deps)\n }));\n }\n\n /**\n * Get cache recommendations\n */\n getRecommendations() {\n const stats = this.getStats();\n const recommendations = [];\n\n if (stats.hitRate < 50) {\n recommendations.push({\n type: 'low-hit-rate',\n message: `Hit rate is ${stats.hitRate}%. Consider increasing cache size or TTL.`,\n priority: 'HIGH'\n });\n }\n\n if (stats.evictions > stats.hits * 0.1) {\n recommendations.push({\n type: 'frequent-evictions',\n message: 'Frequent evictions detected. Consider increasing maxSize.',\n priority: 'MEDIUM'\n });\n }\n\n if (stats.invalidations > stats.hits * 0.05) {\n recommendations.push({\n type: 'frequent-invalidations',\n message: 'Frequent invalidations. Review dependency tracking.',\n priority: 'LOW'\n });\n }\n\n return recommendations;\n }\n\n /**\n * Destroy cache and cleanup\n */\n destroy() {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n }\n this.clear();\n }\n}\n\n/**\n * Create a new component cache instance\n */\nexport function createComponentCache(options = {}) {\n return new ComponentCache(options);\n}\n\n/**\n * Memoization decorator for components\n */\nexport function memoize(component, keyGenerator, options = {}) {\n const cache = new ComponentCache({\n maxSize: options.maxSize || 100,\n defaultTTL: options.ttl || 300000\n });\n\n return function memoizedComponent(...args) {\n const key = keyGenerator ? keyGenerator(...args) : JSON.stringify(args);\n \n const cached = cache.get(key, options.dependencies);\n if (cached) {\n return cached;\n }\n\n const result = typeof component === 'function' ? component(...args) : component;\n cache.set(key, result, options);\n return result;\n };\n}\n\nexport default ComponentCache;", "/**\n * Coherent.js Error Boundary\n * \n * Catches rendering errors and provides fallback UI.\n * Similar to React's Error Boundaries but for Coherent.js.\n * \n * @module components/error-boundary\n */\n\n/**\n * Error boundary state\n */\nclass ErrorBoundaryState {\n constructor() {\n this.hasError = false;\n this.error = null;\n this.errorInfo = null;\n this.errorCount = 0;\n this.lastError = null;\n }\n\n reset() {\n this.hasError = false;\n this.error = null;\n this.errorInfo = null;\n }\n\n setError(error, errorInfo = {}) {\n this.hasError = true;\n this.error = error;\n this.errorInfo = errorInfo;\n this.errorCount++;\n this.lastError = Date.now();\n }\n}\n\n/**\n * Create an error boundary\n * \n * @param {Object} options - Error boundary options\n * @param {Object|Function} options.fallback - Fallback component or function\n * @param {Function} [options.onError] - Error callback\n * @param {Function} [options.onReset] - Reset callback\n * @param {Array<string>} [options.resetKeys] - Keys that trigger reset\n * @param {boolean} [options.resetOnPropsChange] - Reset on props change\n * @param {number} [options.maxErrors] - Maximum errors before permanent fallback\n * @param {number} [options.resetTimeout] - Auto-reset timeout in ms\n * @returns {Function} Error boundary wrapper function\n * \n * @example\n * const boundary = createErrorBoundary({\n * fallback: { div: { text: 'Something went wrong' } },\n * onError: (error, errorInfo) => console.error(error),\n * resetKeys: ['userId']\n * });\n * \n * const SafeComponent = boundary(MyComponent);\n */\nexport function createErrorBoundary(options = {}) {\n const {\n fallback = { div: { className: 'error-boundary', text: 'An error occurred' } },\n onError = null,\n onReset = null,\n resetKeys = [],\n resetOnPropsChange = false,\n maxErrors = Infinity,\n resetTimeout = null\n } = options;\n\n const state = new ErrorBoundaryState();\n let previousProps = {};\n let resetTimer = null;\n\n /**\n * Wrap a component with error boundary\n */\n return function errorBoundaryWrapper(component) {\n return function wrappedComponent(props = {}) {\n try {\n // Check if we should reset based on props\n if (resetOnPropsChange && shouldReset(props, previousProps, resetKeys)) {\n state.reset();\n if (onReset) {\n onReset();\n }\n }\n\n previousProps = { ...props };\n\n // If we have an error and haven't exceeded max errors\n if (state.hasError) {\n if (state.errorCount >= maxErrors) {\n // Permanent fallback\n return typeof fallback === 'function'\n ? fallback(state.error, state.errorInfo, { permanent: true })\n : fallback;\n }\n\n // Return fallback with reset option\n const fallbackComponent = typeof fallback === 'function'\n ? fallback(state.error, state.errorInfo, {\n reset: () => {\n state.reset();\n if (onReset) {\n onReset();\n }\n },\n errorCount: state.errorCount\n })\n : fallback;\n\n return fallbackComponent;\n }\n\n // Try to render the component\n const result = typeof component === 'function'\n ? component(props)\n : component;\n\n return result;\n\n } catch (error) {\n // Capture error\n const errorInfo = {\n componentStack: error.stack,\n props,\n timestamp: Date.now()\n };\n\n state.setError(error, errorInfo);\n\n // Call error callback\n if (onError) {\n try {\n onError(error, errorInfo);\n } catch (callbackError) {\n console.error('Error in onError callback:', callbackError);\n }\n }\n\n // Set auto-reset timer if configured\n if (resetTimeout && !resetTimer) {\n resetTimer = setTimeout(() => {\n state.reset();\n resetTimer = null;\n if (onReset) {\n onReset();\n }\n }, resetTimeout);\n }\n\n // Return fallback\n return typeof fallback === 'function'\n ? fallback(error, errorInfo, {\n reset: () => {\n state.reset();\n if (resetTimer) {\n clearTimeout(resetTimer);\n resetTimer = null;\n }\n if (onReset) {\n onReset();\n }\n },\n errorCount: state.errorCount\n })\n : fallback;\n }\n };\n };\n}\n\n/**\n * Check if error boundary should reset based on props\n */\nfunction shouldReset(newProps, oldProps, resetKeys) {\n if (resetKeys.length === 0) {\n return false;\n }\n\n return resetKeys.some(key => newProps[key] !== oldProps[key]);\n}\n\n/**\n * Create a default error fallback component\n * \n * @param {Object} options - Fallback options\n * @returns {Function} Fallback component function\n */\nexport function createErrorFallback(options = {}) {\n const {\n title = 'Something went wrong',\n showError = true,\n showStack = false,\n showReset = true,\n className = 'error-boundary-fallback',\n style = {}\n } = options;\n\n return function errorFallback(error, errorInfo, context = {}) {\n const children = [\n {\n h2: {\n className: 'error-title',\n text: title\n }\n }\n ];\n\n if (showError && error) {\n children.push({\n p: {\n className: 'error-message',\n text: error.message || 'Unknown error'\n }\n });\n }\n\n if (showStack && error && error.stack) {\n children.push({\n pre: {\n className: 'error-stack',\n text: error.stack\n }\n });\n }\n\n if (showReset && context.reset && !context.permanent) {\n children.push({\n button: {\n className: 'error-reset-button',\n text: 'Try Again',\n onclick: context.reset\n }\n });\n }\n\n if (context.errorCount > 1) {\n children.push({\n p: {\n className: 'error-count',\n text: `Error occurred ${context.errorCount} times`\n }\n });\n }\n\n return {\n div: {\n className,\n style: {\n padding: '20px',\n border: '1px solid #f44336',\n borderRadius: '4px',\n backgroundColor: '#ffebee',\n color: '#c62828',\n ...style\n },\n children\n }\n };\n };\n}\n\n/**\n * Wrap multiple components with the same error boundary\n * \n * @param {Object} options - Error boundary options\n * @param {Object} components - Components to wrap\n * @returns {Object} Wrapped components\n * \n * @example\n * const safeComponents = withErrorBoundary(\n * { fallback: ErrorFallback },\n * { Header, Footer, Content }\n * );\n */\nexport function withErrorBoundary(options, components) {\n const boundary = createErrorBoundary(options);\n const wrapped = {};\n\n Object.entries(components).forEach(([name, component]) => {\n wrapped[name] = boundary(component);\n });\n\n return wrapped;\n}\n\n/**\n * Error boundary for async components\n * \n * @param {Object} options - Error boundary options\n * @returns {Function} Async error boundary wrapper\n */\nexport function createAsyncErrorBoundary(options = {}) {\n const {\n fallback = { div: { text: 'Loading...' } },\n errorFallback = { div: { text: 'Failed to load' } },\n onError = null,\n timeout = 10000\n } = options;\n\n return function asyncBoundaryWrapper(asyncComponent) {\n return async function wrappedAsyncComponent(props = {}) {\n try {\n // Set timeout\n const timeoutPromise = new Promise((_, reject) => {\n setTimeout(() => reject(new Error('Component load timeout')), timeout);\n });\n\n // Race between component load and timeout\n const result = await Promise.race([\n typeof asyncComponent === 'function'\n ? asyncComponent(props)\n : asyncComponent,\n timeoutPromise\n ]);\n\n return result ?? fallback;\n } catch (error) {\n if (onError) {\n onError(error, { props, async: true });\n }\n\n return typeof errorFallback === 'function'\n ? errorFallback(error, { props })\n : errorFallback;\n }\n };\n };\n}\n\n/**\n * Global error handler for uncaught errors\n */\nexport class GlobalErrorHandler {\n constructor(options = {}) {\n this.options = options;\n this.errors = [];\n this.maxErrors = options.maxErrors || 100;\n this.onError = options.onError || null;\n this.enabled = options.enabled !== false;\n }\n\n /**\n * Capture an error\n */\n captureError(error, context = {}) {\n if (!this.enabled) return;\n\n const errorEntry = {\n error,\n context,\n timestamp: Date.now(),\n stack: error.stack\n };\n\n this.errors.push(errorEntry);\n\n // Limit stored errors\n if (this.errors.length > this.maxErrors) {\n this.errors.shift();\n }\n\n // Call error callback\n if (this.onError) {\n try {\n this.onError(error, context);\n } catch (callbackError) {\n console.error('Error in global error handler callback:', callbackError);\n }\n }\n }\n\n /**\n * Get all captured errors\n */\n getErrors() {\n return [...this.errors];\n }\n\n /**\n * Clear all errors\n */\n clearErrors() {\n this.errors = [];\n }\n\n /**\n * Get error statistics\n */\n getStats() {\n return {\n totalErrors: this.errors.length,\n enabled: this.enabled,\n maxErrors: this.maxErrors\n };\n }\n\n /**\n * Enable error handler\n */\n enable() {\n this.enabled = true;\n }\n\n /**\n * Disable error handler\n */\n disable() {\n this.enabled = false;\n }\n}\n\n/**\n * Create a global error handler\n */\nexport function createGlobalErrorHandler(options = {}) {\n return new GlobalErrorHandler(options);\n}\n\n/**\n * Export all error boundary utilities\n */\nexport default {\n createErrorBoundary,\n createErrorFallback,\n withErrorBoundary,\n createAsyncErrorBoundary,\n GlobalErrorHandler,\n createGlobalErrorHandler\n};\n", "/**\n * Shared rendering utilities for framework integrations\n * Eliminates code duplication across Express, Fastify, Koa, Next.js integrations\n */\n\nimport { render } from '../rendering/html-renderer.js';\nimport { performanceMonitor } from '../performance/monitor.js';\n\n/**\n * Render a component with optional performance monitoring\n * This is the canonical rendering function used by all framework integrations\n * \n * @param {Object} component - Coherent.js component to render\n * @param {Object} options - Rendering options\n * @param {boolean} options.enablePerformanceMonitoring - Enable performance tracking\n * @param {string} options.template - HTML template with {{content}} placeholder\n * @returns {string} Rendered HTML\n */\nexport function renderWithMonitoring(component, options = {}) {\n const {\n enablePerformanceMonitoring = false\n } = options;\n\n let html;\n\n if (enablePerformanceMonitoring) {\n const renderId = performanceMonitor.startRender();\n html = render(component);\n performanceMonitor.endRender(renderId);\n } else {\n html = render(component);\n }\n\n return html;\n}\n\n/**\n * Render a component and apply an HTML template\n * \n * @param {Object} component - Coherent.js component to render\n * @param {Object} options - Rendering options\n * @param {boolean} options.enablePerformanceMonitoring - Enable performance tracking\n * @param {string} options.template - HTML template with {{content}} placeholder\n * @returns {string} Final HTML with template applied\n */\nexport function renderWithTemplate(component, options = {}) {\n const {\n template = '<!DOCTYPE html>\\n{{content}}'\n } = options;\n\n const html = renderWithMonitoring(component, options);\n return template.replace('{{content}}', html);\n}\n\n/**\n * Create a component factory handler for framework integrations\n * Handles component creation, rendering, and error handling\n * \n * @param {Function} componentFactory - Function that creates a component\n * @param {Object} factoryArgs - Arguments to pass to the component factory\n * @param {Object} options - Rendering options\n * @returns {Promise<string>} Rendered HTML\n * @throws {Error} If component factory returns null/undefined or rendering fails\n */\nexport async function renderComponentFactory(componentFactory, factoryArgs, options = {}) {\n // Create component with provided arguments\n const component = await Promise.resolve(\n componentFactory(...factoryArgs)\n );\n\n if (!component) {\n throw new Error('Component factory returned null/undefined');\n }\n\n // Render with template\n return renderWithTemplate(component, options);\n}\n\n/**\n * Check if an object is a Coherent.js component\n * A Coherent.js component is a plain object with a single key representing an HTML tag\n * \n * @param {any} obj - Object to check\n * @returns {boolean} True if object is a Coherent.js component\n */\nexport function isCoherentComponent(obj) {\n if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {\n return false;\n }\n\n const keys = Object.keys(obj);\n return keys.length === 1;\n}\n\n/**\n * Create a standardized error response for framework integrations\n * \n * @param {Error} error - The error that occurred\n * @param {string} context - Context where the error occurred\n * @returns {Object} Error response object\n */\nexport function createErrorResponse(error, context = 'rendering') {\n return {\n error: 'Internal Server Error',\n message: error.message,\n context,\n timestamp: new Date().toISOString()\n };\n}\n", "/**\n * Utility functions for handling optional peer dependencies\n */\n\n/**\n * Check if a peer dependency is available\n * @param {string} packageName - Name of the package to check\n * @returns {boolean} - Whether the package is available\n */\nexport function isPeerDependencyAvailable(packageName) {\n try {\n // Try to import the package synchronously using require.resolve\n // This is more compatible with code analysis tools\n if (typeof require !== 'undefined' && require.resolve) {\n require.resolve(packageName);\n return true;\n }\n // Fallback: assume available if require is not available (browser context)\n return false;\n } catch {\n return false;\n }\n}\n\n/**\n * Dynamically import a peer dependency with _error handling\n * @param {string} packageName - Name of the package to import\n * @param {string} integrationName - Human-readable name of the integration\n * @returns {Promise<any>} - The imported module\n * @throws {Error} - If the dependency is not available\n */\nexport async function importPeerDependency(packageName, integrationName) {\n try {\n return await import(packageName);\n } catch {\n throw new Error(\n `${integrationName} integration requires the '${packageName}' package to be installed.\\n` +\n `Please install it with: npm install ${packageName}\\n` +\n `Or with pnpm: pnpm add ${packageName}\\n` +\n `Or with yarn: yarn add ${packageName}`\n );\n }\n}\n\n/**\n * Create a lazy-loaded integration that only imports dependencies when needed\n * @param {string} packageName - Name of the package to import\n * @param {string} integrationName - Human-readable name of the integration\n * @param {Function} createIntegration - Function that creates the integration using the imported package\n * @returns {Function} - Lazy-loaded integration function\n */\nexport function createLazyIntegration(packageName, integrationName, createIntegration) {\n let cachedIntegration = null;\n let importPromise = null;\n\n return async function(...args) {\n // Return cached integration if available\n if (cachedIntegration) {\n return cachedIntegration(...args);\n }\n\n // Avoid multiple concurrent imports\n if (!importPromise) {\n importPromise = importPeerDependency(packageName, integrationName)\n .then(module => {\n cachedIntegration = createIntegration(module);\n return cachedIntegration;\n });\n }\n\n const integration = await importPromise;\n return integration(...args);\n };\n}\n\n/**\n * Check multiple peer dependencies and provide helpful _error messages\n * @param {Array<{package: string, integration: string}>} dependencies - List of dependencies to check\n * @returns {Object} - Object with availability status for each dependency\n */\nexport function checkPeerDependencies(dependencies) {\n const results = {};\n const missing = [];\n\n for (const { package: packageName, integration } of dependencies) {\n const available = isPeerDependencyAvailable(packageName);\n results[packageName] = available;\n \n if (!available) {\n missing.push({ package: packageName, integration });\n }\n }\n\n if (missing.length > 0) {\n const installCommands = missing.map(({ package: pkg }) => pkg).join(' ');\n const integrationsList = missing.map(({ integration }) => integration).join(', ');\n \n console.warn(\n `Optional dependencies missing for ${integrationsList} integration(s).\\n` +\n `To use these integrations, install: npm install ${installCommands}\\n` +\n `Or with pnpm: pnpm add ${installCommands}\\n` +\n `Or with yarn: yarn add ${installCommands}`\n );\n }\n\n return results;\n}\n\n/**\n * Create a function that checks for a dependency before executing\n * @param {string} packageName - Name of the package required\n * @param {string} integrationName - Human-readable name of the integration\n * @param {Function} fn - Function to execute if dependency is available\n * @returns {Function} - Wrapped function with dependency check\n */\nexport function requirePeerDependency(packageName, integrationName, fn) {\n return function(...args) {\n if (!isPeerDependencyAvailable(packageName)) {\n throw new Error(\n `${integrationName} integration requires the '${packageName}' package to be installed.\\n` +\n `Please install it with: npm install ${packageName}`\n );\n }\n return fn.apply(this, args);\n };\n}\n", "/**\n * Shadow DOM Component System for Coherent.js\n * Provides true style encapsulation using native Shadow DOM\n */\n\n// Check if Shadow DOM is supported\nexport function isShadowDOMSupported() {\n if (typeof window === 'undefined') return false;\n if (typeof window.Element === 'undefined') return false;\n \n return 'attachShadow' in window.Element.prototype && \n 'getRootNode' in window.Element.prototype;\n}\n\n// Create a Shadow DOM component\nexport function createShadowComponent(element, componentDef, options = {}) {\n if (!isShadowDOMSupported()) {\n throw new Error('Shadow DOM is not supported in this environment');\n }\n \n const shadowRoot = element.attachShadow({ \n mode: options.mode || 'closed',\n delegatesFocus: options.delegatesFocus || false\n });\n \n // Extract and inject styles\n const styles = extractStyles(componentDef);\n if (styles && typeof window !== 'undefined' && window.document) {\n const styleElement = window.document.createElement('style');\n styleElement.textContent = styles;\n shadowRoot.appendChild(styleElement);\n }\n \n // Render component content\n const content = renderToShadowDOM(componentDef);\n shadowRoot.innerHTML += content;\n \n return shadowRoot;\n}\n\n// Extract CSS from component definition\nfunction extractStyles(componentDef) {\n let allStyles = '';\n \n function extractFromElement(element) {\n if (!element || typeof element !== 'object') return;\n \n if (Array.isArray(element)) {\n element.forEach(extractFromElement);\n return;\n }\n \n for (const [tagName, props] of Object.entries(element)) {\n if (tagName === 'style' && typeof props === 'object' && props.text) {\n allStyles += `${props.text }\\n`;\n } else if (typeof props === 'object' && props !== null) {\n if (props.children) {\n extractFromElement(props.children);\n }\n }\n }\n }\n \n extractFromElement(componentDef);\n return allStyles;\n}\n\n// Render component content for Shadow DOM (without style tags)\nfunction renderToShadowDOM(componentDef) {\n function stripStyles(element) {\n if (!element || typeof element !== 'object') return element;\n \n if (Array.isArray(element)) {\n return element.map(stripStyles);\n }\n \n const result = {};\n for (const [tagName, props] of Object.entries(element)) {\n // Skip style elements - they're handled separately\n if (tagName === 'style') continue;\n \n if (typeof props === 'object' && props !== null) {\n const cleanProps = { ...props };\n if (cleanProps.children) {\n cleanProps.children = stripStyles(cleanProps.children);\n }\n result[tagName] = cleanProps;\n } else {\n result[tagName] = props;\n }\n }\n \n return result;\n }\n \n const cleanComponent = stripStyles(componentDef);\n \n // Import renderRaw from main module (avoiding circular deps)\n // This would need to be properly imported in real usage\n return renderComponentContent(cleanComponent);\n}\n\n// Simple DOM-based rendering for Shadow DOM content\nfunction renderComponentContent(obj) {\n if (obj === null || obj === undefined) return '';\n if (typeof obj === 'string' || typeof obj === 'number') {\n return escapeHTML(String(obj));\n }\n if (Array.isArray(obj)) {\n return obj.map(renderComponentContent).join('');\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 \n // Build attributes string\n const attrsStr = Object.entries(attributes)\n .filter(([, value]) => value !== null && value !== undefined && value !== false)\n .map(([key, value]) => {\n const attrName = key === 'className' ? 'class' : key;\n if (value === true) return attrName;\n return `${attrName}=\"${escapeHTML(String(value))}\"`;\n })\n .join(' ');\n \n const openTag = attrsStr ? `<${tagName} ${attrsStr}>` : `<${tagName}>`;\n \n // Handle void elements\n if (['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',\n 'link', 'meta', 'param', 'source', 'track', 'wbr'].includes(tagName)) {\n return openTag.replace('>', ' />');\n }\n \n let content = '';\n if (text !== undefined) {\n content = escapeHTML(String(text));\n } else if (children) {\n content = renderComponentContent(children);\n }\n \n return `${openTag}${content}</${tagName}>`;\n } else if (typeof props === 'string') {\n const content = escapeHTML(props);\n return `<${tagName}>${content}</${tagName}>`;\n }\n }\n\n return '';\n}\n\nfunction escapeHTML(text) {\n if (typeof window === 'undefined' || !window.document) {\n // Server-side fallback\n return String(text)\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n }\n const div = window.document.createElement('div');\n div.textContent = text;\n return div.innerHTML;\n}\n\n// Hybrid rendering: Shadow DOM on client, scoped on server\nexport function renderWithBestEncapsulation(componentDef, containerElement = null) {\n if (isShadowDOMSupported() && containerElement) {\n // Use Shadow DOM for true isolation\n return createShadowComponent(containerElement, componentDef);\n } else {\n // Fallback to scoped rendering\n // This would import from main module in real usage\n console.warn('Shadow DOM not available, falling back to scoped rendering');\n return null; // Would return scoped render result\n }\n}\n\nexport default {\n isShadowDOMSupported,\n createShadowComponent,\n renderWithBestEncapsulation\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 * Component Integration for Coherent.js Event Bus\n *\n * Provides higher-order components and utilities for integrating\n * the event bus with Coherent.js components and state management.\n */\n\nimport { globalEventBus } from './event-bus.js';\nimport { withState } from '../components/component-system.js';\n\n/**\n * Higher-order component that provides event bus integration\n * @param {Object} options - Integration options\n * @returns {Function} HOC function\n */\nexport function withEventBus(options = {}) {\n const {\n scope = null, // Event scope for namespacing\n events = {}, // Event listeners to register\n actions = {}, // Action handlers to register\n eventBus = globalEventBus,\n debug = false,\n autoCleanup = true\n } = options;\n\n return function withEventBusHOC(WrappedComponent) {\n function EventBusComponent(props = {}, state = {}, context = {}) {\n // Create scoped event bus if scope is provided\n const bus = scope ? eventBus.createScope(scope) : eventBus;\n\n // Register event listeners\n const listenerIds = new Map();\n\n Object.entries(events).forEach(([event, handler]) => {\n const listenerId = bus.on(event, (data, eventName) => {\n if (typeof handler === 'function') {\n handler.call(this, data, eventName, {props, state, context});\n }\n });\n listenerIds.set(event, listenerId);\n });\n\n // Register action handlers\n Object.entries(actions).forEach(([action, handler]) => {\n bus.registerAction(action, (actionContext) => {\n if (typeof handler === 'function') {\n handler.call(this, actionContext, {props, state, context});\n }\n });\n });\n\n // Create event bus utilities for the component\n const eventUtils = {\n emit: bus.emit.bind(bus),\n emitSync: bus.emitSync.bind(bus),\n on: bus.on.bind(bus),\n once: bus.once.bind(bus),\n off: bus.off.bind(bus),\n registerAction: bus.registerAction.bind(bus),\n handleAction: bus.handleAction.bind(bus),\n\n // Cleanup function\n cleanup: () => {\n listenerIds.forEach((listenerId, event) => {\n bus.off(event, listenerId);\n });\n listenerIds.clear();\n }\n };\n\n // Enhanced props with event bus\n const enhancedProps = {\n ...props,\n eventBus: bus,\n eventUtils\n };\n\n if (debug) {\n console.log('[withEventBus] Rendering component with event bus:', {\n scope,\n registeredEvents: Object.keys(events),\n registeredActions: Object.keys(actions)\n });\n }\n\n // Render the wrapped component\n const result = typeof WrappedComponent === 'function'\n ? WrappedComponent(enhancedProps, state, context)\n : WrappedComponent;\n\n // Auto-cleanup on unmount (if supported)\n if (autoCleanup && result && typeof result === 'object') {\n // Add cleanup to the component if it supports lifecycle\n if (result.componentWillUnmount) {\n const originalUnmount = result.componentWillUnmount;\n result.componentWillUnmount = function() {\n eventUtils.cleanup();\n originalUnmount.call(this);\n };\n } else {\n result.__eventBusCleanup = eventUtils.cleanup;\n }\n }\n\n return result;\n }\n\n EventBusComponent.displayName = `withEventBus(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`;\n EventBusComponent.__isHOC = true;\n EventBusComponent.__eventBusIntegration = true;\n\n return EventBusComponent;\n };\n}\n\n/**\n * Higher-order component that combines event bus with state management\n * @param {Object} initialState - Initial component state\n * @param {Object} options - Integration options\n * @returns {Function} HOC function\n */\nexport function withEventState(initialState = {}, options = {}) {\n const {\n events = {},\n actions = {},\n stateActions = {}, // Actions that modify state\n eventBus = globalEventBus,\n scope = null,\n debug = false\n } = options;\n\n return function withEventStateHOC(WrappedComponent) {\n // First apply state management\n const StatefulComponent = withState(initialState, {\n actions: stateActions,\n debug\n })(WrappedComponent);\n\n // Then apply event bus integration\n return withEventBus({\n scope,\n events: {\n ...events,\n // Add state-aware event handlers\n ...Object.entries(events).reduce((acc, [event, handler]) => {\n acc[event] = function(data, eventName, context) {\n // Pass state utilities to event handlers\n return handler.call(this, data, eventName, {\n ...context,\n stateUtils: context.props.stateUtils\n });\n };\n return acc;\n }, {})\n },\n actions: {\n ...actions,\n // Add state-aware action handlers\n ...Object.entries(actions).reduce((acc, [action, handler]) => {\n acc[action] = function(actionContext, componentContext) {\n // Pass state utilities to action handlers\n return handler.call(this, actionContext, {\n ...componentContext,\n stateUtils: componentContext.props.stateUtils\n });\n };\n return acc;\n }, {})\n },\n eventBus,\n debug\n })(StatefulComponent);\n };\n}\n\n/**\n * Create action handlers for common patterns\n */\nexport const createActionHandlers = {\n /**\n * Create a modal control action handler\n * @param {string} modalId - Modal identifier\n * @returns {Object} Action handlers for modal control\n */\n modal: (modalId) => ({\n 'open-modal': ({data, emit}) => {\n const targetModalId = data.modalId || modalId;\n emit('modal:open', {modalId: targetModalId});\n },\n 'close-modal': ({data, emit}) => {\n const targetModalId = data.modalId || modalId;\n emit('modal:close', {modalId: targetModalId});\n },\n 'toggle-modal': ({data, emit}) => {\n const targetModalId = data.modalId || modalId;\n emit('modal:toggle', {modalId: targetModalId});\n }\n }),\n\n /**\n * Create form handling action handlers\n * @param {Object} options - Form handling options\n * @returns {Object} Action handlers for forms\n */\n form: (options = {}) => {\n const {\n onSubmit = null,\n onValidate = null,\n onReset = null\n } = options;\n\n return {\n 'submit-form': ({element, emit}) => {\n const formData = extractFormData(element.closest('form'));\n\n if (onValidate) {\n const isValid = onValidate(formData);\n if (!isValid) {\n emit('form:validation-failed', {formData});\n return;\n }\n }\n\n if (onSubmit) {\n onSubmit(formData);\n }\n\n emit('form:submit', {formData, element});\n },\n 'reset-form': ({element, emit}) => {\n const form = element.closest('form');\n if (form) {\n form.reset();\n }\n\n if (onReset) {\n onReset();\n }\n\n emit('form:reset', {element});\n },\n 'validate-form': ({element, emit}) => {\n const formData = extractFormData(element.closest('form'));\n\n if (onValidate) {\n const isValid = onValidate(formData);\n emit('form:validation', {formData, isValid});\n }\n }\n };\n },\n\n /**\n * Create CRUD action handlers\n * @param {Object} options - CRUD options\n * @returns {Object} Action handlers for CRUD operations\n */\n crud: (options = {}) => {\n const {\n entityName = 'item',\n onCreate = null,\n onUpdate = null,\n onDelete = null,\n onRead = null\n } = options;\n\n return {\n [`create-${entityName}`]: ({data, emit}) => {\n if (onCreate) {\n onCreate(data);\n }\n emit(`${entityName}:create`, data);\n },\n [`update-${entityName}`]: ({data, emit}) => {\n if (onUpdate) {\n onUpdate(data);\n }\n emit(`${entityName}:update`, data);\n },\n [`delete-${entityName}`]: ({data, emit}) => {\n if (onDelete) {\n onDelete(data);\n }\n emit(`${entityName}:delete`, data);\n },\n [`read-${entityName}`]: ({data, emit}) => {\n if (onRead) {\n onRead(data);\n }\n emit(`${entityName}:read`, data);\n }\n };\n },\n\n /**\n * Create navigation action handlers\n * @param {Object} options - Navigation options\n * @returns {Object} Action handlers for navigation\n */\n navigation: (options = {}) => {\n const {\n onNavigate = null,\n history = null\n } = options;\n\n return {\n 'navigate-to': ({data, emit}) => {\n const {url, replace = false} = data;\n\n if (history) {\n if (replace) {\n history.replace(url);\n } else {\n history.push(url);\n }\n } else if (typeof window !== 'undefined') {\n if (replace) {\n window.location.replace(url);\n } else {\n window.location.href = url;\n }\n }\n\n if (onNavigate) {\n onNavigate(url, replace);\n }\n\n emit('navigation:change', {url, replace});\n },\n 'navigate-back': ({emit}) => {\n if (history) {\n history.goBack();\n } else if (typeof window !== 'undefined') {\n window.history.back();\n }\n\n emit('navigation:back');\n }\n };\n }\n};\n\n/**\n * Create event handlers for common patterns\n */\nexport const createEventHandlers = {\n /**\n * Create notification event handlers\n * @param {Function} showNotification - Function to show notifications\n * @returns {Object} Event handlers for notifications\n */\n notifications: (showNotification) => ({\n 'notification:show': (data) => {\n showNotification(data);\n },\n 'notification:success': (data) => {\n showNotification({\n type: 'success',\n message: data.message || 'Operation successful',\n ...data\n });\n },\n 'notification:error': (data) => {\n showNotification({\n type: 'error',\n message: data.message || 'An error occurred',\n ...data\n });\n },\n 'notification:warning': (data) => {\n showNotification({\n type: 'warning',\n message: data.message || 'Warning',\n ...data\n });\n },\n 'notification:info': (data) => {\n showNotification({\n type: 'info',\n message: data.message || 'Information',\n ...data\n });\n }\n }),\n\n /**\n * Create loading state event handlers\n * @param {Function} setLoading - Function to set loading state\n * @returns {Object} Event handlers for loading states\n */\n loading: (setLoading) => ({\n 'loading:start': (data) => {\n setLoading(true, data);\n },\n 'loading:stop': (data) => {\n setLoading(false, data);\n },\n 'loading:toggle': (data) => {\n setLoading(current => !current, data);\n }\n })\n};\n\n/**\n * Utility to create a component with built-in event patterns\n * @param {Function} component - Component function\n * @param {Object} options - Configuration options\n * @returns {Function} Enhanced component\n */\nexport function createEventComponent(component, options = {}) {\n const {\n initialState = {},\n scope = null,\n patterns = [], // Array of pattern names: ['modal', 'form', 'crud', 'navigation']\n patternOptions = {}, // Options for each pattern\n customActions = {},\n customEvents = {},\n debug = false\n } = options;\n\n // Build actions from patterns\n let actions = {...customActions};\n patterns.forEach(pattern => {\n const patternActions = createActionHandlers[pattern]?.(patternOptions[pattern] || {});\n if (patternActions) {\n actions = {...actions, ...patternActions};\n }\n });\n\n // Build events from patterns\n let events = {...customEvents};\n patterns.forEach(pattern => {\n const patternEvents = createEventHandlers[pattern]?.(patternOptions[pattern]);\n if (patternEvents) {\n events = {...events, ...patternEvents};\n }\n });\n\n return withEventState(initialState, {\n scope,\n actions,\n events,\n debug\n })(component);\n}\n\n/**\n * Decorator for adding event bus to component methods\n * @param {string} eventName - Event to emit\n * @param {Object} options - Emit options\n * @returns {Function} Method decorator\n */\nexport function emitEvent(eventName, options = {}) {\n const {\n scope = null,\n data = null,\n async = false\n } = options;\n\n return function decorator(target, propertyKey, descriptor) {\n const originalMethod = descriptor.value;\n\n descriptor.value = function(...args) {\n const bus = scope ? globalEventBus.createScope(scope) : globalEventBus;\n\n const result = originalMethod.apply(this, args);\n\n const eventData = typeof data === 'function' ? data(args, result) : data;\n\n if (async) {\n bus.emit(eventName, eventData);\n } else {\n bus.emitSync(eventName, eventData);\n }\n\n return result;\n };\n\n return descriptor;\n };\n}\n\n/**\n * Utility function to extract form data\n * @private\n */\nfunction extractFormData(form) {\n if (!form) return {};\n\n const formData = new FormData(form);\n const data = {};\n\n for (const [key, value] of formData.entries()) {\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\nexport default {\n withEventBus,\n withEventState,\n createActionHandlers,\n createEventHandlers,\n createEventComponent,\n emitEvent\n};", "/**\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 //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AG,QAAO,IAAI,IAAIA,UAAS;AAEhD,QAAM,SAAS,CAAC;AAChB,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,GAAG,GAAG;AAC9C,WAAO,GAAG,IAAIA,WAAU,KAAK;AAAA,EAC/B;AACA,SAAO;AACT;AAGA,IAAM,mBAAmB,KAAK;AAAA,MAC5B,6BAAa,IAAI,IAAI,mBAAmB,YAAY,GAAG,GAAG,OAAO;AACnE;AACO,IAAM,UAAU,iBAAiB;AA0DxC,IAAM,WAAW;AAAA;AAAA,EAEf,QAAAC;AAAA;AAAA,EAGA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA,MAAAC;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA,aAAa;AAAA,EACb;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA,mBAAAC;AAAA,EACA,kBAAAC;AAAA,EACA,WAAAC;AAAA,EACA,YAAAC;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAO,gBAAQ;",
6
- "names": ["deepClone", "isCoherentObject", "memo", "render", "validateComponent", "context", "context", "context", "html", "context", "middleware", "context", "context", "context", "module", "context", "emit", "eventSystem", "escapeHtml", "render", "memo", "validateComponent", "isCoherentObject", "deepClone", "render", "memo", "validateComponent", "isCoherentObject", "deepClone", "escapeHtml"]
3
+ "sources": ["../src/index.js", "../src/performance/monitor.js", "../src/core/object-utils.js", "../src/rendering/base-renderer.js", "../src/core/html-nesting-rules.js", "../src/core/html-utils.js", "../src/performance/cache-manager.js", "../src/utils/error-handler.js", "../src/rendering/html-renderer.js", "../src/components/component-system.js", "../src/components/lifecycle.js", "../src/types/constants.js", "../src/core/object-factory.js", "../src/performance/component-cache.js", "../src/components/error-boundary.js", "../src/utils/render-utils.js", "../src/utils/dependency-utils.js", "../src/shadow-dom.js", "../src/events/event-bus.js", "../src/events/dom-integration.js", "../src/events/component-integration.js", "../src/events/index.js", "../src/components/enhanced-composition.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 1.0.0-beta.7\n * @author Coherent Framework Team\n * @license MIT\n */\n\nimport { readFileSync } from 'node:fs';\n\n// Performance monitoring\nimport { performanceMonitor } from './performance/monitor.js';\n\n// Unified HTML renderer\nimport { render as renderWithHtmlRenderer } from './rendering/html-renderer.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, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#x27;');\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// Hydration attribute injection\nfunction injectHydrationAttributes(component, options) {\n if (!component || typeof component !== 'object' || Array.isArray(component)) {\n return component;\n }\n\n const tagName = Object.keys(component)[0];\n if (!tagName) return component;\n\n const props = component[tagName];\n if (typeof props !== 'object' || props === null) return component;\n\n const injected = { ...props };\n\n if (options.hydratable) {\n injected['data-hydratable'] = 'true';\n }\n\n if (options.island) {\n injected['data-coherent-island'] = 'true';\n }\n\n if (options._islandComponentName) {\n injected['data-coherent-island-component'] = options._islandComponentName;\n }\n\n return { [tagName]: injected };\n}\n\n/**\n * Island wrapper - marks a component for island-based hydration\n * @param {Function} componentFn - A function component to wrap as an island\n * @returns {Function} Wrapped component that renders with island attributes\n */\nexport function Island(componentFn) {\n const componentName = componentFn.name || 'Anonymous';\n\n return function IslandComponent(props) {\n const result = componentFn(props);\n return injectHydrationAttributes(result, {\n island: true,\n _islandComponentName: componentName\n });\n };\n}\n\n// Main rendering function\nexport function render(obj, options = {}) {\n const scoped = options.scoped ?? options.encapsulate ?? false;\n\n const { scoped: _scoped, encapsulate: _encapsulate, hydratable: _hydratable, island: _island, ...rendererOptions } = options;\n\n let component = scoped ? renderScopedComponent(obj) : obj;\n\n // Handle function components passed directly to render\n if (typeof component === 'function') {\n component = component(options);\n }\n\n // Inject hydration attributes if needed\n if (_hydratable || _island) {\n component = injectHydrationAttributes(component, { hydratable: _hydratable, island: _island });\n }\n\n return renderWithHtmlRenderer(component, rendererOptions);\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 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};\n\nexport {\n renderWithMonitoring,\n renderWithTemplate,\n renderComponentFactory,\n isCoherentComponent,\n createErrorResponse\n} from './utils/render-utils.js';\n\nexport {\n isPeerDependencyAvailable,\n importPeerDependency,\n createLazyIntegration,\n checkPeerDependencies\n} from './utils/dependency-utils.js';\n\nexport {\n hasChildren,\n normalizeChildren\n} from './core/object-utils.js';\n\n// HTML nesting validation exports\nexport {\n validateNesting,\n FORBIDDEN_CHILDREN,\n HTMLNestingError\n} from './core/html-nesting-rules.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 if (memoCache.has(key)) {\n return memoCache.get(key);\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\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\nconst _corePackageJson = JSON.parse(\n readFileSync(new URL('../package.json', import.meta.url), 'utf-8')\n);\nexport const VERSION = _corePackageJson.version;\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// Enhanced FP composition tools\nexport { hoc, compose } from './components/enhanced-composition.js';\nimport { hoc, compose } from './components/enhanced-composition.js';\n\n/**\n * Functional programming utilities\n */\nexport const fp = {\n /**\n * Curried map: fp.map(fn)(array)\n */\n map(fn) {\n return (array) => array.map(fn);\n }\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", "/**\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 debounceMs: 5000,\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 debounceMs period)\n if (!lastTriggered || now - lastTriggered > opts.alerts.debounceMs) {\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 * Validate component without throwing - returns { valid: boolean, reason?: string, path?: string }\n * Use this in render contexts where graceful degradation is preferred\n */\nexport function validateComponentGraceful(component, path = 'root') {\n if (component === null || component === undefined) {\n return { valid: false, reason: 'Component is null or undefined', path };\n }\n\n // Allow strings, numbers, booleans as text content\n if (['string', 'number', 'boolean'].includes(typeof component)) {\n return { valid: true };\n }\n\n // Allow functions (will be evaluated during render)\n if (typeof component === 'function') {\n return { valid: true };\n }\n\n // Handle arrays\n if (Array.isArray(component)) {\n for (let i = 0; i < component.length; i++) {\n const result = validateComponentGraceful(component[i], `${path}[${i}]`);\n if (!result.valid) return result;\n }\n return { valid: true };\n }\n\n // Handle objects\n if (typeof component === 'object') {\n const keys = Object.keys(component);\n if (keys.length === 0) {\n return { valid: false, reason: 'Empty object', path };\n }\n return { valid: true };\n }\n\n return { valid: false, reason: `Invalid type: ${typeof component}`, path };\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 * Base Renderer Class\n * Provides common functionality shared across all Coherent.js renderers\n * Reduces code duplication and ensures consistent behavior\n */\n\nimport {\n validateComponent,\n isCoherentObject,\n extractProps,\n hasChildren,\n normalizeChildren,\n} from '../core/object-utils.js';\n\nimport { performanceMonitor } from '../performance/monitor.js';\n\n/**\n * Unified configuration for all Coherent.js renderers\n * Includes options for HTML, Streaming, and DOM renderers\n */\nexport const DEFAULT_RENDERER_CONFIG = {\n // Core rendering options\n maxDepth: 100,\n enableValidation: true,\n enableMonitoring: false,\n validateInput: true,\n\n // HTML Renderer specific options\n enableCache: true,\n minify: false,\n cacheSize: 1000,\n cacheTTL: 300000, // 5 minutes\n\n // Streaming Renderer specific options\n chunkSize: 1024, // Size of each chunk in bytes\n bufferSize: 4096, // Internal buffer size\n enableMetrics: false, // Track streaming metrics\n yieldThreshold: 100, // Yield control after N elements\n encoding: 'utf8', // Output encoding\n\n // DOM Renderer specific options\n enableHydration: true, // Enable hydration support\n namespace: null, // SVG namespace support\n\n // Performance options\n enablePerformanceTracking: false,\n performanceThreshold: 10, // ms threshold for slow renders\n\n // Development options\n enableDevWarnings: typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'development',\n enableDebugLogging: false,\n\n // Error handling options\n errorFallback: '', // Fallback content on errors\n throwOnError: true, // Whether to throw or return fallback\n};\n\n/**\n * Base renderer class with common functionality\n */\nexport class BaseRenderer {\n constructor(options = {}) {\n this.config = this.validateAndMergeConfig(options);\n this.metrics = {\n startTime: null,\n endTime: null,\n elementsProcessed: 0\n };\n }\n\n /**\n * Validate and merge configuration options\n */\n validateAndMergeConfig(options) {\n const config = { ...DEFAULT_RENDERER_CONFIG, ...options };\n \n // Validate critical options\n if (typeof config.maxDepth !== 'number') {\n throw new Error('maxDepth must be a number');\n }\n if (config.maxDepth <= 0) {\n throw new Error('maxDepth must be a positive number');\n }\n \n if (typeof config.chunkSize !== 'number') {\n throw new Error('chunkSize must be a number');\n }\n if (config.chunkSize <= 0) {\n throw new Error('chunkSize must be a positive number');\n }\n \n if (typeof config.yieldThreshold !== 'number') {\n throw new Error('yieldThreshold must be a number');\n }\n if (config.yieldThreshold <= 0) {\n throw new Error('yieldThreshold must be a positive number');\n }\n \n // Warn about potentially problematic configurations\n if (config.enableDevWarnings) {\n if (config.maxDepth > 1000) {\n console.warn('Coherent.js: maxDepth > 1000 may cause performance issues');\n }\n \n if (config.chunkSize > 16384) {\n console.warn('Coherent.js: Large chunkSize may increase memory usage');\n }\n }\n \n return config;\n }\n\n /**\n * Get configuration for specific renderer type\n */\n getRendererConfig(rendererType) {\n const baseConfig = { ...this.config };\n \n switch (rendererType) {\n case 'html':\n return {\n ...baseConfig,\n // HTML-specific defaults\n enableCache: baseConfig.enableCache !== false,\n enableMonitoring: baseConfig.enableMonitoring !== false\n };\n \n case 'streaming':\n return {\n ...baseConfig,\n // Streaming-specific defaults\n enableMetrics: baseConfig.enableMetrics ?? false,\n maxDepth: baseConfig.maxDepth ?? 1000 // Higher default for streaming\n };\n \n case 'dom':\n return {\n ...baseConfig,\n // DOM-specific defaults\n enableHydration: baseConfig.enableHydration !== false\n };\n \n default:\n return baseConfig;\n }\n }\n\n /**\n * Validate component structure\n */\n validateComponent(component) {\n if (this.config.validateInput !== false) {\n return validateComponent(component);\n }\n return true;\n }\n\n /**\n * Check if component is valid for rendering\n */\n isValidComponent(component) {\n if (component === null || component === undefined) return true;\n if (typeof component === 'string' || typeof component === 'number') return true;\n if (typeof component === 'function') return true;\n if (Array.isArray(component)) return component.every(child => this.isValidComponent(child));\n if (isCoherentObject(component)) return true;\n return false;\n }\n\n /**\n * Validate rendering depth to prevent stack overflow\n */\n validateDepth(depth) {\n if (depth > this.config.maxDepth) {\n throw new Error(`Maximum render depth (${this.config.maxDepth}) exceeded`);\n }\n }\n\n /**\n * Handle different component types with consistent logic\n */\n processComponentType(component) {\n // Null/undefined\n if (component === null || component === undefined) {\n return { type: 'empty', value: '' };\n }\n\n // String\n if (typeof component === 'string') {\n return { type: 'text', value: component };\n }\n\n // Number/Boolean\n if (typeof component === 'number' || typeof component === 'boolean') {\n return { type: 'text', value: String(component) };\n }\n\n // Function\n if (typeof component === 'function') {\n return { type: 'function', value: component };\n }\n\n // Array\n if (Array.isArray(component)) {\n return { type: 'array', value: component };\n }\n\n // Object (Coherent element)\n if (isCoherentObject(component)) {\n return { type: 'element', value: component };\n }\n\n // Unknown type\n return { type: 'unknown', value: component };\n }\n\n /**\n * Execute function components with _error handling\n */\n executeFunctionComponent(func, depth = 0) {\n try {\n // Check if this is a context provider by checking function arity or a marker\n const isContextProvider = func.length > 0 || func.isContextProvider;\n \n let result;\n if (isContextProvider) {\n // Call with render function for context providers\n result = func((children) => {\n return this.renderComponent(children, this.config, depth + 1);\n });\n } else {\n // Regular function component\n result = func();\n }\n \n // Handle case where function returns another function\n if (typeof result === 'function') {\n return this.executeFunctionComponent(result, depth);\n }\n \n return result;\n } catch (_error) {\n if (this.config.enableMonitoring) {\n performanceMonitor.recordError('functionComponent', _error);\n }\n \n // In development, provide detailed _error info\n if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'development') {\n console.warn('Coherent.js Function Component Error:', _error.message);\n }\n \n return null;\n }\n }\n\n /**\n * Process element children consistently\n */\n processChildren(children, options, depth) {\n if (!hasChildren({ children })) {\n return [];\n }\n\n const normalizedChildren = normalizeChildren(children);\n return normalizedChildren.map(child => \n this.renderComponent(child, options, depth + 1)\n );\n }\n\n /**\n * Extract and process element attributes\n */\n extractElementAttributes(props) {\n if (!props || typeof props !== 'object') return {};\n\n const attributes = { ...props };\n delete attributes.children;\n delete attributes.text;\n return attributes;\n }\n\n /**\n * Record performance metrics\n */\n recordPerformance(operation, startTime, fromCache = false, metadata = {}) {\n if (this.config.enableMonitoring) {\n performanceMonitor.recordRender(\n operation,\n this.getCurrentTime() - startTime,\n fromCache,\n metadata\n );\n }\n }\n\n /**\n * Record _error for monitoring\n */\n recordError(operation, _error, metadata = {}) {\n if (this.config.enableMonitoring) {\n performanceMonitor.recordError(operation, _error, metadata);\n }\n }\n\n /**\n * Get current timestamp with fallback\n */\n getCurrentTime() {\n if (typeof performance !== 'undefined' && performance.now) {\n return performance.now();\n }\n return Date.now();\n }\n\n /**\n * Start performance timing\n */\n startTiming() {\n this.metrics.startTime = this.getCurrentTime();\n }\n\n /**\n * End performance timing\n */\n endTiming() {\n this.metrics.endTime = this.getCurrentTime();\n }\n\n /**\n * Get performance metrics\n */\n getMetrics() {\n const duration = this.metrics.endTime ? \n this.metrics.endTime - this.metrics.startTime :\n this.getCurrentTime() - this.metrics.startTime;\n\n return {\n ...this.metrics,\n duration,\n elementsPerSecond: this.metrics.elementsProcessed / (duration / 1000)\n };\n }\n\n /**\n * Reset metrics for new render\n */\n resetMetrics() {\n this.metrics = {\n startTime: null,\n endTime: null,\n elementsProcessed: 0\n };\n }\n\n /**\n * Abstract method - must be implemented by subclasses\n */\n renderComponent() {\n throw new Error('renderComponent must be implemented by subclass');\n }\n\n /**\n * Abstract method - must be implemented by subclasses\n */\n render() {\n throw new Error('render must be implemented by subclass');\n }\n}\n\n/**\n * Utility functions for renderer implementations\n */\nexport const RendererUtils = {\n /**\n * Check if element is static (no functions or circular references)\n */\n isStaticElement(element, visited = new WeakSet()) {\n if (!element || typeof element !== 'object') {\n return typeof element === 'string' || typeof element === 'number';\n }\n\n // Handle circular references - treat as non-static (will be caught during render)\n if (visited.has(element)) {\n return false;\n }\n visited.add(element);\n\n // Check if element has any dynamic content\n for (const [_key, value] of Object.entries(element)) {\n if (typeof value === 'function') return false;\n\n // Recursively check arrays (including children)\n if (Array.isArray(value)) {\n const allStatic = value.every(child => RendererUtils.isStaticElement(child, visited));\n if (!allStatic) return false;\n }\n // Recursively check nested objects\n else if (typeof value === 'object' && value !== null) {\n if (!RendererUtils.isStaticElement(value, visited)) return false;\n }\n }\n\n return true;\n },\n\n /**\n * Check if object has functions (for caching decisions)\n */\n hasFunctions(obj, visited = new WeakSet()) {\n if (visited.has(obj)) return false;\n visited.add(obj);\n\n for (const value of Object.values(obj)) {\n if (typeof value === 'function') return true;\n if (typeof value === 'object' && value !== null && RendererUtils.hasFunctions(value, visited)) {\n return true;\n }\n }\n return false;\n },\n\n /**\n * Get element complexity score\n */\n getElementComplexity(element) {\n if (!element || typeof element !== 'object') return 1;\n\n let complexity = Object.keys(element).length;\n\n if (element.children && Array.isArray(element.children)) {\n complexity += element.children.reduce(\n (sum, child) => sum + RendererUtils.getElementComplexity(child),\n 0\n );\n }\n\n return complexity;\n },\n\n /**\n * Generate cache key for element\n */\n generateCacheKey(tagName, element) {\n try {\n // Create a stable cache key for the element\n const keyData = {\n tag: tagName,\n props: extractProps(element),\n hasChildren: hasChildren(element),\n childrenType: Array.isArray(element.children) ? 'array' : typeof element.children\n };\n\n return `element:${JSON.stringify(keyData)}`;\n } catch (_error) {\n // Log _error in development mode\n if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'development') {\n console.warn('Failed to generate cache key:', _error);\n }\n // Return null to indicate uncacheable element\n return null;\n }\n },\n\n /**\n * Check if element is cacheable\n */\n isCacheable(element, options) {\n // Don't cache if caching is disabled\n if (!options.enableCache) return false;\n\n // Don't cache elements with functions (dynamic content)\n if (RendererUtils.hasFunctions(element)) return false;\n\n // Don't cache very large elements (memory consideration)\n if (RendererUtils.getElementComplexity(element) > 1000) return false;\n\n // Don't cache if we can't generate a stable cache key\n const cacheKey = RendererUtils.generateCacheKey(element.tagName || 'unknown', element);\n if (!cacheKey) return false;\n\n return true;\n }\n};\n\nexport default BaseRenderer;\n", "/**\n * HTML Nesting Validation Rules\n * Prevents invalid HTML structures that browsers will auto-correct,\n * which causes hydration mismatches between server and client.\n */\n\n/**\n * Map of parent tags to their forbidden child tags.\n * Based on HTML spec content model rules.\n * See: https://html.spec.whatwg.org/multipage/dom.html#content-models\n */\nexport const FORBIDDEN_CHILDREN = {\n // Phrasing content only - cannot contain flow content\n p: new Set([\n 'address', 'article', 'aside', 'blockquote', 'div', 'dl',\n 'fieldset', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',\n 'header', 'hr', 'main', 'nav', 'ol', 'p', 'pre', 'section',\n 'table', 'ul', 'figure', 'figcaption'\n ]),\n // Interactive content restrictions\n a: new Set(['a']), // Links cannot nest\n button: new Set(['button', 'a', 'input', 'select', 'textarea', 'label']),\n label: new Set(['label']),\n // Table structure restrictions\n thead: new Set(['thead', 'tbody', 'tfoot', 'caption', 'colgroup', 'tr']),\n tbody: new Set(['thead', 'tbody', 'tfoot', 'caption', 'colgroup']),\n tfoot: new Set(['thead', 'tbody', 'tfoot', 'caption', 'colgroup']),\n tr: new Set(['tr', 'thead', 'tbody', 'tfoot', 'table']),\n td: new Set(['td', 'th', 'tr', 'thead', 'tbody', 'tfoot', 'table']),\n th: new Set(['td', 'th', 'tr', 'thead', 'tbody', 'tfoot', 'table']),\n // Other common restrictions\n select: new Set(['select', 'input', 'textarea']),\n option: new Set(['option', 'optgroup']),\n};\n\n/**\n * Validate that a child tag is allowed inside a parent tag.\n *\n * @param {string} parentTag - The parent element tag name\n * @param {string} childTag - The child element tag name\n * @param {string} path - The render path for error reporting\n * @param {Object} options - Validation options\n * @param {boolean} options.warn - Whether to emit console warnings (default: true in dev)\n * @param {boolean} options.throwOnError - Whether to throw instead of warn (default: false)\n * @returns {boolean} True if nesting is valid, false otherwise\n */\nexport function validateNesting(parentTag, childTag, path = '', options = {}) {\n if (!parentTag || !childTag) {\n return true; // Can't validate without both tags\n }\n\n const parent = parentTag.toLowerCase();\n const child = childTag.toLowerCase();\n\n const forbidden = FORBIDDEN_CHILDREN[parent];\n if (!forbidden || !forbidden.has(child)) {\n return true; // Nesting is valid\n }\n\n // Invalid nesting detected\n const pathSuffix = path ? ` at ${path}` : '';\n const message = `Invalid HTML nesting: <${child}> cannot be a child of <${parent}>${pathSuffix}. Browsers will auto-correct this, causing potential hydration mismatches.`;\n\n if (options.throwOnError) {\n throw new HTMLNestingError(message, { parent, child, path });\n }\n\n // Only warn in development mode by default\n const shouldWarn = options.warn !== false &&\n (typeof process === 'undefined' ||\n !process.env ||\n process.env.NODE_ENV !== 'production');\n\n if (shouldWarn) {\n console.warn(`[Coherent.js] ${message}`);\n }\n\n return false;\n}\n\n/**\n * Custom error class for HTML nesting violations\n */\nexport class HTMLNestingError extends Error {\n constructor(message, context = {}) {\n super(message);\n this.name = 'HTMLNestingError';\n this.parent = context.parent;\n this.child = context.child;\n this.path = context.path;\n }\n}\n\n/**\n * Check if a tag is a void element (self-closing, no children allowed)\n * Useful for validation - void elements can't have invalid children\n */\nexport const VOID_ELEMENTS = new Set([\n 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',\n 'link', 'meta', 'param', 'source', 'track', 'wbr'\n]);\n\nexport function isVoidElement(tagName) {\n return VOID_ELEMENTS.has(tagName?.toLowerCase());\n}\n", "/**\n * HTML-specific utility functions\n */\n\nexport function escapeHtml(text) {\n if (typeof text !== 'string') return text;\n\n return text\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n}\n\nexport function unescapeHtml(text) {\n if (typeof text !== 'string') return text;\n\n return text\n .replace(/&quot;/g, '\"')\n .replace(/&#39;/g, \"'\")\n .replace(/&gt;/g, '>')\n .replace(/&lt;/g, '<')\n .replace(/&amp;/g, '&');\n}\n\nexport function isVoidElement(tagName) {\n // Ensure tagName is a string before processing\n if (typeof tagName !== 'string') {\n return false;\n }\n\n const voidElements = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n ]);\n return voidElements.has(tagName.toLowerCase());\n}\n\nexport function formatAttributes(props) {\n let formatted = '';\n for (const key in props) {\n if (props.hasOwnProperty(key)) {\n let value = props[key];\n\n // Convert className to class for HTML output\n const attributeName = key === 'className' ? 'class' : key;\n\n // Handle function values - for event handlers, use data-action attributes\n if (typeof value === 'function') {\n // Check if this is an event handler (starts with 'on')\n if (attributeName.startsWith('on')) {\n // For event handlers, create a unique action identifier\n const actionId = `__coherent_action_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n const DEBUG = (typeof process !== 'undefined' && process && process.env && (process.env.COHERENT_DEBUG === '1' || process.env.NODE_ENV === 'development'))\n || (typeof window !== 'undefined' && window && window.COHERENT_DEBUG === true);\n \n // Store the function in a global registry that will be available during hydration\n // Check if we're in Node.js or browser environment\n if (typeof global !== 'undefined') {\n // Server-side, store in global for hydration\n if (!global.__coherentActionRegistry) {\n global.__coherentActionRegistry = {};\n if (DEBUG) console.log('Initialized global action registry');\n }\n global.__coherentActionRegistry[actionId] = value;\n if (DEBUG) console.log(`Added action ${actionId} to global registry, total: ${Object.keys(global.__coherentActionRegistry).length}`);\n if (DEBUG) console.log(`Global registry keys: ${Object.keys(global.__coherentActionRegistry).join(', ')}`);\n \n // Log the global object to see if it's being reset\n if (DEBUG) {\n if (typeof global.__coherentActionRegistryLog === 'undefined') {\n global.__coherentActionRegistryLog = [];\n }\n global.__coherentActionRegistryLog.push({\n action: 'add',\n actionId: actionId,\n timestamp: Date.now(),\n registrySize: Object.keys(global.__coherentActionRegistry).length\n });\n }\n } else if (typeof window !== 'undefined') {\n // Browser-side, store in window\n if (!window.__coherentActionRegistry) {\n window.__coherentActionRegistry = {};\n if (DEBUG) console.log('Initialized window action registry');\n }\n window.__coherentActionRegistry[actionId] = value;\n if (DEBUG) console.log(`Added action ${actionId} to window registry, total: ${Object.keys(window.__coherentActionRegistry).length}`);\n if (DEBUG) console.log(`Window registry keys: ${Object.keys(window.__coherentActionRegistry).join(', ')}`);\n }\n \n // Use data-action and data-event attributes instead of inline JS\n const eventType = attributeName.substring(2); // Remove 'on' prefix\n formatted += ` data-action=\"${actionId}\" data-event=\"${eventType}\"`;\n continue; // Skip normal processing\n } else {\n // For other function attributes, call them to get the value\n try {\n value = value();\n } catch (_error) {\n console.warn(`Error executing function for attribute '${key}':`, {\n _error: _error.message,\n stack: _error.stack,\n attributeKey: key,\n });\n // Consider different fallback strategies based on attribute type\n value = '';\n }\n }\n }\n\n // Handle style objects by converting to CSS string\n if (attributeName === 'style' && typeof value === 'object' && value !== null) {\n const cssString = Object.entries(value)\n .map(([prop, val]) => {\n // Convert camelCase to kebab-case\n const kebabProp = prop.replace(/[A-Z]/g, m => `-${m.toLowerCase()}`);\n return `${kebabProp}: ${val}`;\n })\n .join('; ');\n formatted += ` ${attributeName}=\"${escapeHtml(cssString)}\"`;\n } else if (value === true) {\n formatted += ` ${attributeName}`;\n } else if (value !== false && value !== null && value !== undefined) {\n formatted += ` ${attributeName}=\"${escapeHtml(String(value))}\"`;\n }\n }\n }\n return formatted.trim();\n}\n\nexport function minifyHtml(html, options = {}) {\n if (!options.minify) return html;\n\n return (\n html\n // Remove comments\n .replace(/<!--[\\s\\S]*?-->/g, '')\n // Remove extra whitespace\n .replace(/\\s+/g, ' ')\n // Remove whitespace around tags\n .replace(/>\\s+</g, '><')\n // Remove leading/trailing whitespace\n .trim()\n );\n}\n\n/**\n * HTML Void Elements - elements that cannot have children\n * These elements are self-closing and don't need closing tags\n */\nexport const voidElements = new Set([\n 'area',\n 'base',\n 'br',\n 'col',\n 'embed',\n 'hr',\n 'img',\n 'input',\n 'link',\n 'meta',\n 'param',\n 'source',\n 'track',\n 'wbr',\n]);\n", "/**\n * Advanced caching system with memory management and smart invalidation for Coherent.js\n * \n * @module @coherent/performance/cache-manager\n * @license MIT\n */\n\n/**\n * @typedef {Object} CacheEntry\n * @property {any} value - The cached value\n * @property {number} timestamp - When the entry was created\n * @property {number} lastAccess - Last access time\n * @property {number} size - Approximate size in bytes\n * @property {Object} metadata - Additional metadata\n * @property {number} accessCount - Number of times accessed\n */\n\n/**\n * @typedef {Object} CacheStats\n * @property {number} hits - Number of cache hits\n * @property {number} misses - Number of cache misses\n * @property {number} size - Current cache size in bytes\n * @property {number} entries - Number of cache entries\n * @property {Record<string, number>} hitRate - Hit rate by cache type\n */\n\n/**\n * @typedef {Object} CacheOptions\n * @property {number} [maxCacheSize=1000] - Maximum number of entries per cache type\n * @property {number} [maxMemoryMB=100] - Maximum memory usage in MB\n * @property {number} [ttlMs=300000] - Default time-to-live in milliseconds (5 minutes)\n * @property {boolean} [enableStatistics=true] - Whether to collect usage statistics\n */\n\n/**\n * Creates a new CacheManager instance\n * @param {CacheOptions} [options] - Configuration options\n * @returns {Object} Cache manager instance\n */\nexport function createCacheManager(options = {}) {\n const {\n maxCacheSize = 1000,\n maxMemoryMB = 100,\n ttlMs = 1000 * 60 * 5, // 5 minutes\n enableStatistics = true\n } = options;\n\n // Internal state\n const caches = {\n static: new Map(), // Never-changing components\n component: new Map(), // Component results with deps\n template: new Map(), // Template strings\n data: new Map() // General purpose data\n };\n\n let memoryUsage = 0;\n const stats = {\n hits: 0,\n misses: 0,\n hitRate: {\n static: 0,\n component: 0,\n template: 0,\n data: 0\n },\n accessCount: {\n static: 0,\n component: 0,\n template: 0,\n data: 0\n }\n };\n\n // Cleanup interval (doesn't keep Node.js process alive)\n let cleanupInterval;\n if (typeof setInterval === 'function') {\n cleanupInterval = setInterval(() => cleanup(), 30000);\n if (cleanupInterval.unref) {\n cleanupInterval.unref();\n }\n }\n\n /**\n * Generate a cache key from component and props\n * @param {any} component - Component or component name\n * @param {Object} [props={}] - Component props\n * @param {Object} [context={}] - Additional context\n * @returns {string} Cache key\n */\n function generateCacheKey(component, props = {}, context = {}) {\n const componentStr = typeof component === 'function'\n ? component.name || component.toString()\n : JSON.stringify(component);\n\n const propsStr = JSON.stringify(props, Object.keys(props).sort());\n const contextStr = JSON.stringify(context);\n const hash = simpleHash(componentStr + propsStr + contextStr);\n \n return `${extractComponentName(component)}_${hash}`;\n }\n\n /**\n * Get a value from the cache\n * @param {string} key - Cache key\n * @param {string} [type='component'] - Cache type\n * @returns {any|null} Cached value or null if not found\n */\n function get(key, type = 'component') {\n const cache = caches[type] || caches.component;\n const entry = cache.get(key);\n\n if (!entry) {\n stats.misses++;\n if (enableStatistics) stats.accessCount[type]++;\n return null;\n }\n\n // Check TTL\n if (Date.now() - entry.timestamp > ttlMs) {\n cache.delete(key);\n updateMemoryUsage(-entry.size);\n stats.misses++;\n if (enableStatistics) stats.accessCount[type]++;\n return null;\n }\n\n // Update access time and stats\n entry.lastAccess = Date.now();\n entry.accessCount++;\n stats.hits++;\n if (enableStatistics) {\n stats.accessCount[type]++;\n stats.hitRate[type] = (stats.hits / (stats.hits + stats.misses)) * 100;\n }\n\n return entry.value;\n }\n\n /**\n * Store a value in the cache\n * @param {string} key - Cache key\n * @param {any} value - Value to cache\n * @param {string} [type='component'] - Cache type\n * @param {Object} [metadata={}] - Additional metadata\n */\n function set(key, value, type = 'component', metadata = {}) {\n const cache = caches[type] || caches.component;\n const size = calculateSize(value);\n\n // Check memory limits\n if (memoryUsage + size > maxMemoryMB * 1024 * 1024) {\n optimize(type, size);\n }\n\n const entry = {\n value,\n timestamp: Date.now(),\n lastAccess: Date.now(),\n size,\n metadata,\n accessCount: 0\n };\n\n // Remove existing entry if it exists\n const existing = cache.get(key);\n if (existing) {\n updateMemoryUsage(-existing.size);\n }\n\n cache.set(key, entry);\n updateMemoryUsage(size);\n\n // Enforce cache size limits\n if (cache.size > maxCacheSize) {\n optimize(type);\n }\n }\n\n /**\n * Remove an entry from the cache\n * @param {string} key - Cache key\n * @param {string} [type] - Cache type (optional, checks all caches if not provided)\n * @returns {boolean} True if an entry was removed\n */\n function remove(key, type) {\n if (type) {\n const cache = caches[type];\n if (!cache) return false;\n \n const entry = cache.get(key);\n if (entry) {\n updateMemoryUsage(-entry.size);\n return cache.delete(key);\n }\n return false;\n }\n\n // Check all caches if no type specified\n for (const [, cache] of Object.entries(caches)) {\n const entry = cache.get(key);\n if (entry) {\n updateMemoryUsage(-entry.size);\n return cache.delete(key);\n }\n }\n return false;\n }\n\n /**\n * Clear all caches or a specific cache type\n * @param {string} [type] - Cache type to clear (optional, clears all if not provided)\n */\n function clear(type) {\n if (type) {\n const cache = caches[type];\n if (cache) {\n cache.clear();\n }\n } else {\n Object.values(caches).forEach(cache => cache.clear());\n }\n memoryUsage = 0;\n }\n\n /**\n * Get cache statistics\n * @returns {CacheStats} Cache statistics\n */\n function getStats() {\n const entries = Object.values(caches).reduce((sum, cache) => sum + cache.size, 0);\n \n return {\n hits: stats.hits,\n misses: stats.misses,\n size: memoryUsage,\n entries,\n hitRate: stats.hitRate,\n accessCount: stats.accessCount\n };\n }\n\n /**\n * Clean up expired entries\n */\n function cleanup() {\n const now = Date.now();\n let freed = 0;\n\n for (const [, cache] of Object.entries(caches)) {\n for (const [key, entry] of cache.entries()) {\n if (now - entry.timestamp > ttlMs) {\n cache.delete(key);\n updateMemoryUsage(-entry.size);\n freed++;\n }\n }\n }\n\n return { freed };\n }\n\n // Internal helper functions\n function calculateSize(value) {\n if (value === null || value === undefined) return 0;\n if (typeof value === 'string') return value.length * 2; // UTF-16\n if (typeof value === 'number') return 8; // 64-bit float\n if (typeof value === 'boolean') return 4;\n if (Array.isArray(value)) {\n return value.reduce((sum, item) => sum + calculateSize(item), 0);\n }\n if (typeof value === 'object') {\n return Object.values(value).reduce((sum, val) => sum + calculateSize(val), 0);\n }\n return 0;\n }\n\n function updateMemoryUsage(delta) {\n memoryUsage = Math.max(0, memoryUsage + delta);\n }\n\n function optimize(type, requiredSpace = 0) {\n const cache = caches[type] || caches.component;\n const entries = Array.from(cache.entries())\n .sort(([, a], [, b]) => a.lastAccess - b.lastAccess);\n\n let freed = 0;\n for (const [key, entry] of entries) {\n if (freed >= requiredSpace) break;\n \n cache.delete(key);\n updateMemoryUsage(-entry.size);\n freed += entry.size;\n }\n\n return { freed };\n }\n\n function simpleHash(str) {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i);\n hash = ((hash << 5) - hash) + char;\n hash = hash & hash; // Convert to 32-bit integer\n }\n return Math.abs(hash).toString(36);\n }\n\n function extractComponentName(component) {\n if (typeof component === 'function') {\n return component.name || 'AnonymousComponent';\n }\n if (component && typeof component === 'object') {\n const keys = Object.keys(component);\n return keys.length > 0 ? keys[0] : 'ObjectComponent';\n }\n return 'UnknownComponent';\n }\n\n // Clean up on destroy\n function destroy() {\n if (cleanupInterval) {\n clearInterval(cleanupInterval);\n }\n clear();\n }\n\n // Public API\n function hashObject(obj) {\n return simpleHash(JSON.stringify(obj));\n }\n\n return {\n get,\n set,\n remove,\n clear,\n getStats,\n cleanup,\n destroy,\n generateCacheKey,\n hashObject,\n get memoryUsage() {\n return memoryUsage;\n },\n get maxMemory() {\n return maxMemoryMB * 1024 * 1024;\n }\n };\n}\n\n// Create a default instance for convenience\nexport const cacheManager = createCacheManager();\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.code = options.code || `COHERENT_${String(this.type).toUpperCase()}`;\n this.docsUrl = options.docsUrl || `/docs/core/errors#${this.code}`;\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 code: this.code,\n docsUrl: this.docsUrl,\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 // Add renderPath for debugging if available in context\n if (context && context.path) {\n this.renderPath = context.path;\n }\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 const isDev = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'development';\n const envForceSilent = typeof process !== 'undefined' && process.env && process.env.COHERENT_SILENT === '1';\n const envForceDebug = typeof process !== 'undefined' && process.env && process.env.COHERENT_DEBUG === '1';\n const defaultEnableLogging = envForceSilent ? false : (envForceDebug ? true : isDev);\n\n this.options = {\n enableStackTrace: options.enableStackTrace !== false,\n enableSuggestions: options.enableSuggestions !== false,\n enableLogging: options.enableLogging ?? defaultEnableLogging,\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 if (_error.code) {\n console.log('\uD83C\uDFF7\uFE0F Code:', _error.code);\n }\n\n if (_error.docsUrl) {\n console.log('\uD83D\uDCD6 Docs:', _error.docsUrl);\n }\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 if (_error.context && typeof _error.context === 'object' && _error.context.path) {\n console.log('\uD83D\uDCCD Path:', _error.context.path);\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", "/**\n * High-performance HTML renderer with caching, monitoring, and streaming support\n * Converts object-based components to HTML strings with advanced optimizations\n */\n\nimport { BaseRenderer, RendererUtils } from './base-renderer.js';\nimport {\n hasChildren,\n normalizeChildren,\n} from '../core/object-utils.js';\n\nimport { validateNesting } from '../core/html-nesting-rules.js';\n\nimport {\n escapeHtml,\n isVoidElement,\n formatAttributes,\n minifyHtml\n} from '../core/html-utils.js';\n\nimport { performanceMonitor } from '../performance/monitor.js';\nimport { createCacheManager } from '../performance/cache-manager.js';\nimport { cssUtils, defaultCSSManager } from './css-manager.js';\nimport { CoherentError, RenderingError, globalErrorHandler } from '../utils/error-handler.js';\n\n// Create a global cache instance for the renderer\nconst rendererCache = createCacheManager({\n maxSize: 1000,\n ttlMs: 300000 // 5 minutes\n});\n\nfunction formatRenderPath(path) {\n if (!path || path.length === 0) return 'root';\n\n let rendered = 'root';\n for (const segment of path) {\n if (typeof segment !== 'string' || segment.length === 0) continue;\n if (segment.startsWith('[')) {\n rendered += segment;\n } else {\n rendered += `.${segment}`;\n }\n }\n return rendered;\n}\n\n/**\n * HTML Renderer Class extending BaseRenderer\n *\n * @class HTMLRenderer\n * @extends BaseRenderer\n * @description High-performance HTML renderer with caching, monitoring, and streaming support.\n * Converts object-based components to HTML strings with advanced optimizations.\n *\n * @param {Object} [options={}] - Renderer configuration options\n * @param {boolean} [options.enableCache=true] - Enable component caching\n * @param {boolean} [options.enableMonitoring=true] - Enable performance monitoring\n * @param {boolean} [options.minify=false] - Enable HTML minification\n * @param {boolean} [options.streaming=false] - Enable streaming mode\n * @param {number} [options.maxDepth=100] - Maximum rendering depth\n * @param {number} [options.cacheSize=1000] - Cache size limit\n * @param {number} [options.cacheTTL=300000] - Cache TTL in milliseconds\n *\n * @example\n * const renderer = new HTMLRenderer({\n * enableCache: true,\n * enableMonitoring: true,\n * minify: true\n * });\n *\n * const html = renderer.render({ div: { text: 'Hello World' } });\n */\nclass HTMLRenderer extends BaseRenderer {\n constructor(options = {}) {\n super({\n enableCache: options.enableCache !== false,\n enableMonitoring: options.enableMonitoring !== false,\n minify: options.minify || false,\n streaming: options.streaming || false,\n maxDepth: options.maxDepth || 100,\n ...options\n });\n\n // Initialize cache if enabled\n if (this.config.enableCache && !this.cache) {\n this.cache = rendererCache;\n }\n }\n\n /**\n * Main render method - converts components to HTML string\n *\n * @param {Object|Array|string|Function} component - Component to render\n * @param {Object} [options={}] - Rendering options\n * @param {Object} [options.context] - Rendering context\n * @param {boolean} [options.enableCache] - Override cache setting\n * @param {number} [options.depth=0] - Current rendering depth\n * @returns {string} Rendered HTML string\n *\n * @example\n * const html = renderer.render({\n * div: {\n * className: 'container',\n * children: [\n * { h1: { text: 'Title' } },\n * { p: { text: 'Content' } }\n * ]\n * }\n * });\n */\n render(component, options = {}) {\n const config = { ...this.config, ...options };\n this.startTiming();\n\n try {\n // Input validation\n if (config.validateInput && !this.isValidComponent(component)) {\n throw new Error('Invalid component structure');\n }\n\n // Initialize seenObjects for circular reference detection\n const renderOptions = {\n ...config,\n seenObjects: new WeakSet()\n };\n\n // Main rendering logic\n const html = this.renderComponent(component, renderOptions, 0, []);\n const finalHtml = config.minify ? minifyHtml(html, config) : html;\n\n // Performance monitoring\n this.endTiming();\n this.recordPerformance('render', this.metrics.startTime, false, {\n cacheEnabled: config.enableCache\n });\n\n return finalHtml;\n\n } catch (_error) {\n this.recordError('render', _error);\n const enhancedError = globalErrorHandler.handle(_error, {\n renderContext: { path: 'root', renderer: 'html' }\n });\n\n if (config.throwOnError === false) {\n return config.errorFallback;\n }\n\n throw enhancedError;\n }\n }\n\n /**\n * Render a single component with full optimization pipeline\n */\n renderComponent(component, options, depth = 0, path = []) {\n // Handle nullish and empty inputs immediately\n if (component === null || component === undefined) {\n return '';\n }\n if (Array.isArray(component) && component.length === 0) {\n return '';\n }\n\n // Detect circular references (objects only)\n if (typeof component === 'object' && component !== null && !Array.isArray(component)) {\n if (options.seenObjects && options.seenObjects.has(component)) {\n throw new RenderingError(\n 'Circular reference detected in component tree',\n component,\n { path: formatRenderPath(path) },\n ['Remove the circular reference', 'Use lazy loading to break the cycle']\n );\n }\n if (options.seenObjects) {\n options.seenObjects.add(component);\n }\n }\n\n // Use base class depth validation\n this.validateDepth(depth);\n\n try {\n // Use base class component type processing\n const { type, value } = this.processComponentType(component);\n\n switch (type) {\n case 'empty':\n return '';\n case 'text':\n return escapeHtml(value);\n case 'function':\n {\n const result = this.executeFunctionComponent(value, depth);\n return this.renderComponent(result, options, depth + 1, [...path, '()']);\n }\n case 'array':\n // Development mode warning for missing keys\n if (typeof process !== 'undefined' &&\n process.env &&\n process.env.NODE_ENV !== 'production' &&\n value.length > 1) {\n\n const missingKeyCount = value.filter((child) => {\n if (child && typeof child === 'object' && !Array.isArray(child)) {\n const tagName = Object.keys(child)[0];\n const props = child[tagName];\n return props && typeof props === 'object' && props.key === undefined;\n }\n return false; // primitives don't need keys\n }).length;\n\n if (missingKeyCount > 0) {\n console.warn(\n `[Coherent.js] Array of ${value.length} elements at ${formatRenderPath(path)} ` +\n `has ${missingKeyCount} items missing \"key\" props. ` +\n `Keys help identify which items changed for efficient updates. ` +\n `Add unique key props like: { div: { key: 'unique-id', ... } }`\n );\n }\n }\n return value.map((child, index) => this.renderComponent(child, options, depth + 1, [...path, `[${index}]`])).join('');\n case 'element':\n {\n // Process object-based component\n const tagName = Object.keys(value)[0];\n const elementContent = value[tagName];\n return this.renderElement(tagName, elementContent, options, depth, [...path, tagName]);\n }\n default:\n this.recordError('renderComponent', new Error(`Unknown component type: ${type}`));\n return '';\n }\n } catch (_error) {\n const renderPath = formatRenderPath(path);\n\n if (_error instanceof CoherentError) {\n if (!_error.context || typeof _error.context !== 'object') {\n _error.context = { path: renderPath };\n } else if (!_error.context.path) {\n _error.context = { ..._error.context, path: renderPath };\n }\n throw _error;\n }\n\n throw new RenderingError(_error.message, undefined, { path: renderPath, renderer: 'html' });\n }\n }\n\n /**\n * Render an HTML element with advanced caching and optimization\n */\n renderElement(tagName, element, options, depth = 0, path = []) {\n const startTime = performance.now();\n\n // Check for circular references in element props\n if (element && typeof element === 'object' && !Array.isArray(element)) {\n if (options.seenObjects && options.seenObjects.has(element)) {\n throw new RenderingError(\n 'Circular reference detected in component tree',\n element,\n { path: formatRenderPath(path) },\n ['Remove the circular reference', 'Use lazy loading to break the cycle']\n );\n }\n if (options.seenObjects) {\n options.seenObjects.add(element);\n }\n }\n\n // Track element usage for performance analysis (via stats in the new cache manager)\n if (options.enableMonitoring && this.cache) {\n // The new cache manager tracks usage automatically via get/set operations\n }\n\n // Check cache first for static elements\n if (options.enableCache && this.cache && RendererUtils.isStaticElement(element)) {\n try {\n const cacheKey = `static:${tagName}:${JSON.stringify(element)}`;\n const cached = this.cache.get('static', cacheKey);\n if (cached) {\n this.recordPerformance(tagName, startTime, true);\n return cached.value; // Return the cached HTML\n }\n } catch {\n // Circular reference in element - skip caching and continue with rendering\n // The circular reference will be detected and properly reported during render\n }\n }\n\n // Handle text-only elements including booleans\n if (typeof element === 'string' || typeof element === 'number' || typeof element === 'boolean') {\n const html = isVoidElement(tagName)\n ? `<${tagName}>`\n : `<${tagName}>${escapeHtml(String(element))}</${tagName}>`;\n\n this.cacheIfStatic(tagName, element, html, options);\n this.recordPerformance(tagName, startTime, false);\n return html;\n }\n\n // Handle function elements\n if (typeof element === 'function') {\n const result = this.executeFunctionComponent(element, depth);\n return this.renderElement(tagName, result, options, depth, [...path, '()']);\n }\n\n // Handle object elements (complex elements with props and children)\n if (element && typeof element === 'object') {\n return this.renderObjectElement(tagName, element, options, depth, path);\n }\n\n // Handle null and undefined by returning empty tags\n if (element === null || element === undefined) {\n const html = isVoidElement(tagName)\n ? `<${tagName}>`\n : `<${tagName}></${tagName}>`;\n this.recordPerformance(tagName, startTime, false);\n return html;\n }\n\n // Fallback for any other types\n const html = `<${tagName}>${escapeHtml(String(element))}</${tagName}>`;\n this.recordPerformance(tagName, startTime, false);\n return html;\n }\n\n /**\n * Cache element if it's static\n */\n cacheIfStatic(tagName, element, html) {\n if (this.config.enableCache && this.cache && RendererUtils.isStaticElement(element)) {\n try {\n const cacheKey = `static:${tagName}:${JSON.stringify(element)}`;\n this.cache.set('static', cacheKey, html, {\n ttlMs: this.config.cacheTTL || 5 * 60 * 1000, // 5 minutes default\n size: html.length // Approximate size\n });\n } catch {\n // Circular reference - skip caching\n }\n }\n }\n\n /**\n * Render complex object elements with attributes and children\n */\n renderObjectElement(tagName, element, options, depth = 0, path = []) {\n const startTime = performance.now();\n\n // Check component-level cache\n if (options.enableCache && this.cache) {\n const cacheKey = RendererUtils.generateCacheKey(tagName, element);\n if (cacheKey) {\n const cached = this.cache.get(cacheKey);\n if (cached) {\n this.recordPerformance(tagName, startTime, true);\n return cached;\n }\n }\n }\n\n // Extract props and children directly from element content\n // Note: key is extracted but NOT rendered as an HTML attribute\n // It's used for reconciliation identity, not DOM output\n // html prop is extracted to prevent it from being rendered as an attribute\n const { children, text, key: _key, html: _rawHtml, ...attributes } = element || {};\n\n // Build opening tag with attributes\n const attributeString = formatAttributes(attributes);\n const openingTag = attributeString\n ? `<${tagName} ${attributeString}>`\n : `<${tagName}>`;\n\n // Handle text content\n let textContent = '';\n if (text !== undefined) {\n const isScript = tagName === 'script';\n const isStyle = tagName === 'style';\n const isRawTag = isScript || isStyle;\n const raw = typeof text === 'function' ? String(text()) : String(text);\n if (isRawTag) {\n // Prevent </script> or </style> early-terminating the tag\n const safe = raw\n .replace(/<\\/(script)/gi, '<\\\\/$1')\n .replace(/<\\/(style)/gi, '<\\\\/$1')\n // Escape problematic Unicode line separators in JS\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029');\n textContent = safe;\n } else {\n textContent = escapeHtml(raw);\n }\n }\n\n // Handle children\n let childrenHtml = '';\n if (hasChildren(element)) {\n const normalizedChildren = normalizeChildren(children);\n childrenHtml = normalizedChildren\n .map((child, index) => {\n // Validate HTML nesting before rendering child\n if (child && typeof child === 'object' && !Array.isArray(child)) {\n const childTagName = Object.keys(child)[0];\n if (childTagName) {\n validateNesting(tagName, childTagName, formatRenderPath([...path, `children[${index}]`]));\n }\n }\n return this.renderComponent(child, options, depth + 1, [...path, `children[${index}]`]);\n })\n .join('');\n }\n\n // Build complete HTML\n const html = `${openingTag}${textContent}${childrenHtml}</${tagName}>`;\n\n // Cache the result if appropriate\n if (options.enableCache && this.cache && RendererUtils.isCacheable(element, options)) {\n const cacheKey = RendererUtils.generateCacheKey(tagName, element);\n if (cacheKey) {\n this.cache.set(cacheKey, html);\n }\n }\n\n this.recordPerformance(tagName, startTime, false);\n return html;\n }\n}\n\n// Note: globalCache is now imported from cache-manager.js\n\n/**\n * Main render function - converts object components to HTML\n */\nexport function render(component, options = {}) {\n // Merge default options with provided options\n const mergedOptions = {\n enableCache: true,\n enableMonitoring: false,\n ...options\n };\n\n const renderer = new HTMLRenderer(mergedOptions);\n return renderer.render(component, mergedOptions);\n}\n\n/**\n * Renders component to complete HTML document with DOCTYPE\n * Better alternative to manual DOCTYPE concatenation\n * Supports CSS file inclusion and inline styles\n */\nexport async function renderHTML(component, options = {}) {\n const htmlContent = render(component, options);\n\n // Process CSS options\n const cssOptions = cssUtils.processCSSOptions(options);\n\n // Generate CSS HTML if any CSS is specified\n let cssHtml = '';\n if (cssOptions.files.length > 0 || cssOptions.links.length > 0 || cssOptions.inline) {\n cssHtml = await cssUtils.generateCSSHtml(cssOptions, defaultCSSManager);\n }\n\n // If the component includes a head tag, inject CSS into it\n if (cssHtml && htmlContent.includes('<head>')) {\n const htmlWithCSS = htmlContent.replace(\n '</head>',\n `${cssHtml}\\n</head>`\n );\n return `<!DOCTYPE html>\\n${htmlWithCSS}`;\n }\n\n // If there's CSS but no head tag, wrap the component with a basic HTML structure\n if (cssHtml) {\n return `<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n${cssHtml}\n</head>\n<body>\n${htmlContent}\n</body>\n</html>`;\n }\n\n return `<!DOCTYPE html>\\n${htmlContent}`;\n}\n\n/**\n * Synchronous version of render for cases without CSS files\n * Falls back to async if CSS files are detected\n */\nexport function renderHTMLSync(component, options = {}) {\n const cssOptions = cssUtils.processCSSOptions(options);\n\n // If CSS files are specified, return a promise\n if (cssOptions.files.length > 0) {\n console.warn('CSS files detected, use render() (async) instead of renderSync()');\n return render(component, options);\n }\n\n const htmlContent = render(component, options);\n\n // Handle inline CSS and external links only\n let cssHtml = '';\n if (cssOptions.links.length > 0) {\n cssHtml += defaultCSSManager.generateCSSLinks(cssOptions.links);\n }\n if (cssOptions.inline) {\n cssHtml += `\\n${ defaultCSSManager.generateInlineStyles(cssOptions.inline)}`;\n }\n\n if (cssHtml && htmlContent.includes('<head>')) {\n const htmlWithCSS = htmlContent.replace(\n '</head>',\n `${cssHtml}\\n</head>`\n );\n return `<!DOCTYPE html>\\n${htmlWithCSS}`;\n }\n\n if (cssHtml) {\n return `<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n${cssHtml}\n</head>\n<body>\n${htmlContent}\n</body>\n</html>`;\n }\n\n return `<!DOCTYPE html>\\n${htmlContent}`;\n}\n\n\n// Old functions removed - now part of HTMLRenderer class\n\n// Old helper functions removed - now available in RendererUtils from BaseRenderer\n\n/**\n * Batch rendering for multiple components\n */\nexport function renderBatch(components, options = {}) {\n if (!Array.isArray(components)) {\n throw new Error('renderBatch expects an array of components');\n }\n\n // Merge default options with provided options\n const mergedOptions = {\n enableCache: true,\n enableMonitoring: false,\n ...options\n };\n\n const renderer = new HTMLRenderer(mergedOptions);\n return components.map(component => renderer.render(component, mergedOptions));\n}\n\n/**\n * Real streaming render - yields chunks progressively as HTML is generated\n * Ideal for large component trees or memory-constrained environments\n */\nexport async function* renderToStream(component, options = {}) {\n const config = {\n chunkSize: 8192, // 8KB default chunk size\n maxDepth: 1000,\n yieldThreshold: 100, // Yield control every 100 elements\n encoding: 'utf8',\n ...options\n };\n\n let buffer = '';\n let elementCount = 0;\n\n // Helper to flush buffer when it reaches chunk size\n async function* flushBuffer(force = false) {\n if (force || buffer.length >= config.chunkSize) {\n if (buffer.length > 0) {\n yield buffer;\n buffer = '';\n }\n }\n }\n\n // Helper to add to buffer\n async function* write(text) {\n buffer += text;\n yield* flushBuffer();\n }\n\n // Recursive streaming component renderer\n async function* streamComponent(comp, depth = 0) {\n if (depth > config.maxDepth) {\n throw new Error(`Maximum nesting depth exceeded: ${config.maxDepth}`);\n }\n\n // Handle null/undefined\n if (comp === null || comp === undefined) return;\n\n // Handle primitives\n if (typeof comp === 'string' || typeof comp === 'number') {\n yield* write(escapeHtml(String(comp)));\n return;\n }\n\n // Handle arrays\n if (Array.isArray(comp)) {\n for (const child of comp) {\n yield* streamComponent(child, depth);\n\n // Yield control periodically\n if (elementCount++ % config.yieldThreshold === 0) {\n await new Promise(resolve => setImmediate(resolve));\n }\n }\n return;\n }\n\n // Handle functions\n if (typeof comp === 'function') {\n const result = comp();\n yield* streamComponent(result, depth);\n return;\n }\n\n // Handle objects (HTML elements)\n if (typeof comp === 'object') {\n for (const [tagName, props] of Object.entries(comp)) {\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 yield* write(openTag.replace('>', ' />'));\n elementCount++;\n return;\n }\n\n yield* write(openTag);\n\n if (text !== undefined) {\n yield* write(escapeHtml(String(text)));\n } else if (children) {\n yield* streamComponent(children, depth + 1);\n }\n\n yield* write(`</${tagName}>`);\n elementCount++;\n } else if (props === null || props === undefined) {\n // Handle null/undefined props - render empty element\n if (isVoidElement(tagName)) {\n yield* write(`<${tagName} />`);\n } else {\n yield* write(`<${tagName}></${tagName}>`);\n }\n elementCount++;\n } else if (typeof props === 'string') {\n const content = escapeHtml(props);\n if (isVoidElement(tagName)) {\n yield* write(`<${tagName} />`);\n } else {\n yield* write(`<${tagName}>${content}</${tagName}>`);\n }\n elementCount++;\n }\n }\n }\n }\n\n // Start streaming\n try {\n yield* streamComponent(component);\n yield* flushBuffer(true); // Force flush remaining buffer\n } catch (error) {\n // Stream error as HTML comment\n yield `<!-- Streaming Error: ${error.message} -->`;\n }\n}\n\n/**\n * Streaming utilities for common use cases\n */\nexport const streamingUtils = {\n /**\n * Collect all chunks into a single string\n */\n async collectChunks(chunkGenerator) {\n let html = '';\n for await (const chunk of chunkGenerator) {\n html += chunk;\n }\n return html;\n },\n\n /**\n * Stream directly to a Node.js response\n */\n async streamToResponse(chunkGenerator, response) {\n let totalBytes = 0;\n response.setHeader('Content-Type', 'text/html; charset=utf-8');\n response.setHeader('Transfer-Encoding', 'chunked');\n\n for await (const chunk of chunkGenerator) {\n response.write(chunk);\n totalBytes += Buffer.byteLength(chunk);\n }\n\n response.end();\n return totalBytes;\n },\n\n /**\n * Stream with progress callback\n */\n async* streamWithProgress(chunkGenerator, onProgress) {\n let totalBytes = 0;\n let chunkCount = 0;\n\n for await (const chunk of chunkGenerator) {\n totalBytes += Buffer.byteLength(chunk);\n chunkCount++;\n\n if (onProgress) {\n onProgress({ chunkCount, totalBytes, chunk });\n }\n\n yield chunk;\n }\n }\n};\n\n/**\n * Render to chunks (legacy - kept for backward compatibility)\n * For true streaming, use renderToStream() instead\n */\nexport function* renderToChunks(component, options = {}) {\n const mergedOptions = {\n enableCache: true,\n enableMonitoring: false,\n ...options,\n chunkSize: options.chunkSize || 1024 // Default 1KB chunks\n };\n\n const html = render(component, mergedOptions);\n\n for (let i = 0; i < html.length; i += mergedOptions.chunkSize) {\n yield html.slice(i, i + mergedOptions.chunkSize);\n }\n}\n\n/**\n * Get global cache instance for external access\n */\nexport function getCache() {\n return rendererCache;\n}\n\n/**\n * Reset cache (useful for testing)\n */\nexport function resetCache() {\n if (rendererCache) {\n rendererCache.clear();\n }\n}\n\n/**\n * Get rendering statistics\n */\nexport function getRenderingStats() {\n return {\n cache: rendererCache ? rendererCache.getStats() : null,\n performance: performanceMonitor.getStats()\n };\n}\n\n/**\n * Precompile static components for maximum performance\n */\nexport function precompileComponent(component, options = {}) {\n if (!isStaticElement(component)) {\n throw new Error('Can only precompile static components');\n }\n\n const html = render(component, { ...options, enableCache: false });\n\n return {\n html,\n isPrecompiled: true,\n render: () => html\n };\n}\n\n/**\n * Development helper - render with detailed timing\n */\nexport function renderWithTiming(component, options = {}) {\n const start = performance.now();\n const html = render(component, { ...options, enableMonitoring: true });\n const end = performance.now();\n\n return {\n html,\n timing: {\n total: end - start,\n breakdown: performanceMonitor.getStats()\n }\n };\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 setState: stateUtils.setState,\n getState: stateUtils.getState,\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 * 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 * Core constants and types for the Coherent framework\n */\n\nexport const CoherentTypes = {\n OBJECT: 'coherent-object',\n COMPONENT: 'coherent-component',\n ELEMENT: 'coherent-element'\n};\n\nexport const HTML_ELEMENTS = new Set([\n 'a', 'abbr', 'address', 'area', 'article', 'aside', 'audio',\n 'b', 'base', 'bdi', 'bdo', 'blockquote', 'body', 'br', 'button',\n 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup',\n 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt',\n 'em', 'embed',\n 'fieldset', 'figcaption', 'figure', 'footer', 'form',\n 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hr', 'html',\n 'i', 'iframe', 'img', 'input', 'ins',\n 'kbd',\n 'label', 'legend', 'li', 'link',\n 'main', 'map', 'mark', 'meta', 'meter',\n 'nav', 'noscript',\n 'object', 'ol', 'optgroup', 'option', 'output',\n 'p', 'param', 'picture', 'pre', 'progress',\n 'q',\n 'rp', 'rt', 'ruby',\n 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup',\n 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track',\n 'u', 'ul',\n 'var', 'video',\n 'wbr'\n]);\n\nexport const VOID_ELEMENTS = new Set([\n 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',\n 'link', 'meta', 'param', 'source', 'track', 'wbr'\n]);\n", "/**\n * Object Factory for Coherent.js\n * @fileoverview Creates Coherent objects with HTML elements and text nodes\n */\n\nimport { HTML_ELEMENTS, CoherentTypes } from '../types/constants.js';\n\n/**\n * Creates a Coherent object with the specified tag and properties\n * @param {string} tag - HTML tag name\n * @param {Object} [props={}] - Properties object\n * @returns {Object} Coherent object with element structure\n * @throws {Error} When invalid HTML element is provided\n */\nexport function createElement(tag, props = {}) {\n if (!HTML_ELEMENTS.has(tag)) {\n throw new Error(`Invalid HTML element: ${tag}`);\n }\n\n // Create the coherent object structure\n const coherentObj = {\n [tag]: {\n ...props,\n _type: CoherentTypes.ELEMENT\n }\n };\n\n return coherentObj;\n}\n\n/**\n * Creates a text node\n * @param {string} text - Text content\n * @returns {Object} Coherent text object\n */\nexport function createTextNode(text) {\n return {\n text: String(text),\n _type: CoherentTypes.OBJECT\n };\n}\n\n/**\n * Helper function to create common elements\n */\nexport const h = {\n div: (props) => createElement('div', props),\n span: (props) => createElement('span', props),\n p: (props) => createElement('p', props),\n h1: (props) => createElement('h1', props),\n h2: (props) => createElement('h2', props),\n h3: (props) => createElement('h3', props),\n h4: (props) => createElement('h4', props),\n h5: (props) => createElement('h5', props),\n h6: (props) => createElement('h6', props),\n a: (props) => createElement('a', props),\n img: (props) => createElement('img', props),\n button: (props) => createElement('button', props),\n input: (props) => createElement('input', props),\n form: (props) => createElement('form', props),\n ul: (props) => createElement('ul', props),\n ol: (props) => createElement('ol', props),\n li: (props) => createElement('li', props),\n table: (props) => createElement('table', props),\n tr: (props) => createElement('tr', props),\n td: (props) => createElement('td', props),\n th: (props) => createElement('th', props)\n};\n", "/**\n * Advanced Component Caching System for Coherent.js\n * Provides intelligent caching with dependency tracking and invalidation\n */\n\nimport { deepClone } from '../core/object-utils.js';\n\n/**\n * Cache entry structure\n */\nclass CacheEntry {\n constructor(key, component, deps = [], options = {}) {\n this.key = key;\n this.component = deepClone(component);\n this.deps = new Set(deps);\n this.createdAt = Date.now();\n this.lastAccessed = Date.now();\n this.accessCount = 1;\n this.ttl = options.ttl || 300000; // 5 minutes default\n this.persistent = options.persistent || false;\n }\n\n isExpired() {\n return !this.persistent && (Date.now() - this.createdAt) > this.ttl;\n }\n\n touch() {\n this.lastAccessed = Date.now();\n this.accessCount++;\n }\n\n hasDependency(dep) {\n return this.deps.has(dep);\n }\n\n addDependency(dep) {\n this.deps.add(dep);\n }\n\n removeDependency(dep) {\n this.deps.delete(dep);\n }\n}\n\n/**\n * Component Cache Manager with intelligent invalidation\n */\nexport class ComponentCache {\n constructor(options = {}) {\n this.options = {\n maxSize: options.maxSize || 1000,\n defaultTTL: options.defaultTTL || 300000,\n cleanupInterval: options.cleanupInterval || 60000, // 1 minute\n enableStats: options.enableStats !== false,\n ...options\n };\n\n this.cache = new Map();\n this.dependencies = new Map(); // dependency -> Set of cache keys\n this.stats = {\n hits: 0,\n misses: 0,\n evictions: 0,\n cleanups: 0,\n invalidations: 0\n };\n\n // Start periodic cleanup\n if (this.options.cleanupInterval > 0) {\n this.cleanupTimer = setInterval(() => {\n this.cleanup();\n }, this.options.cleanupInterval);\n }\n }\n\n /**\n * Generate cache key from component and props\n */\n generateKey(component, props = {}, context = {}) {\n if (typeof component === 'string') {\n return `str:${component}`;\n }\n\n if (typeof component === 'function') {\n return `fn:${component.name || 'anonymous'}:${JSON.stringify(props)}`;\n }\n\n if (typeof component === 'object' && component !== null) {\n const serialized = this.serializeComponent(component);\n const propsHash = Object.keys(props).length > 0 ? `:${JSON.stringify(props)}` : '';\n const contextHash = Object.keys(context).length > 0 ? `:${JSON.stringify(context)}` : '';\n return `obj:${serialized}${propsHash}${contextHash}`;\n }\n\n return `primitive:${String(component)}`;\n }\n\n /**\n * Serialize component for cache key generation\n */\n serializeComponent(component, maxDepth = 3, currentDepth = 0) {\n if (currentDepth > maxDepth) {\n return '[DEEP]';\n }\n\n if (typeof component !== 'object' || component === null) {\n return String(component);\n }\n\n if (Array.isArray(component)) {\n return `[${component.map(item => \n this.serializeComponent(item, maxDepth, currentDepth + 1)\n ).join(',')}]`;\n }\n\n const entries = Object.entries(component);\n if (entries.length === 1) {\n const [key, value] = entries[0];\n const serializedValue = typeof value === 'object' \n ? this.serializeComponent(value, maxDepth, currentDepth + 1)\n : String(value);\n return `${key}:${serializedValue}`;\n }\n\n return '[COMPLEX]';\n }\n\n /**\n * Get component from cache\n */\n get(key, dependencies = []) {\n const entry = this.cache.get(key);\n\n if (!entry) {\n this.stats.misses++;\n return null;\n }\n\n if (entry.isExpired()) {\n this.cache.delete(key);\n this.removeDependencyMappings(key);\n this.stats.misses++;\n return null;\n }\n\n entry.touch();\n this.stats.hits++;\n\n // Update dependency tracking\n dependencies.forEach(dep => {\n if (!entry.hasDependency(dep)) {\n entry.addDependency(dep);\n this.addDependencyMapping(dep, key);\n }\n });\n\n return deepClone(entry.component);\n }\n\n /**\n * Set component in cache\n */\n set(key, component, options = {}) {\n // Enforce size limit\n if (this.cache.size >= this.options.maxSize) {\n this.evictLeastUsed();\n }\n\n const deps = options.dependencies || [];\n const entry = new CacheEntry(key, component, deps, {\n ttl: options.ttl || this.options.defaultTTL,\n persistent: options.persistent || false\n });\n\n this.cache.set(key, entry);\n\n // Update dependency mappings\n deps.forEach(dep => {\n this.addDependencyMapping(dep, key);\n });\n\n return true;\n }\n\n /**\n * Check if component exists in cache\n */\n has(key) {\n const entry = this.cache.get(key);\n return entry && !entry.isExpired();\n }\n\n /**\n * Invalidate cache entries by dependency\n */\n invalidate(dependency) {\n const dependentKeys = this.dependencies.get(dependency);\n if (!dependentKeys) {\n return 0;\n }\n\n let invalidated = 0;\n for (const key of dependentKeys) {\n if (this.cache.delete(key)) {\n invalidated++;\n this.stats.invalidations++;\n }\n }\n\n this.dependencies.delete(dependency);\n return invalidated;\n }\n\n /**\n * Invalidate multiple dependencies\n */\n invalidateMultiple(dependencies) {\n let totalInvalidated = 0;\n dependencies.forEach(dep => {\n totalInvalidated += this.invalidate(dep);\n });\n return totalInvalidated;\n }\n\n /**\n * Clear entire cache\n */\n clear() {\n const size = this.cache.size;\n this.cache.clear();\n this.dependencies.clear();\n return size;\n }\n\n /**\n * Add dependency mapping\n */\n addDependencyMapping(dependency, key) {\n if (!this.dependencies.has(dependency)) {\n this.dependencies.set(dependency, new Set());\n }\n this.dependencies.get(dependency).add(key);\n }\n\n /**\n * Remove dependency mappings for a cache key\n */\n removeDependencyMappings(key) {\n for (const [dep, keys] of this.dependencies.entries()) {\n keys.delete(key);\n if (keys.size === 0) {\n this.dependencies.delete(dep);\n }\n }\n }\n\n /**\n * Evict least recently used entry\n */\n evictLeastUsed() {\n let oldestKey = null;\n let oldestTime = Date.now();\n\n for (const [key, entry] of this.cache.entries()) {\n if (!entry.persistent && entry.lastAccessed < oldestTime) {\n oldestTime = entry.lastAccessed;\n oldestKey = key;\n }\n }\n\n if (oldestKey) {\n this.cache.delete(oldestKey);\n this.removeDependencyMappings(oldestKey);\n this.stats.evictions++;\n }\n }\n\n /**\n * Cleanup expired entries\n */\n cleanup() {\n const before = this.cache.size;\n const expiredKeys = [];\n\n for (const [key, entry] of this.cache.entries()) {\n if (entry.isExpired()) {\n expiredKeys.push(key);\n }\n }\n\n expiredKeys.forEach(key => {\n this.cache.delete(key);\n this.removeDependencyMappings(key);\n });\n\n const cleaned = before - this.cache.size;\n if (cleaned > 0) {\n this.stats.cleanups++;\n }\n\n return cleaned;\n }\n\n /**\n * Get cache statistics\n */\n getStats() {\n const totalRequests = this.stats.hits + this.stats.misses;\n return {\n size: this.cache.size,\n maxSize: this.options.maxSize,\n hits: this.stats.hits,\n misses: this.stats.misses,\n hitRate: totalRequests > 0 ? (this.stats.hits / totalRequests * 100).toFixed(2) : 0,\n evictions: this.stats.evictions,\n cleanups: this.stats.cleanups,\n invalidations: this.stats.invalidations,\n dependencies: this.dependencies.size,\n memoryUsage: this.estimateMemoryUsage()\n };\n }\n\n /**\n * Estimate memory usage (rough approximation)\n */\n estimateMemoryUsage() {\n let totalSize = 0;\n for (const entry of this.cache.values()) {\n // Rough estimate: 1KB per component + overhead\n totalSize += JSON.stringify(entry.component).length + 500;\n }\n return Math.round(totalSize / 1024); // Return in KB\n }\n\n /**\n * Get hot path components (most accessed)\n */\n getHotComponents(limit = 10) {\n const entries = Array.from(this.cache.entries());\n return entries\n .sort((a, b) => b[1].accessCount - a[1].accessCount)\n .slice(0, limit)\n .map(([key, entry]) => ({\n key,\n accessCount: entry.accessCount,\n component: entry.component,\n dependencies: Array.from(entry.deps)\n }));\n }\n\n /**\n * Get cache recommendations\n */\n getRecommendations() {\n const stats = this.getStats();\n const recommendations = [];\n\n if (stats.hitRate < 50) {\n recommendations.push({\n type: 'low-hit-rate',\n message: `Hit rate is ${stats.hitRate}%. Consider increasing cache size or TTL.`,\n priority: 'HIGH'\n });\n }\n\n if (stats.evictions > stats.hits * 0.1) {\n recommendations.push({\n type: 'frequent-evictions',\n message: 'Frequent evictions detected. Consider increasing maxSize.',\n priority: 'MEDIUM'\n });\n }\n\n if (stats.invalidations > stats.hits * 0.05) {\n recommendations.push({\n type: 'frequent-invalidations',\n message: 'Frequent invalidations. Review dependency tracking.',\n priority: 'LOW'\n });\n }\n\n return recommendations;\n }\n\n /**\n * Destroy cache and cleanup\n */\n destroy() {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n }\n this.clear();\n }\n}\n\n/**\n * Create a new component cache instance\n */\nexport function createComponentCache(options = {}) {\n return new ComponentCache(options);\n}\n\n/**\n * Memoization decorator for components\n */\nexport function memoize(component, keyGenerator, options = {}) {\n const cache = new ComponentCache({\n maxSize: options.maxSize || 100,\n defaultTTL: options.ttl || 300000\n });\n\n return function memoizedComponent(...args) {\n const key = keyGenerator ? keyGenerator(...args) : JSON.stringify(args);\n \n const cached = cache.get(key, options.dependencies);\n if (cached) {\n return cached;\n }\n\n const result = typeof component === 'function' ? component(...args) : component;\n cache.set(key, result, options);\n return result;\n };\n}\n\nexport default ComponentCache;", "/**\n * Coherent.js Error Boundary\n * \n * Catches rendering errors and provides fallback UI.\n * Similar to React's Error Boundaries but for Coherent.js.\n * \n * @module components/error-boundary\n */\n\n/**\n * Error boundary state\n */\nclass ErrorBoundaryState {\n constructor() {\n this.hasError = false;\n this.error = null;\n this.errorInfo = null;\n this.errorCount = 0;\n this.lastError = null;\n }\n\n reset() {\n this.hasError = false;\n this.error = null;\n this.errorInfo = null;\n }\n\n setError(error, errorInfo = {}) {\n this.hasError = true;\n this.error = error;\n this.errorInfo = errorInfo;\n this.errorCount++;\n this.lastError = Date.now();\n }\n}\n\n/**\n * Create an error boundary\n * \n * @param {Object} options - Error boundary options\n * @param {Object|Function} options.fallback - Fallback component or function\n * @param {Function} [options.onError] - Error callback\n * @param {Function} [options.onReset] - Reset callback\n * @param {Array<string>} [options.resetKeys] - Keys that trigger reset\n * @param {boolean} [options.resetOnPropsChange] - Reset on props change\n * @param {number} [options.maxErrors] - Maximum errors before permanent fallback\n * @param {number} [options.resetTimeout] - Auto-reset timeout in ms\n * @returns {Function} Error boundary wrapper function\n * \n * @example\n * const boundary = createErrorBoundary({\n * fallback: { div: { text: 'Something went wrong' } },\n * onError: (error, errorInfo) => console.error(error),\n * resetKeys: ['userId']\n * });\n * \n * const SafeComponent = boundary(MyComponent);\n */\nexport function createErrorBoundary(options = {}) {\n const {\n fallback = { div: { className: 'error-boundary', text: 'An error occurred' } },\n onError = null,\n onReset = null,\n resetKeys = [],\n resetOnPropsChange = false,\n maxErrors = Infinity,\n resetTimeout = null\n } = options;\n\n const state = new ErrorBoundaryState();\n let previousProps = {};\n let resetTimer = null;\n\n /**\n * Wrap a component with error boundary\n */\n return function errorBoundaryWrapper(component) {\n return function wrappedComponent(props = {}) {\n try {\n // Check if we should reset based on props\n if (resetOnPropsChange && shouldReset(props, previousProps, resetKeys)) {\n state.reset();\n if (onReset) {\n onReset();\n }\n }\n\n previousProps = { ...props };\n\n // If we have an error and haven't exceeded max errors\n if (state.hasError) {\n if (state.errorCount >= maxErrors) {\n // Permanent fallback\n return typeof fallback === 'function'\n ? fallback(state.error, state.errorInfo, { permanent: true })\n : fallback;\n }\n\n // Return fallback with reset option\n const fallbackComponent = typeof fallback === 'function'\n ? fallback(state.error, state.errorInfo, {\n reset: () => {\n state.reset();\n if (onReset) {\n onReset();\n }\n },\n errorCount: state.errorCount\n })\n : fallback;\n\n return fallbackComponent;\n }\n\n // Try to render the component\n const result = typeof component === 'function'\n ? component(props)\n : component;\n\n return result;\n\n } catch (error) {\n // Capture error\n const errorInfo = {\n componentStack: error.stack,\n props,\n timestamp: Date.now()\n };\n\n state.setError(error, errorInfo);\n\n // Call error callback\n if (onError) {\n try {\n onError(error, errorInfo);\n } catch (callbackError) {\n console.error('Error in onError callback:', callbackError);\n }\n }\n\n // Set auto-reset timer if configured\n if (resetTimeout && !resetTimer) {\n resetTimer = setTimeout(() => {\n state.reset();\n resetTimer = null;\n if (onReset) {\n onReset();\n }\n }, resetTimeout);\n }\n\n // Return fallback\n return typeof fallback === 'function'\n ? fallback(error, errorInfo, {\n reset: () => {\n state.reset();\n if (resetTimer) {\n clearTimeout(resetTimer);\n resetTimer = null;\n }\n if (onReset) {\n onReset();\n }\n },\n errorCount: state.errorCount\n })\n : fallback;\n }\n };\n };\n}\n\n/**\n * Check if error boundary should reset based on props\n */\nfunction shouldReset(newProps, oldProps, resetKeys) {\n if (resetKeys.length === 0) {\n return false;\n }\n\n return resetKeys.some(key => newProps[key] !== oldProps[key]);\n}\n\n/**\n * Create a default error fallback component\n * \n * @param {Object} options - Fallback options\n * @returns {Function} Fallback component function\n */\nexport function createErrorFallback(options = {}) {\n const {\n title = 'Something went wrong',\n showError = true,\n showStack = false,\n showReset = true,\n className = 'error-boundary-fallback',\n style = {}\n } = options;\n\n return function errorFallback(error, errorInfo, context = {}) {\n const children = [\n {\n h2: {\n className: 'error-title',\n text: title\n }\n }\n ];\n\n if (showError && error) {\n children.push({\n p: {\n className: 'error-message',\n text: error.message || 'Unknown error'\n }\n });\n }\n\n if (showStack && error && error.stack) {\n children.push({\n pre: {\n className: 'error-stack',\n text: error.stack\n }\n });\n }\n\n if (showReset && context.reset && !context.permanent) {\n children.push({\n button: {\n className: 'error-reset-button',\n text: 'Try Again',\n onclick: context.reset\n }\n });\n }\n\n if (context.errorCount > 1) {\n children.push({\n p: {\n className: 'error-count',\n text: `Error occurred ${context.errorCount} times`\n }\n });\n }\n\n return {\n div: {\n className,\n style: {\n padding: '20px',\n border: '1px solid #f44336',\n borderRadius: '4px',\n backgroundColor: '#ffebee',\n color: '#c62828',\n ...style\n },\n children\n }\n };\n };\n}\n\n/**\n * Wrap multiple components with the same error boundary\n * \n * @param {Object} options - Error boundary options\n * @param {Object} components - Components to wrap\n * @returns {Object} Wrapped components\n * \n * @example\n * const safeComponents = withErrorBoundary(\n * { fallback: ErrorFallback },\n * { Header, Footer, Content }\n * );\n */\nexport function withErrorBoundary(options, components) {\n const boundary = createErrorBoundary(options);\n const wrapped = {};\n\n Object.entries(components).forEach(([name, component]) => {\n wrapped[name] = boundary(component);\n });\n\n return wrapped;\n}\n\n/**\n * Error boundary for async components\n * \n * @param {Object} options - Error boundary options\n * @returns {Function} Async error boundary wrapper\n */\nexport function createAsyncErrorBoundary(options = {}) {\n const {\n fallback = { div: { text: 'Loading...' } },\n errorFallback = { div: { text: 'Failed to load' } },\n onError = null,\n timeout = 10000\n } = options;\n\n return function asyncBoundaryWrapper(asyncComponent) {\n return async function wrappedAsyncComponent(props = {}) {\n try {\n // Set timeout\n const timeoutPromise = new Promise((_, reject) => {\n setTimeout(() => reject(new Error('Component load timeout')), timeout);\n });\n\n // Race between component load and timeout\n const result = await Promise.race([\n typeof asyncComponent === 'function'\n ? asyncComponent(props)\n : asyncComponent,\n timeoutPromise\n ]);\n\n return result ?? fallback;\n } catch (error) {\n if (onError) {\n onError(error, { props, async: true });\n }\n\n return typeof errorFallback === 'function'\n ? errorFallback(error, { props })\n : errorFallback;\n }\n };\n };\n}\n\n/**\n * Global error handler for uncaught errors\n */\nexport class GlobalErrorHandler {\n constructor(options = {}) {\n this.options = options;\n this.errors = [];\n this.maxErrors = options.maxErrors || 100;\n this.onError = options.onError || null;\n this.enabled = options.enabled !== false;\n }\n\n /**\n * Capture an error\n */\n captureError(error, context = {}) {\n if (!this.enabled) return;\n\n const errorEntry = {\n error,\n context,\n timestamp: Date.now(),\n stack: error.stack\n };\n\n this.errors.push(errorEntry);\n\n // Limit stored errors\n if (this.errors.length > this.maxErrors) {\n this.errors.shift();\n }\n\n // Call error callback\n if (this.onError) {\n try {\n this.onError(error, context);\n } catch (callbackError) {\n console.error('Error in global error handler callback:', callbackError);\n }\n }\n }\n\n /**\n * Get all captured errors\n */\n getErrors() {\n return [...this.errors];\n }\n\n /**\n * Clear all errors\n */\n clearErrors() {\n this.errors = [];\n }\n\n /**\n * Get error statistics\n */\n getStats() {\n return {\n totalErrors: this.errors.length,\n enabled: this.enabled,\n maxErrors: this.maxErrors\n };\n }\n\n /**\n * Enable error handler\n */\n enable() {\n this.enabled = true;\n }\n\n /**\n * Disable error handler\n */\n disable() {\n this.enabled = false;\n }\n}\n\n/**\n * Create a global error handler\n */\nexport function createGlobalErrorHandler(options = {}) {\n return new GlobalErrorHandler(options);\n}\n\n/**\n * Export all error boundary utilities\n */\nexport default {\n createErrorBoundary,\n createErrorFallback,\n withErrorBoundary,\n createAsyncErrorBoundary,\n GlobalErrorHandler,\n createGlobalErrorHandler\n};\n", "/**\n * Shared rendering utilities for framework integrations\n * Eliminates code duplication across Express, Fastify, Koa, Next.js integrations\n */\n\nimport { render } from '../rendering/html-renderer.js';\nimport { performanceMonitor } from '../performance/monitor.js';\n\n/**\n * Render a component with optional performance monitoring\n * This is the canonical rendering function used by all framework integrations\n * \n * @param {Object} component - Coherent.js component to render\n * @param {Object} options - Rendering options\n * @param {boolean} options.enablePerformanceMonitoring - Enable performance tracking\n * @param {string} options.template - HTML template with {{content}} placeholder\n * @returns {string} Rendered HTML\n */\nexport function renderWithMonitoring(component, options = {}) {\n const {\n enablePerformanceMonitoring = false\n } = options;\n\n let html;\n\n if (enablePerformanceMonitoring) {\n const renderId = performanceMonitor.startRender();\n html = render(component);\n performanceMonitor.endRender(renderId);\n } else {\n html = render(component);\n }\n\n return html;\n}\n\n/**\n * Render a component and apply an HTML template\n * \n * @param {Object} component - Coherent.js component to render\n * @param {Object} options - Rendering options\n * @param {boolean} options.enablePerformanceMonitoring - Enable performance tracking\n * @param {string} options.template - HTML template with {{content}} placeholder\n * @returns {string} Final HTML with template applied\n */\nexport function renderWithTemplate(component, options = {}) {\n const {\n template = '<!DOCTYPE html>\\n{{content}}'\n } = options;\n\n const html = renderWithMonitoring(component, options);\n return template.replace('{{content}}', html);\n}\n\n/**\n * Create a component factory handler for framework integrations\n * Handles component creation, rendering, and error handling\n * \n * @param {Function} componentFactory - Function that creates a component\n * @param {Object} factoryArgs - Arguments to pass to the component factory\n * @param {Object} options - Rendering options\n * @returns {Promise<string>} Rendered HTML\n * @throws {Error} If component factory returns null/undefined or rendering fails\n */\nexport async function renderComponentFactory(componentFactory, factoryArgs, options = {}) {\n // Create component with provided arguments\n const component = await Promise.resolve(\n componentFactory(...factoryArgs)\n );\n\n if (!component) {\n throw new Error('Component factory returned null/undefined');\n }\n\n // Render with template\n return renderWithTemplate(component, options);\n}\n\n/**\n * Check if an object is a Coherent.js component\n * A Coherent.js component is a plain object with a single key representing an HTML tag\n * \n * @param {any} obj - Object to check\n * @returns {boolean} True if object is a Coherent.js component\n */\nexport function isCoherentComponent(obj) {\n if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {\n return false;\n }\n\n const keys = Object.keys(obj);\n return keys.length === 1;\n}\n\n/**\n * Create a standardized error response for framework integrations\n * \n * @param {Error} error - The error that occurred\n * @param {string} context - Context where the error occurred\n * @returns {Object} Error response object\n */\nexport function createErrorResponse(error, context = 'rendering') {\n return {\n error: 'Internal Server Error',\n message: error.message,\n context,\n timestamp: new Date().toISOString()\n };\n}\n", "/**\n * Utility functions for handling optional peer dependencies\n */\n\n/**\n * Check if a peer dependency is available\n * @param {string} packageName - Name of the package to check\n * @returns {boolean} - Whether the package is available\n */\nexport function isPeerDependencyAvailable(packageName) {\n try {\n // Try to import the package synchronously using require.resolve\n // This is more compatible with code analysis tools\n if (typeof require !== 'undefined' && require.resolve) {\n require.resolve(packageName);\n return true;\n }\n // Fallback: assume available if require is not available (browser context)\n return false;\n } catch {\n return false;\n }\n}\n\n/**\n * Dynamically import a peer dependency with _error handling\n * @param {string} packageName - Name of the package to import\n * @param {string} integrationName - Human-readable name of the integration\n * @returns {Promise<any>} - The imported module\n * @throws {Error} - If the dependency is not available\n */\nexport async function importPeerDependency(packageName, integrationName) {\n try {\n return await import(packageName);\n } catch {\n throw new Error(\n `${integrationName} integration requires the '${packageName}' package to be installed.\\n` +\n `Please install it with: npm install ${packageName}\\n` +\n `Or with pnpm: pnpm add ${packageName}\\n` +\n `Or with yarn: yarn add ${packageName}`\n );\n }\n}\n\n/**\n * Create a lazy-loaded integration that only imports dependencies when needed\n * @param {string} packageName - Name of the package to import\n * @param {string} integrationName - Human-readable name of the integration\n * @param {Function} createIntegration - Function that creates the integration using the imported package\n * @returns {Function} - Lazy-loaded integration function\n */\nexport function createLazyIntegration(packageName, integrationName, createIntegration) {\n let cachedIntegration = null;\n let importPromise = null;\n\n return async function(...args) {\n // Return cached integration if available\n if (cachedIntegration) {\n return cachedIntegration(...args);\n }\n\n // Avoid multiple concurrent imports\n if (!importPromise) {\n importPromise = importPeerDependency(packageName, integrationName)\n .then(module => {\n cachedIntegration = createIntegration(module);\n return cachedIntegration;\n });\n }\n\n const integration = await importPromise;\n return integration(...args);\n };\n}\n\n/**\n * Check multiple peer dependencies and provide helpful _error messages\n * @param {Array<{package: string, integration: string}>} dependencies - List of dependencies to check\n * @returns {Object} - Object with availability status for each dependency\n */\nexport function checkPeerDependencies(dependencies) {\n const results = {};\n const missing = [];\n\n for (const { package: packageName, integration } of dependencies) {\n const available = isPeerDependencyAvailable(packageName);\n results[packageName] = available;\n \n if (!available) {\n missing.push({ package: packageName, integration });\n }\n }\n\n if (missing.length > 0) {\n const installCommands = missing.map(({ package: pkg }) => pkg).join(' ');\n const integrationsList = missing.map(({ integration }) => integration).join(', ');\n \n console.warn(\n `Optional dependencies missing for ${integrationsList} integration(s).\\n` +\n `To use these integrations, install: npm install ${installCommands}\\n` +\n `Or with pnpm: pnpm add ${installCommands}\\n` +\n `Or with yarn: yarn add ${installCommands}`\n );\n }\n\n return results;\n}\n\n/**\n * Create a function that checks for a dependency before executing\n * @param {string} packageName - Name of the package required\n * @param {string} integrationName - Human-readable name of the integration\n * @param {Function} fn - Function to execute if dependency is available\n * @returns {Function} - Wrapped function with dependency check\n */\nexport function requirePeerDependency(packageName, integrationName, fn) {\n return function(...args) {\n if (!isPeerDependencyAvailable(packageName)) {\n throw new Error(\n `${integrationName} integration requires the '${packageName}' package to be installed.\\n` +\n `Please install it with: npm install ${packageName}`\n );\n }\n return fn.apply(this, args);\n };\n}\n", "/**\n * Shadow DOM Component System for Coherent.js\n * Provides true style encapsulation using native Shadow DOM\n */\n\n// Check if Shadow DOM is supported\nexport function isShadowDOMSupported() {\n if (typeof window === 'undefined') return false;\n if (typeof window.Element === 'undefined') return false;\n \n return 'attachShadow' in window.Element.prototype && \n 'getRootNode' in window.Element.prototype;\n}\n\n// Create a Shadow DOM component\nexport function createShadowComponent(element, componentDef, options = {}) {\n if (!isShadowDOMSupported()) {\n throw new Error('Shadow DOM is not supported in this environment');\n }\n \n const shadowRoot = element.attachShadow({ \n mode: options.mode || 'closed',\n delegatesFocus: options.delegatesFocus || false\n });\n \n // Extract and inject styles\n const styles = extractStyles(componentDef);\n if (styles && typeof window !== 'undefined' && window.document) {\n const styleElement = window.document.createElement('style');\n styleElement.textContent = styles;\n shadowRoot.appendChild(styleElement);\n }\n \n // Render component content\n const content = renderToShadowDOM(componentDef);\n shadowRoot.innerHTML += content;\n \n return shadowRoot;\n}\n\n// Extract CSS from component definition\nfunction extractStyles(componentDef) {\n let allStyles = '';\n \n function extractFromElement(element) {\n if (!element || typeof element !== 'object') return;\n \n if (Array.isArray(element)) {\n element.forEach(extractFromElement);\n return;\n }\n \n for (const [tagName, props] of Object.entries(element)) {\n if (tagName === 'style' && typeof props === 'object' && props.text) {\n allStyles += `${props.text }\\n`;\n } else if (typeof props === 'object' && props !== null) {\n if (props.children) {\n extractFromElement(props.children);\n }\n }\n }\n }\n \n extractFromElement(componentDef);\n return allStyles;\n}\n\n// Render component content for Shadow DOM (without style tags)\nfunction renderToShadowDOM(componentDef) {\n function stripStyles(element) {\n if (!element || typeof element !== 'object') return element;\n \n if (Array.isArray(element)) {\n return element.map(stripStyles);\n }\n \n const result = {};\n for (const [tagName, props] of Object.entries(element)) {\n // Skip style elements - they're handled separately\n if (tagName === 'style') continue;\n \n if (typeof props === 'object' && props !== null) {\n const cleanProps = { ...props };\n if (cleanProps.children) {\n cleanProps.children = stripStyles(cleanProps.children);\n }\n result[tagName] = cleanProps;\n } else {\n result[tagName] = props;\n }\n }\n \n return result;\n }\n \n const cleanComponent = stripStyles(componentDef);\n \n // Import renderRaw from main module (avoiding circular deps)\n // This would need to be properly imported in real usage\n return renderComponentContent(cleanComponent);\n}\n\n// Simple DOM-based rendering for Shadow DOM content\nfunction renderComponentContent(obj) {\n if (obj === null || obj === undefined) return '';\n if (typeof obj === 'string' || typeof obj === 'number') {\n return escapeHTML(String(obj));\n }\n if (Array.isArray(obj)) {\n return obj.map(renderComponentContent).join('');\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 \n // Build attributes string\n const attrsStr = Object.entries(attributes)\n .filter(([, value]) => value !== null && value !== undefined && value !== false)\n .map(([key, value]) => {\n const attrName = key === 'className' ? 'class' : key;\n if (value === true) return attrName;\n return `${attrName}=\"${escapeHTML(String(value))}\"`;\n })\n .join(' ');\n \n const openTag = attrsStr ? `<${tagName} ${attrsStr}>` : `<${tagName}>`;\n \n // Handle void elements\n if (['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',\n 'link', 'meta', 'param', 'source', 'track', 'wbr'].includes(tagName)) {\n return openTag.replace('>', ' />');\n }\n \n let content = '';\n if (text !== undefined) {\n content = escapeHTML(String(text));\n } else if (children) {\n content = renderComponentContent(children);\n }\n \n return `${openTag}${content}</${tagName}>`;\n } else if (typeof props === 'string') {\n const content = escapeHTML(props);\n return `<${tagName}>${content}</${tagName}>`;\n }\n }\n\n return '';\n}\n\nfunction escapeHTML(text) {\n if (typeof window === 'undefined' || !window.document) {\n // Server-side fallback\n return String(text)\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;');\n }\n const div = window.document.createElement('div');\n div.textContent = text;\n return div.innerHTML;\n}\n\n// Hybrid rendering: Shadow DOM on client, scoped on server\nexport function renderWithBestEncapsulation(componentDef, containerElement = null) {\n if (isShadowDOMSupported() && containerElement) {\n // Use Shadow DOM for true isolation\n return createShadowComponent(containerElement, componentDef);\n } else {\n // Fallback to scoped rendering\n // This would import from main module in real usage\n console.warn('Shadow DOM not available, falling back to scoped rendering');\n return null; // Would return scoped render result\n }\n}\n\nexport default {\n isShadowDOMSupported,\n createShadowComponent,\n renderWithBestEncapsulation\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 * Component Integration for Coherent.js Event Bus\n *\n * Provides higher-order components and utilities for integrating\n * the event bus with Coherent.js components and state management.\n */\n\nimport { globalEventBus } from './event-bus.js';\nimport { withState } from '../components/component-system.js';\n\n/**\n * Higher-order component that provides event bus integration\n * @param {Object} options - Integration options\n * @returns {Function} HOC function\n */\nexport function withEventBus(options = {}) {\n const {\n scope = null, // Event scope for namespacing\n events = {}, // Event listeners to register\n actions = {}, // Action handlers to register\n eventBus = globalEventBus,\n debug = false,\n autoCleanup = true\n } = options;\n\n return function withEventBusHOC(WrappedComponent) {\n function EventBusComponent(props = {}, state = {}, context = {}) {\n // Create scoped event bus if scope is provided\n const bus = scope ? eventBus.createScope(scope) : eventBus;\n\n // Register event listeners\n const listenerIds = new Map();\n\n Object.entries(events).forEach(([event, handler]) => {\n const listenerId = bus.on(event, (data, eventName) => {\n if (typeof handler === 'function') {\n handler.call(this, data, eventName, {props, state, context});\n }\n });\n listenerIds.set(event, listenerId);\n });\n\n // Register action handlers\n Object.entries(actions).forEach(([action, handler]) => {\n bus.registerAction(action, (actionContext) => {\n if (typeof handler === 'function') {\n handler.call(this, actionContext, {props, state, context});\n }\n });\n });\n\n // Create event bus utilities for the component\n const eventUtils = {\n emit: bus.emit.bind(bus),\n emitSync: bus.emitSync.bind(bus),\n on: bus.on.bind(bus),\n once: bus.once.bind(bus),\n off: bus.off.bind(bus),\n registerAction: bus.registerAction.bind(bus),\n handleAction: bus.handleAction.bind(bus),\n\n // Cleanup function\n cleanup: () => {\n listenerIds.forEach((listenerId, event) => {\n bus.off(event, listenerId);\n });\n listenerIds.clear();\n }\n };\n\n // Enhanced props with event bus\n const enhancedProps = {\n ...props,\n eventBus: bus,\n eventUtils\n };\n\n if (debug) {\n console.log('[withEventBus] Rendering component with event bus:', {\n scope,\n registeredEvents: Object.keys(events),\n registeredActions: Object.keys(actions)\n });\n }\n\n // Render the wrapped component\n const result = typeof WrappedComponent === 'function'\n ? WrappedComponent(enhancedProps, state, context)\n : WrappedComponent;\n\n // Auto-cleanup on unmount (if supported)\n if (autoCleanup && result && typeof result === 'object') {\n // Add cleanup to the component if it supports lifecycle\n if (result.componentWillUnmount) {\n const originalUnmount = result.componentWillUnmount;\n result.componentWillUnmount = function() {\n eventUtils.cleanup();\n originalUnmount.call(this);\n };\n } else {\n result.__eventBusCleanup = eventUtils.cleanup;\n }\n }\n\n return result;\n }\n\n EventBusComponent.displayName = `withEventBus(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`;\n EventBusComponent.__isHOC = true;\n EventBusComponent.__eventBusIntegration = true;\n\n return EventBusComponent;\n };\n}\n\n/**\n * Higher-order component that combines event bus with state management\n * @param {Object} initialState - Initial component state\n * @param {Object} options - Integration options\n * @returns {Function} HOC function\n */\nexport function withEventState(initialState = {}, options = {}) {\n const {\n events = {},\n actions = {},\n stateActions = {}, // Actions that modify state\n eventBus = globalEventBus,\n scope = null,\n debug = false\n } = options;\n\n return function withEventStateHOC(WrappedComponent) {\n // First apply state management\n const StatefulComponent = withState(initialState, {\n actions: stateActions,\n debug\n })(WrappedComponent);\n\n // Then apply event bus integration\n return withEventBus({\n scope,\n events: {\n ...events,\n // Add state-aware event handlers\n ...Object.entries(events).reduce((acc, [event, handler]) => {\n acc[event] = function(data, eventName, context) {\n // Pass state utilities to event handlers\n return handler.call(this, data, eventName, {\n ...context,\n stateUtils: context.props.stateUtils\n });\n };\n return acc;\n }, {})\n },\n actions: {\n ...actions,\n // Add state-aware action handlers\n ...Object.entries(actions).reduce((acc, [action, handler]) => {\n acc[action] = function(actionContext, componentContext) {\n // Pass state utilities to action handlers\n return handler.call(this, actionContext, {\n ...componentContext,\n stateUtils: componentContext.props.stateUtils\n });\n };\n return acc;\n }, {})\n },\n eventBus,\n debug\n })(StatefulComponent);\n };\n}\n\n/**\n * Create action handlers for common patterns\n */\nexport const createActionHandlers = {\n /**\n * Create a modal control action handler\n * @param {string} modalId - Modal identifier\n * @returns {Object} Action handlers for modal control\n */\n modal: (modalId) => ({\n 'open-modal': ({data, emit}) => {\n const targetModalId = data.modalId || modalId;\n emit('modal:open', {modalId: targetModalId});\n },\n 'close-modal': ({data, emit}) => {\n const targetModalId = data.modalId || modalId;\n emit('modal:close', {modalId: targetModalId});\n },\n 'toggle-modal': ({data, emit}) => {\n const targetModalId = data.modalId || modalId;\n emit('modal:toggle', {modalId: targetModalId});\n }\n }),\n\n /**\n * Create form handling action handlers\n * @param {Object} options - Form handling options\n * @returns {Object} Action handlers for forms\n */\n form: (options = {}) => {\n const {\n onSubmit = null,\n onValidate = null,\n onReset = null\n } = options;\n\n return {\n 'submit-form': ({element, emit}) => {\n const formData = extractFormData(element.closest('form'));\n\n if (onValidate) {\n const isValid = onValidate(formData);\n if (!isValid) {\n emit('form:validation-failed', {formData});\n return;\n }\n }\n\n if (onSubmit) {\n onSubmit(formData);\n }\n\n emit('form:submit', {formData, element});\n },\n 'reset-form': ({element, emit}) => {\n const form = element.closest('form');\n if (form) {\n form.reset();\n }\n\n if (onReset) {\n onReset();\n }\n\n emit('form:reset', {element});\n },\n 'validate-form': ({element, emit}) => {\n const formData = extractFormData(element.closest('form'));\n\n if (onValidate) {\n const isValid = onValidate(formData);\n emit('form:validation', {formData, isValid});\n }\n }\n };\n },\n\n /**\n * Create CRUD action handlers\n * @param {Object} options - CRUD options\n * @returns {Object} Action handlers for CRUD operations\n */\n crud: (options = {}) => {\n const {\n entityName = 'item',\n onCreate = null,\n onUpdate = null,\n onDelete = null,\n onRead = null\n } = options;\n\n return {\n [`create-${entityName}`]: ({data, emit}) => {\n if (onCreate) {\n onCreate(data);\n }\n emit(`${entityName}:create`, data);\n },\n [`update-${entityName}`]: ({data, emit}) => {\n if (onUpdate) {\n onUpdate(data);\n }\n emit(`${entityName}:update`, data);\n },\n [`delete-${entityName}`]: ({data, emit}) => {\n if (onDelete) {\n onDelete(data);\n }\n emit(`${entityName}:delete`, data);\n },\n [`read-${entityName}`]: ({data, emit}) => {\n if (onRead) {\n onRead(data);\n }\n emit(`${entityName}:read`, data);\n }\n };\n },\n\n /**\n * Create navigation action handlers\n * @param {Object} options - Navigation options\n * @returns {Object} Action handlers for navigation\n */\n navigation: (options = {}) => {\n const {\n onNavigate = null,\n history = null\n } = options;\n\n return {\n 'navigate-to': ({data, emit}) => {\n const {url, replace = false} = data;\n\n if (history) {\n if (replace) {\n history.replace(url);\n } else {\n history.push(url);\n }\n } else if (typeof window !== 'undefined') {\n if (replace) {\n window.location.replace(url);\n } else {\n window.location.href = url;\n }\n }\n\n if (onNavigate) {\n onNavigate(url, replace);\n }\n\n emit('navigation:change', {url, replace});\n },\n 'navigate-back': ({emit}) => {\n if (history) {\n history.goBack();\n } else if (typeof window !== 'undefined') {\n window.history.back();\n }\n\n emit('navigation:back');\n }\n };\n }\n};\n\n/**\n * Create event handlers for common patterns\n */\nexport const createEventHandlers = {\n /**\n * Create notification event handlers\n * @param {Function} showNotification - Function to show notifications\n * @returns {Object} Event handlers for notifications\n */\n notifications: (showNotification) => ({\n 'notification:show': (data) => {\n showNotification(data);\n },\n 'notification:success': (data) => {\n showNotification({\n type: 'success',\n message: data.message || 'Operation successful',\n ...data\n });\n },\n 'notification:error': (data) => {\n showNotification({\n type: 'error',\n message: data.message || 'An error occurred',\n ...data\n });\n },\n 'notification:warning': (data) => {\n showNotification({\n type: 'warning',\n message: data.message || 'Warning',\n ...data\n });\n },\n 'notification:info': (data) => {\n showNotification({\n type: 'info',\n message: data.message || 'Information',\n ...data\n });\n }\n }),\n\n /**\n * Create loading state event handlers\n * @param {Function} setLoading - Function to set loading state\n * @returns {Object} Event handlers for loading states\n */\n loading: (setLoading) => ({\n 'loading:start': (data) => {\n setLoading(true, data);\n },\n 'loading:stop': (data) => {\n setLoading(false, data);\n },\n 'loading:toggle': (data) => {\n setLoading(current => !current, data);\n }\n })\n};\n\n/**\n * Utility to create a component with built-in event patterns\n * @param {Function} component - Component function\n * @param {Object} options - Configuration options\n * @returns {Function} Enhanced component\n */\nexport function createEventComponent(component, options = {}) {\n const {\n initialState = {},\n scope = null,\n patterns = [], // Array of pattern names: ['modal', 'form', 'crud', 'navigation']\n patternOptions = {}, // Options for each pattern\n customActions = {},\n customEvents = {},\n debug = false\n } = options;\n\n // Build actions from patterns\n let actions = {...customActions};\n patterns.forEach(pattern => {\n const patternActions = createActionHandlers[pattern]?.(patternOptions[pattern] || {});\n if (patternActions) {\n actions = {...actions, ...patternActions};\n }\n });\n\n // Build events from patterns\n let events = {...customEvents};\n patterns.forEach(pattern => {\n const patternEvents = createEventHandlers[pattern]?.(patternOptions[pattern]);\n if (patternEvents) {\n events = {...events, ...patternEvents};\n }\n });\n\n return withEventState(initialState, {\n scope,\n actions,\n events,\n debug\n })(component);\n}\n\n/**\n * Decorator for adding event bus to component methods\n * @param {string} eventName - Event to emit\n * @param {Object} options - Emit options\n * @returns {Function} Method decorator\n */\nexport function emitEvent(eventName, options = {}) {\n const {\n scope = null,\n data = null,\n async = false\n } = options;\n\n return function decorator(target, propertyKey, descriptor) {\n const originalMethod = descriptor.value;\n\n descriptor.value = function(...args) {\n const bus = scope ? globalEventBus.createScope(scope) : globalEventBus;\n\n const result = originalMethod.apply(this, args);\n\n const eventData = typeof data === 'function' ? data(args, result) : data;\n\n if (async) {\n bus.emit(eventName, eventData);\n } else {\n bus.emitSync(eventName, eventData);\n }\n\n return result;\n };\n\n return descriptor;\n };\n}\n\n/**\n * Utility function to extract form data\n * @private\n */\nfunction extractFormData(form) {\n if (!form) return {};\n\n const formData = new FormData(form);\n const data = {};\n\n for (const [key, value] of formData.entries()) {\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\nexport default {\n withEventBus,\n withEventState,\n createActionHandlers,\n createEventHandlers,\n createEventComponent,\n emitEvent\n};", "/**\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 * Enhanced FP Component Composition Tools for Coherent.js\n *\n * Advanced composition utilities that maintain functional purity\n * while providing powerful component patterns\n */\n\n/**\n * Higher-Order Component (HOC) patterns\n */\nexport const hoc = {\n /**\n * Wrap component with additional props\n */\n withProps(additionalProps) {\n return (Component) => (props) => {\n return Component({ ...props, ...additionalProps });\n };\n },\n\n /**\n * Conditional rendering HOC\n */\n withCondition(condition) {\n return (Component) => (props) => {\n return condition(props) ? Component(props) : null;\n };\n },\n\n /**\n * Loading state HOC\n */\n withLoading(loadingComponent) {\n return (Component) => (props) => {\n return props.loading ? loadingComponent(props) : Component(props);\n };\n },\n\n /**\n * Error boundary HOC\n */\n withError(errorComponent) {\n return (Component) => (props) => {\n try {\n return Component(props);\n } catch (error) {\n return errorComponent({ error, ...props });\n }\n };\n },\n\n /**\n * Memoization HOC\n */\n withMemo(getMemoKey) {\n const cache = new Map();\n\n return (Component) => (props) => {\n const key = getMemoKey ? getMemoKey(props) : JSON.stringify(props);\n\n if (cache.has(key)) {\n return cache.get(key);\n }\n\n const result = Component(props);\n cache.set(key, result);\n return result;\n };\n }\n};\n\n/**\n * Component composition utilities\n */\nexport const compose = {\n /**\n * Combine multiple components into one\n */\n combine(...components) {\n return (props) => ({\n fragment: {\n children: components.map(Component => Component(props))\n }\n });\n },\n\n /**\n * Pipe components through transformations\n */\n pipe(...transformers) {\n return (Component) => {\n return transformers.reduce((acc, transformer) => transformer(acc), Component);\n };\n },\n\n /**\n * Branch based on conditions\n */\n branch(condition, leftComponent, rightComponent) {\n return (props) => {\n return condition(props) ? leftComponent(props) : rightComponent(props);\n };\n },\n\n /**\n * Render component or fallback\n */\n maybe(Component, fallback = null) {\n return (props) => {\n return Component ? Component(props) : fallback;\n };\n }\n};\n\n/**\n * Layout composition patterns\n */\nexport const layout = {\n /**\n * Stack components vertically\n */\n stack(spacing = '1rem', ...components) {\n return {\n div: {\n style: `display: flex; flex-direction: column; gap: ${spacing};`,\n children: components\n }\n };\n },\n\n /**\n * Stack components horizontally\n */\n hstack(spacing = '1rem', ...components) {\n return {\n div: {\n style: `display: flex; flex-direction: row; gap: ${spacing}; align-items: center;`,\n children: components\n }\n };\n },\n\n /**\n * Grid layout\n */\n grid(columns = 'auto', rows = 'auto', gap = '1rem', ...components) {\n return {\n div: {\n style: `display: grid; grid-template-columns: ${columns}; grid-template-rows: ${rows}; gap: ${gap};`,\n children: components\n }\n };\n },\n\n /**\n * Card layout wrapper\n */\n card(title, content, actions = []) {\n return {\n div: {\n className: 'card',\n style: 'border: 1px solid #ddd; border-radius: 8px; padding: 1rem; margin: 0.5rem;',\n children: [\n ...(title ? [{\n h3: {\n style: 'margin-top: 0; margin-bottom: 1rem;',\n text: title\n }\n }] : []),\n ...(Array.isArray(content) ? content : [content]),\n ...(actions.length > 0 ? [{\n div: {\n style: 'margin-top: 1rem; display: flex; gap: 0.5rem;',\n children: actions\n }\n }] : [])\n ]\n }\n };\n },\n\n /**\n * Sidebar layout\n */\n sidebar(sidebar, main, sidebarWidth = '250px') {\n return {\n div: {\n style: 'display: flex; min-height: 100vh;',\n children: [\n {\n aside: {\n style: `width: ${sidebarWidth}; border-right: 1px solid #ddd; padding: 1rem;`,\n children: sidebar\n }\n },\n {\n main: {\n style: 'flex: 1; padding: 1rem;',\n children: main\n }\n }\n ]\n }\n };\n }\n};\n\n/**\n * Data flow patterns\n */\nexport const data = {\n /**\n * Map over array data\n */\n map(dataArray, itemComponent, keyExtractor = (item, index) => index) {\n return {\n fragment: {\n children: dataArray.map((item, index) => ({\n ...itemComponent(item, index),\n key: keyExtractor(item, index)\n }))\n }\n };\n },\n\n /**\n * Conditional rendering based on data\n */\n when(data, component, emptyComponent = null) {\n if (Array.isArray(data)) {\n return data.length > 0 ? component(data) : emptyComponent;\n }\n return data ? component(data) : emptyComponent;\n },\n\n /**\n * Switch/case pattern for data\n */\n switch(value, cases, defaultCase = null) {\n const component = cases[value] || defaultCase;\n return component ? component(value) : null;\n },\n\n /**\n * Async data loader\n */\n async(_loader, _loadingComponent, _errorComponent, _successComponent) {\n return {\n fragment: {\n children: [\n // This would be handled by the rendering system\n // For now, return a placeholder\n { div: { text: 'Loading async data...' }}\n ]\n }\n };\n }\n};\n\n/**\n * Form composition utilities\n */\nexport const form = {\n /**\n * Form field wrapper\n */\n field(label, inputComponent, error = null) {\n return {\n div: {\n className: 'form-field',\n style: 'margin-bottom: 1rem;',\n children: [\n ...(label ? [{\n label: {\n style: 'display: block; margin-bottom: 0.25rem; font-weight: bold;',\n text: label\n }\n }] : []),\n inputComponent,\n ...(error ? [{\n div: {\n style: 'color: red; font-size: 0.875rem; margin-top: 0.25rem;',\n text: error\n }\n }] : [])\n ]\n }\n };\n },\n\n /**\n * Input field generator\n */\n input(type, options = {}) {\n return (props) => ({\n input: {\n type,\n ...options,\n ...props\n }\n });\n },\n\n /**\n * Select field generator\n */\n select(optionsArray, placeholder = 'Select an option') {\n return (props) => ({\n select: {\n ...props,\n children: [\n ...(placeholder ? [{\n option: {\n value: '',\n text: placeholder,\n disabled: true,\n selected: !props.value\n }\n }] : []),\n ...optionsArray.map(option => ({\n option: {\n value: option.value,\n text: option.label,\n selected: props.value === option.value\n }\n }))\n ]\n }\n });\n },\n\n /**\n * Form wrapper with validation\n */\n wrapper(onSubmit, children) {\n return {\n form: {\n onsubmit: (e) => {\n e.preventDefault();\n onSubmit(new FormData(e.target));\n },\n children\n }\n };\n }\n};\n\n/**\n * Animation and transition utilities\n */\nexport const animation = {\n /**\n * Fade in component\n */\n fadeIn(duration = '300ms', component) {\n return {\n div: {\n style: `animation: fadeIn ${duration} ease-in;`,\n children: component\n }\n };\n },\n\n /**\n * Slide in component\n */\n slideIn(direction = 'left', duration = '300ms', component) {\n const animations = {\n left: 'slideInLeft',\n right: 'slideInRight',\n up: 'slideInUp',\n down: 'slideInDown'\n };\n\n return {\n div: {\n style: `animation: ${animations[direction]} ${duration} ease-out;`,\n children: component\n }\n };\n },\n\n /**\n * Transition wrapper\n */\n transition(property = 'all', duration = '300ms', component) {\n return {\n div: {\n style: `transition: ${property} ${duration} ease;`,\n children: component\n }\n };\n }\n};\n\n/**\n * Responsive design utilities\n */\nexport const responsive = {\n /**\n * Responsive container\n */\n container(maxWidth = '1200px', component) {\n return {\n div: {\n style: `max-width: ${maxWidth}; margin: 0 auto; padding: 0 1rem;`,\n children: component\n }\n };\n },\n\n /**\n * Hide on mobile\n */\n hideMobile(component) {\n return {\n div: {\n className: 'hide-mobile',\n style: '@media (max-width: 768px) { display: none; }',\n children: component\n }\n };\n },\n\n /**\n * Show only on mobile\n */\n mobileOnly(component) {\n return {\n div: {\n className: 'mobile-only',\n style: '@media (min-width: 769px) { display: none; }',\n children: component\n }\n };\n }\n};\n\n/**\n * Component factories for common patterns\n */\nexport const factories = {\n /**\n * Button factory\n */\n button(variant = 'primary', size = 'medium') {\n const variants = {\n primary: 'background: #007bff; color: white; border: none;',\n secondary: 'background: #6c757d; color: white; border: none;',\n danger: 'background: #dc3545; color: white; border: none;',\n outline: 'background: transparent; border: 1px solid #007bff; color: #007bff;'\n };\n\n const sizes = {\n small: 'padding: 0.25rem 0.5rem; font-size: 0.875rem;',\n medium: 'padding: 0.5rem 1rem; font-size: 1rem;',\n large: 'padding: 0.75rem 1.5rem; font-size: 1.125rem;'\n };\n\n return (props) => ({\n button: {\n style: `${variants[variant]} ${sizes[size]} border-radius: 4px; cursor: pointer;`,\n ...props\n }\n });\n },\n\n /**\n * Card factory\n */\n card(variant = 'default') {\n const variants = {\n default: 'border: 1px solid #ddd; border-radius: 8px; padding: 1rem;',\n elevated: 'border: none; border-radius: 8px; padding: 1rem; box-shadow: 0 2px 8px rgba(0,0,0,0.1);',\n outlined: 'border: 2px solid #007bff; border-radius: 8px; padding: 1rem;'\n };\n\n return (props) => ({\n div: {\n className: `card card-${variant}`,\n style: variants[variant],\n ...props\n }\n });\n },\n\n /**\n * Alert factory\n */\n alert(type = 'info') {\n const types = {\n info: 'background: #d1ecf1; color: #0c5460; border: 1px solid #bee5eb;',\n success: 'background: #d4edda; color: #155724; border: 1px solid #c3e6cb;',\n warning: 'background: #fff3cd; color: #856404; border: 1px solid #ffeaa7;',\n error: 'background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb;'\n };\n\n return (props) => ({\n div: {\n className: `alert alert-${type}`,\n style: `${types[type]} padding: 0.75rem 1rem; border-radius: 4px; margin-bottom: 1rem;`,\n ...props\n }\n });\n }\n};\n\n/**\n * Demo of enhanced composition\n */\nexport function demoEnhancedComposition() {\n // Create enhanced components using composition utilities\n const PrimaryButton = factories.button('primary', 'medium');\n const SecondaryButton = factories.button('secondary', 'small');\n const ElevatedCard = factories.card('elevated');\n const SuccessAlert = factories.alert('success');\n\n // Form with enhanced composition\n const UserForm = ({ onSubmit, errors = {} }) => {\n const NameInput = form.input('text', { placeholder: 'Enter name' });\n const EmailInput = form.input('email', { placeholder: 'Enter email' });\n\n return form.wrapper(onSubmit, [\n layout.card('User Information', [\n form.field('Name', NameInput({ name: 'name' }), errors.name),\n form.field('Email', EmailInput({ name: 'email' }), errors.email),\n layout.hstack('0.5rem',\n PrimaryButton({ type: 'submit', text: 'Save' }),\n SecondaryButton({ type: 'button', text: 'Cancel', onclick: () => console.log('Cancel') })\n )\n ])\n ]);\n };\n\n // List with enhanced composition\n const UserList = ({ users, onEdit, onDelete }) => {\n const UserItem = (user, _index) => ElevatedCard({\n key: user.id,\n children: [\n layout.hstack('1rem',\n { div: { children: [\n { h4: { text: user.name }},\n { p: { text: user.email }}\n ]}},\n layout.hstack('0.25rem',\n PrimaryButton({ text: 'Edit', onclick: () => onEdit(user) }),\n factories.button('danger', 'small')({ text: 'Delete', onclick: () => onDelete(user) })\n )\n )\n ]\n });\n\n return data.when(users,\n (users) => data.map(users, UserItem, user => user.id),\n SuccessAlert({ text: 'No users found' })\n );\n };\n\n return {\n UserForm,\n UserList,\n PrimaryButton,\n SecondaryButton,\n ElevatedCard,\n SuccessAlert\n };\n}\n\nexport default {\n hoc,\n compose,\n layout,\n data,\n form,\n animation,\n responsive,\n factories,\n demoEnhancedComposition\n};\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,0BAAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,cAAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA,2BAAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASA,qBAA6B;;;ACgBtB,SAAS,yBAAyB,UAAU,CAAC,GAAG;AACrD,QAAM,OAAO;AAAA,IACX,SAAS;AAAA,IACT,SAAS;AAAA,MACP,QAAQ,CAAC;AAAA,IACX;AAAA,IACA,UAAU;AAAA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,QAAQ,GAAG,GAAG;AAC9C,WAAO,GAAG,IAAIA,WAAU,KAAK;AAAA,EAC/B;AACA,SAAO;AACT;AAGA,IAAM,mBAAmB,KAAK;AAAA,MAC5B,6BAAa,IAAI,IAAI,mBAAmB,YAAY,GAAG,GAAG,OAAO;AACnE;AACO,IAAM,UAAU,iBAAiB;AA8DjC,IAAM,KAAK;AAAA;AAAA;AAAA;AAAA,EAIhB,IAAI,IAAI;AACN,WAAO,CAAC,UAAU,MAAM,IAAI,EAAE;AAAA,EAChC;AACF;AAKA,IAAM,WAAW;AAAA;AAAA,EAEf,QAAAC;AAAA;AAAA,EAGA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA,MAAAC;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA,aAAa;AAAA,EACb;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA,mBAAAC;AAAA,EACA,kBAAAC;AAAA,EACA,WAAAC;AAAA,EACA,YAAAC;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAO,gBAAQ;",
6
+ "names": ["deepClone", "isCoherentObject", "memo", "render", "validateComponent", "context", "context", "context", "html", "context", "middleware", "context", "context", "context", "module", "context", "emit", "eventSystem", "Component", "escapeHtml", "render", "memo", "validateComponent", "isCoherentObject", "deepClone", "render", "memo", "validateComponent", "isCoherentObject", "deepClone", "escapeHtml"]
7
7
  }