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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,18 @@
1
1
  var __defProp = Object.defineProperty;
2
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
+ }) : x)(function(x) {
5
+ if (typeof require !== "undefined") return require.apply(this, arguments);
6
+ throw Error('Dynamic require of "' + x + '" is not supported');
7
+ });
2
8
  var __export = (target, all) => {
3
9
  for (var name in all)
4
10
  __defProp(target, name, { get: all[name], enumerable: true });
5
11
  };
6
12
 
13
+ // src/index.js
14
+ import { readFileSync } from "node:fs";
15
+
7
16
  // src/performance/monitor.js
8
17
  function createPerformanceMonitor(options = {}) {
9
18
  const opts = {
@@ -593,737 +602,2256 @@ function validateComponent(component, path = "root") {
593
602
  }
594
603
  throw new Error(`Invalid component type at ${path}: ${typeof component}`);
595
604
  }
596
-
597
- // src/components/component-system.js
598
- var COMPONENT_REGISTRY = /* @__PURE__ */ new Map();
599
- var COMPONENT_METADATA = /* @__PURE__ */ new WeakMap();
600
- var ComponentState = class {
601
- constructor(initialState = {}) {
602
- this.state = { ...initialState };
603
- this.listeners = /* @__PURE__ */ new Set();
604
- this.isUpdating = false;
605
+ function isCoherentObject(obj) {
606
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
607
+ return false;
605
608
  }
606
- /**
607
- * Get state value by key or entire state
608
- *
609
- * @param {string} [key] - State key to retrieve
610
- * @returns {*} State value or entire state object
611
- */
612
- get(key) {
613
- return key ? this.state[key] : { ...this.state };
609
+ const keys = Object.keys(obj);
610
+ if (keys.length === 0) {
611
+ return false;
614
612
  }
615
- /**
616
- * Update state with new values
617
- *
618
- * @param {Object} updates - State updates to apply
619
- * @returns {ComponentState} This instance for chaining
620
- */
621
- set(updates) {
622
- if (this.isUpdating) return this;
623
- const oldState = { ...this.state };
624
- if (typeof updates === "function") {
625
- updates = updates(oldState);
613
+ return keys.every((key) => {
614
+ if (key === "text") return true;
615
+ return /^[a-zA-Z][a-zA-Z0-9-]*$/.test(key);
616
+ });
617
+ }
618
+ function extractProps(coherentObj) {
619
+ if (!isCoherentObject(coherentObj)) {
620
+ return {};
621
+ }
622
+ const props = {};
623
+ const keys = Object.keys(coherentObj);
624
+ keys.forEach((tag) => {
625
+ const value = coherentObj[tag];
626
+ if (value && typeof value === "object" && !Array.isArray(value)) {
627
+ props[tag] = { ...value };
628
+ } else {
629
+ props[tag] = { text: value };
626
630
  }
627
- this.state = { ...this.state, ...updates };
628
- this.notifyListeners(oldState, this.state);
629
- return this;
630
- }
631
- subscribe(listener) {
632
- this.listeners.add(listener);
633
- return () => this.listeners.delete(listener);
631
+ });
632
+ return props;
633
+ }
634
+ function hasChildren(component) {
635
+ if (Array.isArray(component)) {
636
+ return component.length > 0;
634
637
  }
635
- notifyListeners(oldState, newState) {
636
- if (this.listeners.size === 0) return;
637
- this.isUpdating = true;
638
- this.listeners.forEach((listener) => {
639
- try {
640
- listener(newState, oldState);
641
- } catch (_error) {
642
- console.error("State listener _error:", _error);
643
- }
638
+ if (isCoherentObject(component)) {
639
+ if (component.children !== void 0 && component.children !== null) {
640
+ return Array.isArray(component.children) ? component.children.length > 0 : true;
641
+ }
642
+ const keys = Object.keys(component);
643
+ return keys.some((key) => {
644
+ const value = component[key];
645
+ return value && typeof value === "object" && value.children;
644
646
  });
645
- this.isUpdating = false;
646
647
  }
648
+ return false;
649
+ }
650
+ function normalizeChildren(children) {
651
+ if (children === null || children === void 0) {
652
+ return [];
653
+ }
654
+ if (Array.isArray(children)) {
655
+ return children.flat().filter((child) => child !== null && child !== void 0);
656
+ }
657
+ return [children];
658
+ }
659
+
660
+ // src/rendering/base-renderer.js
661
+ var DEFAULT_RENDERER_CONFIG = {
662
+ // Core rendering options
663
+ maxDepth: 100,
664
+ enableValidation: true,
665
+ enableMonitoring: false,
666
+ validateInput: true,
667
+ // HTML Renderer specific options
668
+ enableCache: true,
669
+ minify: false,
670
+ cacheSize: 1e3,
671
+ cacheTTL: 3e5,
672
+ // 5 minutes
673
+ // Streaming Renderer specific options
674
+ chunkSize: 1024,
675
+ // Size of each chunk in bytes
676
+ bufferSize: 4096,
677
+ // Internal buffer size
678
+ enableMetrics: false,
679
+ // Track streaming metrics
680
+ yieldThreshold: 100,
681
+ // Yield control after N elements
682
+ encoding: "utf8",
683
+ // Output encoding
684
+ // DOM Renderer specific options
685
+ enableHydration: true,
686
+ // Enable hydration support
687
+ namespace: null,
688
+ // SVG namespace support
689
+ // Performance options
690
+ enablePerformanceTracking: false,
691
+ performanceThreshold: 10,
692
+ // ms threshold for slow renders
693
+ // Development options
694
+ enableDevWarnings: typeof process !== "undefined" && process.env && true,
695
+ enableDebugLogging: false,
696
+ // Error handling options
697
+ errorFallback: "",
698
+ // Fallback content on errors
699
+ throwOnError: true
700
+ // Whether to throw or return fallback
647
701
  };
648
- var Component = class _Component {
649
- constructor(definition = {}) {
650
- this.definition = definition;
651
- this.name = definition.name || "AnonymousComponent";
652
- this.props = {};
653
- this.state = new ComponentState(definition.state || {});
654
- this.children = [];
655
- this.parent = null;
656
- this.rendered = null;
657
- this.isMounted = false;
658
- this.isDestroyed = false;
659
- this.hooks = {
660
- beforeCreate: definition.beforeCreate || (() => {
661
- }),
662
- created: definition.created || (() => {
663
- }),
664
- beforeMount: definition.beforeMount || (() => {
665
- }),
666
- mounted: definition.mounted || (() => {
667
- }),
668
- beforeUpdate: definition.beforeUpdate || (() => {
669
- }),
670
- updated: definition.updated || (() => {
671
- }),
672
- beforeDestroy: definition.beforeDestroy || (() => {
673
- }),
674
- destroyed: definition.destroyed || (() => {
675
- }),
676
- errorCaptured: definition.errorCaptured || (() => {
677
- })
702
+ var BaseRenderer = class {
703
+ constructor(options = {}) {
704
+ this.config = this.validateAndMergeConfig(options);
705
+ this.metrics = {
706
+ startTime: null,
707
+ endTime: null,
708
+ elementsProcessed: 0
678
709
  };
679
- this.methods = definition.methods || {};
680
- Object.keys(this.methods).forEach((methodName) => {
681
- if (typeof this.methods[methodName] === "function") {
682
- this[methodName] = this.methods[methodName].bind(this);
683
- }
684
- });
685
- this.computed = definition.computed || {};
686
- this.computedCache = /* @__PURE__ */ new Map();
687
- this.watchers = definition.watch || {};
688
- this.setupWatchers();
689
- COMPONENT_METADATA.set(this, {
690
- createdAt: Date.now(),
691
- updateCount: 0,
692
- renderCount: 0
693
- });
694
- this.callHook("beforeCreate");
695
- this.initialize();
696
- this.callHook("created");
697
710
  }
698
711
  /**
699
- * Initialize component
712
+ * Validate and merge configuration options
700
713
  */
701
- initialize() {
702
- this.unsubscribeState = this.state.subscribe((newState, oldState) => {
703
- this.onStateChange(newState, oldState);
704
- });
705
- this.initializeComputed();
714
+ validateAndMergeConfig(options) {
715
+ const config = { ...DEFAULT_RENDERER_CONFIG, ...options };
716
+ if (typeof config.maxDepth !== "number") {
717
+ throw new Error("maxDepth must be a number");
718
+ }
719
+ if (config.maxDepth <= 0) {
720
+ throw new Error("maxDepth must be a positive number");
721
+ }
722
+ if (typeof config.chunkSize !== "number") {
723
+ throw new Error("chunkSize must be a number");
724
+ }
725
+ if (config.chunkSize <= 0) {
726
+ throw new Error("chunkSize must be a positive number");
727
+ }
728
+ if (typeof config.yieldThreshold !== "number") {
729
+ throw new Error("yieldThreshold must be a number");
730
+ }
731
+ if (config.yieldThreshold <= 0) {
732
+ throw new Error("yieldThreshold must be a positive number");
733
+ }
734
+ if (config.enableDevWarnings) {
735
+ if (config.maxDepth > 1e3) {
736
+ console.warn("Coherent.js: maxDepth > 1000 may cause performance issues");
737
+ }
738
+ if (config.chunkSize > 16384) {
739
+ console.warn("Coherent.js: Large chunkSize may increase memory usage");
740
+ }
741
+ }
742
+ return config;
706
743
  }
707
744
  /**
708
- * Set up watchers for reactive data
745
+ * Get configuration for specific renderer type
709
746
  */
710
- setupWatchers() {
711
- Object.keys(this.watchers).forEach((key) => {
712
- const handler = this.watchers[key];
713
- this.state.subscribe((newState, oldState) => {
714
- if (newState[key] !== oldState[key]) {
715
- handler.call(this, newState[key], oldState[key]);
716
- }
717
- });
718
- });
747
+ getRendererConfig(rendererType) {
748
+ const baseConfig = { ...this.config };
749
+ switch (rendererType) {
750
+ case "html":
751
+ return {
752
+ ...baseConfig,
753
+ // HTML-specific defaults
754
+ enableCache: baseConfig.enableCache !== false,
755
+ enableMonitoring: baseConfig.enableMonitoring !== false
756
+ };
757
+ case "streaming":
758
+ return {
759
+ ...baseConfig,
760
+ // Streaming-specific defaults
761
+ enableMetrics: baseConfig.enableMetrics ?? false,
762
+ maxDepth: baseConfig.maxDepth ?? 1e3
763
+ // Higher default for streaming
764
+ };
765
+ case "dom":
766
+ return {
767
+ ...baseConfig,
768
+ // DOM-specific defaults
769
+ enableHydration: baseConfig.enableHydration !== false
770
+ };
771
+ default:
772
+ return baseConfig;
773
+ }
719
774
  }
720
775
  /**
721
- * Initialize computed properties
776
+ * Validate component structure
722
777
  */
723
- initializeComputed() {
724
- Object.keys(this.computed).forEach((key) => {
725
- Object.defineProperty(this, key, {
726
- get: () => {
727
- if (!this.computedCache.has(key)) {
728
- const value = this.computed[key].call(this);
729
- this.computedCache.set(key, value);
730
- }
731
- return this.computedCache.get(key);
732
- },
733
- enumerable: true
734
- });
735
- });
778
+ validateComponent(component) {
779
+ if (this.config.validateInput !== false) {
780
+ return validateComponent(component);
781
+ }
782
+ return true;
736
783
  }
737
784
  /**
738
- * Handle state changes
785
+ * Check if component is valid for rendering
739
786
  */
740
- onStateChange() {
741
- if (this.isDestroyed) return;
742
- this.computedCache.clear();
743
- if (this.isMounted) {
744
- this.update();
745
- }
787
+ isValidComponent(component) {
788
+ if (component === null || component === void 0) return true;
789
+ if (typeof component === "string" || typeof component === "number") return true;
790
+ if (typeof component === "function") return true;
791
+ if (Array.isArray(component)) return component.every((child) => this.isValidComponent(child));
792
+ if (isCoherentObject(component)) return true;
793
+ return false;
746
794
  }
747
795
  /**
748
- * Call lifecycle hook
796
+ * Validate rendering depth to prevent stack overflow
749
797
  */
750
- callHook(hookName, ...args) {
751
- try {
752
- if (this.hooks[hookName]) {
753
- return this.hooks[hookName].call(this, ...args);
754
- }
755
- } catch (_error) {
756
- this.handleError(_error, `${hookName} hook`);
798
+ validateDepth(depth) {
799
+ if (depth > this.config.maxDepth) {
800
+ throw new Error(`Maximum render depth (${this.config.maxDepth}) exceeded`);
757
801
  }
758
802
  }
759
803
  /**
760
- * Handle component errors
804
+ * Handle different component types with consistent logic
761
805
  */
762
- handleError(_error) {
763
- console.error(`Component Error in ${this.name}:`, _error);
764
- this.callHook("errorCaptured", _error);
765
- if (this.parent && this.parent.handleError) {
766
- this.parent.handleError(_error, `${this.name} -> ${context}`);
806
+ processComponentType(component) {
807
+ if (component === null || component === void 0) {
808
+ return { type: "empty", value: "" };
809
+ }
810
+ if (typeof component === "string") {
811
+ return { type: "text", value: component };
812
+ }
813
+ if (typeof component === "number" || typeof component === "boolean") {
814
+ return { type: "text", value: String(component) };
815
+ }
816
+ if (typeof component === "function") {
817
+ return { type: "function", value: component };
818
+ }
819
+ if (Array.isArray(component)) {
820
+ return { type: "array", value: component };
821
+ }
822
+ if (isCoherentObject(component)) {
823
+ return { type: "element", value: component };
767
824
  }
825
+ return { type: "unknown", value: component };
768
826
  }
769
827
  /**
770
- * Render the component
828
+ * Execute function components with _error handling
771
829
  */
772
- render(props = {}) {
773
- if (this.isDestroyed) {
774
- console.warn(`Attempting to render destroyed component: ${this.name}`);
775
- return null;
776
- }
830
+ executeFunctionComponent(func, depth = 0) {
777
831
  try {
778
- const metadata = COMPONENT_METADATA.get(this);
779
- if (metadata) {
780
- metadata.renderCount++;
781
- }
782
- this.props = { ...props };
783
- if (typeof this.definition.render === "function") {
784
- this.rendered = this.definition.render.call(this, this.props, this.state.get());
785
- } else if (typeof this.definition.template !== "undefined") {
786
- this.rendered = this.processTemplate(this.definition.template, this.props, this.state.get());
832
+ const isContextProvider = func.length > 0 || func.isContextProvider;
833
+ let result;
834
+ if (isContextProvider) {
835
+ result = func((children) => {
836
+ return this.renderComponent(children, this.config, depth + 1);
837
+ });
787
838
  } else {
788
- throw new Error(`Component ${this.name} must have either render method or template`);
839
+ result = func();
789
840
  }
790
- if (this.rendered !== null) {
791
- validateComponent(this.rendered, this.name);
841
+ if (typeof result === "function") {
842
+ return this.executeFunctionComponent(result, depth);
792
843
  }
793
- return this.rendered;
844
+ return result;
794
845
  } catch (_error) {
795
- this.handleError(_error);
796
- return { div: { className: "component-_error", text: `Error in ${this.name}` } };
846
+ if (this.config.enableMonitoring) {
847
+ performanceMonitor.recordError("functionComponent", _error);
848
+ }
849
+ if (typeof process !== "undefined" && process.env && true) {
850
+ console.warn("Coherent.js Function Component Error:", _error.message);
851
+ }
852
+ return null;
797
853
  }
798
854
  }
799
855
  /**
800
- * Process template with data
856
+ * Process element children consistently
801
857
  */
802
- processTemplate(template, props, state) {
803
- if (typeof template === "function") {
804
- return template.call(this, props, state);
805
- }
806
- if (typeof template === "string") {
807
- return template.replace(/\{\{(\w+)\}\}/g, (match, key) => {
808
- return props[key] || state[key] || "";
809
- });
858
+ processChildren(children, options, depth) {
859
+ if (!hasChildren({ children })) {
860
+ return [];
810
861
  }
811
- const processed = deepClone(template);
812
- this.interpolateObject(processed, { ...props, ...state });
813
- return processed;
862
+ const normalizedChildren = normalizeChildren(children);
863
+ return normalizedChildren.map(
864
+ (child) => this.renderComponent(child, options, depth + 1)
865
+ );
814
866
  }
815
867
  /**
816
- * Interpolate object with data
868
+ * Extract and process element attributes
817
869
  */
818
- interpolateObject(obj, data) {
819
- if (typeof obj === "string") {
820
- return obj.replace(/\{\{(\w+)\}\}/g, (match, key) => data[key] || "");
870
+ extractElementAttributes(props) {
871
+ if (!props || typeof props !== "object") return {};
872
+ const attributes = { ...props };
873
+ delete attributes.children;
874
+ delete attributes.text;
875
+ return attributes;
876
+ }
877
+ /**
878
+ * Record performance metrics
879
+ */
880
+ recordPerformance(operation, startTime, fromCache = false, metadata = {}) {
881
+ if (this.config.enableMonitoring) {
882
+ performanceMonitor.recordRender(
883
+ operation,
884
+ this.getCurrentTime() - startTime,
885
+ fromCache,
886
+ metadata
887
+ );
821
888
  }
822
- if (Array.isArray(obj)) {
823
- return obj.map((item) => this.interpolateObject(item, data));
889
+ }
890
+ /**
891
+ * Record _error for monitoring
892
+ */
893
+ recordError(operation, _error, metadata = {}) {
894
+ if (this.config.enableMonitoring) {
895
+ performanceMonitor.recordError(operation, _error, metadata);
824
896
  }
825
- if (obj && typeof obj === "object") {
826
- Object.keys(obj).forEach((key) => {
827
- obj[key] = this.interpolateObject(obj[key], data);
828
- });
897
+ }
898
+ /**
899
+ * Get current timestamp with fallback
900
+ */
901
+ getCurrentTime() {
902
+ if (typeof performance !== "undefined" && performance.now) {
903
+ return performance.now();
829
904
  }
830
- return obj;
905
+ return Date.now();
831
906
  }
832
907
  /**
833
- * Mount the component
908
+ * Start performance timing
834
909
  */
835
- mount() {
836
- if (this.isMounted || this.isDestroyed) return this;
837
- this.callHook("beforeMount");
838
- this.isMounted = true;
839
- this.callHook("mounted");
840
- return this;
910
+ startTiming() {
911
+ this.metrics.startTime = this.getCurrentTime();
841
912
  }
842
913
  /**
843
- * Update the component
914
+ * End performance timing
844
915
  */
845
- update() {
846
- if (!this.isMounted || this.isDestroyed) return this;
847
- const metadata = COMPONENT_METADATA.get(this);
848
- if (metadata) {
849
- metadata.updateCount++;
850
- }
851
- this.callHook("beforeUpdate");
852
- this.callHook("updated");
853
- return this;
916
+ endTiming() {
917
+ this.metrics.endTime = this.getCurrentTime();
854
918
  }
855
919
  /**
856
- * Destroy the component
920
+ * Get performance metrics
857
921
  */
858
- destroy() {
859
- if (this.isDestroyed) return this;
860
- this.callHook("beforeDestroy");
861
- if (this.unsubscribeState) {
862
- this.unsubscribeState();
863
- }
864
- this.children.forEach((child) => {
865
- if (child.destroy) {
866
- child.destroy();
867
- }
868
- });
869
- this.isMounted = false;
870
- this.isDestroyed = true;
871
- this.children = [];
872
- this.parent = null;
873
- this.callHook("destroyed");
874
- return this;
922
+ getMetrics() {
923
+ const duration = this.metrics.endTime ? this.metrics.endTime - this.metrics.startTime : this.getCurrentTime() - this.metrics.startTime;
924
+ return {
925
+ ...this.metrics,
926
+ duration,
927
+ elementsPerSecond: this.metrics.elementsProcessed / (duration / 1e3)
928
+ };
875
929
  }
876
930
  /**
877
- * Get component metadata
931
+ * Reset metrics for new render
878
932
  */
879
- getMetadata() {
880
- return COMPONENT_METADATA.get(this) || {};
933
+ resetMetrics() {
934
+ this.metrics = {
935
+ startTime: null,
936
+ endTime: null,
937
+ elementsProcessed: 0
938
+ };
881
939
  }
882
940
  /**
883
- * Clone component with new props/state
941
+ * Abstract method - must be implemented by subclasses
884
942
  */
885
- clone(overrides = {}) {
886
- const newDefinition = { ...this.definition, ...overrides };
887
- return new _Component(newDefinition);
943
+ renderComponent() {
944
+ throw new Error("renderComponent must be implemented by subclass");
945
+ }
946
+ /**
947
+ * Abstract method - must be implemented by subclasses
948
+ */
949
+ render() {
950
+ throw new Error("render must be implemented by subclass");
888
951
  }
889
952
  };
890
- function createComponent(definition) {
891
- if (typeof definition === "function") {
892
- definition = {
893
- name: definition.name || "FunctionalComponent",
894
- render: definition
895
- };
953
+ var RendererUtils = {
954
+ /**
955
+ * Check if element is static (no functions or circular references)
956
+ */
957
+ isStaticElement(element, visited = /* @__PURE__ */ new WeakSet()) {
958
+ if (!element || typeof element !== "object") {
959
+ return typeof element === "string" || typeof element === "number";
960
+ }
961
+ if (visited.has(element)) {
962
+ return false;
963
+ }
964
+ visited.add(element);
965
+ for (const [_key, value] of Object.entries(element)) {
966
+ if (typeof value === "function") return false;
967
+ if (Array.isArray(value)) {
968
+ const allStatic = value.every((child) => RendererUtils.isStaticElement(child, visited));
969
+ if (!allStatic) return false;
970
+ } else if (typeof value === "object" && value !== null) {
971
+ if (!RendererUtils.isStaticElement(value, visited)) return false;
972
+ }
973
+ }
974
+ return true;
975
+ },
976
+ /**
977
+ * Check if object has functions (for caching decisions)
978
+ */
979
+ hasFunctions(obj, visited = /* @__PURE__ */ new WeakSet()) {
980
+ if (visited.has(obj)) return false;
981
+ visited.add(obj);
982
+ for (const value of Object.values(obj)) {
983
+ if (typeof value === "function") return true;
984
+ if (typeof value === "object" && value !== null && RendererUtils.hasFunctions(value, visited)) {
985
+ return true;
986
+ }
987
+ }
988
+ return false;
989
+ },
990
+ /**
991
+ * Get element complexity score
992
+ */
993
+ getElementComplexity(element) {
994
+ if (!element || typeof element !== "object") return 1;
995
+ let complexity = Object.keys(element).length;
996
+ if (element.children && Array.isArray(element.children)) {
997
+ complexity += element.children.reduce(
998
+ (sum, child) => sum + RendererUtils.getElementComplexity(child),
999
+ 0
1000
+ );
1001
+ }
1002
+ return complexity;
1003
+ },
1004
+ /**
1005
+ * Generate cache key for element
1006
+ */
1007
+ generateCacheKey(tagName, element) {
1008
+ try {
1009
+ const keyData = {
1010
+ tag: tagName,
1011
+ props: extractProps(element),
1012
+ hasChildren: hasChildren(element),
1013
+ childrenType: Array.isArray(element.children) ? "array" : typeof element.children
1014
+ };
1015
+ return `element:${JSON.stringify(keyData)}`;
1016
+ } catch (_error) {
1017
+ if (typeof process !== "undefined" && process.env && true) {
1018
+ console.warn("Failed to generate cache key:", _error);
1019
+ }
1020
+ return null;
1021
+ }
1022
+ },
1023
+ /**
1024
+ * Check if element is cacheable
1025
+ */
1026
+ isCacheable(element, options) {
1027
+ if (!options.enableCache) return false;
1028
+ if (RendererUtils.hasFunctions(element)) return false;
1029
+ if (RendererUtils.getElementComplexity(element) > 1e3) return false;
1030
+ const cacheKey = RendererUtils.generateCacheKey(element.tagName || "unknown", element);
1031
+ if (!cacheKey) return false;
1032
+ return true;
896
1033
  }
897
- return new Component(definition);
898
- }
899
- function defineComponent(definition) {
900
- const componentFactory = (props) => {
901
- const component = new Component(definition);
902
- return component.render(props);
903
- };
904
- componentFactory.componentName = definition.name || "Component";
905
- componentFactory.definition = definition;
906
- return componentFactory;
1034
+ };
1035
+
1036
+ // src/core/html-nesting-rules.js
1037
+ var FORBIDDEN_CHILDREN = {
1038
+ // Phrasing content only - cannot contain flow content
1039
+ p: /* @__PURE__ */ new Set([
1040
+ "address",
1041
+ "article",
1042
+ "aside",
1043
+ "blockquote",
1044
+ "div",
1045
+ "dl",
1046
+ "fieldset",
1047
+ "footer",
1048
+ "form",
1049
+ "h1",
1050
+ "h2",
1051
+ "h3",
1052
+ "h4",
1053
+ "h5",
1054
+ "h6",
1055
+ "header",
1056
+ "hr",
1057
+ "main",
1058
+ "nav",
1059
+ "ol",
1060
+ "p",
1061
+ "pre",
1062
+ "section",
1063
+ "table",
1064
+ "ul",
1065
+ "figure",
1066
+ "figcaption"
1067
+ ]),
1068
+ // Interactive content restrictions
1069
+ a: /* @__PURE__ */ new Set(["a"]),
1070
+ // Links cannot nest
1071
+ button: /* @__PURE__ */ new Set(["button", "a", "input", "select", "textarea", "label"]),
1072
+ label: /* @__PURE__ */ new Set(["label"]),
1073
+ // Table structure restrictions
1074
+ thead: /* @__PURE__ */ new Set(["thead", "tbody", "tfoot", "caption", "colgroup", "tr"]),
1075
+ tbody: /* @__PURE__ */ new Set(["thead", "tbody", "tfoot", "caption", "colgroup"]),
1076
+ tfoot: /* @__PURE__ */ new Set(["thead", "tbody", "tfoot", "caption", "colgroup"]),
1077
+ tr: /* @__PURE__ */ new Set(["tr", "thead", "tbody", "tfoot", "table"]),
1078
+ td: /* @__PURE__ */ new Set(["td", "th", "tr", "thead", "tbody", "tfoot", "table"]),
1079
+ th: /* @__PURE__ */ new Set(["td", "th", "tr", "thead", "tbody", "tfoot", "table"]),
1080
+ // Other common restrictions
1081
+ select: /* @__PURE__ */ new Set(["select", "input", "textarea"]),
1082
+ option: /* @__PURE__ */ new Set(["option", "optgroup"])
1083
+ };
1084
+ function validateNesting(parentTag, childTag, path = "", options = {}) {
1085
+ if (!parentTag || !childTag) {
1086
+ return true;
1087
+ }
1088
+ const parent = parentTag.toLowerCase();
1089
+ const child = childTag.toLowerCase();
1090
+ const forbidden = FORBIDDEN_CHILDREN[parent];
1091
+ if (!forbidden || !forbidden.has(child)) {
1092
+ return true;
1093
+ }
1094
+ const pathSuffix = path ? ` at ${path}` : "";
1095
+ const message = `Invalid HTML nesting: <${child}> cannot be a child of <${parent}>${pathSuffix}. Browsers will auto-correct this, causing potential hydration mismatches.`;
1096
+ if (options.throwOnError) {
1097
+ throw new HTMLNestingError(message, { parent, child, path });
1098
+ }
1099
+ const shouldWarn = options.warn !== false && (typeof process === "undefined" || !process.env || true);
1100
+ if (shouldWarn) {
1101
+ console.warn(`[Coherent.js] ${message}`);
1102
+ }
1103
+ return false;
907
1104
  }
908
- function registerComponent(name, definition) {
909
- if (COMPONENT_REGISTRY.has(name)) {
910
- console.warn(`Component ${name} is already registered. Overriding.`);
1105
+ var HTMLNestingError = class extends Error {
1106
+ constructor(message, context2 = {}) {
1107
+ super(message);
1108
+ this.name = "HTMLNestingError";
1109
+ this.parent = context2.parent;
1110
+ this.child = context2.child;
1111
+ this.path = context2.path;
911
1112
  }
912
- const component = typeof definition === "function" ? defineComponent({ name, render: definition }) : defineComponent(definition);
913
- COMPONENT_REGISTRY.set(name, component);
914
- return component;
1113
+ };
1114
+
1115
+ // src/core/html-utils.js
1116
+ function escapeHtml(text) {
1117
+ if (typeof text !== "string") return text;
1118
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
915
1119
  }
916
- function getComponent(name) {
917
- return COMPONENT_REGISTRY.get(name);
1120
+ function isVoidElement(tagName) {
1121
+ if (typeof tagName !== "string") {
1122
+ return false;
1123
+ }
1124
+ const voidElements = /* @__PURE__ */ new Set([
1125
+ "area",
1126
+ "base",
1127
+ "br",
1128
+ "col",
1129
+ "embed",
1130
+ "hr",
1131
+ "img",
1132
+ "input",
1133
+ "link",
1134
+ "meta",
1135
+ "param",
1136
+ "source",
1137
+ "track",
1138
+ "wbr"
1139
+ ]);
1140
+ return voidElements.has(tagName.toLowerCase());
918
1141
  }
919
- function getRegisteredComponents() {
920
- return new Map(COMPONENT_REGISTRY);
1142
+ function formatAttributes(props) {
1143
+ let formatted = "";
1144
+ for (const key in props) {
1145
+ if (props.hasOwnProperty(key)) {
1146
+ let value = props[key];
1147
+ const attributeName = key === "className" ? "class" : key;
1148
+ if (typeof value === "function") {
1149
+ if (attributeName.startsWith("on")) {
1150
+ const actionId = `__coherent_action_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
1151
+ const DEBUG = typeof process !== "undefined" && process && process.env && (process.env.COHERENT_DEBUG === "1" || true) || typeof window !== "undefined" && window && window.COHERENT_DEBUG === true;
1152
+ if (typeof global !== "undefined") {
1153
+ if (!global.__coherentActionRegistry) {
1154
+ global.__coherentActionRegistry = {};
1155
+ if (DEBUG) console.log("Initialized global action registry");
1156
+ }
1157
+ global.__coherentActionRegistry[actionId] = value;
1158
+ if (DEBUG) console.log(`Added action ${actionId} to global registry, total: ${Object.keys(global.__coherentActionRegistry).length}`);
1159
+ if (DEBUG) console.log(`Global registry keys: ${Object.keys(global.__coherentActionRegistry).join(", ")}`);
1160
+ if (DEBUG) {
1161
+ if (typeof global.__coherentActionRegistryLog === "undefined") {
1162
+ global.__coherentActionRegistryLog = [];
1163
+ }
1164
+ global.__coherentActionRegistryLog.push({
1165
+ action: "add",
1166
+ actionId,
1167
+ timestamp: Date.now(),
1168
+ registrySize: Object.keys(global.__coherentActionRegistry).length
1169
+ });
1170
+ }
1171
+ } else if (typeof window !== "undefined") {
1172
+ if (!window.__coherentActionRegistry) {
1173
+ window.__coherentActionRegistry = {};
1174
+ if (DEBUG) console.log("Initialized window action registry");
1175
+ }
1176
+ window.__coherentActionRegistry[actionId] = value;
1177
+ if (DEBUG) console.log(`Added action ${actionId} to window registry, total: ${Object.keys(window.__coherentActionRegistry).length}`);
1178
+ if (DEBUG) console.log(`Window registry keys: ${Object.keys(window.__coherentActionRegistry).join(", ")}`);
1179
+ }
1180
+ const eventType = attributeName.substring(2);
1181
+ formatted += ` data-action="${actionId}" data-event="${eventType}"`;
1182
+ continue;
1183
+ } else {
1184
+ try {
1185
+ value = value();
1186
+ } catch (_error) {
1187
+ console.warn(`Error executing function for attribute '${key}':`, {
1188
+ _error: _error.message,
1189
+ stack: _error.stack,
1190
+ attributeKey: key
1191
+ });
1192
+ value = "";
1193
+ }
1194
+ }
1195
+ }
1196
+ if (value === true) {
1197
+ formatted += ` ${attributeName}`;
1198
+ } else if (value !== false && value !== null && value !== void 0) {
1199
+ formatted += ` ${attributeName}="${escapeHtml(String(value))}"`;
1200
+ }
1201
+ }
1202
+ }
1203
+ return formatted.trim();
921
1204
  }
922
- if (performanceMonitor) {
923
- const originalRender = Component.prototype.render;
924
- Component.prototype.render = function(...args) {
925
- const start = performance.now();
926
- const result = originalRender.apply(this, args);
927
- const duration = performance.now() - start;
928
- performanceMonitor.recordMetric("renderTime", duration, {
929
- type: "component",
930
- name: this.name,
931
- propsSize: JSON.stringify(this.props || {}).length,
932
- hasState: Object.keys(this.state?.get() || {}).length > 0
933
- });
934
- return result;
935
- };
1205
+ function minifyHtml(html, options = {}) {
1206
+ if (!options.minify) return html;
1207
+ return html.replace(/<!--[\s\S]*?-->/g, "").replace(/\s+/g, " ").replace(/>\s+</g, "><").trim();
936
1208
  }
937
- function lazy(factory, options = {}) {
1209
+
1210
+ // src/performance/cache-manager.js
1211
+ function createCacheManager(options = {}) {
938
1212
  const {
939
- cache = true,
940
- // Cache the result after first evaluation
941
- timeout = null,
942
- // Optional timeout for evaluation
943
- fallback = null,
944
- // Fallback value if evaluation fails
945
- onError = null,
946
- // Error handler
947
- dependencies = []
948
- // Dependencies that invalidate cache
1213
+ maxCacheSize = 1e3,
1214
+ maxMemoryMB = 100,
1215
+ ttlMs = 1e3 * 60 * 5,
1216
+ // 5 minutes
1217
+ enableStatistics = true
949
1218
  } = options;
950
- let cached = false;
951
- let cachedValue = null;
952
- let isEvaluating = false;
953
- let lastDependencyHash = null;
954
- const lazyWrapper = {
955
- // Mark as lazy for identification
956
- __isLazy: true,
957
- __factory: factory,
958
- __options: options,
959
- // Evaluation method
960
- evaluate(...args) {
961
- if (isEvaluating) {
962
- console.warn("Lazy evaluation cycle detected, returning fallback");
963
- return fallback;
1219
+ const caches = {
1220
+ static: /* @__PURE__ */ new Map(),
1221
+ // Never-changing components
1222
+ component: /* @__PURE__ */ new Map(),
1223
+ // Component results with deps
1224
+ template: /* @__PURE__ */ new Map(),
1225
+ // Template strings
1226
+ data: /* @__PURE__ */ new Map()
1227
+ // General purpose data
1228
+ };
1229
+ let memoryUsage = 0;
1230
+ const stats = {
1231
+ hits: 0,
1232
+ misses: 0,
1233
+ hitRate: {
1234
+ static: 0,
1235
+ component: 0,
1236
+ template: 0,
1237
+ data: 0
1238
+ },
1239
+ accessCount: {
1240
+ static: 0,
1241
+ component: 0,
1242
+ template: 0,
1243
+ data: 0
1244
+ }
1245
+ };
1246
+ let cleanupInterval;
1247
+ if (typeof setInterval === "function") {
1248
+ cleanupInterval = setInterval(() => cleanup(), 3e4);
1249
+ if (cleanupInterval.unref) {
1250
+ cleanupInterval.unref();
1251
+ }
1252
+ }
1253
+ function generateCacheKey(component, props = {}, context2 = {}) {
1254
+ const componentStr = typeof component === "function" ? component.name || component.toString() : JSON.stringify(component);
1255
+ const propsStr = JSON.stringify(props, Object.keys(props).sort());
1256
+ const contextStr = JSON.stringify(context2);
1257
+ const hash = simpleHash(componentStr + propsStr + contextStr);
1258
+ return `${extractComponentName(component)}_${hash}`;
1259
+ }
1260
+ function get(key, type = "component") {
1261
+ const cache = caches[type] || caches.component;
1262
+ const entry = cache.get(key);
1263
+ if (!entry) {
1264
+ stats.misses++;
1265
+ if (enableStatistics) stats.accessCount[type]++;
1266
+ return null;
1267
+ }
1268
+ if (Date.now() - entry.timestamp > ttlMs) {
1269
+ cache.delete(key);
1270
+ updateMemoryUsage(-entry.size);
1271
+ stats.misses++;
1272
+ if (enableStatistics) stats.accessCount[type]++;
1273
+ return null;
1274
+ }
1275
+ entry.lastAccess = Date.now();
1276
+ entry.accessCount++;
1277
+ stats.hits++;
1278
+ if (enableStatistics) {
1279
+ stats.accessCount[type]++;
1280
+ stats.hitRate[type] = stats.hits / (stats.hits + stats.misses) * 100;
1281
+ }
1282
+ return entry.value;
1283
+ }
1284
+ function set(key, value, type = "component", metadata = {}) {
1285
+ const cache = caches[type] || caches.component;
1286
+ const size = calculateSize(value);
1287
+ if (memoryUsage + size > maxMemoryMB * 1024 * 1024) {
1288
+ optimize(type, size);
1289
+ }
1290
+ const entry = {
1291
+ value,
1292
+ timestamp: Date.now(),
1293
+ lastAccess: Date.now(),
1294
+ size,
1295
+ metadata,
1296
+ accessCount: 0
1297
+ };
1298
+ const existing = cache.get(key);
1299
+ if (existing) {
1300
+ updateMemoryUsage(-existing.size);
1301
+ }
1302
+ cache.set(key, entry);
1303
+ updateMemoryUsage(size);
1304
+ if (cache.size > maxCacheSize) {
1305
+ optimize(type);
1306
+ }
1307
+ }
1308
+ function remove(key, type) {
1309
+ if (type) {
1310
+ const cache = caches[type];
1311
+ if (!cache) return false;
1312
+ const entry = cache.get(key);
1313
+ if (entry) {
1314
+ updateMemoryUsage(-entry.size);
1315
+ return cache.delete(key);
964
1316
  }
965
- if (cache && dependencies.length > 0) {
966
- const currentHash = hashDependencies(dependencies);
967
- if (lastDependencyHash !== null && lastDependencyHash !== currentHash) {
968
- cached = false;
969
- cachedValue = null;
970
- }
971
- lastDependencyHash = currentHash;
1317
+ return false;
1318
+ }
1319
+ for (const [, cache] of Object.entries(caches)) {
1320
+ const entry = cache.get(key);
1321
+ if (entry) {
1322
+ updateMemoryUsage(-entry.size);
1323
+ return cache.delete(key);
972
1324
  }
973
- if (cache && cached) {
974
- return cachedValue;
1325
+ }
1326
+ return false;
1327
+ }
1328
+ function clear(type) {
1329
+ if (type) {
1330
+ const cache = caches[type];
1331
+ if (cache) {
1332
+ cache.clear();
975
1333
  }
976
- isEvaluating = true;
977
- try {
978
- let result;
979
- if (timeout) {
980
- result = evaluateWithTimeout(factory, timeout, args, fallback);
981
- } else {
982
- result = typeof factory === "function" ? factory(...args) : factory;
983
- }
984
- if (result && typeof result.then === "function") {
985
- return result.catch((_error) => {
986
- if (onError) onError(_error);
987
- return fallback;
988
- });
989
- }
990
- if (cache) {
991
- cached = true;
992
- cachedValue = result;
993
- }
994
- return result;
995
- } catch (_error) {
996
- if (onError) {
997
- onError(_error);
998
- } else {
999
- console.error("Lazy evaluation _error:", _error);
1334
+ } else {
1335
+ Object.values(caches).forEach((cache) => cache.clear());
1336
+ }
1337
+ memoryUsage = 0;
1338
+ }
1339
+ function getStats() {
1340
+ const entries = Object.values(caches).reduce((sum, cache) => sum + cache.size, 0);
1341
+ return {
1342
+ hits: stats.hits,
1343
+ misses: stats.misses,
1344
+ size: memoryUsage,
1345
+ entries,
1346
+ hitRate: stats.hitRate,
1347
+ accessCount: stats.accessCount
1348
+ };
1349
+ }
1350
+ function cleanup() {
1351
+ const now = Date.now();
1352
+ let freed = 0;
1353
+ for (const [, cache] of Object.entries(caches)) {
1354
+ for (const [key, entry] of cache.entries()) {
1355
+ if (now - entry.timestamp > ttlMs) {
1356
+ cache.delete(key);
1357
+ updateMemoryUsage(-entry.size);
1358
+ freed++;
1000
1359
  }
1001
- return fallback;
1002
- } finally {
1003
- isEvaluating = false;
1004
1360
  }
1005
- },
1006
- // Force re-evaluation
1007
- invalidate() {
1008
- cached = false;
1009
- cachedValue = null;
1010
- lastDependencyHash = null;
1011
- return this;
1012
- },
1013
- // Check if evaluated
1014
- isEvaluated() {
1015
- return cached;
1016
- },
1017
- // Get cached value without evaluation
1018
- getCachedValue() {
1019
- return cachedValue;
1020
- },
1021
- // Transform the lazy value
1022
- map(transform) {
1023
- return lazy((...args) => {
1024
- const value = this.evaluate(...args);
1025
- return transform(value);
1026
- }, { ...options, cache: false });
1027
- },
1028
- // Chain lazy evaluations
1029
- flatMap(transform) {
1030
- return lazy((...args) => {
1031
- const value = this.evaluate(...args);
1032
- const transformed = transform(value);
1033
- if (isLazy(transformed)) {
1034
- return transformed.evaluate(...args);
1035
- }
1036
- return transformed;
1037
- }, { ...options, cache: false });
1038
- },
1039
- // Convert to string for debugging
1040
- toString() {
1041
- return `[Lazy${cached ? " (cached)" : ""}]`;
1042
- },
1043
- // JSON serialization
1044
- toJSON() {
1045
- return this.evaluate();
1046
1361
  }
1047
- };
1048
- return lazyWrapper;
1049
- }
1050
- function isLazy(value) {
1051
- return value && typeof value === "object" && value.__isLazy === true;
1052
- }
1053
- function evaluateLazy(obj, ...args) {
1054
- if (isLazy(obj)) {
1055
- return obj.evaluate(...args);
1362
+ return { freed };
1056
1363
  }
1057
- if (Array.isArray(obj)) {
1058
- return obj.map((item) => evaluateLazy(item, ...args));
1364
+ function calculateSize(value) {
1365
+ if (value === null || value === void 0) return 0;
1366
+ if (typeof value === "string") return value.length * 2;
1367
+ if (typeof value === "number") return 8;
1368
+ if (typeof value === "boolean") return 4;
1369
+ if (Array.isArray(value)) {
1370
+ return value.reduce((sum, item) => sum + calculateSize(item), 0);
1371
+ }
1372
+ if (typeof value === "object") {
1373
+ return Object.values(value).reduce((sum, val) => sum + calculateSize(val), 0);
1374
+ }
1375
+ return 0;
1059
1376
  }
1060
- if (obj && typeof obj === "object") {
1061
- const result = {};
1062
- for (const [key, value] of Object.entries(obj)) {
1063
- result[key] = evaluateLazy(value, ...args);
1377
+ function updateMemoryUsage(delta) {
1378
+ memoryUsage = Math.max(0, memoryUsage + delta);
1379
+ }
1380
+ function optimize(type, requiredSpace = 0) {
1381
+ const cache = caches[type] || caches.component;
1382
+ const entries = Array.from(cache.entries()).sort(([, a], [, b]) => a.lastAccess - b.lastAccess);
1383
+ let freed = 0;
1384
+ for (const [key, entry] of entries) {
1385
+ if (freed >= requiredSpace) break;
1386
+ cache.delete(key);
1387
+ updateMemoryUsage(-entry.size);
1388
+ freed += entry.size;
1064
1389
  }
1065
- return result;
1390
+ return { freed };
1066
1391
  }
1067
- return obj;
1068
- }
1069
- function hashDependencies(dependencies) {
1070
- return dependencies.map((dep) => {
1071
- if (typeof dep === "function") {
1072
- return dep.toString();
1392
+ function simpleHash(str) {
1393
+ let hash = 0;
1394
+ for (let i = 0; i < str.length; i++) {
1395
+ const char = str.charCodeAt(i);
1396
+ hash = (hash << 5) - hash + char;
1397
+ hash = hash & hash;
1073
1398
  }
1074
- return JSON.stringify(dep);
1075
- }).join("|");
1076
- }
1077
- function evaluateWithTimeout(factory, timeout, args, fallback) {
1078
- return new Promise((resolve, reject) => {
1079
- const timer = setTimeout(() => {
1080
- reject(new Error(`Lazy evaluation timeout after ${timeout}ms`));
1081
- }, timeout);
1082
- try {
1083
- const result = factory(...args);
1084
- if (result && typeof result.then === "function") {
1085
- result.then((value) => {
1086
- clearTimeout(timer);
1087
- resolve(value);
1088
- }).catch((_error) => {
1089
- clearTimeout(timer);
1090
- reject(_error);
1091
- });
1092
- } else {
1093
- clearTimeout(timer);
1094
- resolve(result);
1095
- }
1096
- } catch (_error) {
1097
- clearTimeout(timer);
1098
- reject(_error);
1399
+ return Math.abs(hash).toString(36);
1400
+ }
1401
+ function extractComponentName(component) {
1402
+ if (typeof component === "function") {
1403
+ return component.name || "AnonymousComponent";
1099
1404
  }
1100
- }).catch(() => fallback);
1101
- }
1102
- function memo(fn, options = {}) {
1103
- const {
1104
- // Caching strategy
1105
- strategy = "lru",
1106
- // 'lru', 'ttl', 'weak', 'simple'
1107
- maxSize = 100,
1108
- // Maximum cache entries
1109
- ttl = null,
1110
- // Time to live in milliseconds
1111
- // Key generation
1112
- keyFn = null,
1113
- // Custom key function
1114
- keySerializer = JSON.stringify,
1115
- // Default serialization
1116
- // Comparison
1117
- // eslint-disable-next-line no-unused-vars
1118
- compareFn = null,
1119
- // Custom equality comparison
1120
- // eslint-disable-next-line no-unused-vars
1121
- shallow = false,
1122
- // Shallow comparison for objects
1123
- // Lifecycle hooks
1124
- onHit = null,
1125
- // Called on cache hit
1126
- onMiss = null,
1127
- // Called on cache miss
1128
- onEvict = null,
1129
- // Called when item evicted
1130
- // Performance
1131
- stats = false,
1132
- // Track hit/miss statistics
1133
- // Development
1134
- debug = false
1135
- // Debug logging
1136
- } = options;
1137
- let cache;
1138
- const stats_data = stats ? { hits: 0, misses: 0, evictions: 0 } : null;
1139
- switch (strategy) {
1140
- case "lru":
1141
- cache = new LRUCache(maxSize, { onEvict });
1142
- break;
1143
- case "ttl":
1144
- cache = new TTLCache(ttl, { onEvict });
1145
- break;
1146
- case "weak":
1147
- cache = /* @__PURE__ */ new WeakMap();
1148
- break;
1149
- default:
1150
- cache = /* @__PURE__ */ new Map();
1405
+ if (component && typeof component === "object") {
1406
+ const keys = Object.keys(component);
1407
+ return keys.length > 0 ? keys[0] : "ObjectComponent";
1408
+ }
1409
+ return "UnknownComponent";
1151
1410
  }
1152
- const generateKey = keyFn || ((...args) => {
1153
- if (args.length === 0) return "__empty__";
1154
- if (args.length === 1) return keySerializer(args[0]);
1155
- return keySerializer(args);
1156
- });
1157
- const memoizedFn = (...args) => {
1158
- const key = generateKey(...args);
1159
- if (cache.has(key)) {
1160
- const cached = cache.get(key);
1161
- if (cached && (!cached.expires || Date.now() < cached.expires)) {
1162
- if (debug) console.log(`Memo cache hit for key: ${key}`);
1163
- if (onHit) onHit(key, cached.value, args);
1164
- if (stats_data) stats_data.hits++;
1165
- return cached.value || cached;
1166
- } else {
1167
- cache.delete(key);
1168
- }
1411
+ function destroy() {
1412
+ if (cleanupInterval) {
1413
+ clearInterval(cleanupInterval);
1169
1414
  }
1170
- if (debug) console.log(`Memo cache miss for key: ${key}`);
1171
- if (onMiss) onMiss(key, args);
1172
- if (stats_data) stats_data.misses++;
1173
- const result = fn(...args);
1174
- const cacheEntry = ttl ? { value: result, expires: Date.now() + ttl } : result;
1175
- cache.set(key, cacheEntry);
1176
- return result;
1177
- };
1178
- memoizedFn.cache = cache;
1179
- memoizedFn.clear = () => cache.clear();
1180
- memoizedFn.delete = (key) => cache.delete(key);
1181
- memoizedFn.has = (key) => cache.has(key);
1182
- memoizedFn.size = () => cache.size;
1183
- if (stats_data) {
1184
- memoizedFn.stats = () => ({ ...stats_data });
1185
- memoizedFn.resetStats = () => {
1186
- stats_data.hits = 0;
1187
- stats_data.misses = 0;
1188
- stats_data.evictions = 0;
1189
- };
1415
+ clear();
1190
1416
  }
1191
- memoizedFn.refresh = (...args) => {
1192
- const key = generateKey(...args);
1193
- cache.delete(key);
1194
- return memoizedFn(...args);
1417
+ return {
1418
+ get,
1419
+ set,
1420
+ remove,
1421
+ clear,
1422
+ getStats,
1423
+ cleanup,
1424
+ destroy,
1425
+ generateCacheKey,
1426
+ get memoryUsage() {
1427
+ return memoryUsage;
1428
+ },
1429
+ get maxMemory() {
1430
+ return maxMemoryMB * 1024 * 1024;
1431
+ }
1195
1432
  };
1196
- return memoizedFn;
1197
1433
  }
1198
- var LRUCache = class {
1199
- constructor(maxSize = 100, options = {}) {
1200
- this.maxSize = maxSize;
1201
- this.cache = /* @__PURE__ */ new Map();
1202
- this.onEvict = options.onEvict;
1203
- }
1204
- get(key) {
1205
- if (this.cache.has(key)) {
1206
- const value = this.cache.get(key);
1207
- this.cache.delete(key);
1208
- this.cache.set(key, value);
1209
- return value;
1210
- }
1211
- return void 0;
1212
- }
1213
- set(key, value) {
1214
- if (this.cache.has(key)) {
1215
- this.cache.delete(key);
1216
- } else if (this.cache.size >= this.maxSize) {
1217
- const firstKey = this.cache.keys().next().value;
1218
- const evicted = this.cache.get(firstKey);
1219
- this.cache.delete(firstKey);
1220
- if (this.onEvict) {
1221
- this.onEvict(firstKey, evicted);
1222
- }
1434
+ var cacheManager = createCacheManager();
1435
+
1436
+ // src/utils/error-handler.js
1437
+ var CoherentError = class _CoherentError extends Error {
1438
+ constructor(message, options = {}) {
1439
+ super(message);
1440
+ this.name = "CoherentError";
1441
+ this.type = options.type || "generic";
1442
+ this.code = options.code || `COHERENT_${String(this.type).toUpperCase()}`;
1443
+ this.docsUrl = options.docsUrl || `/docs/core/errors#${this.code}`;
1444
+ this.component = options.component;
1445
+ this.context = options.context;
1446
+ this.suggestions = options.suggestions || [];
1447
+ this.timestamp = Date.now();
1448
+ if (Error.captureStackTrace) {
1449
+ Error.captureStackTrace(this, _CoherentError);
1223
1450
  }
1224
- this.cache.set(key, value);
1225
- }
1226
- has(key) {
1227
- return this.cache.has(key);
1228
- }
1229
- delete(key) {
1230
- return this.cache.delete(key);
1231
- }
1232
- clear() {
1233
- this.cache.clear();
1234
1451
  }
1235
- get size() {
1236
- return this.cache.size;
1452
+ toJSON() {
1453
+ return {
1454
+ name: this.name,
1455
+ message: this.message,
1456
+ type: this.type,
1457
+ code: this.code,
1458
+ docsUrl: this.docsUrl,
1459
+ component: this.component,
1460
+ context: this.context,
1461
+ suggestions: this.suggestions,
1462
+ timestamp: this.timestamp,
1463
+ stack: this.stack
1464
+ };
1237
1465
  }
1238
1466
  };
1239
- var TTLCache = class {
1240
- constructor(ttl, options = {}) {
1241
- this.ttl = ttl;
1242
- this.cache = /* @__PURE__ */ new Map();
1243
- this.timers = /* @__PURE__ */ new Map();
1244
- this.onEvict = options.onEvict;
1245
- }
1246
- get(key) {
1247
- if (this.cache.has(key)) {
1248
- const entry = this.cache.get(key);
1249
- if (Date.now() < entry.expires) {
1250
- return entry.value;
1251
- } else {
1252
- this.delete(key);
1253
- }
1254
- }
1255
- return void 0;
1467
+ var ComponentValidationError = class extends CoherentError {
1468
+ constructor(message, component, suggestions = []) {
1469
+ super(message, {
1470
+ type: "validation",
1471
+ component,
1472
+ suggestions: [
1473
+ "Check component structure and syntax",
1474
+ "Ensure all required properties are present",
1475
+ "Validate prop types and values",
1476
+ ...suggestions
1477
+ ]
1478
+ });
1479
+ this.name = "ComponentValidationError";
1256
1480
  }
1257
- set(key, value) {
1258
- if (this.timers.has(key)) {
1259
- clearTimeout(this.timers.get(key));
1481
+ };
1482
+ var RenderingError = class extends CoherentError {
1483
+ constructor(message, component, context2, suggestions = []) {
1484
+ super(message, {
1485
+ type: "rendering",
1486
+ component,
1487
+ context: context2,
1488
+ suggestions: [
1489
+ "Check for circular references",
1490
+ "Validate component depth",
1491
+ "Ensure all functions return valid components",
1492
+ ...suggestions
1493
+ ]
1494
+ });
1495
+ this.name = "RenderingError";
1496
+ if (context2 && context2.path) {
1497
+ this.renderPath = context2.path;
1260
1498
  }
1261
- const expires = Date.now() + this.ttl;
1262
- this.cache.set(key, { value, expires });
1263
- const timer = setTimeout(() => {
1264
- this.delete(key);
1265
- }, this.ttl);
1266
- this.timers.set(key, timer);
1267
1499
  }
1268
- has(key) {
1269
- if (this.cache.has(key)) {
1270
- const entry = this.cache.get(key);
1271
- return Date.now() < entry.expires;
1272
- }
1273
- return false;
1500
+ };
1501
+ var PerformanceError = class extends CoherentError {
1502
+ constructor(message, metrics, suggestions = []) {
1503
+ super(message, {
1504
+ type: "performance",
1505
+ context: metrics,
1506
+ suggestions: [
1507
+ "Consider component memoization",
1508
+ "Reduce component complexity",
1509
+ "Enable caching",
1510
+ ...suggestions
1511
+ ]
1512
+ });
1513
+ this.name = "PerformanceError";
1274
1514
  }
1275
- delete(key) {
1276
- const had = this.cache.has(key);
1277
- if (had) {
1278
- const entry = this.cache.get(key);
1279
- this.cache.delete(key);
1280
- if (this.timers.has(key)) {
1281
- clearTimeout(this.timers.get(key));
1282
- this.timers.delete(key);
1283
- }
1284
- if (this.onEvict) {
1285
- this.onEvict(key, entry.value);
1286
- }
1515
+ };
1516
+ var StateError = class extends CoherentError {
1517
+ constructor(message, state, suggestions = []) {
1518
+ super(message, {
1519
+ type: "state",
1520
+ context: state,
1521
+ suggestions: [
1522
+ "Check state mutations",
1523
+ "Ensure proper state initialization",
1524
+ "Validate state transitions",
1525
+ ...suggestions
1526
+ ]
1527
+ });
1528
+ this.name = "StateError";
1529
+ }
1530
+ };
1531
+ var ErrorHandler = class {
1532
+ constructor(options = {}) {
1533
+ const isDev = typeof process !== "undefined" && process.env && true;
1534
+ const envForceSilent = typeof process !== "undefined" && process.env && process.env.COHERENT_SILENT === "1";
1535
+ const envForceDebug = typeof process !== "undefined" && process.env && process.env.COHERENT_DEBUG === "1";
1536
+ const defaultEnableLogging = envForceSilent ? false : envForceDebug ? true : isDev;
1537
+ this.options = {
1538
+ enableStackTrace: options.enableStackTrace !== false,
1539
+ enableSuggestions: options.enableSuggestions !== false,
1540
+ enableLogging: options.enableLogging ?? defaultEnableLogging,
1541
+ logLevel: options.logLevel || "_error",
1542
+ maxErrorHistory: options.maxErrorHistory || 100,
1543
+ ...options
1544
+ };
1545
+ this.errorHistory = [];
1546
+ this.errorCounts = /* @__PURE__ */ new Map();
1547
+ this.suppressedErrors = /* @__PURE__ */ new Set();
1548
+ }
1549
+ /**
1550
+ * Handle and report errors with detailed context
1551
+ */
1552
+ handle(_error, context2 = {}) {
1553
+ const enhancedError = this.enhanceError(_error, context2);
1554
+ this.addToHistory(enhancedError);
1555
+ if (this.options.enableLogging) {
1556
+ this.logError(enhancedError);
1287
1557
  }
1288
- return had;
1558
+ return enhancedError;
1289
1559
  }
1290
- clear() {
1291
- this.timers.forEach((timer) => clearTimeout(timer));
1292
- this.timers.clear();
1293
- this.cache.clear();
1560
+ /**
1561
+ * Enhance existing errors with more context
1562
+ */
1563
+ enhanceError(_error, context2 = {}) {
1564
+ if (_error instanceof CoherentError) {
1565
+ return _error;
1566
+ }
1567
+ const errorType = this.classifyError(_error, context2);
1568
+ switch (errorType) {
1569
+ case "validation":
1570
+ return new ComponentValidationError(
1571
+ _error.message,
1572
+ context2.component,
1573
+ this.generateSuggestions(_error, context2)
1574
+ );
1575
+ case "rendering":
1576
+ return new RenderingError(
1577
+ _error.message,
1578
+ context2.component,
1579
+ context2.renderContext,
1580
+ this.generateSuggestions(_error, context2)
1581
+ );
1582
+ case "performance":
1583
+ return new PerformanceError(
1584
+ _error.message,
1585
+ context2.metrics,
1586
+ this.generateSuggestions(_error, context2)
1587
+ );
1588
+ case "state":
1589
+ return new StateError(
1590
+ _error.message,
1591
+ context2.state,
1592
+ this.generateSuggestions(_error, context2)
1593
+ );
1594
+ default:
1595
+ return new CoherentError(_error.message, {
1596
+ type: errorType,
1597
+ component: context2.component,
1598
+ context: context2.context,
1599
+ suggestions: this.generateSuggestions(_error, context2)
1600
+ });
1601
+ }
1294
1602
  }
1295
- get size() {
1296
- return this.cache.size;
1603
+ /**
1604
+ * Classify _error type based on message and context
1605
+ */
1606
+ classifyError(_error, context2) {
1607
+ const message = _error.message.toLowerCase();
1608
+ if (message.includes("invalid") || message.includes("validation") || message.includes("required") || message.includes("type")) {
1609
+ return "validation";
1610
+ }
1611
+ if (message.includes("render") || message.includes("circular") || message.includes("depth") || message.includes("cannot render")) {
1612
+ return "rendering";
1613
+ }
1614
+ if (message.includes("slow") || message.includes("memory") || message.includes("performance") || message.includes("timeout")) {
1615
+ return "performance";
1616
+ }
1617
+ if (message.includes("state") || message.includes("mutation") || message.includes("store") || context2.state) {
1618
+ return "state";
1619
+ }
1620
+ if (context2.component) return "validation";
1621
+ if (context2.renderContext) return "rendering";
1622
+ if (context2.metrics) return "performance";
1623
+ return "generic";
1297
1624
  }
1298
- };
1299
- function withState(initialState = {}, options = {}) {
1300
- const {
1301
- // State options
1302
- persistent = false,
1303
- // Persist state across component unmounts
1304
- storageKey = null,
1305
- // Key for persistent storage
1306
- storage = typeof window !== "undefined" && typeof window.localStorage !== "undefined" ? window.localStorage : {
1307
- // Fallback storage for Node.js environments
1308
- _data: /* @__PURE__ */ new Map(),
1309
- setItem(key, value) {
1310
- this._data.set(key, value);
1625
+ /**
1626
+ * Generate helpful suggestions based on _error
1627
+ */
1628
+ generateSuggestions(_error, context2 = {}) {
1629
+ const suggestions = [];
1630
+ const message = _error.message.toLowerCase();
1631
+ const patterns = [
1632
+ {
1633
+ pattern: /cannot render|render.*failed/,
1634
+ suggestions: [
1635
+ "Check if component returns a valid object structure",
1636
+ "Ensure all properties are properly defined",
1637
+ "Look for undefined variables or null references"
1638
+ ]
1311
1639
  },
1312
- getItem(key) {
1313
- return this._data.get(key) || null;
1640
+ {
1641
+ pattern: /circular.*reference/,
1642
+ suggestions: [
1643
+ "Remove circular references between components",
1644
+ "Use lazy loading or memoization to break cycles",
1645
+ "Check for self-referencing components"
1646
+ ]
1314
1647
  },
1315
- removeItem(key) {
1316
- this._data.delete(key);
1648
+ {
1649
+ pattern: /maximum.*depth/,
1650
+ suggestions: [
1651
+ "Reduce component nesting depth",
1652
+ "Break complex components into smaller parts",
1653
+ "Check for infinite recursion in component functions"
1654
+ ]
1317
1655
  },
1318
- clear() {
1319
- this._data.clear();
1656
+ {
1657
+ pattern: /invalid.*component/,
1658
+ suggestions: [
1659
+ "Ensure component follows the expected object structure",
1660
+ "Check property names and values for typos",
1661
+ "Verify component is not null or undefined"
1662
+ ]
1663
+ },
1664
+ {
1665
+ pattern: /performance|slow|timeout/,
1666
+ suggestions: [
1667
+ "Enable component caching",
1668
+ "Use memoization for expensive operations",
1669
+ "Reduce component complexity",
1670
+ "Consider lazy loading for large components"
1671
+ ]
1320
1672
  }
1321
- },
1322
- // Storage mechanism
1323
- // State transformation
1324
- stateTransform = null,
1325
- // Transform state before injection
1326
- propName = "state",
1673
+ ];
1674
+ patterns.forEach(({ pattern, suggestions: patternSuggestions }) => {
1675
+ if (pattern.test(message)) {
1676
+ suggestions.push(...patternSuggestions);
1677
+ }
1678
+ });
1679
+ if (context2.component) {
1680
+ const componentType = typeof context2.component;
1681
+ if (componentType === "function") {
1682
+ suggestions.push("Check function component return value");
1683
+ } else if (componentType === "object" && context2.component === null) {
1684
+ suggestions.push("Component is null - ensure proper initialization");
1685
+ } else if (Array.isArray(context2.component)) {
1686
+ suggestions.push("Arrays should contain valid component objects");
1687
+ }
1688
+ }
1689
+ if (suggestions.length === 0) {
1690
+ suggestions.push(
1691
+ "Enable development tools for more detailed debugging",
1692
+ "Check browser console for additional _error details",
1693
+ "Use component validation tools to identify issues"
1694
+ );
1695
+ }
1696
+ return [...new Set(suggestions)];
1697
+ }
1698
+ /**
1699
+ * Add _error to history with deduplication
1700
+ */
1701
+ addToHistory(_error) {
1702
+ const errorKey = `${_error.name}:${_error.message}`;
1703
+ this.errorCounts.set(errorKey, (this.errorCounts.get(errorKey) || 0) + 1);
1704
+ const historyEntry = {
1705
+ ..._error.toJSON(),
1706
+ count: this.errorCounts.get(errorKey),
1707
+ firstSeen: this.errorHistory.find((e) => e.key === errorKey)?.firstSeen || _error.timestamp,
1708
+ key: errorKey
1709
+ };
1710
+ this.errorHistory = this.errorHistory.filter((e) => e.key !== errorKey);
1711
+ this.errorHistory.unshift(historyEntry);
1712
+ if (this.errorHistory.length > this.options.maxErrorHistory) {
1713
+ this.errorHistory = this.errorHistory.slice(0, this.options.maxErrorHistory);
1714
+ }
1715
+ }
1716
+ /**
1717
+ * Log _error with enhanced formatting
1718
+ */
1719
+ logError(_error) {
1720
+ if (this.suppressedErrors.has(`${_error.name}:${_error.message}`)) {
1721
+ return;
1722
+ }
1723
+ const isRepeated = this.errorCounts.get(`${_error.name}:${_error.message}`) > 1;
1724
+ const errorGroup = `\u{1F6A8} ${_error.name}${isRepeated ? ` (\xD7${this.errorCounts.get(`${_error.name}:${_error.message}`)})` : ""}`;
1725
+ console.group(errorGroup);
1726
+ console.error(`\u274C ${_error.message}`);
1727
+ if (_error.code) {
1728
+ console.log("\u{1F3F7}\uFE0F Code:", _error.code);
1729
+ }
1730
+ if (_error.docsUrl) {
1731
+ console.log("\u{1F4D6} Docs:", _error.docsUrl);
1732
+ }
1733
+ if (_error.component) {
1734
+ console.log("\u{1F50D} Component:", this.formatComponent(_error.component));
1735
+ }
1736
+ if (_error.context) {
1737
+ console.log("\u{1F4CB} Context:", _error.context);
1738
+ }
1739
+ if (_error.context && typeof _error.context === "object" && _error.context.path) {
1740
+ console.log("\u{1F4CD} Path:", _error.context.path);
1741
+ }
1742
+ if (this.options.enableSuggestions && _error.suggestions.length > 0) {
1743
+ console.group("\u{1F4A1} Suggestions:");
1744
+ _error.suggestions.forEach((suggestion, index) => {
1745
+ console.log(`${index + 1}. ${suggestion}`);
1746
+ });
1747
+ console.groupEnd();
1748
+ }
1749
+ if (this.options.enableStackTrace && _error.stack) {
1750
+ console.log("\u{1F4DA} Stack trace:", _error.stack);
1751
+ }
1752
+ console.groupEnd();
1753
+ }
1754
+ /**
1755
+ * Format component for logging
1756
+ */
1757
+ formatComponent(component, maxDepth = 2, currentDepth = 0) {
1758
+ if (currentDepth > maxDepth) {
1759
+ return "[...deep]";
1760
+ }
1761
+ if (typeof component === "function") {
1762
+ return `[Function: ${component.name || "anonymous"}]`;
1763
+ }
1764
+ if (Array.isArray(component)) {
1765
+ return component.slice(0, 3).map(
1766
+ (item) => this.formatComponent(item, maxDepth, currentDepth + 1)
1767
+ );
1768
+ }
1769
+ if (component && typeof component === "object") {
1770
+ const formatted = {};
1771
+ const keys = Object.keys(component).slice(0, 5);
1772
+ for (const key of keys) {
1773
+ if (key === "children" && component[key]) {
1774
+ formatted[key] = this.formatComponent(component[key], maxDepth, currentDepth + 1);
1775
+ } else {
1776
+ formatted[key] = component[key];
1777
+ }
1778
+ }
1779
+ if (Object.keys(component).length > 5) {
1780
+ formatted["..."] = `(${Object.keys(component).length - 5} more)`;
1781
+ }
1782
+ return formatted;
1783
+ }
1784
+ return component;
1785
+ }
1786
+ /**
1787
+ * Suppress specific _error types
1788
+ */
1789
+ suppress(errorPattern) {
1790
+ this.suppressedErrors.add(errorPattern);
1791
+ }
1792
+ /**
1793
+ * Clear _error history
1794
+ */
1795
+ clearHistory() {
1796
+ this.errorHistory = [];
1797
+ this.errorCounts.clear();
1798
+ }
1799
+ /**
1800
+ * Get _error statistics
1801
+ */
1802
+ getStats() {
1803
+ const errorsByType = {};
1804
+ const errorsByTime = {};
1805
+ this.errorHistory.forEach((_error) => {
1806
+ errorsByType[_error.type] = (errorsByType[_error.type] || 0) + _error.count;
1807
+ const hour = new Date(_error.timestamp).toISOString().slice(0, 13);
1808
+ errorsByTime[hour] = (errorsByTime[hour] || 0) + _error.count;
1809
+ });
1810
+ return {
1811
+ totalErrors: this.errorHistory.reduce((sum, e) => sum + e.count, 0),
1812
+ uniqueErrors: this.errorHistory.length,
1813
+ errorsByType,
1814
+ errorsByTime,
1815
+ mostCommonErrors: this.getMostCommonErrors(5),
1816
+ recentErrors: this.errorHistory.slice(0, 10)
1817
+ };
1818
+ }
1819
+ /**
1820
+ * Get most common errors
1821
+ */
1822
+ getMostCommonErrors(limit = 10) {
1823
+ return this.errorHistory.sort((a, b) => b.count - a.count).slice(0, limit).map(({ name, message, count, type }) => ({
1824
+ name,
1825
+ message,
1826
+ count,
1827
+ type
1828
+ }));
1829
+ }
1830
+ };
1831
+ var globalErrorHandler = new ErrorHandler();
1832
+
1833
+ // src/rendering/html-renderer.js
1834
+ var rendererCache = createCacheManager({
1835
+ maxSize: 1e3,
1836
+ ttlMs: 3e5
1837
+ // 5 minutes
1838
+ });
1839
+ function formatRenderPath(path) {
1840
+ if (!path || path.length === 0) return "root";
1841
+ let rendered = "root";
1842
+ for (const segment of path) {
1843
+ if (typeof segment !== "string" || segment.length === 0) continue;
1844
+ if (segment.startsWith("[")) {
1845
+ rendered += segment;
1846
+ } else {
1847
+ rendered += `.${segment}`;
1848
+ }
1849
+ }
1850
+ return rendered;
1851
+ }
1852
+ var HTMLRenderer = class extends BaseRenderer {
1853
+ constructor(options = {}) {
1854
+ super({
1855
+ enableCache: options.enableCache !== false,
1856
+ enableMonitoring: options.enableMonitoring !== false,
1857
+ minify: options.minify || false,
1858
+ streaming: options.streaming || false,
1859
+ maxDepth: options.maxDepth || 100,
1860
+ ...options
1861
+ });
1862
+ if (this.config.enableCache && !this.cache) {
1863
+ this.cache = rendererCache;
1864
+ }
1865
+ }
1866
+ /**
1867
+ * Main render method - converts components to HTML string
1868
+ *
1869
+ * @param {Object|Array|string|Function} component - Component to render
1870
+ * @param {Object} [options={}] - Rendering options
1871
+ * @param {Object} [options.context] - Rendering context
1872
+ * @param {boolean} [options.enableCache] - Override cache setting
1873
+ * @param {number} [options.depth=0] - Current rendering depth
1874
+ * @returns {string} Rendered HTML string
1875
+ *
1876
+ * @example
1877
+ * const html = renderer.render({
1878
+ * div: {
1879
+ * className: 'container',
1880
+ * children: [
1881
+ * { h1: { text: 'Title' } },
1882
+ * { p: { text: 'Content' } }
1883
+ * ]
1884
+ * }
1885
+ * });
1886
+ */
1887
+ render(component, options = {}) {
1888
+ const config = { ...this.config, ...options };
1889
+ this.startTiming();
1890
+ try {
1891
+ if (config.validateInput && !this.isValidComponent(component)) {
1892
+ throw new Error("Invalid component structure");
1893
+ }
1894
+ const renderOptions = {
1895
+ ...config,
1896
+ seenObjects: /* @__PURE__ */ new WeakSet()
1897
+ };
1898
+ const html = this.renderComponent(component, renderOptions, 0, []);
1899
+ const finalHtml = config.minify ? minifyHtml(html, config) : html;
1900
+ this.endTiming();
1901
+ this.recordPerformance("render", this.metrics.startTime, false, {
1902
+ cacheEnabled: config.enableCache
1903
+ });
1904
+ return finalHtml;
1905
+ } catch (_error) {
1906
+ this.recordError("render", _error);
1907
+ const enhancedError = globalErrorHandler.handle(_error, {
1908
+ renderContext: { path: "root", renderer: "html" }
1909
+ });
1910
+ if (config.throwOnError === false) {
1911
+ return config.errorFallback;
1912
+ }
1913
+ throw enhancedError;
1914
+ }
1915
+ }
1916
+ /**
1917
+ * Render a single component with full optimization pipeline
1918
+ */
1919
+ renderComponent(component, options, depth = 0, path = []) {
1920
+ if (component === null || component === void 0) {
1921
+ return "";
1922
+ }
1923
+ if (Array.isArray(component) && component.length === 0) {
1924
+ return "";
1925
+ }
1926
+ if (typeof component === "object" && component !== null && !Array.isArray(component)) {
1927
+ if (options.seenObjects && options.seenObjects.has(component)) {
1928
+ throw new RenderingError(
1929
+ "Circular reference detected in component tree",
1930
+ component,
1931
+ { path: formatRenderPath(path) },
1932
+ ["Remove the circular reference", "Use lazy loading to break the cycle"]
1933
+ );
1934
+ }
1935
+ if (options.seenObjects) {
1936
+ options.seenObjects.add(component);
1937
+ }
1938
+ }
1939
+ this.validateDepth(depth);
1940
+ try {
1941
+ const { type, value } = this.processComponentType(component);
1942
+ switch (type) {
1943
+ case "empty":
1944
+ return "";
1945
+ case "text":
1946
+ return escapeHtml(value);
1947
+ case "function": {
1948
+ const result = this.executeFunctionComponent(value, depth);
1949
+ return this.renderComponent(result, options, depth + 1, [...path, "()"]);
1950
+ }
1951
+ case "array":
1952
+ if (typeof process !== "undefined" && process.env && true && value.length > 1) {
1953
+ const missingKeyCount = value.filter((child) => {
1954
+ if (child && typeof child === "object" && !Array.isArray(child)) {
1955
+ const tagName = Object.keys(child)[0];
1956
+ const props = child[tagName];
1957
+ return props && typeof props === "object" && props.key === void 0;
1958
+ }
1959
+ return false;
1960
+ }).length;
1961
+ if (missingKeyCount > 0) {
1962
+ console.warn(
1963
+ `[Coherent.js] Array of ${value.length} elements at ${formatRenderPath(path)} has ${missingKeyCount} items missing "key" props. Keys help identify which items changed for efficient updates. Add unique key props like: { div: { key: 'unique-id', ... } }`
1964
+ );
1965
+ }
1966
+ }
1967
+ return value.map((child, index) => this.renderComponent(child, options, depth + 1, [...path, `[${index}]`])).join("");
1968
+ case "element": {
1969
+ const tagName = Object.keys(value)[0];
1970
+ const elementContent = value[tagName];
1971
+ return this.renderElement(tagName, elementContent, options, depth, [...path, tagName]);
1972
+ }
1973
+ default:
1974
+ this.recordError("renderComponent", new Error(`Unknown component type: ${type}`));
1975
+ return "";
1976
+ }
1977
+ } catch (_error) {
1978
+ const renderPath = formatRenderPath(path);
1979
+ if (_error instanceof CoherentError) {
1980
+ if (!_error.context || typeof _error.context !== "object") {
1981
+ _error.context = { path: renderPath };
1982
+ } else if (!_error.context.path) {
1983
+ _error.context = { ..._error.context, path: renderPath };
1984
+ }
1985
+ throw _error;
1986
+ }
1987
+ throw new RenderingError(_error.message, void 0, { path: renderPath, renderer: "html" });
1988
+ }
1989
+ }
1990
+ /**
1991
+ * Render an HTML element with advanced caching and optimization
1992
+ */
1993
+ renderElement(tagName, element, options, depth = 0, path = []) {
1994
+ const startTime = performance.now();
1995
+ if (element && typeof element === "object" && !Array.isArray(element)) {
1996
+ if (options.seenObjects && options.seenObjects.has(element)) {
1997
+ throw new RenderingError(
1998
+ "Circular reference detected in component tree",
1999
+ element,
2000
+ { path: formatRenderPath(path) },
2001
+ ["Remove the circular reference", "Use lazy loading to break the cycle"]
2002
+ );
2003
+ }
2004
+ if (options.seenObjects) {
2005
+ options.seenObjects.add(element);
2006
+ }
2007
+ }
2008
+ if (options.enableMonitoring && this.cache) {
2009
+ }
2010
+ if (options.enableCache && this.cache && RendererUtils.isStaticElement(element)) {
2011
+ try {
2012
+ const cacheKey = `static:${tagName}:${JSON.stringify(element)}`;
2013
+ const cached = this.cache.get("static", cacheKey);
2014
+ if (cached) {
2015
+ this.recordPerformance(tagName, startTime, true);
2016
+ return cached.value;
2017
+ }
2018
+ } catch {
2019
+ }
2020
+ }
2021
+ if (typeof element === "string" || typeof element === "number" || typeof element === "boolean") {
2022
+ const html2 = isVoidElement(tagName) ? `<${tagName}>` : `<${tagName}>${escapeHtml(String(element))}</${tagName}>`;
2023
+ this.cacheIfStatic(tagName, element, html2, options);
2024
+ this.recordPerformance(tagName, startTime, false);
2025
+ return html2;
2026
+ }
2027
+ if (typeof element === "function") {
2028
+ const result = this.executeFunctionComponent(element, depth);
2029
+ return this.renderElement(tagName, result, options, depth, [...path, "()"]);
2030
+ }
2031
+ if (element && typeof element === "object") {
2032
+ return this.renderObjectElement(tagName, element, options, depth, path);
2033
+ }
2034
+ if (element === null || element === void 0) {
2035
+ const html2 = isVoidElement(tagName) ? `<${tagName}>` : `<${tagName}></${tagName}>`;
2036
+ this.recordPerformance(tagName, startTime, false);
2037
+ return html2;
2038
+ }
2039
+ const html = `<${tagName}>${escapeHtml(String(element))}</${tagName}>`;
2040
+ this.recordPerformance(tagName, startTime, false);
2041
+ return html;
2042
+ }
2043
+ /**
2044
+ * Cache element if it's static
2045
+ */
2046
+ cacheIfStatic(tagName, element, html) {
2047
+ if (this.config.enableCache && this.cache && RendererUtils.isStaticElement(element)) {
2048
+ try {
2049
+ const cacheKey = `static:${tagName}:${JSON.stringify(element)}`;
2050
+ this.cache.set("static", cacheKey, html, {
2051
+ ttlMs: this.config.cacheTTL || 5 * 60 * 1e3,
2052
+ // 5 minutes default
2053
+ size: html.length
2054
+ // Approximate size
2055
+ });
2056
+ } catch {
2057
+ }
2058
+ }
2059
+ }
2060
+ /**
2061
+ * Render complex object elements with attributes and children
2062
+ */
2063
+ renderObjectElement(tagName, element, options, depth = 0, path = []) {
2064
+ const startTime = performance.now();
2065
+ if (options.enableCache && this.cache) {
2066
+ const cacheKey = RendererUtils.generateCacheKey(tagName, element);
2067
+ if (cacheKey) {
2068
+ const cached = this.cache.get(cacheKey);
2069
+ if (cached) {
2070
+ this.recordPerformance(tagName, startTime, true);
2071
+ return cached;
2072
+ }
2073
+ }
2074
+ }
2075
+ const { children, text, key: _key, html: _rawHtml, ...attributes } = element || {};
2076
+ const attributeString = formatAttributes(attributes);
2077
+ const openingTag = attributeString ? `<${tagName} ${attributeString}>` : `<${tagName}>`;
2078
+ let textContent = "";
2079
+ if (text !== void 0) {
2080
+ const isScript = tagName === "script";
2081
+ const isStyle = tagName === "style";
2082
+ const isRawTag = isScript || isStyle;
2083
+ const raw = typeof text === "function" ? String(text()) : String(text);
2084
+ if (isRawTag) {
2085
+ const safe = raw.replace(/<\/(script)/gi, "<\\/$1").replace(/<\/(style)/gi, "<\\/$1").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
2086
+ textContent = safe;
2087
+ } else {
2088
+ textContent = escapeHtml(raw);
2089
+ }
2090
+ }
2091
+ let childrenHtml = "";
2092
+ if (hasChildren(element)) {
2093
+ const normalizedChildren = normalizeChildren(children);
2094
+ childrenHtml = normalizedChildren.map((child, index) => {
2095
+ if (child && typeof child === "object" && !Array.isArray(child)) {
2096
+ const childTagName = Object.keys(child)[0];
2097
+ if (childTagName) {
2098
+ validateNesting(tagName, childTagName, formatRenderPath([...path, `children[${index}]`]));
2099
+ }
2100
+ }
2101
+ return this.renderComponent(child, options, depth + 1, [...path, `children[${index}]`]);
2102
+ }).join("");
2103
+ }
2104
+ const html = `${openingTag}${textContent}${childrenHtml}</${tagName}>`;
2105
+ if (options.enableCache && this.cache && RendererUtils.isCacheable(element, options)) {
2106
+ const cacheKey = RendererUtils.generateCacheKey(tagName, element);
2107
+ if (cacheKey) {
2108
+ this.cache.set(cacheKey, html);
2109
+ }
2110
+ }
2111
+ this.recordPerformance(tagName, startTime, false);
2112
+ return html;
2113
+ }
2114
+ };
2115
+ function render(component, options = {}) {
2116
+ const mergedOptions = {
2117
+ enableCache: true,
2118
+ enableMonitoring: false,
2119
+ ...options
2120
+ };
2121
+ const renderer = new HTMLRenderer(mergedOptions);
2122
+ return renderer.render(component, mergedOptions);
2123
+ }
2124
+
2125
+ // src/components/component-system.js
2126
+ var COMPONENT_REGISTRY = /* @__PURE__ */ new Map();
2127
+ var COMPONENT_METADATA = /* @__PURE__ */ new WeakMap();
2128
+ var ComponentState = class {
2129
+ constructor(initialState = {}) {
2130
+ this.state = { ...initialState };
2131
+ this.listeners = /* @__PURE__ */ new Set();
2132
+ this.isUpdating = false;
2133
+ }
2134
+ /**
2135
+ * Get state value by key or entire state
2136
+ *
2137
+ * @param {string} [key] - State key to retrieve
2138
+ * @returns {*} State value or entire state object
2139
+ */
2140
+ get(key) {
2141
+ return key ? this.state[key] : { ...this.state };
2142
+ }
2143
+ /**
2144
+ * Update state with new values
2145
+ *
2146
+ * @param {Object} updates - State updates to apply
2147
+ * @returns {ComponentState} This instance for chaining
2148
+ */
2149
+ set(updates) {
2150
+ if (this.isUpdating) return this;
2151
+ const oldState = { ...this.state };
2152
+ if (typeof updates === "function") {
2153
+ updates = updates(oldState);
2154
+ }
2155
+ this.state = { ...this.state, ...updates };
2156
+ this.notifyListeners(oldState, this.state);
2157
+ return this;
2158
+ }
2159
+ subscribe(listener) {
2160
+ this.listeners.add(listener);
2161
+ return () => this.listeners.delete(listener);
2162
+ }
2163
+ notifyListeners(oldState, newState) {
2164
+ if (this.listeners.size === 0) return;
2165
+ this.isUpdating = true;
2166
+ this.listeners.forEach((listener) => {
2167
+ try {
2168
+ listener(newState, oldState);
2169
+ } catch (_error) {
2170
+ console.error("State listener _error:", _error);
2171
+ }
2172
+ });
2173
+ this.isUpdating = false;
2174
+ }
2175
+ };
2176
+ var Component = class _Component {
2177
+ constructor(definition = {}) {
2178
+ this.definition = definition;
2179
+ this.name = definition.name || "AnonymousComponent";
2180
+ this.props = {};
2181
+ this.state = new ComponentState(definition.state || {});
2182
+ this.children = [];
2183
+ this.parent = null;
2184
+ this.rendered = null;
2185
+ this.isMounted = false;
2186
+ this.isDestroyed = false;
2187
+ this.hooks = {
2188
+ beforeCreate: definition.beforeCreate || (() => {
2189
+ }),
2190
+ created: definition.created || (() => {
2191
+ }),
2192
+ beforeMount: definition.beforeMount || (() => {
2193
+ }),
2194
+ mounted: definition.mounted || (() => {
2195
+ }),
2196
+ beforeUpdate: definition.beforeUpdate || (() => {
2197
+ }),
2198
+ updated: definition.updated || (() => {
2199
+ }),
2200
+ beforeDestroy: definition.beforeDestroy || (() => {
2201
+ }),
2202
+ destroyed: definition.destroyed || (() => {
2203
+ }),
2204
+ errorCaptured: definition.errorCaptured || (() => {
2205
+ })
2206
+ };
2207
+ this.methods = definition.methods || {};
2208
+ Object.keys(this.methods).forEach((methodName) => {
2209
+ if (typeof this.methods[methodName] === "function") {
2210
+ this[methodName] = this.methods[methodName].bind(this);
2211
+ }
2212
+ });
2213
+ this.computed = definition.computed || {};
2214
+ this.computedCache = /* @__PURE__ */ new Map();
2215
+ this.watchers = definition.watch || {};
2216
+ this.setupWatchers();
2217
+ COMPONENT_METADATA.set(this, {
2218
+ createdAt: Date.now(),
2219
+ updateCount: 0,
2220
+ renderCount: 0
2221
+ });
2222
+ this.callHook("beforeCreate");
2223
+ this.initialize();
2224
+ this.callHook("created");
2225
+ }
2226
+ /**
2227
+ * Initialize component
2228
+ */
2229
+ initialize() {
2230
+ this.unsubscribeState = this.state.subscribe((newState, oldState) => {
2231
+ this.onStateChange(newState, oldState);
2232
+ });
2233
+ this.initializeComputed();
2234
+ }
2235
+ /**
2236
+ * Set up watchers for reactive data
2237
+ */
2238
+ setupWatchers() {
2239
+ Object.keys(this.watchers).forEach((key) => {
2240
+ const handler = this.watchers[key];
2241
+ this.state.subscribe((newState, oldState) => {
2242
+ if (newState[key] !== oldState[key]) {
2243
+ handler.call(this, newState[key], oldState[key]);
2244
+ }
2245
+ });
2246
+ });
2247
+ }
2248
+ /**
2249
+ * Initialize computed properties
2250
+ */
2251
+ initializeComputed() {
2252
+ Object.keys(this.computed).forEach((key) => {
2253
+ Object.defineProperty(this, key, {
2254
+ get: () => {
2255
+ if (!this.computedCache.has(key)) {
2256
+ const value = this.computed[key].call(this);
2257
+ this.computedCache.set(key, value);
2258
+ }
2259
+ return this.computedCache.get(key);
2260
+ },
2261
+ enumerable: true
2262
+ });
2263
+ });
2264
+ }
2265
+ /**
2266
+ * Handle state changes
2267
+ */
2268
+ onStateChange() {
2269
+ if (this.isDestroyed) return;
2270
+ this.computedCache.clear();
2271
+ if (this.isMounted) {
2272
+ this.update();
2273
+ }
2274
+ }
2275
+ /**
2276
+ * Call lifecycle hook
2277
+ */
2278
+ callHook(hookName, ...args) {
2279
+ try {
2280
+ if (this.hooks[hookName]) {
2281
+ return this.hooks[hookName].call(this, ...args);
2282
+ }
2283
+ } catch (_error) {
2284
+ this.handleError(_error, `${hookName} hook`);
2285
+ }
2286
+ }
2287
+ /**
2288
+ * Handle component errors
2289
+ */
2290
+ handleError(_error) {
2291
+ console.error(`Component Error in ${this.name}:`, _error);
2292
+ this.callHook("errorCaptured", _error);
2293
+ if (this.parent && this.parent.handleError) {
2294
+ this.parent.handleError(_error, `${this.name} -> ${context}`);
2295
+ }
2296
+ }
2297
+ /**
2298
+ * Render the component
2299
+ */
2300
+ render(props = {}) {
2301
+ if (this.isDestroyed) {
2302
+ console.warn(`Attempting to render destroyed component: ${this.name}`);
2303
+ return null;
2304
+ }
2305
+ try {
2306
+ const metadata = COMPONENT_METADATA.get(this);
2307
+ if (metadata) {
2308
+ metadata.renderCount++;
2309
+ }
2310
+ this.props = { ...props };
2311
+ if (typeof this.definition.render === "function") {
2312
+ this.rendered = this.definition.render.call(this, this.props, this.state.get());
2313
+ } else if (typeof this.definition.template !== "undefined") {
2314
+ this.rendered = this.processTemplate(this.definition.template, this.props, this.state.get());
2315
+ } else {
2316
+ throw new Error(`Component ${this.name} must have either render method or template`);
2317
+ }
2318
+ if (this.rendered !== null) {
2319
+ validateComponent(this.rendered, this.name);
2320
+ }
2321
+ return this.rendered;
2322
+ } catch (_error) {
2323
+ this.handleError(_error);
2324
+ return { div: { className: "component-_error", text: `Error in ${this.name}` } };
2325
+ }
2326
+ }
2327
+ /**
2328
+ * Process template with data
2329
+ */
2330
+ processTemplate(template, props, state) {
2331
+ if (typeof template === "function") {
2332
+ return template.call(this, props, state);
2333
+ }
2334
+ if (typeof template === "string") {
2335
+ return template.replace(/\{\{(\w+)\}\}/g, (match, key) => {
2336
+ return props[key] || state[key] || "";
2337
+ });
2338
+ }
2339
+ const processed = deepClone(template);
2340
+ this.interpolateObject(processed, { ...props, ...state });
2341
+ return processed;
2342
+ }
2343
+ /**
2344
+ * Interpolate object with data
2345
+ */
2346
+ interpolateObject(obj, data) {
2347
+ if (typeof obj === "string") {
2348
+ return obj.replace(/\{\{(\w+)\}\}/g, (match, key) => data[key] || "");
2349
+ }
2350
+ if (Array.isArray(obj)) {
2351
+ return obj.map((item) => this.interpolateObject(item, data));
2352
+ }
2353
+ if (obj && typeof obj === "object") {
2354
+ Object.keys(obj).forEach((key) => {
2355
+ obj[key] = this.interpolateObject(obj[key], data);
2356
+ });
2357
+ }
2358
+ return obj;
2359
+ }
2360
+ /**
2361
+ * Mount the component
2362
+ */
2363
+ mount() {
2364
+ if (this.isMounted || this.isDestroyed) return this;
2365
+ this.callHook("beforeMount");
2366
+ this.isMounted = true;
2367
+ this.callHook("mounted");
2368
+ return this;
2369
+ }
2370
+ /**
2371
+ * Update the component
2372
+ */
2373
+ update() {
2374
+ if (!this.isMounted || this.isDestroyed) return this;
2375
+ const metadata = COMPONENT_METADATA.get(this);
2376
+ if (metadata) {
2377
+ metadata.updateCount++;
2378
+ }
2379
+ this.callHook("beforeUpdate");
2380
+ this.callHook("updated");
2381
+ return this;
2382
+ }
2383
+ /**
2384
+ * Destroy the component
2385
+ */
2386
+ destroy() {
2387
+ if (this.isDestroyed) return this;
2388
+ this.callHook("beforeDestroy");
2389
+ if (this.unsubscribeState) {
2390
+ this.unsubscribeState();
2391
+ }
2392
+ this.children.forEach((child) => {
2393
+ if (child.destroy) {
2394
+ child.destroy();
2395
+ }
2396
+ });
2397
+ this.isMounted = false;
2398
+ this.isDestroyed = true;
2399
+ this.children = [];
2400
+ this.parent = null;
2401
+ this.callHook("destroyed");
2402
+ return this;
2403
+ }
2404
+ /**
2405
+ * Get component metadata
2406
+ */
2407
+ getMetadata() {
2408
+ return COMPONENT_METADATA.get(this) || {};
2409
+ }
2410
+ /**
2411
+ * Clone component with new props/state
2412
+ */
2413
+ clone(overrides = {}) {
2414
+ const newDefinition = { ...this.definition, ...overrides };
2415
+ return new _Component(newDefinition);
2416
+ }
2417
+ };
2418
+ function createComponent(definition) {
2419
+ if (typeof definition === "function") {
2420
+ definition = {
2421
+ name: definition.name || "FunctionalComponent",
2422
+ render: definition
2423
+ };
2424
+ }
2425
+ return new Component(definition);
2426
+ }
2427
+ function defineComponent(definition) {
2428
+ const componentFactory = (props) => {
2429
+ const component = new Component(definition);
2430
+ return component.render(props);
2431
+ };
2432
+ componentFactory.componentName = definition.name || "Component";
2433
+ componentFactory.definition = definition;
2434
+ return componentFactory;
2435
+ }
2436
+ function registerComponent(name, definition) {
2437
+ if (COMPONENT_REGISTRY.has(name)) {
2438
+ console.warn(`Component ${name} is already registered. Overriding.`);
2439
+ }
2440
+ const component = typeof definition === "function" ? defineComponent({ name, render: definition }) : defineComponent(definition);
2441
+ COMPONENT_REGISTRY.set(name, component);
2442
+ return component;
2443
+ }
2444
+ function getComponent(name) {
2445
+ return COMPONENT_REGISTRY.get(name);
2446
+ }
2447
+ function getRegisteredComponents() {
2448
+ return new Map(COMPONENT_REGISTRY);
2449
+ }
2450
+ if (performanceMonitor) {
2451
+ const originalRender = Component.prototype.render;
2452
+ Component.prototype.render = function(...args) {
2453
+ const start = performance.now();
2454
+ const result = originalRender.apply(this, args);
2455
+ const duration = performance.now() - start;
2456
+ performanceMonitor.recordMetric("renderTime", duration, {
2457
+ type: "component",
2458
+ name: this.name,
2459
+ propsSize: JSON.stringify(this.props || {}).length,
2460
+ hasState: Object.keys(this.state?.get() || {}).length > 0
2461
+ });
2462
+ return result;
2463
+ };
2464
+ }
2465
+ function lazy(factory, options = {}) {
2466
+ const {
2467
+ cache = true,
2468
+ // Cache the result after first evaluation
2469
+ timeout = null,
2470
+ // Optional timeout for evaluation
2471
+ fallback = null,
2472
+ // Fallback value if evaluation fails
2473
+ onError = null,
2474
+ // Error handler
2475
+ dependencies = []
2476
+ // Dependencies that invalidate cache
2477
+ } = options;
2478
+ let cached = false;
2479
+ let cachedValue = null;
2480
+ let isEvaluating = false;
2481
+ let lastDependencyHash = null;
2482
+ const lazyWrapper = {
2483
+ // Mark as lazy for identification
2484
+ __isLazy: true,
2485
+ __factory: factory,
2486
+ __options: options,
2487
+ // Evaluation method
2488
+ evaluate(...args) {
2489
+ if (isEvaluating) {
2490
+ console.warn("Lazy evaluation cycle detected, returning fallback");
2491
+ return fallback;
2492
+ }
2493
+ if (cache && dependencies.length > 0) {
2494
+ const currentHash = hashDependencies(dependencies);
2495
+ if (lastDependencyHash !== null && lastDependencyHash !== currentHash) {
2496
+ cached = false;
2497
+ cachedValue = null;
2498
+ }
2499
+ lastDependencyHash = currentHash;
2500
+ }
2501
+ if (cache && cached) {
2502
+ return cachedValue;
2503
+ }
2504
+ isEvaluating = true;
2505
+ try {
2506
+ let result;
2507
+ if (timeout) {
2508
+ result = evaluateWithTimeout(factory, timeout, args, fallback);
2509
+ } else {
2510
+ result = typeof factory === "function" ? factory(...args) : factory;
2511
+ }
2512
+ if (result && typeof result.then === "function") {
2513
+ return result.catch((_error) => {
2514
+ if (onError) onError(_error);
2515
+ return fallback;
2516
+ });
2517
+ }
2518
+ if (cache) {
2519
+ cached = true;
2520
+ cachedValue = result;
2521
+ }
2522
+ return result;
2523
+ } catch (_error) {
2524
+ if (onError) {
2525
+ onError(_error);
2526
+ } else {
2527
+ console.error("Lazy evaluation _error:", _error);
2528
+ }
2529
+ return fallback;
2530
+ } finally {
2531
+ isEvaluating = false;
2532
+ }
2533
+ },
2534
+ // Force re-evaluation
2535
+ invalidate() {
2536
+ cached = false;
2537
+ cachedValue = null;
2538
+ lastDependencyHash = null;
2539
+ return this;
2540
+ },
2541
+ // Check if evaluated
2542
+ isEvaluated() {
2543
+ return cached;
2544
+ },
2545
+ // Get cached value without evaluation
2546
+ getCachedValue() {
2547
+ return cachedValue;
2548
+ },
2549
+ // Transform the lazy value
2550
+ map(transform) {
2551
+ return lazy((...args) => {
2552
+ const value = this.evaluate(...args);
2553
+ return transform(value);
2554
+ }, { ...options, cache: false });
2555
+ },
2556
+ // Chain lazy evaluations
2557
+ flatMap(transform) {
2558
+ return lazy((...args) => {
2559
+ const value = this.evaluate(...args);
2560
+ const transformed = transform(value);
2561
+ if (isLazy(transformed)) {
2562
+ return transformed.evaluate(...args);
2563
+ }
2564
+ return transformed;
2565
+ }, { ...options, cache: false });
2566
+ },
2567
+ // Convert to string for debugging
2568
+ toString() {
2569
+ return `[Lazy${cached ? " (cached)" : ""}]`;
2570
+ },
2571
+ // JSON serialization
2572
+ toJSON() {
2573
+ return this.evaluate();
2574
+ }
2575
+ };
2576
+ return lazyWrapper;
2577
+ }
2578
+ function isLazy(value) {
2579
+ return value && typeof value === "object" && value.__isLazy === true;
2580
+ }
2581
+ function evaluateLazy(obj, ...args) {
2582
+ if (isLazy(obj)) {
2583
+ return obj.evaluate(...args);
2584
+ }
2585
+ if (Array.isArray(obj)) {
2586
+ return obj.map((item) => evaluateLazy(item, ...args));
2587
+ }
2588
+ if (obj && typeof obj === "object") {
2589
+ const result = {};
2590
+ for (const [key, value] of Object.entries(obj)) {
2591
+ result[key] = evaluateLazy(value, ...args);
2592
+ }
2593
+ return result;
2594
+ }
2595
+ return obj;
2596
+ }
2597
+ function hashDependencies(dependencies) {
2598
+ return dependencies.map((dep) => {
2599
+ if (typeof dep === "function") {
2600
+ return dep.toString();
2601
+ }
2602
+ return JSON.stringify(dep);
2603
+ }).join("|");
2604
+ }
2605
+ function evaluateWithTimeout(factory, timeout, args, fallback) {
2606
+ return new Promise((resolve, reject) => {
2607
+ const timer = setTimeout(() => {
2608
+ reject(new Error(`Lazy evaluation timeout after ${timeout}ms`));
2609
+ }, timeout);
2610
+ try {
2611
+ const result = factory(...args);
2612
+ if (result && typeof result.then === "function") {
2613
+ result.then((value) => {
2614
+ clearTimeout(timer);
2615
+ resolve(value);
2616
+ }).catch((_error) => {
2617
+ clearTimeout(timer);
2618
+ reject(_error);
2619
+ });
2620
+ } else {
2621
+ clearTimeout(timer);
2622
+ resolve(result);
2623
+ }
2624
+ } catch (_error) {
2625
+ clearTimeout(timer);
2626
+ reject(_error);
2627
+ }
2628
+ }).catch(() => fallback);
2629
+ }
2630
+ function memo(fn, options = {}) {
2631
+ const {
2632
+ // Caching strategy
2633
+ strategy = "lru",
2634
+ // 'lru', 'ttl', 'weak', 'simple'
2635
+ maxSize = 100,
2636
+ // Maximum cache entries
2637
+ ttl = null,
2638
+ // Time to live in milliseconds
2639
+ // Key generation
2640
+ keyFn = null,
2641
+ // Custom key function
2642
+ keySerializer = JSON.stringify,
2643
+ // Default serialization
2644
+ // Comparison
2645
+ // eslint-disable-next-line no-unused-vars
2646
+ compareFn = null,
2647
+ // Custom equality comparison
2648
+ // eslint-disable-next-line no-unused-vars
2649
+ shallow = false,
2650
+ // Shallow comparison for objects
2651
+ // Lifecycle hooks
2652
+ onHit = null,
2653
+ // Called on cache hit
2654
+ onMiss = null,
2655
+ // Called on cache miss
2656
+ onEvict = null,
2657
+ // Called when item evicted
2658
+ // Performance
2659
+ stats = false,
2660
+ // Track hit/miss statistics
2661
+ // Development
2662
+ debug = false
2663
+ // Debug logging
2664
+ } = options;
2665
+ let cache;
2666
+ const stats_data = stats ? { hits: 0, misses: 0, evictions: 0 } : null;
2667
+ switch (strategy) {
2668
+ case "lru":
2669
+ cache = new LRUCache(maxSize, { onEvict });
2670
+ break;
2671
+ case "ttl":
2672
+ cache = new TTLCache(ttl, { onEvict });
2673
+ break;
2674
+ case "weak":
2675
+ cache = /* @__PURE__ */ new WeakMap();
2676
+ break;
2677
+ default:
2678
+ cache = /* @__PURE__ */ new Map();
2679
+ }
2680
+ const generateKey = keyFn || ((...args) => {
2681
+ if (args.length === 0) return "__empty__";
2682
+ if (args.length === 1) return keySerializer(args[0]);
2683
+ return keySerializer(args);
2684
+ });
2685
+ const memoizedFn = (...args) => {
2686
+ const key = generateKey(...args);
2687
+ if (cache.has(key)) {
2688
+ const cached = cache.get(key);
2689
+ if (cached && (!cached.expires || Date.now() < cached.expires)) {
2690
+ if (debug) console.log(`Memo cache hit for key: ${key}`);
2691
+ if (onHit) onHit(key, cached.value, args);
2692
+ if (stats_data) stats_data.hits++;
2693
+ return cached.value || cached;
2694
+ } else {
2695
+ cache.delete(key);
2696
+ }
2697
+ }
2698
+ if (debug) console.log(`Memo cache miss for key: ${key}`);
2699
+ if (onMiss) onMiss(key, args);
2700
+ if (stats_data) stats_data.misses++;
2701
+ const result = fn(...args);
2702
+ const cacheEntry = ttl ? { value: result, expires: Date.now() + ttl } : result;
2703
+ cache.set(key, cacheEntry);
2704
+ return result;
2705
+ };
2706
+ memoizedFn.cache = cache;
2707
+ memoizedFn.clear = () => cache.clear();
2708
+ memoizedFn.delete = (key) => cache.delete(key);
2709
+ memoizedFn.has = (key) => cache.has(key);
2710
+ memoizedFn.size = () => cache.size;
2711
+ if (stats_data) {
2712
+ memoizedFn.stats = () => ({ ...stats_data });
2713
+ memoizedFn.resetStats = () => {
2714
+ stats_data.hits = 0;
2715
+ stats_data.misses = 0;
2716
+ stats_data.evictions = 0;
2717
+ };
2718
+ }
2719
+ memoizedFn.refresh = (...args) => {
2720
+ const key = generateKey(...args);
2721
+ cache.delete(key);
2722
+ return memoizedFn(...args);
2723
+ };
2724
+ return memoizedFn;
2725
+ }
2726
+ var LRUCache = class {
2727
+ constructor(maxSize = 100, options = {}) {
2728
+ this.maxSize = maxSize;
2729
+ this.cache = /* @__PURE__ */ new Map();
2730
+ this.onEvict = options.onEvict;
2731
+ }
2732
+ get(key) {
2733
+ if (this.cache.has(key)) {
2734
+ const value = this.cache.get(key);
2735
+ this.cache.delete(key);
2736
+ this.cache.set(key, value);
2737
+ return value;
2738
+ }
2739
+ return void 0;
2740
+ }
2741
+ set(key, value) {
2742
+ if (this.cache.has(key)) {
2743
+ this.cache.delete(key);
2744
+ } else if (this.cache.size >= this.maxSize) {
2745
+ const firstKey = this.cache.keys().next().value;
2746
+ const evicted = this.cache.get(firstKey);
2747
+ this.cache.delete(firstKey);
2748
+ if (this.onEvict) {
2749
+ this.onEvict(firstKey, evicted);
2750
+ }
2751
+ }
2752
+ this.cache.set(key, value);
2753
+ }
2754
+ has(key) {
2755
+ return this.cache.has(key);
2756
+ }
2757
+ delete(key) {
2758
+ return this.cache.delete(key);
2759
+ }
2760
+ clear() {
2761
+ this.cache.clear();
2762
+ }
2763
+ get size() {
2764
+ return this.cache.size;
2765
+ }
2766
+ };
2767
+ var TTLCache = class {
2768
+ constructor(ttl, options = {}) {
2769
+ this.ttl = ttl;
2770
+ this.cache = /* @__PURE__ */ new Map();
2771
+ this.timers = /* @__PURE__ */ new Map();
2772
+ this.onEvict = options.onEvict;
2773
+ }
2774
+ get(key) {
2775
+ if (this.cache.has(key)) {
2776
+ const entry = this.cache.get(key);
2777
+ if (Date.now() < entry.expires) {
2778
+ return entry.value;
2779
+ } else {
2780
+ this.delete(key);
2781
+ }
2782
+ }
2783
+ return void 0;
2784
+ }
2785
+ set(key, value) {
2786
+ if (this.timers.has(key)) {
2787
+ clearTimeout(this.timers.get(key));
2788
+ }
2789
+ const expires = Date.now() + this.ttl;
2790
+ this.cache.set(key, { value, expires });
2791
+ const timer = setTimeout(() => {
2792
+ this.delete(key);
2793
+ }, this.ttl);
2794
+ this.timers.set(key, timer);
2795
+ }
2796
+ has(key) {
2797
+ if (this.cache.has(key)) {
2798
+ const entry = this.cache.get(key);
2799
+ return Date.now() < entry.expires;
2800
+ }
2801
+ return false;
2802
+ }
2803
+ delete(key) {
2804
+ const had = this.cache.has(key);
2805
+ if (had) {
2806
+ const entry = this.cache.get(key);
2807
+ this.cache.delete(key);
2808
+ if (this.timers.has(key)) {
2809
+ clearTimeout(this.timers.get(key));
2810
+ this.timers.delete(key);
2811
+ }
2812
+ if (this.onEvict) {
2813
+ this.onEvict(key, entry.value);
2814
+ }
2815
+ }
2816
+ return had;
2817
+ }
2818
+ clear() {
2819
+ this.timers.forEach((timer) => clearTimeout(timer));
2820
+ this.timers.clear();
2821
+ this.cache.clear();
2822
+ }
2823
+ get size() {
2824
+ return this.cache.size;
2825
+ }
2826
+ };
2827
+ function withState(initialState = {}, options = {}) {
2828
+ const {
2829
+ // State options
2830
+ persistent = false,
2831
+ // Persist state across component unmounts
2832
+ storageKey = null,
2833
+ // Key for persistent storage
2834
+ storage = typeof window !== "undefined" && typeof window.localStorage !== "undefined" ? window.localStorage : {
2835
+ // Fallback storage for Node.js environments
2836
+ _data: /* @__PURE__ */ new Map(),
2837
+ setItem(key, value) {
2838
+ this._data.set(key, value);
2839
+ },
2840
+ getItem(key) {
2841
+ return this._data.get(key) || null;
2842
+ },
2843
+ removeItem(key) {
2844
+ this._data.delete(key);
2845
+ },
2846
+ clear() {
2847
+ this._data.clear();
2848
+ }
2849
+ },
2850
+ // Storage mechanism
2851
+ // State transformation
2852
+ stateTransform = null,
2853
+ // Transform state before injection
2854
+ propName = "state",
1327
2855
  // Prop name for state injection
1328
2856
  actionsName = "actions",
1329
2857
  // Prop name for action injection
@@ -1438,6 +2966,8 @@ function withState(initialState = {}, options = {}) {
1438
2966
  ...props,
1439
2967
  [propName]: transformedState,
1440
2968
  [actionsName]: boundActions,
2969
+ setState: stateUtils.setState,
2970
+ getState: stateUtils.getState,
1441
2971
  stateUtils
1442
2972
  };
1443
2973
  if (debug) {
@@ -1542,631 +3072,254 @@ function createStateContainer(initialState, options) {
1542
3072
  unsubscribe(listener) {
1543
3073
  return listeners.delete(listener);
1544
3074
  },
1545
- batch(batchFn) {
1546
- const originalListeners = listeners;
1547
- listeners = /* @__PURE__ */ new Set();
1548
- try {
1549
- batchFn();
1550
- } finally {
1551
- listeners = originalListeners;
1552
- listeners.forEach((listener) => listener(state));
1553
- }
1554
- },
1555
- destroy() {
1556
- listeners.clear();
1557
- if (persistent && storageKey) {
1558
- try {
1559
- storage.removeItem(storageKey);
1560
- } catch (_error) {
1561
- if (debug) console.warn("Failed to remove persisted state:", _error);
1562
- }
1563
- }
1564
- }
1565
- };
1566
- return container;
1567
- }
1568
- function createBoundActions(actions, stateContainer, options) {
1569
- const { props, context: context2, supportAsync, debug } = options;
1570
- const boundActions = {};
1571
- Object.entries(actions).forEach(([actionName, actionCreator]) => {
1572
- boundActions[actionName] = (...args) => {
1573
- try {
1574
- const result = actionCreator(
1575
- stateContainer.getState(),
1576
- stateContainer.setState.bind(stateContainer),
1577
- { props, context: context2, args }
1578
- );
1579
- if (supportAsync && result && typeof result.then === "function") {
1580
- return result.catch((_error) => {
1581
- if (debug) console.error(`Async action ${actionName} failed:`, _error);
1582
- throw _error;
1583
- });
1584
- }
1585
- return result;
1586
- } catch (_error) {
1587
- if (debug) console.error(`Action ${actionName} failed:`, _error);
1588
- throw _error;
1589
- }
1590
- };
1591
- });
1592
- return boundActions;
1593
- }
1594
- var withStateUtils = {
1595
- /**
1596
- * Simple local state
1597
- */
1598
- local: (initialState) => withState(initialState),
1599
- /**
1600
- * Persistent state with localStorage
1601
- */
1602
- persistent: (initialState, key) => withState(initialState, {
1603
- persistent: true,
1604
- storageKey: key
1605
- }),
1606
- /**
1607
- * State with reducer pattern
1608
- */
1609
- reducer: (initialState, reducer, actions = {}) => withState(initialState, {
1610
- reducer,
1611
- actions
1612
- }),
1613
- /**
1614
- * Async state management
1615
- */
1616
- async: (initialState, asyncActions = {}) => withState(initialState, {
1617
- supportAsync: true,
1618
- actions: asyncActions
1619
- }),
1620
- /**
1621
- * State with validation
1622
- */
1623
- validated: (initialState, validator) => withState(initialState, {
1624
- validator,
1625
- debug: true
1626
- }),
1627
- /**
1628
- * Shared state across components
1629
- */
1630
- shared: (initialState, sharedKey) => {
1631
- const sharedStates = withStateUtils._shared || (withStateUtils._shared = /* @__PURE__ */ new Map());
1632
- if (!sharedStates.has(sharedKey)) {
1633
- sharedStates.set(sharedKey, createStateContainer(initialState, {}));
1634
- }
1635
- return (WrappedComponent) => {
1636
- const sharedContainer = sharedStates.get(sharedKey);
1637
- function SharedStateComponent(props, globalState, context2) {
1638
- const currentState = sharedContainer.getState();
1639
- const enhancedProps = {
1640
- ...props,
1641
- state: currentState,
1642
- setState: sharedContainer.setState.bind(sharedContainer),
1643
- subscribe: sharedContainer.subscribe.bind(sharedContainer)
1644
- };
1645
- return typeof WrappedComponent === "function" ? WrappedComponent(enhancedProps, globalState, context2) : WrappedComponent;
1646
- }
1647
- SharedStateComponent.displayName = `withSharedState(${getComponentName(WrappedComponent)})`;
1648
- return SharedStateComponent;
1649
- };
1650
- },
1651
- /**
1652
- * State with form utilities
1653
- */
1654
- form: (initialFormState) => withState(initialFormState, {
1655
- actions: {
1656
- updateField: (state, setState, { args: [field, value] }) => {
1657
- setState({ [field]: value });
1658
- },
1659
- updateMultiple: (state, setState, { args: [updates] }) => {
1660
- setState(updates);
1661
- },
1662
- resetForm: (state, setState) => {
1663
- setState(initialFormState);
1664
- },
1665
- validateForm: (state, setState, { args: [validator] }) => {
1666
- const errors = validator(state);
1667
- setState({ _errors: errors });
1668
- return Object.keys(errors).length === 0;
3075
+ batch(batchFn) {
3076
+ const originalListeners = listeners;
3077
+ listeners = /* @__PURE__ */ new Set();
3078
+ try {
3079
+ batchFn();
3080
+ } finally {
3081
+ listeners = originalListeners;
3082
+ listeners.forEach((listener) => listener(state));
1669
3083
  }
1670
- }
1671
- }),
1672
- /**
1673
- * State with loading/_error handling
1674
- */
1675
- withLoading: async (initialState) => withState({
1676
- ...initialState,
1677
- _loading: false,
1678
- _error: null
1679
- }, {
1680
- supportAsync: true,
1681
- actions: {
1682
- setLoading: (state, setState, { args: [loading] }) => {
1683
- setState({ _loading: loading });
1684
- },
1685
- setError: (state, setState, { args: [_error] }) => {
1686
- setState({ _error, _loading: false });
1687
- },
1688
- clearError: (state, setState) => {
1689
- setState({ _error: null });
1690
- },
1691
- asyncAction: async (state, setState, { args: [asyncFn] }) => {
1692
- setState({ _loading: true, _error: null });
3084
+ },
3085
+ destroy() {
3086
+ listeners.clear();
3087
+ if (persistent && storageKey) {
1693
3088
  try {
1694
- const result = await asyncFn(state);
1695
- setState({ _loading: false });
1696
- return result;
3089
+ storage.removeItem(storageKey);
1697
3090
  } catch (_error) {
1698
- setState({ _loading: false, _error });
1699
- throw _error;
3091
+ if (debug) console.warn("Failed to remove persisted state:", _error);
1700
3092
  }
1701
3093
  }
1702
3094
  }
1703
- }),
1704
- /**
1705
- * State with undo/redo functionality
1706
- */
1707
- withHistory: (initialState, maxHistory = 10) => {
1708
- const historyState = {
1709
- present: initialState,
1710
- past: [],
1711
- future: []
1712
- };
1713
- return withState(historyState, {
1714
- actions: {
1715
- undo: (state, setState) => {
1716
- if (state.past.length === 0) return;
1717
- const previous = state.past[state.past.length - 1];
1718
- const newPast = state.past.slice(0, state.past.length - 1);
1719
- setState({
1720
- past: newPast,
1721
- present: previous,
1722
- future: [state.present, ...state.future]
1723
- });
1724
- },
1725
- redo: (state, setState) => {
1726
- if (state.future.length === 0) return;
1727
- const next = state.future[0];
1728
- const newFuture = state.future.slice(1);
1729
- setState({
1730
- past: [...state.past, state.present],
1731
- present: next,
1732
- future: newFuture
1733
- });
1734
- },
1735
- updatePresent: (state, setState, { args: [newPresent] }) => {
1736
- setState({
1737
- past: [...state.past, state.present].slice(-maxHistory),
1738
- present: newPresent,
1739
- future: []
1740
- });
1741
- },
1742
- canUndo: (state) => state.past.length > 0,
1743
- canRedo: (state) => state.future.length > 0
1744
- }
1745
- });
1746
- },
1747
- /**
1748
- * Computed state properties
1749
- */
1750
- computed: (initialState, computedProps) => withState(initialState, {
1751
- stateTransform: (state) => {
1752
- const computed = {};
1753
- Object.entries(computedProps).forEach(([key, computeFn]) => {
1754
- computed[key] = computeFn(state);
1755
- });
1756
- return { ...state, ...computed };
1757
- },
1758
- memoizeState: true
1759
- })
1760
- };
1761
- function createStateManager(config) {
1762
- const {
1763
- initialState = {},
1764
- reducers = {},
1765
- actions = {},
1766
- middleware = [],
1767
- plugins = []
1768
- } = config;
1769
- const rootReducer = (state, action) => {
1770
- let nextState = state;
1771
- Object.entries(reducers).forEach(([key, reducer]) => {
1772
- nextState = {
1773
- ...nextState,
1774
- [key]: reducer(nextState[key], action)
1775
- };
1776
- });
1777
- return nextState;
1778
3095
  };
1779
- const enhancedConfig = plugins.reduce(
1780
- (acc, plugin) => plugin(acc),
1781
- { initialState, reducer: rootReducer, actions, middleware }
1782
- );
1783
- return withState(enhancedConfig.initialState, {
1784
- reducer: enhancedConfig.reducer,
1785
- actions: enhancedConfig.actions,
1786
- middleware: enhancedConfig.middleware
1787
- });
1788
- }
1789
- function getComponentName(component) {
1790
- if (!component) return "Component";
1791
- return component.displayName || component.name || component.constructor?.name || "Component";
3096
+ return container;
1792
3097
  }
1793
-
1794
- // src/utils/error-handler.js
1795
- var CoherentError = class _CoherentError extends Error {
1796
- constructor(message, options = {}) {
1797
- super(message);
1798
- this.name = "CoherentError";
1799
- this.type = options.type || "generic";
1800
- this.component = options.component;
1801
- this.context = options.context;
1802
- this.suggestions = options.suggestions || [];
1803
- this.timestamp = Date.now();
1804
- if (Error.captureStackTrace) {
1805
- Error.captureStackTrace(this, _CoherentError);
1806
- }
1807
- }
1808
- toJSON() {
1809
- return {
1810
- name: this.name,
1811
- message: this.message,
1812
- type: this.type,
1813
- component: this.component,
1814
- context: this.context,
1815
- suggestions: this.suggestions,
1816
- timestamp: this.timestamp,
1817
- stack: this.stack
1818
- };
1819
- }
1820
- };
1821
- var ComponentValidationError = class extends CoherentError {
1822
- constructor(message, component, suggestions = []) {
1823
- super(message, {
1824
- type: "validation",
1825
- component,
1826
- suggestions: [
1827
- "Check component structure and syntax",
1828
- "Ensure all required properties are present",
1829
- "Validate prop types and values",
1830
- ...suggestions
1831
- ]
1832
- });
1833
- this.name = "ComponentValidationError";
1834
- }
1835
- };
1836
- var RenderingError = class extends CoherentError {
1837
- constructor(message, component, context2, suggestions = []) {
1838
- super(message, {
1839
- type: "rendering",
1840
- component,
1841
- context: context2,
1842
- suggestions: [
1843
- "Check for circular references",
1844
- "Validate component depth",
1845
- "Ensure all functions return valid components",
1846
- ...suggestions
1847
- ]
1848
- });
1849
- this.name = "RenderingError";
1850
- }
1851
- };
1852
- var PerformanceError = class extends CoherentError {
1853
- constructor(message, metrics, suggestions = []) {
1854
- super(message, {
1855
- type: "performance",
1856
- context: metrics,
1857
- suggestions: [
1858
- "Consider component memoization",
1859
- "Reduce component complexity",
1860
- "Enable caching",
1861
- ...suggestions
1862
- ]
1863
- });
1864
- this.name = "PerformanceError";
1865
- }
1866
- };
1867
- var StateError = class extends CoherentError {
1868
- constructor(message, state, suggestions = []) {
1869
- super(message, {
1870
- type: "state",
1871
- context: state,
1872
- suggestions: [
1873
- "Check state mutations",
1874
- "Ensure proper state initialization",
1875
- "Validate state transitions",
1876
- ...suggestions
1877
- ]
1878
- });
1879
- this.name = "StateError";
1880
- }
1881
- };
1882
- var ErrorHandler = class {
1883
- constructor(options = {}) {
1884
- this.options = {
1885
- enableStackTrace: options.enableStackTrace !== false,
1886
- enableSuggestions: options.enableSuggestions !== false,
1887
- enableLogging: options.enableLogging !== false,
1888
- logLevel: options.logLevel || "_error",
1889
- maxErrorHistory: options.maxErrorHistory || 100,
1890
- ...options
1891
- };
1892
- this.errorHistory = [];
1893
- this.errorCounts = /* @__PURE__ */ new Map();
1894
- this.suppressedErrors = /* @__PURE__ */ new Set();
1895
- }
1896
- /**
1897
- * Handle and report errors with detailed context
1898
- */
1899
- handle(_error, context2 = {}) {
1900
- const enhancedError = this.enhanceError(_error, context2);
1901
- this.addToHistory(enhancedError);
1902
- if (this.options.enableLogging) {
1903
- this.logError(enhancedError);
1904
- }
1905
- return enhancedError;
1906
- }
3098
+ function createBoundActions(actions, stateContainer, options) {
3099
+ const { props, context: context2, supportAsync, debug } = options;
3100
+ const boundActions = {};
3101
+ Object.entries(actions).forEach(([actionName, actionCreator]) => {
3102
+ boundActions[actionName] = (...args) => {
3103
+ try {
3104
+ const result = actionCreator(
3105
+ stateContainer.getState(),
3106
+ stateContainer.setState.bind(stateContainer),
3107
+ { props, context: context2, args }
3108
+ );
3109
+ if (supportAsync && result && typeof result.then === "function") {
3110
+ return result.catch((_error) => {
3111
+ if (debug) console.error(`Async action ${actionName} failed:`, _error);
3112
+ throw _error;
3113
+ });
3114
+ }
3115
+ return result;
3116
+ } catch (_error) {
3117
+ if (debug) console.error(`Action ${actionName} failed:`, _error);
3118
+ throw _error;
3119
+ }
3120
+ };
3121
+ });
3122
+ return boundActions;
3123
+ }
3124
+ var withStateUtils = {
1907
3125
  /**
1908
- * Enhance existing errors with more context
3126
+ * Simple local state
1909
3127
  */
1910
- enhanceError(_error, context2 = {}) {
1911
- if (_error instanceof CoherentError) {
1912
- return _error;
1913
- }
1914
- const errorType = this.classifyError(_error, context2);
1915
- switch (errorType) {
1916
- case "validation":
1917
- return new ComponentValidationError(
1918
- _error.message,
1919
- context2.component,
1920
- this.generateSuggestions(_error, context2)
1921
- );
1922
- case "rendering":
1923
- return new RenderingError(
1924
- _error.message,
1925
- context2.component,
1926
- context2.renderContext,
1927
- this.generateSuggestions(_error, context2)
1928
- );
1929
- case "performance":
1930
- return new PerformanceError(
1931
- _error.message,
1932
- context2.metrics,
1933
- this.generateSuggestions(_error, context2)
1934
- );
1935
- case "state":
1936
- return new StateError(
1937
- _error.message,
1938
- context2.state,
1939
- this.generateSuggestions(_error, context2)
1940
- );
1941
- default:
1942
- return new CoherentError(_error.message, {
1943
- type: errorType,
1944
- component: context2.component,
1945
- context: context2.context,
1946
- suggestions: this.generateSuggestions(_error, context2)
1947
- });
1948
- }
1949
- }
3128
+ local: (initialState) => withState(initialState),
1950
3129
  /**
1951
- * Classify _error type based on message and context
3130
+ * Persistent state with localStorage
1952
3131
  */
1953
- classifyError(_error, context2) {
1954
- const message = _error.message.toLowerCase();
1955
- if (message.includes("invalid") || message.includes("validation") || message.includes("required") || message.includes("type")) {
1956
- return "validation";
1957
- }
1958
- if (message.includes("render") || message.includes("circular") || message.includes("depth") || message.includes("cannot render")) {
1959
- return "rendering";
1960
- }
1961
- if (message.includes("slow") || message.includes("memory") || message.includes("performance") || message.includes("timeout")) {
1962
- return "performance";
1963
- }
1964
- if (message.includes("state") || message.includes("mutation") || message.includes("store") || context2.state) {
1965
- return "state";
1966
- }
1967
- if (context2.component) return "validation";
1968
- if (context2.renderContext) return "rendering";
1969
- if (context2.metrics) return "performance";
1970
- return "generic";
1971
- }
3132
+ persistent: (initialState, key) => withState(initialState, {
3133
+ persistent: true,
3134
+ storageKey: key
3135
+ }),
1972
3136
  /**
1973
- * Generate helpful suggestions based on _error
3137
+ * State with reducer pattern
1974
3138
  */
1975
- generateSuggestions(_error, context2 = {}) {
1976
- const suggestions = [];
1977
- const message = _error.message.toLowerCase();
1978
- const patterns = [
1979
- {
1980
- pattern: /cannot render|render.*failed/,
1981
- suggestions: [
1982
- "Check if component returns a valid object structure",
1983
- "Ensure all properties are properly defined",
1984
- "Look for undefined variables or null references"
1985
- ]
1986
- },
1987
- {
1988
- pattern: /circular.*reference/,
1989
- suggestions: [
1990
- "Remove circular references between components",
1991
- "Use lazy loading or memoization to break cycles",
1992
- "Check for self-referencing components"
1993
- ]
1994
- },
1995
- {
1996
- pattern: /maximum.*depth/,
1997
- suggestions: [
1998
- "Reduce component nesting depth",
1999
- "Break complex components into smaller parts",
2000
- "Check for infinite recursion in component functions"
2001
- ]
2002
- },
2003
- {
2004
- pattern: /invalid.*component/,
2005
- suggestions: [
2006
- "Ensure component follows the expected object structure",
2007
- "Check property names and values for typos",
2008
- "Verify component is not null or undefined"
2009
- ]
2010
- },
2011
- {
2012
- pattern: /performance|slow|timeout/,
2013
- suggestions: [
2014
- "Enable component caching",
2015
- "Use memoization for expensive operations",
2016
- "Reduce component complexity",
2017
- "Consider lazy loading for large components"
2018
- ]
2019
- }
2020
- ];
2021
- patterns.forEach(({ pattern, suggestions: patternSuggestions }) => {
2022
- if (pattern.test(message)) {
2023
- suggestions.push(...patternSuggestions);
2024
- }
2025
- });
2026
- if (context2.component) {
2027
- const componentType = typeof context2.component;
2028
- if (componentType === "function") {
2029
- suggestions.push("Check function component return value");
2030
- } else if (componentType === "object" && context2.component === null) {
2031
- suggestions.push("Component is null - ensure proper initialization");
2032
- } else if (Array.isArray(context2.component)) {
2033
- suggestions.push("Arrays should contain valid component objects");
2034
- }
2035
- }
2036
- if (suggestions.length === 0) {
2037
- suggestions.push(
2038
- "Enable development tools for more detailed debugging",
2039
- "Check browser console for additional _error details",
2040
- "Use component validation tools to identify issues"
2041
- );
2042
- }
2043
- return [...new Set(suggestions)];
2044
- }
3139
+ reducer: (initialState, reducer, actions = {}) => withState(initialState, {
3140
+ reducer,
3141
+ actions
3142
+ }),
2045
3143
  /**
2046
- * Add _error to history with deduplication
3144
+ * Async state management
2047
3145
  */
2048
- addToHistory(_error) {
2049
- const errorKey = `${_error.name}:${_error.message}`;
2050
- this.errorCounts.set(errorKey, (this.errorCounts.get(errorKey) || 0) + 1);
2051
- const historyEntry = {
2052
- ..._error.toJSON(),
2053
- count: this.errorCounts.get(errorKey),
2054
- firstSeen: this.errorHistory.find((e) => e.key === errorKey)?.firstSeen || _error.timestamp,
2055
- key: errorKey
2056
- };
2057
- this.errorHistory = this.errorHistory.filter((e) => e.key !== errorKey);
2058
- this.errorHistory.unshift(historyEntry);
2059
- if (this.errorHistory.length > this.options.maxErrorHistory) {
2060
- this.errorHistory = this.errorHistory.slice(0, this.options.maxErrorHistory);
2061
- }
2062
- }
3146
+ async: (initialState, asyncActions = {}) => withState(initialState, {
3147
+ supportAsync: true,
3148
+ actions: asyncActions
3149
+ }),
2063
3150
  /**
2064
- * Log _error with enhanced formatting
3151
+ * State with validation
2065
3152
  */
2066
- logError(_error) {
2067
- if (this.suppressedErrors.has(`${_error.name}:${_error.message}`)) {
2068
- return;
2069
- }
2070
- const isRepeated = this.errorCounts.get(`${_error.name}:${_error.message}`) > 1;
2071
- const errorGroup = `\u{1F6A8} ${_error.name}${isRepeated ? ` (\xD7${this.errorCounts.get(`${_error.name}:${_error.message}`)})` : ""}`;
2072
- console.group(errorGroup);
2073
- console.error(`\u274C ${_error.message}`);
2074
- if (_error.component) {
2075
- console.log("\u{1F50D} Component:", this.formatComponent(_error.component));
2076
- }
2077
- if (_error.context) {
2078
- console.log("\u{1F4CB} Context:", _error.context);
2079
- }
2080
- if (this.options.enableSuggestions && _error.suggestions.length > 0) {
2081
- console.group("\u{1F4A1} Suggestions:");
2082
- _error.suggestions.forEach((suggestion, index) => {
2083
- console.log(`${index + 1}. ${suggestion}`);
2084
- });
2085
- console.groupEnd();
2086
- }
2087
- if (this.options.enableStackTrace && _error.stack) {
2088
- console.log("\u{1F4DA} Stack trace:", _error.stack);
2089
- }
2090
- console.groupEnd();
2091
- }
3153
+ validated: (initialState, validator) => withState(initialState, {
3154
+ validator,
3155
+ debug: true
3156
+ }),
2092
3157
  /**
2093
- * Format component for logging
3158
+ * Shared state across components
2094
3159
  */
2095
- formatComponent(component, maxDepth = 2, currentDepth = 0) {
2096
- if (currentDepth > maxDepth) {
2097
- return "[...deep]";
2098
- }
2099
- if (typeof component === "function") {
2100
- return `[Function: ${component.name || "anonymous"}]`;
2101
- }
2102
- if (Array.isArray(component)) {
2103
- return component.slice(0, 3).map(
2104
- (item) => this.formatComponent(item, maxDepth, currentDepth + 1)
2105
- );
2106
- }
2107
- if (component && typeof component === "object") {
2108
- const formatted = {};
2109
- const keys = Object.keys(component).slice(0, 5);
2110
- for (const key of keys) {
2111
- if (key === "children" && component[key]) {
2112
- formatted[key] = this.formatComponent(component[key], maxDepth, currentDepth + 1);
2113
- } else {
2114
- formatted[key] = component[key];
2115
- }
2116
- }
2117
- if (Object.keys(component).length > 5) {
2118
- formatted["..."] = `(${Object.keys(component).length - 5} more)`;
2119
- }
2120
- return formatted;
3160
+ shared: (initialState, sharedKey) => {
3161
+ const sharedStates = withStateUtils._shared || (withStateUtils._shared = /* @__PURE__ */ new Map());
3162
+ if (!sharedStates.has(sharedKey)) {
3163
+ sharedStates.set(sharedKey, createStateContainer(initialState, {}));
2121
3164
  }
2122
- return component;
2123
- }
3165
+ return (WrappedComponent) => {
3166
+ const sharedContainer = sharedStates.get(sharedKey);
3167
+ function SharedStateComponent(props, globalState, context2) {
3168
+ const currentState = sharedContainer.getState();
3169
+ const enhancedProps = {
3170
+ ...props,
3171
+ state: currentState,
3172
+ setState: sharedContainer.setState.bind(sharedContainer),
3173
+ subscribe: sharedContainer.subscribe.bind(sharedContainer)
3174
+ };
3175
+ return typeof WrappedComponent === "function" ? WrappedComponent(enhancedProps, globalState, context2) : WrappedComponent;
3176
+ }
3177
+ SharedStateComponent.displayName = `withSharedState(${getComponentName(WrappedComponent)})`;
3178
+ return SharedStateComponent;
3179
+ };
3180
+ },
2124
3181
  /**
2125
- * Suppress specific _error types
3182
+ * State with form utilities
2126
3183
  */
2127
- suppress(errorPattern) {
2128
- this.suppressedErrors.add(errorPattern);
2129
- }
3184
+ form: (initialFormState) => withState(initialFormState, {
3185
+ actions: {
3186
+ updateField: (state, setState, { args: [field, value] }) => {
3187
+ setState({ [field]: value });
3188
+ },
3189
+ updateMultiple: (state, setState, { args: [updates] }) => {
3190
+ setState(updates);
3191
+ },
3192
+ resetForm: (state, setState) => {
3193
+ setState(initialFormState);
3194
+ },
3195
+ validateForm: (state, setState, { args: [validator] }) => {
3196
+ const errors = validator(state);
3197
+ setState({ _errors: errors });
3198
+ return Object.keys(errors).length === 0;
3199
+ }
3200
+ }
3201
+ }),
2130
3202
  /**
2131
- * Clear _error history
3203
+ * State with loading/_error handling
2132
3204
  */
2133
- clearHistory() {
2134
- this.errorHistory = [];
2135
- this.errorCounts.clear();
2136
- }
3205
+ withLoading: async (initialState) => withState({
3206
+ ...initialState,
3207
+ _loading: false,
3208
+ _error: null
3209
+ }, {
3210
+ supportAsync: true,
3211
+ actions: {
3212
+ setLoading: (state, setState, { args: [loading] }) => {
3213
+ setState({ _loading: loading });
3214
+ },
3215
+ setError: (state, setState, { args: [_error] }) => {
3216
+ setState({ _error, _loading: false });
3217
+ },
3218
+ clearError: (state, setState) => {
3219
+ setState({ _error: null });
3220
+ },
3221
+ asyncAction: async (state, setState, { args: [asyncFn] }) => {
3222
+ setState({ _loading: true, _error: null });
3223
+ try {
3224
+ const result = await asyncFn(state);
3225
+ setState({ _loading: false });
3226
+ return result;
3227
+ } catch (_error) {
3228
+ setState({ _loading: false, _error });
3229
+ throw _error;
3230
+ }
3231
+ }
3232
+ }
3233
+ }),
2137
3234
  /**
2138
- * Get _error statistics
3235
+ * State with undo/redo functionality
2139
3236
  */
2140
- getStats() {
2141
- const errorsByType = {};
2142
- const errorsByTime = {};
2143
- this.errorHistory.forEach((_error) => {
2144
- errorsByType[_error.type] = (errorsByType[_error.type] || 0) + _error.count;
2145
- const hour = new Date(_error.timestamp).toISOString().slice(0, 13);
2146
- errorsByTime[hour] = (errorsByTime[hour] || 0) + _error.count;
2147
- });
2148
- return {
2149
- totalErrors: this.errorHistory.reduce((sum, e) => sum + e.count, 0),
2150
- uniqueErrors: this.errorHistory.length,
2151
- errorsByType,
2152
- errorsByTime,
2153
- mostCommonErrors: this.getMostCommonErrors(5),
2154
- recentErrors: this.errorHistory.slice(0, 10)
3237
+ withHistory: (initialState, maxHistory = 10) => {
3238
+ const historyState = {
3239
+ present: initialState,
3240
+ past: [],
3241
+ future: []
2155
3242
  };
2156
- }
3243
+ return withState(historyState, {
3244
+ actions: {
3245
+ undo: (state, setState) => {
3246
+ if (state.past.length === 0) return;
3247
+ const previous = state.past[state.past.length - 1];
3248
+ const newPast = state.past.slice(0, state.past.length - 1);
3249
+ setState({
3250
+ past: newPast,
3251
+ present: previous,
3252
+ future: [state.present, ...state.future]
3253
+ });
3254
+ },
3255
+ redo: (state, setState) => {
3256
+ if (state.future.length === 0) return;
3257
+ const next = state.future[0];
3258
+ const newFuture = state.future.slice(1);
3259
+ setState({
3260
+ past: [...state.past, state.present],
3261
+ present: next,
3262
+ future: newFuture
3263
+ });
3264
+ },
3265
+ updatePresent: (state, setState, { args: [newPresent] }) => {
3266
+ setState({
3267
+ past: [...state.past, state.present].slice(-maxHistory),
3268
+ present: newPresent,
3269
+ future: []
3270
+ });
3271
+ },
3272
+ canUndo: (state) => state.past.length > 0,
3273
+ canRedo: (state) => state.future.length > 0
3274
+ }
3275
+ });
3276
+ },
2157
3277
  /**
2158
- * Get most common errors
3278
+ * Computed state properties
2159
3279
  */
2160
- getMostCommonErrors(limit = 10) {
2161
- return this.errorHistory.sort((a, b) => b.count - a.count).slice(0, limit).map(({ name, message, count, type }) => ({
2162
- name,
2163
- message,
2164
- count,
2165
- type
2166
- }));
2167
- }
3280
+ computed: (initialState, computedProps) => withState(initialState, {
3281
+ stateTransform: (state) => {
3282
+ const computed = {};
3283
+ Object.entries(computedProps).forEach(([key, computeFn]) => {
3284
+ computed[key] = computeFn(state);
3285
+ });
3286
+ return { ...state, ...computed };
3287
+ },
3288
+ memoizeState: true
3289
+ })
2168
3290
  };
2169
- var globalErrorHandler = new ErrorHandler();
3291
+ function createStateManager(config) {
3292
+ const {
3293
+ initialState = {},
3294
+ reducers = {},
3295
+ actions = {},
3296
+ middleware = [],
3297
+ plugins = []
3298
+ } = config;
3299
+ const rootReducer = (state, action) => {
3300
+ let nextState = state;
3301
+ Object.entries(reducers).forEach(([key, reducer]) => {
3302
+ nextState = {
3303
+ ...nextState,
3304
+ [key]: reducer(nextState[key], action)
3305
+ };
3306
+ });
3307
+ return nextState;
3308
+ };
3309
+ const enhancedConfig = plugins.reduce(
3310
+ (acc, plugin) => plugin(acc),
3311
+ { initialState, reducer: rootReducer, actions, middleware }
3312
+ );
3313
+ return withState(enhancedConfig.initialState, {
3314
+ reducer: enhancedConfig.reducer,
3315
+ actions: enhancedConfig.actions,
3316
+ middleware: enhancedConfig.middleware
3317
+ });
3318
+ }
3319
+ function getComponentName(component) {
3320
+ if (!component) return "Component";
3321
+ return component.displayName || component.name || component.constructor?.name || "Component";
3322
+ }
2170
3323
 
2171
3324
  // src/components/lifecycle.js
2172
3325
  var LIFECYCLE_PHASES = {
@@ -3408,6 +4561,117 @@ function createGlobalErrorHandler(options = {}) {
3408
4561
  return new GlobalErrorHandler(options);
3409
4562
  }
3410
4563
 
4564
+ // src/utils/render-utils.js
4565
+ function renderWithMonitoring(component, options = {}) {
4566
+ const {
4567
+ enablePerformanceMonitoring = false
4568
+ } = options;
4569
+ let html;
4570
+ if (enablePerformanceMonitoring) {
4571
+ const renderId = performanceMonitor.startRender();
4572
+ html = render(component);
4573
+ performanceMonitor.endRender(renderId);
4574
+ } else {
4575
+ html = render(component);
4576
+ }
4577
+ return html;
4578
+ }
4579
+ function renderWithTemplate(component, options = {}) {
4580
+ const {
4581
+ template = "<!DOCTYPE html>\n{{content}}"
4582
+ } = options;
4583
+ const html = renderWithMonitoring(component, options);
4584
+ return template.replace("{{content}}", html);
4585
+ }
4586
+ async function renderComponentFactory(componentFactory, factoryArgs, options = {}) {
4587
+ const component = await Promise.resolve(
4588
+ componentFactory(...factoryArgs)
4589
+ );
4590
+ if (!component) {
4591
+ throw new Error("Component factory returned null/undefined");
4592
+ }
4593
+ return renderWithTemplate(component, options);
4594
+ }
4595
+ function isCoherentComponent(obj) {
4596
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
4597
+ return false;
4598
+ }
4599
+ const keys = Object.keys(obj);
4600
+ return keys.length === 1;
4601
+ }
4602
+ function createErrorResponse(error, context2 = "rendering") {
4603
+ return {
4604
+ error: "Internal Server Error",
4605
+ message: error.message,
4606
+ context: context2,
4607
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
4608
+ };
4609
+ }
4610
+
4611
+ // src/utils/dependency-utils.js
4612
+ function isPeerDependencyAvailable(packageName) {
4613
+ try {
4614
+ if (typeof __require !== "undefined" && __require.resolve) {
4615
+ __require.resolve(packageName);
4616
+ return true;
4617
+ }
4618
+ return false;
4619
+ } catch {
4620
+ return false;
4621
+ }
4622
+ }
4623
+ async function importPeerDependency(packageName, integrationName) {
4624
+ try {
4625
+ return await import(packageName);
4626
+ } catch {
4627
+ throw new Error(
4628
+ `${integrationName} integration requires the '${packageName}' package to be installed.
4629
+ Please install it with: npm install ${packageName}
4630
+ Or with pnpm: pnpm add ${packageName}
4631
+ Or with yarn: yarn add ${packageName}`
4632
+ );
4633
+ }
4634
+ }
4635
+ function createLazyIntegration(packageName, integrationName, createIntegration) {
4636
+ let cachedIntegration = null;
4637
+ let importPromise = null;
4638
+ return async function(...args) {
4639
+ if (cachedIntegration) {
4640
+ return cachedIntegration(...args);
4641
+ }
4642
+ if (!importPromise) {
4643
+ importPromise = importPeerDependency(packageName, integrationName).then((module) => {
4644
+ cachedIntegration = createIntegration(module);
4645
+ return cachedIntegration;
4646
+ });
4647
+ }
4648
+ const integration = await importPromise;
4649
+ return integration(...args);
4650
+ };
4651
+ }
4652
+ function checkPeerDependencies(dependencies) {
4653
+ const results = {};
4654
+ const missing = [];
4655
+ for (const { package: packageName, integration } of dependencies) {
4656
+ const available = isPeerDependencyAvailable(packageName);
4657
+ results[packageName] = available;
4658
+ if (!available) {
4659
+ missing.push({ package: packageName, integration });
4660
+ }
4661
+ }
4662
+ if (missing.length > 0) {
4663
+ const installCommands = missing.map(({ package: pkg }) => pkg).join(" ");
4664
+ const integrationsList = missing.map(({ integration }) => integration).join(", ");
4665
+ console.warn(
4666
+ `Optional dependencies missing for ${integrationsList} integration(s).
4667
+ To use these integrations, install: npm install ${installCommands}
4668
+ Or with pnpm: pnpm add ${installCommands}
4669
+ Or with yarn: yarn add ${installCommands}`
4670
+ );
4671
+ }
4672
+ return results;
4673
+ }
4674
+
3411
4675
  // src/shadow-dom.js
3412
4676
  var shadow_dom_exports = {};
3413
4677
  __export(shadow_dom_exports, {
@@ -4917,7 +6181,7 @@ function applyScopeToElement(element, scopeId) {
4917
6181
  }
4918
6182
  return element;
4919
6183
  }
4920
- function escapeHtml(text) {
6184
+ function escapeHtml2(text) {
4921
6185
  if (typeof text !== "string") return text;
4922
6186
  return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#x27;");
4923
6187
  }
@@ -4927,83 +6191,11 @@ function dangerouslySetInnerContent(content) {
4927
6191
  __trusted: true
4928
6192
  };
4929
6193
  }
4930
- function isTrustedContent(value) {
4931
- return value && typeof value === "object" && value.__trusted === true && typeof value.__html === "string";
4932
- }
4933
- function isVoidElement(tagName) {
4934
- const voidElements = /* @__PURE__ */ new Set([
4935
- "area",
4936
- "base",
4937
- "br",
4938
- "col",
4939
- "embed",
4940
- "hr",
4941
- "img",
4942
- "input",
4943
- "link",
4944
- "meta",
4945
- "param",
4946
- "source",
4947
- "track",
4948
- "wbr"
4949
- ]);
4950
- return voidElements.has(tagName.toLowerCase());
4951
- }
4952
- function formatAttributes(attrs) {
4953
- if (!attrs || typeof attrs !== "object") return "";
4954
- return Object.entries(attrs).filter(([, value]) => value !== null && value !== void 0 && value !== false).map(([key, value]) => {
4955
- if (typeof value === "function") {
4956
- value = value();
4957
- }
4958
- const attrName = key === "className" ? "class" : key;
4959
- if (value === true) return attrName;
4960
- return `${attrName}="${escapeHtml(String(value))}"`;
4961
- }).join(" ");
4962
- }
4963
- function renderRaw(obj) {
4964
- if (obj === null || obj === void 0) return "";
4965
- if (typeof obj === "string" || typeof obj === "number") return escapeHtml(String(obj));
4966
- if (Array.isArray(obj)) return obj.map(renderRaw).join("");
4967
- if (typeof obj === "function") {
4968
- const result = obj(renderRaw);
4969
- return renderRaw(result);
4970
- }
4971
- if (typeof obj !== "object") return escapeHtml(String(obj));
4972
- if (obj.text !== void 0) {
4973
- return escapeHtml(String(obj.text));
4974
- }
4975
- for (const [tagName, props] of Object.entries(obj)) {
4976
- if (typeof props === "object" && props !== null) {
4977
- const { children, text, ...attributes } = props;
4978
- const attrsStr = formatAttributes(attributes);
4979
- const openTag = attrsStr ? `<${tagName} ${attrsStr}>` : `<${tagName}>`;
4980
- if (isVoidElement(tagName)) {
4981
- return openTag.replace(">", " />");
4982
- }
4983
- let content = "";
4984
- if (text !== void 0) {
4985
- if (isTrustedContent(text)) {
4986
- content = text.__html;
4987
- } else {
4988
- content = escapeHtml(String(text));
4989
- }
4990
- } else if (children) {
4991
- content = renderRaw(children);
4992
- }
4993
- return `${openTag}${content}</${tagName}>`;
4994
- } else if (typeof props === "string") {
4995
- const content = isTrustedContent(props) ? props.__html : escapeHtml(props);
4996
- return isVoidElement(tagName) ? `<${tagName} />` : `<${tagName}>${content}</${tagName}>`;
4997
- }
4998
- }
4999
- return "";
5000
- }
5001
- function render(obj, options = {}) {
5002
- const { scoped = false } = options;
5003
- if (scoped) {
5004
- return renderScopedComponent(obj);
5005
- }
5006
- return renderRaw(obj);
6194
+ function render2(obj, options = {}) {
6195
+ const scoped = options.scoped ?? options.encapsulate ?? false;
6196
+ const { scoped: _scoped, encapsulate: _encapsulate, ...rendererOptions } = options;
6197
+ const component = scoped ? renderScopedComponent(obj) : obj;
6198
+ return render(component, rendererOptions);
5007
6199
  }
5008
6200
  function renderScopedComponent(component) {
5009
6201
  const scopeId = generateScopeId();
@@ -5035,7 +6227,7 @@ function renderScopedComponent(component) {
5035
6227
  }
5036
6228
  const processedComponent = processScopedElement(component);
5037
6229
  const scopedComponent = applyScopeToElement(processedComponent, scopeId);
5038
- return renderRaw(scopedComponent);
6230
+ return scopedComponent;
5039
6231
  }
5040
6232
  var memoCache = /* @__PURE__ */ new Map();
5041
6233
  function memo2(component, keyGenerator) {
@@ -5059,7 +6251,7 @@ function validateComponent2(obj) {
5059
6251
  }
5060
6252
  return true;
5061
6253
  }
5062
- function isCoherentObject(obj) {
6254
+ function isCoherentObject2(obj) {
5063
6255
  return obj && typeof obj === "object" && !Array.isArray(obj);
5064
6256
  }
5065
6257
  function deepClone2(obj) {
@@ -5072,10 +6264,13 @@ function deepClone2(obj) {
5072
6264
  }
5073
6265
  return cloned;
5074
6266
  }
5075
- var VERSION = "2.0.0";
6267
+ var _corePackageJson = JSON.parse(
6268
+ readFileSync(new URL("../package.json", import.meta.url), "utf-8")
6269
+ );
6270
+ var VERSION = _corePackageJson.version;
5076
6271
  var coherent = {
5077
6272
  // Core rendering
5078
- render,
6273
+ render: render2,
5079
6274
  // Shadow DOM (client-side only)
5080
6275
  shadowDOM: shadow_dom_exports,
5081
6276
  // Component system
@@ -5127,9 +6322,9 @@ var coherent = {
5127
6322
  withEventState,
5128
6323
  // Utilities
5129
6324
  validateComponent: validateComponent2,
5130
- isCoherentObject,
6325
+ isCoherentObject: isCoherentObject2,
5131
6326
  deepClone: deepClone2,
5132
- escapeHtml,
6327
+ escapeHtml: escapeHtml2,
5133
6328
  performanceMonitor,
5134
6329
  VERSION
5135
6330
  };
@@ -5139,9 +6334,12 @@ export {
5139
6334
  ComponentLifecycle,
5140
6335
  DOMEventIntegration,
5141
6336
  EventBus,
6337
+ FORBIDDEN_CHILDREN,
5142
6338
  GlobalErrorHandler,
6339
+ HTMLNestingError,
5143
6340
  LIFECYCLE_PHASES,
5144
6341
  VERSION,
6342
+ checkPeerDependencies,
5145
6343
  createActionHandlers,
5146
6344
  createAsyncErrorBoundary,
5147
6345
  createComponent,
@@ -5149,10 +6347,12 @@ export {
5149
6347
  createElement,
5150
6348
  createErrorBoundary,
5151
6349
  createErrorFallback,
6350
+ createErrorResponse,
5152
6351
  createEventBus,
5153
6352
  createEventComponent,
5154
6353
  createEventHandlers,
5155
6354
  createGlobalErrorHandler,
6355
+ createLazyIntegration,
5156
6356
  createLifecycleHooks,
5157
6357
  createStateManager,
5158
6358
  createTextNode,
@@ -5170,23 +6370,32 @@ export {
5170
6370
  globalEventBus,
5171
6371
  h,
5172
6372
  handleAction,
6373
+ hasChildren,
6374
+ importPeerDependency,
5173
6375
  initializeDOMIntegration,
5174
- isCoherentObject,
6376
+ isCoherentComponent,
6377
+ isCoherentObject2 as isCoherentObject,
5175
6378
  isLazy,
6379
+ isPeerDependencyAvailable,
5176
6380
  lazy,
5177
6381
  componentUtils as lifecycleUtils,
5178
6382
  memo2 as memo,
5179
6383
  memoize,
6384
+ normalizeChildren,
5180
6385
  off,
5181
6386
  on,
5182
6387
  once,
5183
6388
  performanceMonitor,
5184
6389
  registerAction,
5185
6390
  registerComponent,
5186
- render,
6391
+ render2 as render,
6392
+ renderComponentFactory,
6393
+ renderWithMonitoring,
6394
+ renderWithTemplate,
5187
6395
  shadow_dom_exports as shadowDOM,
5188
6396
  useHooks,
5189
6397
  validateComponent2 as validateComponent,
6398
+ validateNesting,
5190
6399
  withErrorBoundary,
5191
6400
  withEventBus,
5192
6401
  withEventState,
@@ -5194,11 +6403,17 @@ export {
5194
6403
  withState,
5195
6404
  withStateUtils
5196
6405
  };
6406
+ /**
6407
+ * Advanced caching system with memory management and smart invalidation for Coherent.js
6408
+ *
6409
+ * @module @coherent/performance/cache-manager
6410
+ * @license MIT
6411
+ */
5197
6412
  /**
5198
6413
  * Coherent.js - Object-Based Rendering Framework
5199
6414
  * A pure JavaScript framework for server-side rendering using natural object syntax
5200
6415
  *
5201
- * @version 2.0.0
6416
+ * @version 1.0.0-beta.6
5202
6417
  * @author Coherent Framework Team
5203
6418
  * @license MIT
5204
6419
  */