ladrillosjs 2.0.0-beta.3.1 → 2.0.0-beta.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -23,6 +23,7 @@ A lightweight, zero-dependency web component framework for building modular web
23
23
  - [Slots](#slots)
24
24
  - [Component Props](#component-props)
25
25
  - [Advanced Features](#advanced-features)
26
+ - [Lazy Loading](#lazy-loading)
26
27
  - [Global Event Bus](#global-event-bus)
27
28
  - [External Scripts](#external-scripts)
28
29
  - [Shadow DOM](#shadow-dom)
@@ -48,8 +49,9 @@ A lightweight, zero-dependency web component framework for building modular web
48
49
  - 🔌 **Slots** - Content projection with named and default slots
49
50
  - 📝 **TypeScript** - Full type definitions and TypeScript source code
50
51
  - 🎭 **Conditional Rendering** - `$if`, `$else-if`, and `$else` directives
51
- - **List Rendering** - `$for` directive for rendering arrays
52
- - �🚄 **Smart Caching** - LRU cache for components and compiled functions
52
+ - 🔁 **List Rendering** - `$for` directive for rendering arrays
53
+ - **Lazy Loading** - Load components on-demand with Intersection Observer
54
+ - 🚄 **Smart Caching** - LRU cache for components and compiled functions
53
55
  - 🔧 **Framework Utilities** - Helper functions for common tasks
54
56
  - 🧩 **External Scripts** - Load and bind external JavaScript modules
55
57
 
@@ -193,6 +195,21 @@ await registerComponents([
193
195
 
194
196
  // Disable Shadow DOM for a component
195
197
  await registerComponent("global-styles", "./components/global.html", false);
198
+
199
+ // Enable lazy loading for a component
200
+ await registerComponent(
201
+ "footer-section",
202
+ "./components/footer.html",
203
+ true,
204
+ true
205
+ );
206
+
207
+ // Register multiple components with lazy loading
208
+ await registerComponents([
209
+ { name: "hero-section", path: "./components/hero.html" },
210
+ { name: "feature-section", path: "./components/features.html", lazy: true },
211
+ { name: "footer-section", path: "./components/footer.html", lazy: true },
212
+ ]);
196
213
  ```
197
214
 
198
215
  ### State Management
@@ -568,6 +585,93 @@ Pass data to components using HTML attributes:
568
585
 
569
586
  ## Advanced Features
570
587
 
588
+ ### Lazy Loading
589
+
590
+ LadrillosJS supports lazy loading components using the Intersection Observer API. Components are loaded only when they enter or are about to enter the viewport, improving initial page load performance.
591
+
592
+ #### Basic Usage
593
+
594
+ ```javascript
595
+ import { registerComponents } from "ladrillosjs";
596
+
597
+ await registerComponents([
598
+ // Eager loading (default) - loads immediately
599
+ { name: "hero-section", path: "./components/hero.html" },
600
+ { name: "navbar", path: "./components/navbar.html" },
601
+
602
+ // Lazy loading - loads when scrolled into view
603
+ { name: "feature-section", path: "./components/features.html", lazy: true },
604
+ { name: "testimonials", path: "./components/testimonials.html", lazy: true },
605
+ { name: "footer-section", path: "./components/footer.html", lazy: true },
606
+ ]);
607
+ ```
608
+
609
+ ```html
610
+ <body>
611
+ <!-- Loads immediately -->
612
+ <navbar></navbar>
613
+ <hero-section></hero-section>
614
+
615
+ <!-- Loads when user scrolls near these components -->
616
+ <feature-section></feature-section>
617
+ <testimonials></testimonials>
618
+ <footer-section></footer-section>
619
+ </body>
620
+ ```
621
+
622
+ #### Override Lazy Loading with `eager` Attribute
623
+
624
+ You can force a lazy component to load immediately using the `eager` attribute:
625
+
626
+ ```html
627
+ <!-- This lazy component loads immediately despite lazy registration -->
628
+ <footer-section eager></footer-section>
629
+ ```
630
+
631
+ #### Best Practices for Lazy Loading
632
+
633
+ **✅ Good candidates for lazy loading:**
634
+
635
+ - Below-the-fold content (footers, testimonials)
636
+ - Large components with heavy resources
637
+ - Components that may not be viewed by all users
638
+ - Third-party widgets or embeds
639
+
640
+ **❌ Avoid lazy loading for:**
641
+
642
+ - Above-the-fold content (heroes, navigation)
643
+ - Critical interactive elements
644
+ - Small, lightweight components
645
+ - Content needed for SEO
646
+
647
+ **Performance Tips:**
648
+
649
+ 1. **Reserve space for lazy components** to prevent layout shift:
650
+
651
+ ```css
652
+ /* In your global CSS */
653
+ feature-section,
654
+ testimonials,
655
+ footer-section {
656
+ display: block;
657
+ min-height: 400px; /* Approximate height */
658
+ }
659
+ ```
660
+
661
+ 2. **Load strategy**: Lazy components load **100px before** entering the viewport for smooth user experience and to account for network latency.
662
+
663
+ 3. **Multiple instances**: If you use the same lazy component multiple times on a page, only one network request is made. All instances share the loaded component definition.
664
+
665
+ 4. **Caching**: Once loaded, lazy components are cached and reused across page navigation.
666
+
667
+ #### How It Works
668
+
669
+ - **Placeholder**: Lazy components initially render as minimal placeholders
670
+ - **Intersection Observer**: Monitors when placeholders approach the viewport
671
+ - **Automatic Loading**: Component fetches and upgrades when visible
672
+ - **Seamless Swap**: Placeholder is replaced with the real component
673
+ - **Shared Loading**: Multiple instances coordinate to load only once
674
+
571
675
  ### Global Event Bus
572
676
 
573
677
  The global event bus enables communication between components without prop drilling:
@@ -943,8 +1047,48 @@ Show loading indicators while fetching data:
943
1047
  ### Registration Functions
944
1048
 
945
1049
  ```typescript
946
- registerComponent(name: string, path: string, useShadowDOM?: boolean): Promise<void>
947
- registerComponents(components: Array<{name, path, useShadowDOM?}>): Promise<void>
1050
+ registerComponent(
1051
+ name: string,
1052
+ path: string,
1053
+ useShadowDOM?: boolean,
1054
+ lazy?: boolean
1055
+ ): Promise<void>
1056
+
1057
+ registerComponents(
1058
+ components: Array<{
1059
+ name: string,
1060
+ path: string,
1061
+ useShadowDOM?: boolean,
1062
+ lazy?: boolean
1063
+ }>
1064
+ ): Promise<void>
1065
+ ```
1066
+
1067
+ **Parameters:**
1068
+
1069
+ - `name`: Component tag name (must include a hyphen)
1070
+ - `path`: Path to the component file
1071
+ - `useShadowDOM`: Use Shadow DOM for style encapsulation (default: `true`)
1072
+ - `lazy`: Enable lazy loading with Intersection Observer (default: `false`)
1073
+
1074
+ **Examples:**
1075
+
1076
+ ```javascript
1077
+ // Basic registration
1078
+ await registerComponent("my-button", "./button.html");
1079
+
1080
+ // Disable Shadow DOM
1081
+ await registerComponent("global-nav", "./nav.html", false);
1082
+
1083
+ // Enable lazy loading
1084
+ await registerComponent("footer", "./footer.html", true, true);
1085
+
1086
+ // Batch registration
1087
+ await registerComponents([
1088
+ { name: "hero", path: "./hero.html" },
1089
+ { name: "features", path: "./features.html", lazy: true },
1090
+ { name: "footer", path: "./footer.html", useShadowDOM: false, lazy: true },
1091
+ ]);
948
1092
  ```
949
1093
 
950
1094
  ### Component Utilities
@@ -984,6 +1128,10 @@ $reactive(name: string, initialValue: any): (value: any) => void
984
1128
  <li $for="(item, index) in items">{index}: {item}</li>
985
1129
  <div $for="user in users" $key="user.id">{user.name}</div>
986
1130
 
1131
+ <!-- Lazy loading override -->
1132
+ <footer-section eager></footer-section>
1133
+ <!-- Force immediate load -->
1134
+
987
1135
  <!-- Event handlers -->
988
1136
  <button onclick="methodName()">Click</button>
989
1137
  <button onclick="method(arg1, arg2)">Call with args</button>
@@ -344,8 +344,8 @@ T = function(e, r, s) {
344
344
  });
345
345
  },
346
346
  {
347
- rootMargin: "50px"
348
- // Load 50px before entering viewport
347
+ rootMargin: "100px"
348
+ // Load 100px before entering viewport
349
349
  }
350
350
  ), this.observer.observe(this);
351
351
  }
@@ -398,7 +398,7 @@ T = function(e, r, s) {
398
398
  n.log(`Defining real component with temp name: ${m}`);
399
399
  const y = o.components[e].tagName;
400
400
  o.components[e].tagName = m;
401
- const { defineWebComponent: C } = yield import("./webcomponent-CC0mzBGb.mjs");
401
+ const { defineWebComponent: C } = yield import("./webcomponent-DT_kduma.mjs");
402
402
  C(o.components[e], s), n.log(`Real component ${m} defined`), o.components[e].tagName = y, this.upgradePlaceholder();
403
403
  });
404
404
  }
@@ -422,7 +422,7 @@ T = function(e, r, s) {
422
422
  customElements.get(e) || customElements.define(e, i);
423
423
  }, A = function(e, r) {
424
424
  return p(this, null, function* () {
425
- const { defineWebComponent: s } = yield import("./webcomponent-CC0mzBGb.mjs");
425
+ const { defineWebComponent: s } = yield import("./webcomponent-DT_kduma.mjs");
426
426
  this.components[e] && s(this.components[e], r);
427
427
  });
428
428
  };
@@ -577,4 +577,4 @@ export {
577
577
  ce as q,
578
578
  re as r
579
579
  };
580
- //# sourceMappingURL=index-DmNz8gcU.mjs.map
580
+ //# sourceMappingURL=index-JWdjGiUA.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-JWdjGiUA.mjs","sources":["../src/utils/logger.ts","../src/utils/devErrors.ts","../src/cache/index.ts","../src/core/componentSource.ts","../src/utils/regex.ts","../src/core/componentParser.ts","../src/core/main.ts","../src/core/eventBus.ts","../src/index.ts"],"sourcesContent":["/**\r\n * Utility for conditional logging based on environment\r\n */\r\n\r\n// Type guard for Vite environment\r\nconst isDevelopment = (): boolean => {\r\n try {\r\n return (import.meta as any).env?.DEV === true;\r\n } catch {\r\n return process.env.NODE_ENV === 'development';\r\n }\r\n};\r\n\r\nexport const logger = {\r\n /**\r\n * Log a message only in development mode\r\n * @param message - The message to log\r\n * @param args - Additional arguments to log\r\n */\r\n log(message: string, ...args: any[]): void {\r\n if (isDevelopment()) {\r\n console.log(message, ...args);\r\n }\r\n },\r\n\r\n /**\r\n * Log an error (always logs in both dev and production)\r\n * @param message - The error message\r\n * @param args - Additional arguments to log\r\n */\r\n error(message: string, ...args: any[]): void {\r\n console.error(message, ...args);\r\n },\r\n\r\n /**\r\n * Log a warning only in development mode\r\n * @param message - The warning message\r\n * @param args - Additional arguments to log\r\n */\r\n warn(message: string, ...args: any[]): void {\r\n if (isDevelopment()) {\r\n console.warn(message, ...args);\r\n }\r\n },\r\n};\r\n","/**\r\n * Developer-friendly error handling utilities\r\n * Provides contextual error messages with component names, file paths, and code references\r\n */\r\n\r\nimport { logger } from \"./logger\";\r\n\r\nexport type ErrorContext = {\r\n componentName?: string;\r\n componentPath?: string;\r\n expression?: string;\r\n attributeName?: string;\r\n eventType?: string;\r\n elementTag?: string;\r\n lineHint?: string;\r\n};\r\n\r\nexport class LadrillosError extends Error {\r\n public readonly componentName?: string;\r\n public readonly componentPath?: string;\r\n public readonly expression?: string;\r\n public readonly context?: ErrorContext;\r\n\r\n constructor(message: string, context?: ErrorContext) {\r\n super(message);\r\n this.name = \"LadrillosError\";\r\n this.componentName = context?.componentName;\r\n this.componentPath = context?.componentPath;\r\n this.expression = context?.expression;\r\n this.context = context;\r\n\r\n // Maintain proper stack trace for where error was thrown\r\n if (Error.captureStackTrace) {\r\n Error.captureStackTrace(this, LadrillosError);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Formats an error message with component context for developers\r\n */\r\nconst formatErrorMessage = (\r\n message: string,\r\n context?: ErrorContext\r\n): string => {\r\n const parts: string[] = [message];\r\n\r\n if (context) {\r\n if (context.componentName) {\r\n parts.push(`\\n Component: <${context.componentName}>`);\r\n }\r\n\r\n if (context.componentPath) {\r\n parts.push(`\\n File: ${context.componentPath}`);\r\n }\r\n\r\n if (context.expression) {\r\n parts.push(`\\n Expression: ${context.expression}`);\r\n }\r\n\r\n if (context.attributeName) {\r\n parts.push(`\\n Attribute: ${context.attributeName}`);\r\n }\r\n\r\n if (context.eventType) {\r\n parts.push(`\\n Event: ${context.eventType}`);\r\n }\r\n\r\n if (context.elementTag) {\r\n parts.push(`\\n Element: <${context.elementTag}>`);\r\n }\r\n\r\n if (context.lineHint) {\r\n parts.push(`\\n Location: ${context.lineHint}`);\r\n }\r\n }\r\n\r\n return parts.join(\"\");\r\n};\r\n\r\n/**\r\n * Logs a binding error with component context\r\n */\r\nexport const logBindingError = (\r\n expression: string,\r\n error: Error,\r\n context?: ErrorContext\r\n): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Binding Error: Failed to evaluate expression`,\r\n {\r\n ...context,\r\n expression,\r\n lineHint: context?.lineHint || \"Template binding expression\",\r\n }\r\n );\r\n\r\n logger.error(errorMessage);\r\n logger.error(` Error details: ${error.message}`);\r\n\r\n // Log stack trace in development for debugging\r\n if (error.stack) {\r\n console.debug(\" Stack trace:\", error.stack);\r\n }\r\n};\r\n\r\n/**\r\n * Logs an event handler error with component context\r\n */\r\nexport const logEventHandlerError = (\r\n eventType: string,\r\n handlerCode: string,\r\n error: Error,\r\n context?: ErrorContext\r\n): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Event Handler Error: Failed to execute handler`,\r\n {\r\n ...context,\r\n eventType,\r\n expression: handlerCode,\r\n lineHint: context?.lineHint || `on${eventType} handler`,\r\n }\r\n );\r\n\r\n logger.error(errorMessage);\r\n logger.error(` Error details: ${error.message}`);\r\n\r\n if (error.stack) {\r\n console.debug(\" Stack trace:\", error.stack);\r\n }\r\n};\r\n\r\n/**\r\n * Logs a conditional rendering error with component context\r\n */\r\nexport const logConditionalError = (\r\n condition: string,\r\n error: Error,\r\n context?: ErrorContext\r\n): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Conditional Error: Failed to evaluate condition`,\r\n {\r\n ...context,\r\n expression: condition,\r\n lineHint: context?.lineHint || \"$if/$else-if condition\",\r\n }\r\n );\r\n\r\n logger.error(errorMessage);\r\n logger.error(` Error details: ${error.message}`);\r\n\r\n if (error.stack) {\r\n console.debug(\" Stack trace:\", error.stack);\r\n }\r\n};\r\n\r\n/**\r\n * Logs a loop rendering error with component context\r\n */\r\nexport const logLoopError = (\r\n loopExpression: string,\r\n error: Error,\r\n context?: ErrorContext\r\n): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Loop Error: Failed to process loop`,\r\n {\r\n ...context,\r\n expression: loopExpression,\r\n lineHint: context?.lineHint || \"$for loop expression\",\r\n }\r\n );\r\n\r\n logger.error(errorMessage);\r\n logger.error(` Error details: ${error.message}`);\r\n\r\n if (error.stack) {\r\n console.debug(\" Stack trace:\", error.stack);\r\n }\r\n};\r\n\r\n/**\r\n * Logs a component registration error\r\n */\r\nexport const logRegistrationError = (\r\n componentName: string,\r\n componentPath: string,\r\n error: Error\r\n): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Registration Error: Failed to register component`,\r\n {\r\n componentName,\r\n componentPath,\r\n }\r\n );\r\n\r\n logger.error(errorMessage);\r\n logger.error(` Error details: ${error.message}`);\r\n\r\n if (error.stack) {\r\n console.debug(\" Stack trace:\", error.stack);\r\n }\r\n};\r\n\r\n/**\r\n * Logs a fetch error with context\r\n */\r\nexport const logFetchError = (\r\n url: string,\r\n error: Error,\r\n context?: ErrorContext\r\n): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Fetch Error: Failed to load resource`,\r\n {\r\n ...context,\r\n componentPath: url,\r\n }\r\n );\r\n\r\n logger.error(errorMessage);\r\n logger.error(` Error details: ${error.message}`);\r\n};\r\n\r\n/**\r\n * Logs a parsing error with context\r\n */\r\nexport const logParseError = (\r\n message: string,\r\n context?: ErrorContext\r\n): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Parse Error: ${message}`,\r\n context\r\n );\r\n\r\n logger.error(errorMessage);\r\n};\r\n\r\n/**\r\n * Logs a script execution error\r\n */\r\nexport const logScriptError = (error: Error, context?: ErrorContext): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Script Error: Failed to execute component script`,\r\n context\r\n );\r\n\r\n logger.error(errorMessage);\r\n logger.error(` Error details: ${error.message}`);\r\n\r\n if (error.stack) {\r\n console.debug(\" Stack trace:\", error.stack);\r\n }\r\n};\r\n\r\n/**\r\n * Logs a two-way binding error\r\n */\r\nexport const logTwoWayBindingError = (\r\n expression: string,\r\n error: Error,\r\n context?: ErrorContext\r\n): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Two-Way Binding Error: Failed to setup binding`,\r\n {\r\n ...context,\r\n expression,\r\n lineHint: context?.lineHint || \"$model binding\",\r\n }\r\n );\r\n\r\n logger.error(errorMessage);\r\n logger.error(` Error details: ${error.message}`);\r\n};\r\n\r\n/**\r\n * Creates an error context from component metadata\r\n */\r\nexport const createErrorContext = (\r\n component: any,\r\n additionalContext?: Partial<ErrorContext>\r\n): ErrorContext => {\r\n return {\r\n componentName: component?.tagName || component?.constructor?.name,\r\n componentPath: component?.sourcePath || component?._sourcePath,\r\n ...additionalContext,\r\n };\r\n};\r\n","const cache = new Map<string, string>();\r\nconst maxCacheSize = 25; // TODO: make configurable for developer to set\r\n\r\n/**\r\n * LRU Cache: Gets cached content and marks it as recently used\r\n * Moves the accessed item to the end of the Map (most recently used position)\r\n * This ensures frequently accessed components stay in cache longer\r\n * @param path - The file path to retrieve from cache\r\n * @returns The cached content or undefined if not found\r\n */\r\nexport const getCached = (path: string): string | undefined => {\r\n const cached = cache.get(path);\r\n if (cached) {\r\n // LRU: Move to end (most recently used position)\r\n cache.delete(path);\r\n cache.set(path, cached);\r\n }\r\n return cached;\r\n};\r\n\r\n/**\r\n * LRU Cache: Stores content with automatic eviction of least recently used items\r\n * Maintains cache size limit by removing oldest items when full\r\n * Updates existing items without affecting cache size\r\n * @param path - The file path to cache\r\n * @param content - The content to store\r\n */\r\nexport const setCache = (path: string, content: string): void => {\r\n if (cache.has(path)) {\r\n // Update existing: remove and re-add to mark as most recent\r\n cache.delete(path);\r\n } else if (cache.size >= maxCacheSize) {\r\n // Cache full: remove least recently used (first item in Map)\r\n const firstKey = cache.keys().next().value;\r\n if (firstKey) {\r\n cache.delete(firstKey);\r\n }\r\n }\r\n // Add/update as most recently used (end of Map)\r\n cache.set(path, content);\r\n};\r\n","import { getCached, setCache } from \"../cache\";\r\nimport { logger } from \"../utils/logger\";\r\nimport { logFetchError } from \"../utils/devErrors\";\r\n\r\n/**\r\n * Fetches component source with caching support\r\n * @param path - The file path to fetch\r\n * @returns The component source content\r\n */\r\nexport const fetchComponentSource = async (\r\n path: string\r\n): Promise<string | undefined> => {\r\n if (!path) {\r\n throw new Error(\"Path cannot be null or empty\");\r\n }\r\n\r\n const cached = getCached(path);\r\n if (cached) return cached;\r\n\r\n // fetch and cache\r\n try {\r\n const response = await fetch(path);\r\n\r\n if (!response.ok) {\r\n throw new Error(\r\n `Failed to fetch component from ${path}: ${response.statusText}`\r\n );\r\n }\r\n\r\n const text = await response.text();\r\n setCache(path, text);\r\n\r\n return text;\r\n } catch (error) {\r\n logFetchError(path, error as Error, { componentPath: path });\r\n }\r\n};\r\n\r\n/**\r\n * Safe fetch helper that returns empty string on error\r\n * @param url - The URL to fetch\r\n * @returns The fetched content or empty string\r\n */\r\nexport const safeFetch = async (url: string): Promise<string> => {\r\n try {\r\n const res = await fetch(url);\r\n if (!res.ok) throw new Error(`HTTP ${res.status}`);\r\n return await res.text();\r\n } catch (err) {\r\n logFetchError(url, err as Error);\r\n return \"\";\r\n }\r\n};\r\n","import { RegexPatterns } from \"../types/LadrilloTypes\";\r\n\r\nexport const REGEX_PATTERNS: RegexPatterns = {\r\n bindings: /{([^}]+)}/g,\r\n comments: {\r\n js: /\\/\\*[\\s\\S]*?\\*\\/|\\/\\/.*$/gm,\r\n css: /\\/\\*[\\s\\S]*?\\*\\//g,\r\n html: /<!--[\\s\\S]*?-->/g,\r\n },\r\n};\r\n","import {\r\n ExternalScriptElement,\r\n LadrillosComponent,\r\n ScriptElement,\r\n} from \"../types/LadrilloTypes\";\r\nimport { REGEX_PATTERNS } from \"../utils/regex\";\r\nimport { logger } from \"../utils/logger\";\r\nimport { safeFetch } from \"./componentSource\";\r\n\r\nconst parser = new DOMParser();\r\n\r\n/**\r\n * Parses component HTML and extracts scripts and styles\r\n * @param source - The HTML source of the component\r\n * @param name - The name of the component\r\n * @returns Parsed component object\r\n */\r\nexport const parseComponent = async (\r\n source: string,\r\n name: string\r\n): Promise<LadrillosComponent> => {\r\n const doc = parseComponentHTML(source);\r\n const { scripts, externalScripts } = extractScripts(doc);\r\n const styles = await extractStyles(doc);\r\n const template = doc.body.innerHTML.trim();\r\n\r\n return {\r\n tagName: name,\r\n template,\r\n scripts,\r\n externalScripts,\r\n styles,\r\n };\r\n};\r\n\r\n/**\r\n * Parses HTML content and removes comments\r\n * @param source - The HTML source to parse\r\n * @returns Parsed DOM document\r\n */\r\nexport const parseComponentHTML = (source: string): Document => {\r\n return parser.parseFromString(\r\n source.replace(REGEX_PATTERNS.comments.html, \"\"),\r\n \"text/html\"\r\n );\r\n};\r\n\r\n/**\r\n * Checks if a script URL is a development server script that should be ignored.\r\n * Dev server scripts (Vite, Webpack HMR, etc.) are injected by the dev environment\r\n * and should not be processed as part of the component.\r\n */\r\nconst isDevServerScript = (src: string): boolean => {\r\n const devPatterns = [\r\n \"/@vite/\", // Vite dev client\r\n \"/__vite\", // Vite internal\r\n \"/webpack-dev-server\", // Webpack dev server\r\n \"/hot-update\", // Webpack HMR\r\n \"/__webpack_hmr\", // Webpack HMR\r\n \"/browser-sync/\", // Browser Sync\r\n \"/livereload.js\", // LiveReload\r\n ];\r\n\r\n return devPatterns.some((pattern) => src.includes(pattern));\r\n};\r\n\r\n/**\r\n * Extracts and processes script elements from the document\r\n * @param doc - The parsed document\r\n * @returns Object containing scripts and external scripts\r\n */\r\nexport const extractScripts = (\r\n doc: Document\r\n): {\r\n scripts: ScriptElement[];\r\n externalScripts: ExternalScriptElement[];\r\n} => {\r\n const scripts: ScriptElement[] = [];\r\n const externalScripts: ExternalScriptElement[] = [];\r\n\r\n for (const el of doc.querySelectorAll(\"script\")) {\r\n if (el.src) {\r\n // Skip dev server scripts (Vite, Webpack, etc.)\r\n if (isDevServerScript(el.src)) {\r\n el.remove();\r\n continue;\r\n }\r\n\r\n // Only mark as external if the 'external' attribute is explicitly present\r\n const isExternal = el.hasAttribute(\"external\");\r\n\r\n externalScripts.push({\r\n src: el.getAttribute(\"src\") || el.src, // Use getAttribute to preserve relative paths\r\n type: el.type ?? null,\r\n external: isExternal,\r\n });\r\n } else if (el.textContent) {\r\n let content = el.textContent.trim();\r\n // strip JavaScript comments (single‑line and block)\r\n content = content.replace(REGEX_PATTERNS.comments.js, \"\").trim();\r\n scripts.push({\r\n content,\r\n type: el.type ?? null,\r\n });\r\n }\r\n el.remove();\r\n }\r\n\r\n return { scripts, externalScripts };\r\n};\r\n\r\n/**\r\n * Extracts CSS content from various response formats\r\n * Handles:\r\n * - Vite dev server (wrapped in __vite__css variable)\r\n * - Plain CSS files (production/CDN)\r\n * - Other build tool formats\r\n */\r\nconst extractCSSFromResponse = (response: string): string => {\r\n // Check if this is a Vite HMR response (contains __vite__css)\r\n // Use a regex that properly handles escaped quotes within the string\r\n const viteMatch = response.match(/const __vite__css = \"((?:[^\"\\\\]|\\\\.)*)\"/);\r\n if (viteMatch && viteMatch[1]) {\r\n // Unescape the CSS string\r\n return viteMatch[1]\r\n .replace(/\\\\r\\\\n/g, \"\\n\")\r\n .replace(/\\\\n/g, \"\\n\")\r\n .replace(/\\\\t/g, \"\\t\")\r\n .replace(/\\\\\"/g, '\"')\r\n .replace(/\\\\\\\\/g, \"\\\\\");\r\n }\r\n\r\n // Check for other module formats (e.g., \"export default ...\")\r\n const exportMatch = response.match(/export\\s+default\\s+\"((?:[^\"\\\\]|\\\\.)*)\"/);\r\n if (exportMatch && exportMatch[1]) {\r\n return exportMatch[1]\r\n .replace(/\\\\r\\\\n/g, \"\\n\")\r\n .replace(/\\\\n/g, \"\\n\")\r\n .replace(/\\\\t/g, \"\\t\")\r\n .replace(/\\\\\"/g, '\"')\r\n .replace(/\\\\\\\\/g, \"\\\\\");\r\n }\r\n\r\n // If it looks like JavaScript (not CSS), warn and return empty\r\n if (response.includes(\"import\") || response.includes(\"export\")) {\r\n logger.warn(\r\n \"CSS file returned JavaScript module format. CSS may not load correctly.\"\r\n );\r\n return \"\";\r\n }\r\n\r\n // If not a module format, assume it's plain CSS (production or direct file)\r\n return response;\r\n};\r\n\r\n/**\r\n * Extracts and processes style elements from the document\r\n * @param doc - The parsed document\r\n * @returns Concatenated CSS content\r\n */\r\nexport const extractStyles = async (doc: Document): Promise<string> => {\r\n let style = \"\";\r\n\r\n // Process styles in document order (inline styles and external stylesheets)\r\n const styleElements = doc.querySelectorAll(\"style, link[rel='stylesheet']\");\r\n\r\n for (const element of styleElements) {\r\n if (element.tagName === \"LINK\") {\r\n const linkElement = element as HTMLLinkElement;\r\n const response = await safeFetch(linkElement.href);\r\n const cssContent = extractCSSFromResponse(response);\r\n if (cssContent) {\r\n style += \"\\n\" + cssContent;\r\n }\r\n } else if (element.tagName === \"STYLE\") {\r\n const styleEl = element as HTMLStyleElement;\r\n if (styleEl.textContent) {\r\n let css = styleEl.textContent.trim();\r\n // strip CSS comments\r\n css = css.replace(REGEX_PATTERNS.comments.css, \"\").trim();\r\n style += \"\\n\" + css;\r\n }\r\n }\r\n element.remove();\r\n }\r\n\r\n return style.trim();\r\n};\r\n","import { LadrillosComponent } from \"../types/LadrilloTypes\";\r\nimport { logger } from \"../utils/logger\";\r\nimport { logRegistrationError, logParseError } from \"../utils/devErrors\";\r\nimport { fetchComponentSource } from \"./componentSource\";\r\nimport { parseComponent } from \"./componentParser\";\r\n\r\nclass Ladrillos {\r\n // properties\r\n components: Record<string, LadrillosComponent>;\r\n private lazyComponents: Set<string>;\r\n private intersectionObserver: IntersectionObserver | null;\r\n private lazyLoadingInProgress: Map<string, Promise<void>>;\r\n private lazyComponentsLoaded: Set<string>;\r\n\r\n constructor() {\r\n // Initialize the Ladrillos instance\r\n this.components = {};\r\n this.lazyComponents = new Set();\r\n this.intersectionObserver = null;\r\n this.lazyLoadingInProgress = new Map();\r\n this.lazyComponentsLoaded = new Set();\r\n }\r\n\r\n async registerComponent(\r\n name: string,\r\n path: string,\r\n useShadowDOM: boolean = true,\r\n lazy: boolean = false\r\n ): Promise<void> {\r\n if (this.components[name]) {\r\n logger.warn(`Component with name \"${name}\" is already registered.`);\r\n return;\r\n }\r\n\r\n // For lazy components, register a placeholder and defer actual loading\r\n if (lazy) {\r\n this.lazyComponents.add(name);\r\n this.#defineLazyPlaceholder(name, path, useShadowDOM);\r\n logger.log(`Component ${name} registered as lazy-loaded`);\r\n return;\r\n }\r\n\r\n try {\r\n const source = await fetchComponentSource(path);\r\n const component = await parseComponent(source!, name);\r\n\r\n this.components[name] = {\r\n tagName: name,\r\n template: component.template,\r\n scripts: component.scripts,\r\n externalScripts: component.externalScripts,\r\n styles: component.styles,\r\n sourcePath: path,\r\n lazy: false,\r\n };\r\n\r\n // Define the web component\r\n logger.log(`Component ${name} registered successfully`);\r\n await this.#defineWebComponent(name, useShadowDOM);\r\n } catch (error) {\r\n logRegistrationError(name, path, error as Error);\r\n return;\r\n }\r\n }\r\n\r\n /**\r\n * Defines a lazy-loading placeholder component\r\n * @param name - Component name\r\n * @param path - Component path\r\n * @param useShadowDOM - Whether to use Shadow DOM\r\n */\r\n #defineLazyPlaceholder(\r\n name: string,\r\n path: string,\r\n useShadowDOM: boolean\r\n ): void {\r\n const self = this;\r\n\r\n class LazyPlaceholder extends HTMLElement {\r\n private loaded = false;\r\n private observer: IntersectionObserver | null = null;\r\n\r\n constructor() {\r\n super();\r\n\r\n // Show a minimal loading indicator\r\n if (useShadowDOM) {\r\n this.attachShadow({ mode: \"open\" });\r\n if (this.shadowRoot) {\r\n this.shadowRoot.innerHTML = `\r\n <style>\r\n :host { display: block; min-height: 1px; }\r\n </style>\r\n `;\r\n }\r\n }\r\n }\r\n\r\n connectedCallback() {\r\n if (this.loaded) return;\r\n\r\n // Check if 'eager' attribute is present - if so, load immediately\r\n if (this.hasAttribute(\"eager\")) {\r\n this.loaded = true;\r\n this.loadComponent();\r\n return;\r\n }\r\n\r\n // Set up intersection observer for lazy loading\r\n this.observer = new IntersectionObserver(\r\n (entries) => {\r\n entries.forEach((entry) => {\r\n if (entry.isIntersecting && !this.loaded) {\r\n this.loaded = true;\r\n this.loadComponent();\r\n }\r\n });\r\n },\r\n {\r\n rootMargin: \"100px\", // Load 100px before entering viewport\r\n }\r\n );\r\n\r\n this.observer.observe(this);\r\n }\r\n\r\n disconnectedCallback() {\r\n if (this.observer) {\r\n this.observer.disconnect();\r\n this.observer = null;\r\n }\r\n }\r\n\r\n async loadComponent() {\r\n try {\r\n // Check if component is already loaded globally\r\n if (self.lazyComponentsLoaded.has(name)) {\r\n logger.log(\r\n `Component ${name} already loaded, upgrading placeholder...`\r\n );\r\n this.upgradePlaceholder();\r\n return;\r\n }\r\n\r\n // Check if loading is already in progress\r\n if (self.lazyLoadingInProgress.has(name)) {\r\n logger.log(`Component ${name} is already loading, waiting...`);\r\n await self.lazyLoadingInProgress.get(name);\r\n this.upgradePlaceholder();\r\n return;\r\n }\r\n\r\n // Start loading process\r\n const loadingPromise = this.performLoad();\r\n self.lazyLoadingInProgress.set(name, loadingPromise);\r\n\r\n await loadingPromise;\r\n\r\n // Mark as loaded and clean up\r\n self.lazyLoadingInProgress.delete(name);\r\n self.lazyComponentsLoaded.add(name);\r\n self.lazyComponents.delete(name);\r\n\r\n logger.log(`Component ${name} lazy-loaded successfully`);\r\n } catch (error) {\r\n self.lazyLoadingInProgress.delete(name);\r\n logRegistrationError(name, path, error as Error);\r\n }\r\n }\r\n\r\n async performLoad() {\r\n logger.log(`Lazy loading component: ${name}`);\r\n\r\n // Store reference to this placeholder element\r\n const placeholder = this;\r\n const parent = this.parentNode;\r\n const nextSibling = this.nextSibling;\r\n\r\n if (!parent) {\r\n logParseError(`Placeholder for ${name} has no parent node`, {\r\n componentName: name,\r\n componentPath: path,\r\n });\r\n return;\r\n }\r\n\r\n // Fetch and parse the component\r\n const source = await fetchComponentSource(path);\r\n const component = await parseComponent(source!, name);\r\n\r\n logger.log(`Component ${name} parsed successfully`);\r\n\r\n self.components[name] = {\r\n tagName: name,\r\n template: component.template,\r\n scripts: component.scripts,\r\n externalScripts: component.externalScripts,\r\n styles: component.styles,\r\n sourcePath: path,\r\n lazy: true,\r\n };\r\n\r\n // Create a unique temporary name for the real component\r\n const tempName = `${name}-real`;\r\n\r\n logger.log(`Defining real component with temp name: ${tempName}`);\r\n\r\n // Store original name and temporarily use temp name\r\n const originalTagName = self.components[name].tagName;\r\n self.components[name].tagName = tempName;\r\n\r\n // Import and define the real component with temp name\r\n const { defineWebComponent } = await import(\"./webcomponent\");\r\n defineWebComponent(self.components[name], useShadowDOM);\r\n\r\n logger.log(`Real component ${tempName} defined`);\r\n\r\n // Restore original tag name\r\n self.components[name].tagName = originalTagName;\r\n\r\n // Upgrade this placeholder\r\n this.upgradePlaceholder();\r\n }\r\n\r\n upgradePlaceholder() {\r\n const placeholder = this;\r\n const parent = this.parentNode;\r\n const nextSibling = this.nextSibling;\r\n\r\n if (!parent) {\r\n logParseError(`Placeholder for ${name} has no parent node`, {\r\n componentName: name,\r\n componentPath: path,\r\n });\r\n return;\r\n }\r\n\r\n const tempName = `${name}-real`;\r\n\r\n // Create instance of the real component\r\n const realComponent = document.createElement(tempName);\r\n\r\n logger.log(`Created real component instance: ${tempName}`);\r\n\r\n // Copy attributes from placeholder to real component\r\n Array.from(placeholder.attributes).forEach((attr) => {\r\n if (attr.name !== \"eager\") {\r\n // Skip the eager attribute\r\n realComponent.setAttribute(attr.name, attr.value);\r\n }\r\n });\r\n\r\n // Copy child nodes (slot content)\r\n while (placeholder.firstChild) {\r\n realComponent.appendChild(placeholder.firstChild);\r\n }\r\n\r\n // Replace placeholder in DOM\r\n if (nextSibling) {\r\n parent.insertBefore(realComponent, nextSibling);\r\n logger.log(`Inserted real component before next sibling`);\r\n } else {\r\n parent.appendChild(realComponent);\r\n logger.log(`Appended real component to parent`);\r\n }\r\n\r\n parent.removeChild(placeholder);\r\n logger.log(`Removed placeholder element`);\r\n }\r\n }\r\n\r\n // Define the placeholder component\r\n if (!customElements.get(name)) {\r\n customElements.define(name, LazyPlaceholder);\r\n }\r\n }\r\n\r\n /**\r\n * Defines the web component using the webcomponent module\r\n * @param name - Component name\r\n * @param useShadowDOM - Whether to use Shadow DOM\r\n */\r\n async #defineWebComponent(\r\n name: string,\r\n useShadowDOM: boolean\r\n ): Promise<void> {\r\n const { defineWebComponent } = await import(\"./webcomponent\");\r\n\r\n // safety check\r\n if (this.components[name]) {\r\n defineWebComponent(this.components[name], useShadowDOM);\r\n }\r\n }\r\n}\r\n\r\nexport const ladrillos = new Ladrillos();\r\n","/**\r\n * Global Event Bus for component-to-component communication\r\n * Allows components to emit events and listen to events from other components\r\n */\r\n\r\nimport { logger } from \"../utils/logger\";\r\n\r\ntype EventCallback = (data?: any) => void | Promise<void>;\r\ntype EventListeners = Map<string, Set<EventCallback>>;\r\n\r\nclass EventBus {\r\n private listeners: EventListeners = new Map();\r\n\r\n /**\r\n * Emit an event with optional data\r\n * @param eventName - The name of the event to emit\r\n * @param data - Optional data to pass to listeners\r\n * @returns Promise that resolves when all listeners have been called\r\n */\r\n emit(eventName: string, data?: any): Promise<void> {\r\n // Also dispatch as a native DOM CustomEvent so document.addEventListener works\r\n const customEvent = new CustomEvent(eventName, {\r\n detail: data,\r\n bubbles: true,\r\n composed: true,\r\n });\r\n document.dispatchEvent(customEvent);\r\n\r\n const callbacks = this.listeners.get(eventName);\r\n\r\n if (!callbacks || callbacks.size === 0) {\r\n // No listeners, resolve immediately\r\n return Promise.resolve();\r\n }\r\n\r\n // Execute all callbacks and collect promises\r\n const promises: Promise<void>[] = [];\r\n\r\n callbacks.forEach((callback) => {\r\n try {\r\n const result = callback(data);\r\n // If callback returns a promise, add it to promises array\r\n if (result instanceof Promise) {\r\n promises.push(result);\r\n }\r\n } catch (error) {\r\n logger.error(\r\n `⚠️ Event Bus Error: Failed to execute listener for \"${eventName}\"`\r\n );\r\n logger.error(` Error details: ${(error as Error).message}`);\r\n promises.push(Promise.reject(error));\r\n }\r\n });\r\n\r\n // If any callbacks returned promises, wait for all of them\r\n if (promises.length > 0) {\r\n return Promise.all(promises).then(() => undefined);\r\n }\r\n\r\n return Promise.resolve();\r\n }\r\n\r\n /**\r\n * Listen to an event\r\n * @param eventName - The name of the event to listen for\r\n * @param callback - Function to call when event is emitted\r\n * @returns Function to remove the listener\r\n */\r\n listen(eventName: string, callback: EventCallback): () => void {\r\n if (!this.listeners.has(eventName)) {\r\n this.listeners.set(eventName, new Set());\r\n }\r\n\r\n this.listeners.get(eventName)!.add(callback);\r\n\r\n // Return unsubscribe function\r\n return () => {\r\n this.off(eventName, callback);\r\n };\r\n }\r\n\r\n /**\r\n * Remove a specific event listener\r\n * @param eventName - The name of the event\r\n * @param callback - The callback to remove\r\n */\r\n off(eventName: string, callback: EventCallback): void {\r\n const callbacks = this.listeners.get(eventName);\r\n if (callbacks) {\r\n callbacks.delete(callback);\r\n // Clean up empty sets\r\n if (callbacks.size === 0) {\r\n this.listeners.delete(eventName);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Remove all listeners for an event, or all listeners if no event specified\r\n * @param eventName - Optional event name to clear listeners for\r\n */\r\n clear(eventName?: string): void {\r\n if (eventName) {\r\n this.listeners.delete(eventName);\r\n } else {\r\n this.listeners.clear();\r\n }\r\n }\r\n\r\n /**\r\n * Get count of listeners for an event\r\n * @param eventName - The event name\r\n * @returns Number of listeners\r\n */\r\n listenerCount(eventName: string): number {\r\n return this.listeners.get(eventName)?.size ?? 0;\r\n }\r\n}\r\n\r\n// Export singleton instance\r\nexport const eventBus = new EventBus();\r\n","import { ladrillos } from \"./core/main.js\";\r\nimport { eventBus } from \"./core/eventBus.js\";\r\nimport { ComponentRegistration } from \"./types/LadrilloTypes.js\";\r\n\r\ndeclare global {\r\n interface Window {\r\n ladrillosjs: {\r\n registerComponent: typeof registerComponent;\r\n registerComponents: typeof registerComponents;\r\n };\r\n $listen: typeof $listen;\r\n $emit: typeof $emit;\r\n $querySelector: typeof $querySelector;\r\n $querySelectorAll: typeof $querySelectorAll;\r\n $reactive: typeof $reactive;\r\n $setState: typeof $setState;\r\n $getState: typeof $getState;\r\n }\r\n}\r\n\r\nexport const registerComponent = (\r\n name: string,\r\n path: string,\r\n useShadowDOM?: boolean,\r\n lazy?: boolean\r\n) => ladrillos.registerComponent(name, path, useShadowDOM, lazy);\r\n\r\nexport const registerComponents = async (\r\n components: ComponentRegistration[]\r\n): Promise<void> => {\r\n await Promise.all(\r\n components.map(({ name, path, useShadowDOM, lazy }) =>\r\n ladrillos.registerComponent(name, path, useShadowDOM, lazy)\r\n )\r\n );\r\n};\r\n\r\n// Event bus helper functions\r\nexport const $listen = (event: string, callback: (data?: any) => void) => {\r\n return eventBus.listen(event, callback);\r\n};\r\n\r\nexport const $emit = (event: string, data?: any) => {\r\n eventBus.emit(event, data);\r\n};\r\n\r\n// Component context management\r\n// Maps script URLs to their component contexts for persistent association\r\nconst scriptContextMap = new Map<\r\n string,\r\n { shadowRoot?: ShadowRoot; element?: HTMLElement }\r\n>();\r\nconst activeContext: { shadowRoot?: ShadowRoot; element?: HTMLElement } | null =\r\n null;\r\n\r\n/**\r\n * Internal: Set component context for a script\r\n * Called by the framework when loading scripts from components\r\n */\r\nexport const __setComponentContext = (\r\n shadowRoot?: ShadowRoot,\r\n element?: HTMLElement\r\n) => {\r\n // Store in the global registry by component tag name\r\n if (element) {\r\n const tagName = element.tagName.toLowerCase();\r\n if (!(window as any).__ladrilloContexts) {\r\n (window as any).__ladrilloContexts = new Map();\r\n }\r\n (window as any).__ladrilloContexts.set(tagName, { shadowRoot, element });\r\n }\r\n};\r\n\r\n/**\r\n * Internal: Get component context for the current script\r\n */\r\nconst getComponentContext = () => {\r\n const registry = (window as any).__ladrilloContexts as Map<string, any>;\r\n if (registry && registry.size > 0) {\r\n // For now, return the last registered context\r\n // TODO: In the future, we could track which script belongs to which component\r\n const contexts = Array.from(registry.values());\r\n return contexts[contexts.length - 1];\r\n }\r\n return null;\r\n};\r\n\r\n/**\r\n * Get the component's reactive state\r\n * Returns a Proxy that allows direct property access to component.state\r\n * @returns Proxy to component state or empty object if no component context\r\n */\r\nexport const $getState = (): any => {\r\n const ctx = getComponentContext();\r\n if (ctx && ctx.element) {\r\n return (ctx.element as any).state || {};\r\n }\r\n return {};\r\n};\r\n\r\n/**\r\n * Set component state\r\n * @param updates - Object with state updates\r\n */\r\nexport const $setState = (updates: any) => {\r\n const ctx = getComponentContext();\r\n if (ctx && ctx.setState) {\r\n ctx.setState(updates);\r\n }\r\n};\r\n\r\n/**\r\n * Creates a reactive variable that automatically updates the component when changed.\r\n * For use in ES module scripts with the bind attribute.\r\n * @param name - The variable name (must match the binding in the template)\r\n * @param initialValue - The initial value\r\n * @returns A setter function to update the value\r\n *\r\n * @example\r\n * ```javascript\r\n * import { $reactive } from 'ladrillosjs';\r\n *\r\n * // In your module script:\r\n * const setBeers = $reactive('beers', 'loading...');\r\n *\r\n * // Later, update it:\r\n * setBeers('<card>...</card>');\r\n * ```\r\n */\r\nexport const $reactive = <T = any>(\r\n name: string,\r\n initialValue: T\r\n): ((value: T) => void) => {\r\n // Initialize the state\r\n $setState({ [name]: initialValue });\r\n\r\n // Return a setter function\r\n return (value: T) => {\r\n $setState({ [name]: value });\r\n };\r\n};\r\n\r\n// DOM query helpers with smart component context detection\r\n// Automatically searches within component context when appropriate\r\nexport const $querySelector = (\r\n selector: string,\r\n root?: Element | Document | ShadowRoot\r\n): Element | null => {\r\n if (root) {\r\n return root.querySelector(selector);\r\n }\r\n\r\n // Try to get component context\r\n const ctx = getComponentContext();\r\n if (ctx) {\r\n const searchRoot = ctx.shadowRoot || ctx.element;\r\n if (searchRoot) {\r\n const result = searchRoot.querySelector(selector);\r\n if (result) return result;\r\n }\r\n }\r\n\r\n // Fallback to document\r\n return document.querySelector(selector);\r\n};\r\n\r\nexport const $querySelectorAll = (\r\n selector: string,\r\n root?: Element | Document | ShadowRoot\r\n): NodeListOf<Element> => {\r\n if (root) {\r\n return root.querySelectorAll(selector);\r\n }\r\n\r\n // Try to get component context\r\n const ctx = getComponentContext();\r\n if (ctx) {\r\n const searchRoot = ctx.shadowRoot || ctx.element;\r\n if (searchRoot) {\r\n const result = searchRoot.querySelectorAll(selector);\r\n if (result.length > 0) return result;\r\n }\r\n }\r\n\r\n // Fallback to document\r\n return document.querySelectorAll(selector);\r\n};\r\n\r\n// for a browser‑global via <script src=\"…ladrillosjs.js\"></script>\r\nif (typeof window !== \"undefined\") {\r\n window.ladrillosjs = {\r\n registerComponent,\r\n registerComponents,\r\n };\r\n\r\n // Expose helper functions globally for non-module scripts\r\n window.$listen = $listen;\r\n window.$emit = $emit;\r\n window.$querySelector = $querySelector;\r\n window.$querySelectorAll = $querySelectorAll;\r\n window.$reactive = $reactive;\r\n window.$setState = $setState;\r\n window.$getState = $getState;\r\n}\r\n"],"names":["isDevelopment","e","logger","message","args","formatErrorMessage","context","parts","logBindingError","expression","error","errorMessage","__spreadProps","__spreadValues","logEventHandlerError","eventType","handlerCode","logConditionalError","condition","logLoopError","loopExpression","logRegistrationError","componentName","componentPath","logFetchError","url","logParseError","logScriptError","logTwoWayBindingError","createErrorContext","component","additionalContext","_a","cache","maxCacheSize","getCached","path","cached","setCache","content","firstKey","fetchComponentSource","__async","response","text","safeFetch","res","err","REGEX_PATTERNS","parser","parseComponent","source","name","doc","parseComponentHTML","scripts","externalScripts","extractScripts","styles","extractStyles","template","isDevServerScript","src","pattern","_b","el","isExternal","extractCSSFromResponse","viteMatch","exportMatch","style","styleElements","element","cssContent","styleEl","css","_Ladrillos_instances","defineLazyPlaceholder_fn","defineWebComponent_fn","Ladrillos","__privateAdd","useShadowDOM","lazy","__privateMethod","self","LazyPlaceholder","entries","entry","loadingPromise","parent","tempName","originalTagName","defineWebComponent","placeholder","nextSibling","realComponent","attr","ladrillos","EventBus","eventName","data","customEvent","callbacks","promises","callback","result","eventBus","registerComponent","registerComponents","components","$listen","event","$emit","__setComponentContext","shadowRoot","tagName","getComponentContext","registry","contexts","$getState","ctx","$setState","updates","$reactive","initialValue","value","$querySelector","selector","root","searchRoot","$querySelectorAll"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,MAAMA,IAAgB,MAAe;AACnC,MAAI;AACF,WAAQ;AAAA,EACV,SAAQC,GAAA;AACN,WAAO,QAAQ,IAAI,aAAa;AAAA,EAClC;AACF,GAEaC,IAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMpB,IAAIC,MAAoBC,GAAmB;AACzC,IAAIJ,OACF,QAAQ,IAAIG,GAAS,GAAGC,CAAI;AAAA,EAEhC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAMD,MAAoBC,GAAmB;AAC3C,YAAQ,MAAMD,GAAS,GAAGC,CAAI;AAAA,EAChC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,KAAKD,MAAoBC,GAAmB;AAC1C,IAAIJ,OACF,QAAQ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G,QAAOA;AAAA,IAChC;AAAA,EACF;AAGA,SAAO,SAAS,iBAAiBsB,CAAQ;AAC3C;AAGI,OAAO,UAAW,gBACpB,OAAO,cAAc;AAAA,EACnB,mBAAApB;AAAA,EACA,oBAAAC;AAAA,GAIF,OAAO,UAAUE,IACjB,OAAO,QAAQE,IACf,OAAO,iBAAiBc,IACxB,OAAO,oBAAoBI,IAC3B,OAAO,YAAYP,IACnB,OAAO,YAAYF,GACnB,OAAO,YAAYF;"}
@@ -15,5 +15,5 @@
15
15
  <style>
16
16
  :host { display: block; min-height: 1px; }
17
17
  </style>
18
- `))}connectedCallback(){if(!this.loaded){if(this.hasAttribute("eager")){this.loaded=!0,this.loadComponent();return}this.observer=new IntersectionObserver(l=>{l.forEach(c=>{c.isIntersecting&&!this.loaded&&(this.loaded=!0,this.loadComponent())})},{rootMargin:"50px"}),this.observer.observe(this)}}disconnectedCallback(){this.observer&&(this.observer.disconnect(),this.observer=null)}loadComponent(){return g(this,null,function*(){try{if(o.lazyComponentsLoaded.has(e)){n.log(`Component ${e} already loaded, upgrading placeholder...`),this.upgradePlaceholder();return}if(o.lazyLoadingInProgress.has(e)){n.log(`Component ${e} is already loading, waiting...`),yield o.lazyLoadingInProgress.get(e),this.upgradePlaceholder();return}const l=this.performLoad();o.lazyLoadingInProgress.set(e,l),yield l,o.lazyLoadingInProgress.delete(e),o.lazyComponentsLoaded.add(e),o.lazyComponents.delete(e),n.log(`Component ${e} lazy-loaded successfully`)}catch(l){o.lazyLoadingInProgress.delete(e),H(e,r,l)}})}performLoad(){return g(this,null,function*(){n.log(`Lazy loading component: ${e}`);const l=this.parentNode;if(this.nextSibling,!l){v(`Placeholder for ${e} has no parent node`,{componentName:e,componentPath:r});return}const c=yield M(r),d=yield T(c,e);n.log(`Component ${e} parsed successfully`),o.components[e]={tagName:e,template:d.template,scripts:d.scripts,externalScripts:d.externalScripts,styles:d.styles,sourcePath:r,lazy:!0};const f=`${e}-real`;n.log(`Defining real component with temp name: ${f}`);const y=o.components[e].tagName;o.components[e].tagName=f;const{defineWebComponent:E}=yield Promise.resolve().then(()=>require("./webcomponent-DoE_UClU.js"));E(o.components[e],s),n.log(`Real component ${f} defined`),o.components[e].tagName=y,this.upgradePlaceholder()})}upgradePlaceholder(){const l=this,c=this.parentNode,d=this.nextSibling;if(!c){v(`Placeholder for ${e} has no parent node`,{componentName:e,componentPath:r});return}const f=`${e}-real`,y=document.createElement(f);for(n.log(`Created real component instance: ${f}`),Array.from(l.attributes).forEach(E=>{E.name!=="eager"&&y.setAttribute(E.name,E.value)});l.firstChild;)y.appendChild(l.firstChild);d?(c.insertBefore(y,d),n.log("Inserted real component before next sibling")):(c.appendChild(y),n.log("Appended real component to parent")),c.removeChild(l),n.log("Removed placeholder element")}}customElements.get(e)||customElements.define(e,i)},F=function(e,r){return g(this,null,function*(){const{defineWebComponent:s}=yield Promise.resolve().then(()=>require("./webcomponent-DoE_UClU.js"));this.components[e]&&s(this.components[e],r)})};const x=new me;class fe{constructor(){this.listeners=new Map}emit(e,r){const s=new CustomEvent(e,{detail:r,bubbles:!0,composed:!0});document.dispatchEvent(s);const o=this.listeners.get(e);if(!o||o.size===0)return Promise.resolve();const i=[];return o.forEach(a=>{try{const l=a(r);l instanceof Promise&&i.push(l)}catch(l){n.error(`⚠️ Event Bus Error: Failed to execute listener for "${e}"`),n.error(` Error details: ${l.message}`),i.push(Promise.reject(l))}}),i.length>0?Promise.all(i).then(()=>{}):Promise.resolve()}listen(e,r){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(r),()=>{this.off(e,r)}}off(e,r){const s=this.listeners.get(e);s&&(s.delete(r),s.size===0&&this.listeners.delete(e))}clear(e){e?this.listeners.delete(e):this.listeners.clear()}listenerCount(e){var r,s;return(s=(r=this.listeners.get(e))==null?void 0:r.size)!=null?s:0}}const P=new fe,R=(t,e,r,s)=>x.registerComponent(t,e,r,s),B=t=>g(null,null,function*(){yield Promise.all(t.map(({name:e,path:r,useShadowDOM:s,lazy:o})=>x.registerComponent(e,r,s,o)))}),I=(t,e)=>P.listen(t,e),j=(t,e)=>{P.emit(t,e)},ye=(t,e)=>{if(e){const r=e.tagName.toLowerCase();window.__ladrilloContexts||(window.__ladrilloContexts=new Map),window.__ladrilloContexts.set(r,{shadowRoot:t,element:e})}},S=()=>{const t=window.__ladrilloContexts;if(t&&t.size>0){const e=Array.from(t.values());return e[e.length-1]}return null},W=()=>{const t=S();return t&&t.element?t.element.state||{}:{}},C=t=>{const e=S();e&&e.setState&&e.setState(t)},D=(t,e)=>(C({[t]:e}),r=>{C({[t]:r})}),G=(t,e)=>{if(e)return e.querySelector(t);const r=S();if(r){const s=r.shadowRoot||r.element;if(s){const o=s.querySelector(t);if(o)return o}}return document.querySelector(t)},K=(t,e)=>{if(e)return e.querySelectorAll(t);const r=S();if(r){const s=r.shadowRoot||r.element;if(s){const o=s.querySelectorAll(t);if(o.length>0)return o}}return document.querySelectorAll(t)};typeof window!="undefined"&&(window.ladrillosjs={registerComponent:R,registerComponents:B},window.$listen=I,window.$emit=j,window.$querySelector=G,window.$querySelectorAll=K,window.$reactive=D,window.$setState=C,window.$getState=W);exports.$emit=j;exports.$getState=W;exports.$listen=I;exports.$querySelector=G;exports.$querySelectorAll=K;exports.$reactive=D;exports.$setState=C;exports.REGEX_PATTERNS=$;exports.__setComponentContext=ye;exports.createErrorContext=oe;exports.eventBus=P;exports.logBindingError=U;exports.logConditionalError=ee;exports.logEventHandlerError=Z;exports.logLoopError=te;exports.logParseError=v;exports.logScriptError=re;exports.logTwoWayBindingError=se;exports.logger=n;exports.registerComponent=R;exports.registerComponents=B;
19
- //# sourceMappingURL=index-t-QQBc-6.js.map
18
+ `))}connectedCallback(){if(!this.loaded){if(this.hasAttribute("eager")){this.loaded=!0,this.loadComponent();return}this.observer=new IntersectionObserver(l=>{l.forEach(c=>{c.isIntersecting&&!this.loaded&&(this.loaded=!0,this.loadComponent())})},{rootMargin:"100px"}),this.observer.observe(this)}}disconnectedCallback(){this.observer&&(this.observer.disconnect(),this.observer=null)}loadComponent(){return g(this,null,function*(){try{if(o.lazyComponentsLoaded.has(e)){n.log(`Component ${e} already loaded, upgrading placeholder...`),this.upgradePlaceholder();return}if(o.lazyLoadingInProgress.has(e)){n.log(`Component ${e} is already loading, waiting...`),yield o.lazyLoadingInProgress.get(e),this.upgradePlaceholder();return}const l=this.performLoad();o.lazyLoadingInProgress.set(e,l),yield l,o.lazyLoadingInProgress.delete(e),o.lazyComponentsLoaded.add(e),o.lazyComponents.delete(e),n.log(`Component ${e} lazy-loaded successfully`)}catch(l){o.lazyLoadingInProgress.delete(e),H(e,r,l)}})}performLoad(){return g(this,null,function*(){n.log(`Lazy loading component: ${e}`);const l=this.parentNode;if(this.nextSibling,!l){v(`Placeholder for ${e} has no parent node`,{componentName:e,componentPath:r});return}const c=yield M(r),d=yield T(c,e);n.log(`Component ${e} parsed successfully`),o.components[e]={tagName:e,template:d.template,scripts:d.scripts,externalScripts:d.externalScripts,styles:d.styles,sourcePath:r,lazy:!0};const f=`${e}-real`;n.log(`Defining real component with temp name: ${f}`);const y=o.components[e].tagName;o.components[e].tagName=f;const{defineWebComponent:E}=yield Promise.resolve().then(()=>require("./webcomponent-B-2Pj2ku.js"));E(o.components[e],s),n.log(`Real component ${f} defined`),o.components[e].tagName=y,this.upgradePlaceholder()})}upgradePlaceholder(){const l=this,c=this.parentNode,d=this.nextSibling;if(!c){v(`Placeholder for ${e} has no parent node`,{componentName:e,componentPath:r});return}const f=`${e}-real`,y=document.createElement(f);for(n.log(`Created real component instance: ${f}`),Array.from(l.attributes).forEach(E=>{E.name!=="eager"&&y.setAttribute(E.name,E.value)});l.firstChild;)y.appendChild(l.firstChild);d?(c.insertBefore(y,d),n.log("Inserted real component before next sibling")):(c.appendChild(y),n.log("Appended real component to parent")),c.removeChild(l),n.log("Removed placeholder element")}}customElements.get(e)||customElements.define(e,i)},F=function(e,r){return g(this,null,function*(){const{defineWebComponent:s}=yield Promise.resolve().then(()=>require("./webcomponent-B-2Pj2ku.js"));this.components[e]&&s(this.components[e],r)})};const x=new me;class fe{constructor(){this.listeners=new Map}emit(e,r){const s=new CustomEvent(e,{detail:r,bubbles:!0,composed:!0});document.dispatchEvent(s);const o=this.listeners.get(e);if(!o||o.size===0)return Promise.resolve();const i=[];return o.forEach(a=>{try{const l=a(r);l instanceof Promise&&i.push(l)}catch(l){n.error(`⚠️ Event Bus Error: Failed to execute listener for "${e}"`),n.error(` Error details: ${l.message}`),i.push(Promise.reject(l))}}),i.length>0?Promise.all(i).then(()=>{}):Promise.resolve()}listen(e,r){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(r),()=>{this.off(e,r)}}off(e,r){const s=this.listeners.get(e);s&&(s.delete(r),s.size===0&&this.listeners.delete(e))}clear(e){e?this.listeners.delete(e):this.listeners.clear()}listenerCount(e){var r,s;return(s=(r=this.listeners.get(e))==null?void 0:r.size)!=null?s:0}}const P=new fe,R=(t,e,r,s)=>x.registerComponent(t,e,r,s),B=t=>g(null,null,function*(){yield Promise.all(t.map(({name:e,path:r,useShadowDOM:s,lazy:o})=>x.registerComponent(e,r,s,o)))}),I=(t,e)=>P.listen(t,e),j=(t,e)=>{P.emit(t,e)},ye=(t,e)=>{if(e){const r=e.tagName.toLowerCase();window.__ladrilloContexts||(window.__ladrilloContexts=new Map),window.__ladrilloContexts.set(r,{shadowRoot:t,element:e})}},S=()=>{const t=window.__ladrilloContexts;if(t&&t.size>0){const e=Array.from(t.values());return e[e.length-1]}return null},W=()=>{const t=S();return t&&t.element?t.element.state||{}:{}},C=t=>{const e=S();e&&e.setState&&e.setState(t)},D=(t,e)=>(C({[t]:e}),r=>{C({[t]:r})}),G=(t,e)=>{if(e)return e.querySelector(t);const r=S();if(r){const s=r.shadowRoot||r.element;if(s){const o=s.querySelector(t);if(o)return o}}return document.querySelector(t)},K=(t,e)=>{if(e)return e.querySelectorAll(t);const r=S();if(r){const s=r.shadowRoot||r.element;if(s){const o=s.querySelectorAll(t);if(o.length>0)return o}}return document.querySelectorAll(t)};typeof window!="undefined"&&(window.ladrillosjs={registerComponent:R,registerComponents:B},window.$listen=I,window.$emit=j,window.$querySelector=G,window.$querySelectorAll=K,window.$reactive=D,window.$setState=C,window.$getState=W);exports.$emit=j;exports.$getState=W;exports.$listen=I;exports.$querySelector=G;exports.$querySelectorAll=K;exports.$reactive=D;exports.$setState=C;exports.REGEX_PATTERNS=$;exports.__setComponentContext=ye;exports.createErrorContext=oe;exports.eventBus=P;exports.logBindingError=U;exports.logConditionalError=ee;exports.logEventHandlerError=Z;exports.logLoopError=te;exports.logParseError=v;exports.logScriptError=re;exports.logTwoWayBindingError=se;exports.logger=n;exports.registerComponent=R;exports.registerComponents=B;
19
+ //# sourceMappingURL=index-qEisp6n5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-qEisp6n5.js","sources":["../src/utils/logger.ts","../src/utils/devErrors.ts","../src/cache/index.ts","../src/core/componentSource.ts","../src/utils/regex.ts","../src/core/componentParser.ts","../src/core/main.ts","../src/core/eventBus.ts","../src/index.ts"],"sourcesContent":["/**\r\n * Utility for conditional logging based on environment\r\n */\r\n\r\n// Type guard for Vite environment\r\nconst isDevelopment = (): boolean => {\r\n try {\r\n return (import.meta as any).env?.DEV === true;\r\n } catch {\r\n return process.env.NODE_ENV === 'development';\r\n }\r\n};\r\n\r\nexport const logger = {\r\n /**\r\n * Log a message only in development mode\r\n * @param message - The message to log\r\n * @param args - Additional arguments to log\r\n */\r\n log(message: string, ...args: any[]): void {\r\n if (isDevelopment()) {\r\n console.log(message, ...args);\r\n }\r\n },\r\n\r\n /**\r\n * Log an error (always logs in both dev and production)\r\n * @param message - The error message\r\n * @param args - Additional arguments to log\r\n */\r\n error(message: string, ...args: any[]): void {\r\n console.error(message, ...args);\r\n },\r\n\r\n /**\r\n * Log a warning only in development mode\r\n * @param message - The warning message\r\n * @param args - Additional arguments to log\r\n */\r\n warn(message: string, ...args: any[]): void {\r\n if (isDevelopment()) {\r\n console.warn(message, ...args);\r\n }\r\n },\r\n};\r\n","/**\r\n * Developer-friendly error handling utilities\r\n * Provides contextual error messages with component names, file paths, and code references\r\n */\r\n\r\nimport { logger } from \"./logger\";\r\n\r\nexport type ErrorContext = {\r\n componentName?: string;\r\n componentPath?: string;\r\n expression?: string;\r\n attributeName?: string;\r\n eventType?: string;\r\n elementTag?: string;\r\n lineHint?: string;\r\n};\r\n\r\nexport class LadrillosError extends Error {\r\n public readonly componentName?: string;\r\n public readonly componentPath?: string;\r\n public readonly expression?: string;\r\n public readonly context?: ErrorContext;\r\n\r\n constructor(message: string, context?: ErrorContext) {\r\n super(message);\r\n this.name = \"LadrillosError\";\r\n this.componentName = context?.componentName;\r\n this.componentPath = context?.componentPath;\r\n this.expression = context?.expression;\r\n this.context = context;\r\n\r\n // Maintain proper stack trace for where error was thrown\r\n if (Error.captureStackTrace) {\r\n Error.captureStackTrace(this, LadrillosError);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Formats an error message with component context for developers\r\n */\r\nconst formatErrorMessage = (\r\n message: string,\r\n context?: ErrorContext\r\n): string => {\r\n const parts: string[] = [message];\r\n\r\n if (context) {\r\n if (context.componentName) {\r\n parts.push(`\\n Component: <${context.componentName}>`);\r\n }\r\n\r\n if (context.componentPath) {\r\n parts.push(`\\n File: ${context.componentPath}`);\r\n }\r\n\r\n if (context.expression) {\r\n parts.push(`\\n Expression: ${context.expression}`);\r\n }\r\n\r\n if (context.attributeName) {\r\n parts.push(`\\n Attribute: ${context.attributeName}`);\r\n }\r\n\r\n if (context.eventType) {\r\n parts.push(`\\n Event: ${context.eventType}`);\r\n }\r\n\r\n if (context.elementTag) {\r\n parts.push(`\\n Element: <${context.elementTag}>`);\r\n }\r\n\r\n if (context.lineHint) {\r\n parts.push(`\\n Location: ${context.lineHint}`);\r\n }\r\n }\r\n\r\n return parts.join(\"\");\r\n};\r\n\r\n/**\r\n * Logs a binding error with component context\r\n */\r\nexport const logBindingError = (\r\n expression: string,\r\n error: Error,\r\n context?: ErrorContext\r\n): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Binding Error: Failed to evaluate expression`,\r\n {\r\n ...context,\r\n expression,\r\n lineHint: context?.lineHint || \"Template binding expression\",\r\n }\r\n );\r\n\r\n logger.error(errorMessage);\r\n logger.error(` Error details: ${error.message}`);\r\n\r\n // Log stack trace in development for debugging\r\n if (error.stack) {\r\n console.debug(\" Stack trace:\", error.stack);\r\n }\r\n};\r\n\r\n/**\r\n * Logs an event handler error with component context\r\n */\r\nexport const logEventHandlerError = (\r\n eventType: string,\r\n handlerCode: string,\r\n error: Error,\r\n context?: ErrorContext\r\n): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Event Handler Error: Failed to execute handler`,\r\n {\r\n ...context,\r\n eventType,\r\n expression: handlerCode,\r\n lineHint: context?.lineHint || `on${eventType} handler`,\r\n }\r\n );\r\n\r\n logger.error(errorMessage);\r\n logger.error(` Error details: ${error.message}`);\r\n\r\n if (error.stack) {\r\n console.debug(\" Stack trace:\", error.stack);\r\n }\r\n};\r\n\r\n/**\r\n * Logs a conditional rendering error with component context\r\n */\r\nexport const logConditionalError = (\r\n condition: string,\r\n error: Error,\r\n context?: ErrorContext\r\n): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Conditional Error: Failed to evaluate condition`,\r\n {\r\n ...context,\r\n expression: condition,\r\n lineHint: context?.lineHint || \"$if/$else-if condition\",\r\n }\r\n );\r\n\r\n logger.error(errorMessage);\r\n logger.error(` Error details: ${error.message}`);\r\n\r\n if (error.stack) {\r\n console.debug(\" Stack trace:\", error.stack);\r\n }\r\n};\r\n\r\n/**\r\n * Logs a loop rendering error with component context\r\n */\r\nexport const logLoopError = (\r\n loopExpression: string,\r\n error: Error,\r\n context?: ErrorContext\r\n): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Loop Error: Failed to process loop`,\r\n {\r\n ...context,\r\n expression: loopExpression,\r\n lineHint: context?.lineHint || \"$for loop expression\",\r\n }\r\n );\r\n\r\n logger.error(errorMessage);\r\n logger.error(` Error details: ${error.message}`);\r\n\r\n if (error.stack) {\r\n console.debug(\" Stack trace:\", error.stack);\r\n }\r\n};\r\n\r\n/**\r\n * Logs a component registration error\r\n */\r\nexport const logRegistrationError = (\r\n componentName: string,\r\n componentPath: string,\r\n error: Error\r\n): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Registration Error: Failed to register component`,\r\n {\r\n componentName,\r\n componentPath,\r\n }\r\n );\r\n\r\n logger.error(errorMessage);\r\n logger.error(` Error details: ${error.message}`);\r\n\r\n if (error.stack) {\r\n console.debug(\" Stack trace:\", error.stack);\r\n }\r\n};\r\n\r\n/**\r\n * Logs a fetch error with context\r\n */\r\nexport const logFetchError = (\r\n url: string,\r\n error: Error,\r\n context?: ErrorContext\r\n): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Fetch Error: Failed to load resource`,\r\n {\r\n ...context,\r\n componentPath: url,\r\n }\r\n );\r\n\r\n logger.error(errorMessage);\r\n logger.error(` Error details: ${error.message}`);\r\n};\r\n\r\n/**\r\n * Logs a parsing error with context\r\n */\r\nexport const logParseError = (\r\n message: string,\r\n context?: ErrorContext\r\n): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Parse Error: ${message}`,\r\n context\r\n );\r\n\r\n logger.error(errorMessage);\r\n};\r\n\r\n/**\r\n * Logs a script execution error\r\n */\r\nexport const logScriptError = (error: Error, context?: ErrorContext): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Script Error: Failed to execute component script`,\r\n context\r\n );\r\n\r\n logger.error(errorMessage);\r\n logger.error(` Error details: ${error.message}`);\r\n\r\n if (error.stack) {\r\n console.debug(\" Stack trace:\", error.stack);\r\n }\r\n};\r\n\r\n/**\r\n * Logs a two-way binding error\r\n */\r\nexport const logTwoWayBindingError = (\r\n expression: string,\r\n error: Error,\r\n context?: ErrorContext\r\n): void => {\r\n const errorMessage = formatErrorMessage(\r\n `⚠️ Two-Way Binding Error: Failed to setup binding`,\r\n {\r\n ...context,\r\n expression,\r\n lineHint: context?.lineHint || \"$model binding\",\r\n }\r\n );\r\n\r\n logger.error(errorMessage);\r\n logger.error(` Error details: ${error.message}`);\r\n};\r\n\r\n/**\r\n * Creates an error context from component metadata\r\n */\r\nexport const createErrorContext = (\r\n component: any,\r\n additionalContext?: Partial<ErrorContext>\r\n): ErrorContext => {\r\n return {\r\n componentName: component?.tagName || component?.constructor?.name,\r\n componentPath: component?.sourcePath || component?._sourcePath,\r\n ...additionalContext,\r\n };\r\n};\r\n","const cache = new Map<string, string>();\r\nconst maxCacheSize = 25; // TODO: make configurable for developer to set\r\n\r\n/**\r\n * LRU Cache: Gets cached content and marks it as recently used\r\n * Moves the accessed item to the end of the Map (most recently used position)\r\n * This ensures frequently accessed components stay in cache longer\r\n * @param path - The file path to retrieve from cache\r\n * @returns The cached content or undefined if not found\r\n */\r\nexport const getCached = (path: string): string | undefined => {\r\n const cached = cache.get(path);\r\n if (cached) {\r\n // LRU: Move to end (most recently used position)\r\n cache.delete(path);\r\n cache.set(path, cached);\r\n }\r\n return cached;\r\n};\r\n\r\n/**\r\n * LRU Cache: Stores content with automatic eviction of least recently used items\r\n * Maintains cache size limit by removing oldest items when full\r\n * Updates existing items without affecting cache size\r\n * @param path - The file path to cache\r\n * @param content - The content to store\r\n */\r\nexport const setCache = (path: string, content: string): void => {\r\n if (cache.has(path)) {\r\n // Update existing: remove and re-add to mark as most recent\r\n cache.delete(path);\r\n } else if (cache.size >= maxCacheSize) {\r\n // Cache full: remove least recently used (first item in Map)\r\n const firstKey = cache.keys().next().value;\r\n if (firstKey) {\r\n cache.delete(firstKey);\r\n }\r\n }\r\n // Add/update as most recently used (end of Map)\r\n cache.set(path, content);\r\n};\r\n","import { getCached, setCache } from \"../cache\";\r\nimport { logger } from \"../utils/logger\";\r\nimport { logFetchError } from \"../utils/devErrors\";\r\n\r\n/**\r\n * Fetches component source with caching support\r\n * @param path - The file path to fetch\r\n * @returns The component source content\r\n */\r\nexport const fetchComponentSource = async (\r\n path: string\r\n): Promise<string | undefined> => {\r\n if (!path) {\r\n throw new Error(\"Path cannot be null or empty\");\r\n }\r\n\r\n const cached = getCached(path);\r\n if (cached) return cached;\r\n\r\n // fetch and cache\r\n try {\r\n const response = await fetch(path);\r\n\r\n if (!response.ok) {\r\n throw new Error(\r\n `Failed to fetch component from ${path}: ${response.statusText}`\r\n );\r\n }\r\n\r\n const text = await response.text();\r\n setCache(path, text);\r\n\r\n return text;\r\n } catch (error) {\r\n logFetchError(path, error as Error, { componentPath: path });\r\n }\r\n};\r\n\r\n/**\r\n * Safe fetch helper that returns empty string on error\r\n * @param url - The URL to fetch\r\n * @returns The fetched content or empty string\r\n */\r\nexport const safeFetch = async (url: string): Promise<string> => {\r\n try {\r\n const res = await fetch(url);\r\n if (!res.ok) throw new Error(`HTTP ${res.status}`);\r\n return await res.text();\r\n } catch (err) {\r\n logFetchError(url, err as Error);\r\n return \"\";\r\n }\r\n};\r\n","import { RegexPatterns } from \"../types/LadrilloTypes\";\r\n\r\nexport const REGEX_PATTERNS: RegexPatterns = {\r\n bindings: /{([^}]+)}/g,\r\n comments: {\r\n js: /\\/\\*[\\s\\S]*?\\*\\/|\\/\\/.*$/gm,\r\n css: /\\/\\*[\\s\\S]*?\\*\\//g,\r\n html: /<!--[\\s\\S]*?-->/g,\r\n },\r\n};\r\n","import {\r\n ExternalScriptElement,\r\n LadrillosComponent,\r\n ScriptElement,\r\n} from \"../types/LadrilloTypes\";\r\nimport { REGEX_PATTERNS } from \"../utils/regex\";\r\nimport { logger } from \"../utils/logger\";\r\nimport { safeFetch } from \"./componentSource\";\r\n\r\nconst parser = new DOMParser();\r\n\r\n/**\r\n * Parses component HTML and extracts scripts and styles\r\n * @param source - The HTML source of the component\r\n * @param name - The name of the component\r\n * @returns Parsed component object\r\n */\r\nexport const parseComponent = async (\r\n source: string,\r\n name: string\r\n): Promise<LadrillosComponent> => {\r\n const doc = parseComponentHTML(source);\r\n const { scripts, externalScripts } = extractScripts(doc);\r\n const styles = await extractStyles(doc);\r\n const template = doc.body.innerHTML.trim();\r\n\r\n return {\r\n tagName: name,\r\n template,\r\n scripts,\r\n externalScripts,\r\n styles,\r\n };\r\n};\r\n\r\n/**\r\n * Parses HTML content and removes comments\r\n * @param source - The HTML source to parse\r\n * @returns Parsed DOM document\r\n */\r\nexport const parseComponentHTML = (source: string): Document => {\r\n return parser.parseFromString(\r\n source.replace(REGEX_PATTERNS.comments.html, \"\"),\r\n \"text/html\"\r\n );\r\n};\r\n\r\n/**\r\n * Checks if a script URL is a development server script that should be ignored.\r\n * Dev server scripts (Vite, Webpack HMR, etc.) are injected by the dev environment\r\n * and should not be processed as part of the component.\r\n */\r\nconst isDevServerScript = (src: string): boolean => {\r\n const devPatterns = [\r\n \"/@vite/\", // Vite dev client\r\n \"/__vite\", // Vite internal\r\n \"/webpack-dev-server\", // Webpack dev server\r\n \"/hot-update\", // Webpack HMR\r\n \"/__webpack_hmr\", // Webpack HMR\r\n \"/browser-sync/\", // Browser Sync\r\n \"/livereload.js\", // LiveReload\r\n ];\r\n\r\n return devPatterns.some((pattern) => src.includes(pattern));\r\n};\r\n\r\n/**\r\n * Extracts and processes script elements from the document\r\n * @param doc - The parsed document\r\n * @returns Object containing scripts and external scripts\r\n */\r\nexport const extractScripts = (\r\n doc: Document\r\n): {\r\n scripts: ScriptElement[];\r\n externalScripts: ExternalScriptElement[];\r\n} => {\r\n const scripts: ScriptElement[] = [];\r\n const externalScripts: ExternalScriptElement[] = [];\r\n\r\n for (const el of doc.querySelectorAll(\"script\")) {\r\n if (el.src) {\r\n // Skip dev server scripts (Vite, Webpack, etc.)\r\n if (isDevServerScript(el.src)) {\r\n el.remove();\r\n continue;\r\n }\r\n\r\n // Only mark as external if the 'external' attribute is explicitly present\r\n const isExternal = el.hasAttribute(\"external\");\r\n\r\n externalScripts.push({\r\n src: el.getAttribute(\"src\") || el.src, // Use getAttribute to preserve relative paths\r\n type: el.type ?? null,\r\n external: isExternal,\r\n });\r\n } else if (el.textContent) {\r\n let content = el.textContent.trim();\r\n // strip JavaScript comments (single‑line and block)\r\n content = content.replace(REGEX_PATTERNS.comments.js, \"\").trim();\r\n scripts.push({\r\n content,\r\n type: el.type ?? null,\r\n });\r\n }\r\n el.remove();\r\n }\r\n\r\n return { scripts, externalScripts };\r\n};\r\n\r\n/**\r\n * Extracts CSS content from various response formats\r\n * Handles:\r\n * - Vite dev server (wrapped in __vite__css variable)\r\n * - Plain CSS files (production/CDN)\r\n * - Other build tool formats\r\n */\r\nconst extractCSSFromResponse = (response: string): string => {\r\n // Check if this is a Vite HMR response (contains __vite__css)\r\n // Use a regex that properly handles escaped quotes within the string\r\n const viteMatch = response.match(/const __vite__css = \"((?:[^\"\\\\]|\\\\.)*)\"/);\r\n if (viteMatch && viteMatch[1]) {\r\n // Unescape the CSS string\r\n return viteMatch[1]\r\n .replace(/\\\\r\\\\n/g, \"\\n\")\r\n .replace(/\\\\n/g, \"\\n\")\r\n .replace(/\\\\t/g, \"\\t\")\r\n .replace(/\\\\\"/g, '\"')\r\n .replace(/\\\\\\\\/g, \"\\\\\");\r\n }\r\n\r\n // Check for other module formats (e.g., \"export default ...\")\r\n const exportMatch = response.match(/export\\s+default\\s+\"((?:[^\"\\\\]|\\\\.)*)\"/);\r\n if (exportMatch && exportMatch[1]) {\r\n return exportMatch[1]\r\n .replace(/\\\\r\\\\n/g, \"\\n\")\r\n .replace(/\\\\n/g, \"\\n\")\r\n .replace(/\\\\t/g, \"\\t\")\r\n .replace(/\\\\\"/g, '\"')\r\n .replace(/\\\\\\\\/g, \"\\\\\");\r\n }\r\n\r\n // If it looks like JavaScript (not CSS), warn and return empty\r\n if (response.includes(\"import\") || response.includes(\"export\")) {\r\n logger.warn(\r\n \"CSS file returned JavaScript module format. CSS may not load correctly.\"\r\n );\r\n return \"\";\r\n }\r\n\r\n // If not a module format, assume it's plain CSS (production or direct file)\r\n return response;\r\n};\r\n\r\n/**\r\n * Extracts and processes style elements from the document\r\n * @param doc - The parsed document\r\n * @returns Concatenated CSS content\r\n */\r\nexport const extractStyles = async (doc: Document): Promise<string> => {\r\n let style = \"\";\r\n\r\n // Process styles in document order (inline styles and external stylesheets)\r\n const styleElements = doc.querySelectorAll(\"style, link[rel='stylesheet']\");\r\n\r\n for (const element of styleElements) {\r\n if (element.tagName === \"LINK\") {\r\n const linkElement = element as HTMLLinkElement;\r\n const response = await safeFetch(linkElement.href);\r\n const cssContent = extractCSSFromResponse(response);\r\n if (cssContent) {\r\n style += \"\\n\" + cssContent;\r\n }\r\n } else if (element.tagName === \"STYLE\") {\r\n const styleEl = element as HTMLStyleElement;\r\n if (styleEl.textContent) {\r\n let css = styleEl.textContent.trim();\r\n // strip CSS comments\r\n css = css.replace(REGEX_PATTERNS.comments.css, \"\").trim();\r\n style += \"\\n\" + css;\r\n }\r\n }\r\n element.remove();\r\n }\r\n\r\n return style.trim();\r\n};\r\n","import { LadrillosComponent } from \"../types/LadrilloTypes\";\r\nimport { logger } from \"../utils/logger\";\r\nimport { logRegistrationError, logParseError } from \"../utils/devErrors\";\r\nimport { fetchComponentSource } from \"./componentSource\";\r\nimport { parseComponent } from \"./componentParser\";\r\n\r\nclass Ladrillos {\r\n // properties\r\n components: Record<string, LadrillosComponent>;\r\n private lazyComponents: Set<string>;\r\n private intersectionObserver: IntersectionObserver | null;\r\n private lazyLoadingInProgress: Map<string, Promise<void>>;\r\n private lazyComponentsLoaded: Set<string>;\r\n\r\n constructor() {\r\n // Initialize the Ladrillos instance\r\n this.components = {};\r\n this.lazyComponents = new Set();\r\n this.intersectionObserver = null;\r\n this.lazyLoadingInProgress = new Map();\r\n this.lazyComponentsLoaded = new Set();\r\n }\r\n\r\n async registerComponent(\r\n name: string,\r\n path: string,\r\n useShadowDOM: boolean = true,\r\n lazy: boolean = false\r\n ): Promise<void> {\r\n if (this.components[name]) {\r\n logger.warn(`Component with name \"${name}\" is already registered.`);\r\n return;\r\n }\r\n\r\n // For lazy components, register a placeholder and defer actual loading\r\n if (lazy) {\r\n this.lazyComponents.add(name);\r\n this.#defineLazyPlaceholder(name, path, useShadowDOM);\r\n logger.log(`Component ${name} registered as lazy-loaded`);\r\n return;\r\n }\r\n\r\n try {\r\n const source = await fetchComponentSource(path);\r\n const component = await parseComponent(source!, name);\r\n\r\n this.components[name] = {\r\n tagName: name,\r\n template: component.template,\r\n scripts: component.scripts,\r\n externalScripts: component.externalScripts,\r\n styles: component.styles,\r\n sourcePath: path,\r\n lazy: false,\r\n };\r\n\r\n // Define the web component\r\n logger.log(`Component ${name} registered successfully`);\r\n await this.#defineWebComponent(name, useShadowDOM);\r\n } catch (error) {\r\n logRegistrationError(name, path, error as Error);\r\n return;\r\n }\r\n }\r\n\r\n /**\r\n * Defines a lazy-loading placeholder component\r\n * @param name - Component name\r\n * @param path - Component path\r\n * @param useShadowDOM - Whether to use Shadow DOM\r\n */\r\n #defineLazyPlaceholder(\r\n name: string,\r\n path: string,\r\n useShadowDOM: boolean\r\n ): void {\r\n const self = this;\r\n\r\n class LazyPlaceholder extends HTMLElement {\r\n private loaded = false;\r\n private observer: IntersectionObserver | null = null;\r\n\r\n constructor() {\r\n super();\r\n\r\n // Show a minimal loading indicator\r\n if (useShadowDOM) {\r\n this.attachShadow({ mode: \"open\" });\r\n if (this.shadowRoot) {\r\n this.shadowRoot.innerHTML = `\r\n <style>\r\n :host { display: block; min-height: 1px; }\r\n </style>\r\n `;\r\n }\r\n }\r\n }\r\n\r\n connectedCallback() {\r\n if (this.loaded) return;\r\n\r\n // Check if 'eager' attribute is present - if so, load immediately\r\n if (this.hasAttribute(\"eager\")) {\r\n this.loaded = true;\r\n this.loadComponent();\r\n return;\r\n }\r\n\r\n // Set up intersection observer for lazy loading\r\n this.observer = new IntersectionObserver(\r\n (entries) => {\r\n entries.forEach((entry) => {\r\n if (entry.isIntersecting && !this.loaded) {\r\n this.loaded = true;\r\n this.loadComponent();\r\n }\r\n });\r\n },\r\n {\r\n rootMargin: \"100px\", // Load 100px before entering viewport\r\n }\r\n );\r\n\r\n this.observer.observe(this);\r\n }\r\n\r\n disconnectedCallback() {\r\n if (this.observer) {\r\n this.observer.disconnect();\r\n this.observer = null;\r\n }\r\n }\r\n\r\n async loadComponent() {\r\n try {\r\n // Check if component is already loaded globally\r\n if (self.lazyComponentsLoaded.has(name)) {\r\n logger.log(\r\n `Component ${name} already loaded, upgrading placeholder...`\r\n );\r\n this.upgradePlaceholder();\r\n return;\r\n }\r\n\r\n // Check if loading is already in progress\r\n if (self.lazyLoadingInProgress.has(name)) {\r\n logger.log(`Component ${name} is already loading, waiting...`);\r\n await self.lazyLoadingInProgress.get(name);\r\n this.upgradePlaceholder();\r\n return;\r\n }\r\n\r\n // Start loading process\r\n const loadingPromise = this.performLoad();\r\n self.lazyLoadingInProgress.set(name, loadingPromise);\r\n\r\n await loadingPromise;\r\n\r\n // Mark as loaded and clean up\r\n self.lazyLoadingInProgress.delete(name);\r\n self.lazyComponentsLoaded.add(name);\r\n self.lazyComponents.delete(name);\r\n\r\n logger.log(`Component ${name} lazy-loaded successfully`);\r\n } catch (error) {\r\n self.lazyLoadingInProgress.delete(name);\r\n logRegistrationError(name, path, error as Error);\r\n }\r\n }\r\n\r\n async performLoad() {\r\n logger.log(`Lazy loading component: ${name}`);\r\n\r\n // Store reference to this placeholder element\r\n const placeholder = this;\r\n const parent = this.parentNode;\r\n const nextSibling = this.nextSibling;\r\n\r\n if (!parent) {\r\n logParseError(`Placeholder for ${name} has no parent node`, {\r\n componentName: name,\r\n componentPath: path,\r\n });\r\n return;\r\n }\r\n\r\n // Fetch and parse the component\r\n const source = await fetchComponentSource(path);\r\n const component = await parseComponent(source!, name);\r\n\r\n logger.log(`Component ${name} parsed successfully`);\r\n\r\n self.components[name] = {\r\n tagName: name,\r\n template: component.template,\r\n scripts: component.scripts,\r\n externalScripts: component.externalScripts,\r\n styles: component.styles,\r\n sourcePath: path,\r\n lazy: true,\r\n };\r\n\r\n // Create a unique temporary name for the real component\r\n const tempName = `${name}-real`;\r\n\r\n logger.log(`Defining real component with temp name: ${tempName}`);\r\n\r\n // Store original name and temporarily use temp name\r\n const originalTagName = self.components[name].tagName;\r\n self.components[name].tagName = tempName;\r\n\r\n // Import and define the real component with temp name\r\n const { defineWebComponent } = await import(\"./webcomponent\");\r\n defineWebComponent(self.components[name], useShadowDOM);\r\n\r\n logger.log(`Real component ${tempName} defined`);\r\n\r\n // Restore original tag name\r\n self.components[name].tagName = originalTagName;\r\n\r\n // Upgrade this placeholder\r\n this.upgradePlaceholder();\r\n }\r\n\r\n upgradePlaceholder() {\r\n const placeholder = this;\r\n const parent = this.parentNode;\r\n const nextSibling = this.nextSibling;\r\n\r\n if (!parent) {\r\n logParseError(`Placeholder for ${name} has no parent node`, {\r\n componentName: name,\r\n componentPath: path,\r\n });\r\n return;\r\n }\r\n\r\n const tempName = `${name}-real`;\r\n\r\n // Create instance of the real component\r\n const realComponent = document.createElement(tempName);\r\n\r\n logger.log(`Created real component instance: ${tempName}`);\r\n\r\n // Copy attributes from placeholder to real component\r\n Array.from(placeholder.attributes).forEach((attr) => {\r\n if (attr.name !== \"eager\") {\r\n // Skip the eager attribute\r\n realComponent.setAttribute(attr.name, attr.value);\r\n }\r\n });\r\n\r\n // Copy child nodes (slot content)\r\n while (placeholder.firstChild) {\r\n realComponent.appendChild(placeholder.firstChild);\r\n }\r\n\r\n // Replace placeholder in DOM\r\n if (nextSibling) {\r\n parent.insertBefore(realComponent, nextSibling);\r\n logger.log(`Inserted real component before next sibling`);\r\n } else {\r\n parent.appendChild(realComponent);\r\n logger.log(`Appended real component to parent`);\r\n }\r\n\r\n parent.removeChild(placeholder);\r\n logger.log(`Removed placeholder element`);\r\n }\r\n }\r\n\r\n // Define the placeholder component\r\n if (!customElements.get(name)) {\r\n customElements.define(name, LazyPlaceholder);\r\n }\r\n }\r\n\r\n /**\r\n * Defines the web component using the webcomponent module\r\n * @param name - Component name\r\n * @param useShadowDOM - Whether to use Shadow DOM\r\n */\r\n async #defineWebComponent(\r\n name: string,\r\n useShadowDOM: boolean\r\n ): Promise<void> {\r\n const { defineWebComponent } = await import(\"./webcomponent\");\r\n\r\n // safety check\r\n if (this.components[name]) {\r\n defineWebComponent(this.components[name], useShadowDOM);\r\n }\r\n }\r\n}\r\n\r\nexport const ladrillos = new Ladrillos();\r\n","/**\r\n * Global Event Bus for component-to-component communication\r\n * Allows components to emit events and listen to events from other components\r\n */\r\n\r\nimport { logger } from \"../utils/logger\";\r\n\r\ntype EventCallback = (data?: any) => void | Promise<void>;\r\ntype EventListeners = Map<string, Set<EventCallback>>;\r\n\r\nclass EventBus {\r\n private listeners: EventListeners = new Map();\r\n\r\n /**\r\n * Emit an event with optional data\r\n * @param eventName - The name of the event to emit\r\n * @param data - Optional data to pass to listeners\r\n * @returns Promise that resolves when all listeners have been called\r\n */\r\n emit(eventName: string, data?: any): Promise<void> {\r\n // Also dispatch as a native DOM CustomEvent so document.addEventListener works\r\n const customEvent = new CustomEvent(eventName, {\r\n detail: data,\r\n bubbles: true,\r\n composed: true,\r\n });\r\n document.dispatchEvent(customEvent);\r\n\r\n const callbacks = this.listeners.get(eventName);\r\n\r\n if (!callbacks || callbacks.size === 0) {\r\n // No listeners, resolve immediately\r\n return Promise.resolve();\r\n }\r\n\r\n // Execute all callbacks and collect promises\r\n const promises: Promise<void>[] = [];\r\n\r\n callbacks.forEach((callback) => {\r\n try {\r\n const result = callback(data);\r\n // If callback returns a promise, add it to promises array\r\n if (result instanceof Promise) {\r\n promises.push(result);\r\n }\r\n } catch (error) {\r\n logger.error(\r\n `⚠️ Event Bus Error: Failed to execute listener for \"${eventName}\"`\r\n );\r\n logger.error(` Error details: ${(error as Error).message}`);\r\n promises.push(Promise.reject(error));\r\n }\r\n });\r\n\r\n // If any callbacks returned promises, wait for all of them\r\n if (promises.length > 0) {\r\n return Promise.all(promises).then(() => undefined);\r\n }\r\n\r\n return Promise.resolve();\r\n }\r\n\r\n /**\r\n * Listen to an event\r\n * @param eventName - The name of the event to listen for\r\n * @param callback - Function to call when event is emitted\r\n * @returns Function to remove the listener\r\n */\r\n listen(eventName: string, callback: EventCallback): () => void {\r\n if (!this.listeners.has(eventName)) {\r\n this.listeners.set(eventName, new Set());\r\n }\r\n\r\n this.listeners.get(eventName)!.add(callback);\r\n\r\n // Return unsubscribe function\r\n return () => {\r\n this.off(eventName, callback);\r\n };\r\n }\r\n\r\n /**\r\n * Remove a specific event listener\r\n * @param eventName - The name of the event\r\n * @param callback - The callback to remove\r\n */\r\n off(eventName: string, callback: EventCallback): void {\r\n const callbacks = this.listeners.get(eventName);\r\n if (callbacks) {\r\n callbacks.delete(callback);\r\n // Clean up empty sets\r\n if (callbacks.size === 0) {\r\n this.listeners.delete(eventName);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Remove all listeners for an event, or all listeners if no event specified\r\n * @param eventName - Optional event name to clear listeners for\r\n */\r\n clear(eventName?: string): void {\r\n if (eventName) {\r\n this.listeners.delete(eventName);\r\n } else {\r\n this.listeners.clear();\r\n }\r\n }\r\n\r\n /**\r\n * Get count of listeners for an event\r\n * @param eventName - The event name\r\n * @returns Number of listeners\r\n */\r\n listenerCount(eventName: string): number {\r\n return this.listeners.get(eventName)?.size ?? 0;\r\n }\r\n}\r\n\r\n// Export singleton instance\r\nexport const eventBus = new EventBus();\r\n","import { ladrillos } from \"./core/main.js\";\r\nimport { eventBus } from \"./core/eventBus.js\";\r\nimport { ComponentRegistration } from \"./types/LadrilloTypes.js\";\r\n\r\ndeclare global {\r\n interface Window {\r\n ladrillosjs: {\r\n registerComponent: typeof registerComponent;\r\n registerComponents: typeof registerComponents;\r\n };\r\n $listen: typeof $listen;\r\n $emit: typeof $emit;\r\n $querySelector: typeof $querySelector;\r\n $querySelectorAll: typeof $querySelectorAll;\r\n $reactive: typeof $reactive;\r\n $setState: typeof $setState;\r\n $getState: typeof $getState;\r\n }\r\n}\r\n\r\nexport const registerComponent = (\r\n name: string,\r\n path: string,\r\n useShadowDOM?: boolean,\r\n lazy?: boolean\r\n) => ladrillos.registerComponent(name, path, useShadowDOM, lazy);\r\n\r\nexport const registerComponents = async (\r\n components: ComponentRegistration[]\r\n): Promise<void> => {\r\n await Promise.all(\r\n components.map(({ name, path, useShadowDOM, lazy }) =>\r\n ladrillos.registerComponent(name, path, useShadowDOM, lazy)\r\n )\r\n );\r\n};\r\n\r\n// Event bus helper functions\r\nexport const $listen = (event: string, callback: (data?: any) => void) => {\r\n return eventBus.listen(event, callback);\r\n};\r\n\r\nexport const $emit = (event: string, data?: any) => {\r\n eventBus.emit(event, data);\r\n};\r\n\r\n// Component context management\r\n// Maps script URLs to their component contexts for persistent association\r\nconst scriptContextMap = new Map<\r\n string,\r\n { shadowRoot?: ShadowRoot; element?: HTMLElement }\r\n>();\r\nconst activeContext: { shadowRoot?: ShadowRoot; element?: HTMLElement } | null =\r\n null;\r\n\r\n/**\r\n * Internal: Set component context for a script\r\n * Called by the framework when loading scripts from components\r\n */\r\nexport const __setComponentContext = (\r\n shadowRoot?: ShadowRoot,\r\n element?: HTMLElement\r\n) => {\r\n // Store in the global registry by component tag name\r\n if (element) {\r\n const tagName = element.tagName.toLowerCase();\r\n if (!(window as any).__ladrilloContexts) {\r\n (window as any).__ladrilloContexts = new Map();\r\n }\r\n (window as any).__ladrilloContexts.set(tagName, { shadowRoot, element });\r\n }\r\n};\r\n\r\n/**\r\n * Internal: Get component context for the current script\r\n */\r\nconst getComponentContext = () => {\r\n const registry = (window as any).__ladrilloContexts as Map<string, any>;\r\n if (registry && registry.size > 0) {\r\n // For now, return the last registered context\r\n // TODO: In the future, we could track which script belongs to which component\r\n const contexts = Array.from(registry.values());\r\n return contexts[contexts.length - 1];\r\n }\r\n return null;\r\n};\r\n\r\n/**\r\n * Get the component's reactive state\r\n * Returns a Proxy that allows direct property access to component.state\r\n * @returns Proxy to component state or empty object if no component context\r\n */\r\nexport const $getState = (): any => {\r\n const ctx = getComponentContext();\r\n if (ctx && ctx.element) {\r\n return (ctx.element as any).state || {};\r\n }\r\n return {};\r\n};\r\n\r\n/**\r\n * Set component state\r\n * @param updates - Object with state updates\r\n */\r\nexport const $setState = (updates: any) => {\r\n const ctx = getComponentContext();\r\n if (ctx && ctx.setState) {\r\n ctx.setState(updates);\r\n }\r\n};\r\n\r\n/**\r\n * Creates a reactive variable that automatically updates the component when changed.\r\n * For use in ES module scripts with the bind attribute.\r\n * @param name - The variable name (must match the binding in the template)\r\n * @param initialValue - The initial value\r\n * @returns A setter function to update the value\r\n *\r\n * @example\r\n * ```javascript\r\n * import { $reactive } from 'ladrillosjs';\r\n *\r\n * // In your module script:\r\n * const setBeers = $reactive('beers', 'loading...');\r\n *\r\n * // Later, update it:\r\n * setBeers('<card>...</card>');\r\n * ```\r\n */\r\nexport const $reactive = <T = any>(\r\n name: string,\r\n initialValue: T\r\n): ((value: T) => void) => {\r\n // Initialize the state\r\n $setState({ [name]: initialValue });\r\n\r\n // Return a setter function\r\n return (value: T) => {\r\n $setState({ [name]: value });\r\n };\r\n};\r\n\r\n// DOM query helpers with smart component context detection\r\n// Automatically searches within component context when appropriate\r\nexport const $querySelector = (\r\n selector: string,\r\n root?: Element | Document | ShadowRoot\r\n): Element | null => {\r\n if (root) {\r\n return root.querySelector(selector);\r\n }\r\n\r\n // Try to get component context\r\n const ctx = getComponentContext();\r\n if (ctx) {\r\n const searchRoot = ctx.shadowRoot || ctx.element;\r\n if (searchRoot) {\r\n const result = searchRoot.querySelector(selector);\r\n if (result) return result;\r\n }\r\n }\r\n\r\n // Fallback to document\r\n return document.querySelector(selector);\r\n};\r\n\r\nexport const $querySelectorAll = (\r\n selector: string,\r\n root?: Element | Document | ShadowRoot\r\n): NodeListOf<Element> => {\r\n if (root) {\r\n return root.querySelectorAll(selector);\r\n }\r\n\r\n // Try to get component context\r\n const ctx = getComponentContext();\r\n if (ctx) {\r\n const searchRoot = ctx.shadowRoot || ctx.element;\r\n if (searchRoot) {\r\n const result = searchRoot.querySelectorAll(selector);\r\n if (result.length > 0) return result;\r\n }\r\n }\r\n\r\n // Fallback to document\r\n return document.querySelectorAll(selector);\r\n};\r\n\r\n// for a browser‑global via <script src=\"…ladrillosjs.js\"></script>\r\nif (typeof window !== \"undefined\") {\r\n window.ladrillosjs = {\r\n registerComponent,\r\n registerComponents,\r\n };\r\n\r\n // Expose helper functions globally for non-module scripts\r\n window.$listen = $listen;\r\n window.$emit = $emit;\r\n window.$querySelector = $querySelector;\r\n window.$querySelectorAll = $querySelectorAll;\r\n window.$reactive = $reactive;\r\n window.$setState = $setState;\r\n window.$getState = $getState;\r\n}\r\n"],"names":["isDevelopment","e","logger","message","args","formatErrorMessage","context","parts","logBindingError","expression","error","errorMessage","__spreadProps","__spreadValues","logEventHandlerError","eventType","handlerCode","logConditionalError","condition","logLoopError","loopExpression","logRegistrationError","componentName","componentPath","logFetchError","url","logParseError","logScriptError","logTwoWayBindingError","createErrorContext","component","additionalContext","_a","cache","maxCacheSize","getCached","path","cached","setCache","content","firstKey","fetchComponentSource","__async","response","text","safeFetch","res","err","REGEX_PATTERNS","parser","parseComponent","source","name","doc","parseComponentHTML","scripts","externalScripts","extractScripts","styles","extractStyles","template","isDevServerScript","src","pattern","el","isExternal","_b","extractCSSFromResponse","viteMatch","exportMatch","style","styleElements","element","cssContent","styleEl","css","Ladrillos","__privateAdd","_Ladrillos_instances","useShadowDOM","lazy","__privateMethod","defineLazyPlaceholder_fn","defineWebComponent_fn","self","LazyPlaceholder","entries","entry","loadingPromise","parent","tempName","originalTagName","defineWebComponent","placeholder","nextSibling","realComponent","attr","ladrillos","EventBus","eventName","data","customEvent","callbacks","promises","callback","result","eventBus","registerComponent","registerComponents","components","$listen","event","$emit","__setComponentContext","shadowRoot","tagName","getComponentContext","registry","contexts","$getState","ctx","$setState","updates","$reactive","initialValue","value","$querySelector","selector","root","searchRoot","$querySelectorAll"],"mappings":"u3BAKA,MAAMA,EAAgB,IAAe,CACnC,GAAI,CACF,MAAQ,EACV,OAAQC,EAAA,CACN,OAAO,QAAQ,IAAI,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,CACzC,MAAMF,EAAMJ,EAAA,EACRI,GAAOA,EAAI,UACbA,EAAI,SAASE,CAAO,CAExB,EAoBaC,EAAY,CACvBvE,EACAwE,KAGAH,EAAU,CAAE,CAACrE,CAAI,EAAGwE,EAAc,EAG1BC,GAAa,CACnBJ,EAAU,CAAE,CAACrE,CAAI,EAAGyE,EAAO,CAC7B,GAKWC,EAAiB,CAC5BC,EACAC,IACmB,CACnB,GAAIA,EACF,OAAOA,EAAK,cAAcD,CAAQ,EAIpC,MAAMP,EAAMJ,EAAA,EACZ,GAAII,EAAK,CACP,MAAMS,EAAaT,EAAI,YAAcA,EAAI,QACzC,GAAIS,EAAY,CACd,MAAMxB,EAASwB,EAAW,cAAcF,CAAQ,EAChD,GAAItB,EAAQ,OAAOA,CACrB,CACF,CAGA,OAAO,SAAS,cAAcsB,CAAQ,CACxC,EAEaG,EAAoB,CAC/BH,EACAC,IACwB,CACxB,GAAIA,EACF,OAAOA,EAAK,iBAAiBD,CAAQ,EAIvC,MAAMP,EAAMJ,EAAA,EACZ,GAAII,EAAK,CACP,MAAMS,EAAaT,EAAI,YAAcA,EAAI,QACzC,GAAIS,EAAY,CACd,MAAMxB,EAASwB,EAAW,iBAAiBF,CAAQ,EACnD,GAAItB,EAAO,OAAS,EAAG,OAAOA,CAChC,CACF,CAGA,OAAO,SAAS,iBAAiBsB,CAAQ,CAC3C,EAGI,OAAO,QAAW,cACpB,OAAO,YAAc,CACnB,kBAAApB,EACA,mBAAAC,CAAA,EAIF,OAAO,QAAUE,EACjB,OAAO,MAAQE,EACf,OAAO,eAAiBc,EACxB,OAAO,kBAAoBI,EAC3B,OAAO,UAAYP,EACnB,OAAO,UAAYF,EACnB,OAAO,UAAYF"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-t-QQBc-6.js");exports.$emit=e.$emit;exports.$getState=e.$getState;exports.$listen=e.$listen;exports.$querySelector=e.$querySelector;exports.$querySelectorAll=e.$querySelectorAll;exports.$reactive=e.$reactive;exports.$setState=e.$setState;exports.__setComponentContext=e.__setComponentContext;exports.registerComponent=e.registerComponent;exports.registerComponents=e.registerComponents;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-qEisp6n5.js");exports.$emit=e.$emit;exports.$getState=e.$getState;exports.$listen=e.$listen;exports.$querySelector=e.$querySelector;exports.$querySelectorAll=e.$querySelectorAll;exports.$reactive=e.$reactive;exports.$setState=e.$setState;exports.__setComponentContext=e.__setComponentContext;exports.registerComponent=e.registerComponent;exports.registerComponents=e.registerComponents;
2
2
  //# sourceMappingURL=ladrillosjs.cjs.js.map
@@ -1,4 +1,4 @@
1
- import { k as s, m as a, $ as o, p as r, q as n, o as $, n as m, _ as i, r as l, j as p } from "./index-DmNz8gcU.mjs";
1
+ import { k as s, m as a, $ as o, p as r, q as n, o as $, n as m, _ as i, r as l, j as p } from "./index-JWdjGiUA.mjs";
2
2
  export {
3
3
  s as $emit,
4
4
  a as $getState,
@@ -15,7 +15,7 @@
15
15
  <style>
16
16
  :host { display: block; min-height: 1px; }
17
17
  </style>
18
- `))}connectedCallback(){if(!this.loaded){if(this.hasAttribute("eager")){this.loaded=!0,this.loadComponent();return}this.observer=new IntersectionObserver(c=>{c.forEach(f=>{f.isIntersecting&&!this.loaded&&(this.loaded=!0,this.loadComponent())})},{rootMargin:"50px"}),this.observer.observe(this)}}disconnectedCallback(){this.observer&&(this.observer.disconnect(),this.observer=null)}loadComponent(){return T(this,null,function*(){try{if(o.lazyComponentsLoaded.has(e)){d.log(`Component ${e} already loaded, upgrading placeholder...`),this.upgradePlaceholder();return}if(o.lazyLoadingInProgress.has(e)){d.log(`Component ${e} is already loading, waiting...`),yield o.lazyLoadingInProgress.get(e),this.upgradePlaceholder();return}const c=this.performLoad();o.lazyLoadingInProgress.set(e,c),yield c,o.lazyLoadingInProgress.delete(e),o.lazyComponentsLoaded.add(e),o.lazyComponents.delete(e),d.log(`Component ${e} lazy-loaded successfully`)}catch(c){o.lazyLoadingInProgress.delete(e),M(e,t,c)}})}performLoad(){return T(this,null,function*(){d.log(`Lazy loading component: ${e}`);const c=this.parentNode;if(this.nextSibling,!c){re(`Placeholder for ${e} has no parent node`,{componentName:e,componentPath:t});return}const f=yield pe(t),a=yield he(f,e);d.log(`Component ${e} parsed successfully`),o.components[e]={tagName:e,template:a.template,scripts:a.scripts,externalScripts:a.externalScripts,styles:a.styles,sourcePath:t,lazy:!0};const l=`${e}-real`;d.log(`Defining real component with temp name: ${l}`);const u=o.components[e].tagName;o.components[e].tagName=l;const{defineWebComponent:p}=yield Promise.resolve().then(()=>Ne);p(o.components[e],s),d.log(`Real component ${l} defined`),o.components[e].tagName=u,this.upgradePlaceholder()})}upgradePlaceholder(){const c=this,f=this.parentNode,a=this.nextSibling;if(!f){re(`Placeholder for ${e} has no parent node`,{componentName:e,componentPath:t});return}const l=`${e}-real`,u=document.createElement(l);for(d.log(`Created real component instance: ${l}`),Array.from(c.attributes).forEach(p=>{p.name!=="eager"&&u.setAttribute(p.name,p.value)});c.firstChild;)u.appendChild(c.firstChild);a?(f.insertBefore(u,a),d.log("Inserted real component before next sibling")):(f.appendChild(u),d.log("Appended real component to parent")),f.removeChild(c),d.log("Removed placeholder element")}}customElements.get(e)||customElements.define(e,r)},ze=function(e,t){return T(this,null,function*(){const{defineWebComponent:s}=yield Promise.resolve().then(()=>Ne);this.components[e]&&s(this.components[e],t)})};const me=new Ye;class Qe{constructor(){this.listeners=new Map}emit(e,t){const s=new CustomEvent(e,{detail:t,bubbles:!0,composed:!0});document.dispatchEvent(s);const o=this.listeners.get(e);if(!o||o.size===0)return Promise.resolve();const r=[];return o.forEach(i=>{try{const c=i(t);c instanceof Promise&&r.push(c)}catch(c){d.error(`⚠️ Event Bus Error: Failed to execute listener for "${e}"`),d.error(` Error details: ${c.message}`),r.push(Promise.reject(c))}}),r.length>0?Promise.all(r).then(()=>{}):Promise.resolve()}listen(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{this.off(e,t)}}off(e,t){const s=this.listeners.get(e);s&&(s.delete(t),s.size===0&&this.listeners.delete(e))}clear(e){e?this.listeners.delete(e):this.listeners.clear()}listenerCount(e){var t,s;return(s=(t=this.listeners.get(e))==null?void 0:t.size)!=null?s:0}}const ie=new Qe,ge=(n,e,t,s)=>me.registerComponent(n,e,t,s),be=n=>T(null,null,function*(){yield Promise.all(n.map(({name:e,path:t,useShadowDOM:s,lazy:o})=>me.registerComponent(e,t,s,o)))}),ye=(n,e)=>ie.listen(n,e),we=(n,e)=>{ie.emit(n,e)},et=(n,e)=>{if(e){const t=e.tagName.toLowerCase();window.__ladrilloContexts||(window.__ladrilloContexts=new Map),window.__ladrilloContexts.set(t,{shadowRoot:n,element:e})}},Y=()=>{const n=window.__ladrilloContexts;if(n&&n.size>0){const e=Array.from(n.values());return e[e.length-1]}return null},$e=()=>{const n=Y();return n&&n.element?n.element.state||{}:{}},Q=n=>{const e=Y();e&&e.setState&&e.setState(n)},Ee=(n,e)=>(Q({[n]:e}),t=>{Q({[n]:t})}),ve=(n,e)=>{if(e)return e.querySelector(n);const t=Y();if(t){const s=t.shadowRoot||t.element;if(s){const o=s.querySelector(n);if(o)return o}}return document.querySelector(n)},Se=(n,e)=>{if(e)return e.querySelectorAll(n);const t=Y();if(t){const s=t.shadowRoot||t.element;if(s){const o=s.querySelectorAll(n);if(o.length>0)return o}}return document.querySelectorAll(n)};typeof window!="undefined"&&(window.ladrillosjs={registerComponent:ge,registerComponents:be},window.$listen=ye,window.$emit=we,window.$querySelector=ve,window.$querySelectorAll=Se,window.$reactive=Ee,window.$setState=Q,window.$getState=$e);const tt=(n,e,t)=>{if(!e)return;const s=document.createElement("style");s.textContent=e,t?n.appendChild(s):document.head.appendChild(s)},nt=(n,e)=>{n.innerHTML=e;const t=st(n),s=ot(n),o=rt(n),r=ct(n);return{bindings:t,twoWayBindings:s,conditionals:o,loops:r}},Ce=n=>{const e=[],t=n.match(/\((.*)\)/);if(!t)return e;const s=t[1].trim();return s&&s.split(",").map(r=>r.trim()).forEach(r=>{if(/^['"]/.test(r)||/^\d+/.test(r))return;const i=r.match(/^([a-zA-Z_$][a-zA-Z0-9_$]*)/);i&&e.push(i[1])}),e},st=n=>{const e=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),t=[];let s;const o=i=>{let c=i.parentElement;for(;c;){if(c.hasAttribute&&c.hasAttribute("$for"))return!0;c=c.parentElement}return!1};for(;s=e.nextNode();){if(o(s))continue;const i=[...s.textContent.matchAll(G.bindings)];if(i.length>0){const c=s.textContent,f=i.map(a=>{const l=a[1].trim(),u=l.includes("(")&&l.includes(")"),p=/[+*/%<>=!&|]/.test(l)||/\s-\s/.test(l),m=/^(!|typeof\s|void\s|delete\s)/.test(l),E=p||m||/\.(?![\s}])[a-zA-Z_$][\w]*\(/.test(l)||/\bnew\s+/.test(l)||/\b(typeof|instanceof|void|delete)\b/.test(l),b=u?[l.split("(")[0].trim()]:l.split(".").map(H=>H.trim()),y=u?Ce(l):[];return{raw:l,path:b,isFunction:u,isExpression:E,functionArgs:y}});t.push({node:s,bindings:f,original:c})}}return n.querySelectorAll("*").forEach(i=>{if(!(i.hasAttribute("$for")||o(i)))for(const c of i.attributes){if(c.name==="$if"||c.name==="$else-if"||c.name==="$else"||c.name==="$bind")continue;const f=[...c.value.matchAll(G.bindings)];if(f.length>0){const a=c.value,l=f.map(u=>{const p=u[1].trim(),m=p.includes("(")&&p.includes(")"),E=/[+*/%<>=!&|]/.test(p)||/\s-\s/.test(p),b=/^(!|typeof\s|void\s|delete\s)/.test(p),y=E||b||/\.(?![\s}])[a-zA-Z_$][\w]*\(/.test(p)||/\bnew\s+/.test(p)||/\b(typeof|instanceof|void|delete)\b/.test(p),H=m?[p.split("(")[0].trim()]:p.split(".").map(le=>le.trim()),O=m?Ce(p):[];return{raw:p,path:H,isFunction:m,isExpression:y,functionArgs:O}});t.push({node:i,bindings:l,original:a,isAttribute:!0,attributeName:c.name})}}}),t},ot=n=>{const e=[];return n.querySelectorAll("[\\$bind]").forEach(s=>{var c;const o=s.getAttribute("$bind");if(!o)return;const r=o.trim(),i=r.split(".").map(f=>f.trim());s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||s instanceof HTMLSelectElement?(e.push({element:s,path:i,raw:r,isContentEditable:!1,initialValue:s.value||""}),s.removeAttribute("$bind")):s instanceof HTMLElement&&s.hasAttribute("contenteditable")&&(e.push({element:s,path:i,raw:r,isContentEditable:!0,initialValue:((c=s.textContent)==null?void 0:c.trim())||""}),s.removeAttribute("$bind"))}),e},rt=n=>{const e=[],t=new Set;return n.querySelectorAll("[\\$if]").forEach(o=>{if(t.has(o))return;const r=[];let i=o;for(;i;){const c=i.hasAttribute("$if"),f=i.hasAttribute("$else-if"),a=i.hasAttribute("$else");if(!c&&!f&&!a)break;t.add(i);let l,u="";c?(l="if",u=i.getAttribute("$if")||"",i.removeAttribute("$if")):f?(l="else-if",u=i.getAttribute("$else-if")||"",i.removeAttribute("$else-if")):(l="else",i.removeAttribute("$else"));const p=document.createComment(`conditional:${l}:${u}`),m=i.parentElement||n,E=i.nextSibling;m.insertBefore(p,i);const b={element:i,condition:u.trim(),type:l,placeholder:p,group:[],originalParent:m,nextSibling:E};r.push(b);const y=i.nextElementSibling;if(i.remove(),i=y,y&&!y.hasAttribute("$else-if")&&!y.hasAttribute("$else"))break}r.forEach(c=>{c.group=r}),e.push(r)}),e},it=n=>{const e=new Set;return n.forEach(t=>{t.forEach(s=>{let o=s.condition;o=o.replace(/\{([^}]+)\}/g,"$1");const r=/\b([a-zA-Z_$][a-zA-Z0-9_$]*(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*)*)\b/g,i=new Set(["true","false","null","undefined","typeof","instanceof","new","return","if","else","for","while","do","switch","case","break","continue"]);let c;for(;(c=r.exec(o))!==null;){const a=c[1].split(".")[0];i.has(a)||e.add(a)}})}),e},ct=n=>{const e=[];return n.querySelectorAll("[\\$for]").forEach(s=>{var m;const o=s.getAttribute("$for");if(!o)return;const r=s.getAttribute("$key")||void 0,i=o.match(/^\s*(?:\(([^,]+),\s*([^)]+)\)|([^\s]+))\s+(?:in|of)\s+(.+)\s*$/);if(!i){re(`Invalid $for expression: "${o}"`,{expression:o,lineHint:"$for attribute parsing"});return}const c=(i[1]||i[3]).trim(),f=(m=i[2])==null?void 0:m.trim(),a=i[4].trim(),l=document.createComment(`loop:${o}`),u=s.parentElement||n;u.insertBefore(l,s),s.removeAttribute("$for"),r&&s.removeAttribute("$key"),s.remove();const p={template:s,expression:o,itemName:c,indexName:f,arrayName:a,keyAttribute:r,placeholder:l,renderedElements:[],originalParent:u};e.push(p)}),e},at=n=>{const e=new Set;return n.forEach(t=>{const s=t.arrayName.split(".")[0];e.add(s)}),e},I=new Map,lt=100,ce=n=>{const e=I.get(n);if(e)return I.delete(n),I.set(n,e),e;const t=new Function("component",`
18
+ `))}connectedCallback(){if(!this.loaded){if(this.hasAttribute("eager")){this.loaded=!0,this.loadComponent();return}this.observer=new IntersectionObserver(c=>{c.forEach(f=>{f.isIntersecting&&!this.loaded&&(this.loaded=!0,this.loadComponent())})},{rootMargin:"100px"}),this.observer.observe(this)}}disconnectedCallback(){this.observer&&(this.observer.disconnect(),this.observer=null)}loadComponent(){return T(this,null,function*(){try{if(o.lazyComponentsLoaded.has(e)){d.log(`Component ${e} already loaded, upgrading placeholder...`),this.upgradePlaceholder();return}if(o.lazyLoadingInProgress.has(e)){d.log(`Component ${e} is already loading, waiting...`),yield o.lazyLoadingInProgress.get(e),this.upgradePlaceholder();return}const c=this.performLoad();o.lazyLoadingInProgress.set(e,c),yield c,o.lazyLoadingInProgress.delete(e),o.lazyComponentsLoaded.add(e),o.lazyComponents.delete(e),d.log(`Component ${e} lazy-loaded successfully`)}catch(c){o.lazyLoadingInProgress.delete(e),M(e,t,c)}})}performLoad(){return T(this,null,function*(){d.log(`Lazy loading component: ${e}`);const c=this.parentNode;if(this.nextSibling,!c){re(`Placeholder for ${e} has no parent node`,{componentName:e,componentPath:t});return}const f=yield pe(t),a=yield he(f,e);d.log(`Component ${e} parsed successfully`),o.components[e]={tagName:e,template:a.template,scripts:a.scripts,externalScripts:a.externalScripts,styles:a.styles,sourcePath:t,lazy:!0};const l=`${e}-real`;d.log(`Defining real component with temp name: ${l}`);const u=o.components[e].tagName;o.components[e].tagName=l;const{defineWebComponent:p}=yield Promise.resolve().then(()=>Ne);p(o.components[e],s),d.log(`Real component ${l} defined`),o.components[e].tagName=u,this.upgradePlaceholder()})}upgradePlaceholder(){const c=this,f=this.parentNode,a=this.nextSibling;if(!f){re(`Placeholder for ${e} has no parent node`,{componentName:e,componentPath:t});return}const l=`${e}-real`,u=document.createElement(l);for(d.log(`Created real component instance: ${l}`),Array.from(c.attributes).forEach(p=>{p.name!=="eager"&&u.setAttribute(p.name,p.value)});c.firstChild;)u.appendChild(c.firstChild);a?(f.insertBefore(u,a),d.log("Inserted real component before next sibling")):(f.appendChild(u),d.log("Appended real component to parent")),f.removeChild(c),d.log("Removed placeholder element")}}customElements.get(e)||customElements.define(e,r)},ze=function(e,t){return T(this,null,function*(){const{defineWebComponent:s}=yield Promise.resolve().then(()=>Ne);this.components[e]&&s(this.components[e],t)})};const me=new Ye;class Qe{constructor(){this.listeners=new Map}emit(e,t){const s=new CustomEvent(e,{detail:t,bubbles:!0,composed:!0});document.dispatchEvent(s);const o=this.listeners.get(e);if(!o||o.size===0)return Promise.resolve();const r=[];return o.forEach(i=>{try{const c=i(t);c instanceof Promise&&r.push(c)}catch(c){d.error(`⚠️ Event Bus Error: Failed to execute listener for "${e}"`),d.error(` Error details: ${c.message}`),r.push(Promise.reject(c))}}),r.length>0?Promise.all(r).then(()=>{}):Promise.resolve()}listen(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{this.off(e,t)}}off(e,t){const s=this.listeners.get(e);s&&(s.delete(t),s.size===0&&this.listeners.delete(e))}clear(e){e?this.listeners.delete(e):this.listeners.clear()}listenerCount(e){var t,s;return(s=(t=this.listeners.get(e))==null?void 0:t.size)!=null?s:0}}const ie=new Qe,ge=(n,e,t,s)=>me.registerComponent(n,e,t,s),be=n=>T(null,null,function*(){yield Promise.all(n.map(({name:e,path:t,useShadowDOM:s,lazy:o})=>me.registerComponent(e,t,s,o)))}),ye=(n,e)=>ie.listen(n,e),we=(n,e)=>{ie.emit(n,e)},et=(n,e)=>{if(e){const t=e.tagName.toLowerCase();window.__ladrilloContexts||(window.__ladrilloContexts=new Map),window.__ladrilloContexts.set(t,{shadowRoot:n,element:e})}},Y=()=>{const n=window.__ladrilloContexts;if(n&&n.size>0){const e=Array.from(n.values());return e[e.length-1]}return null},$e=()=>{const n=Y();return n&&n.element?n.element.state||{}:{}},Q=n=>{const e=Y();e&&e.setState&&e.setState(n)},Ee=(n,e)=>(Q({[n]:e}),t=>{Q({[n]:t})}),ve=(n,e)=>{if(e)return e.querySelector(n);const t=Y();if(t){const s=t.shadowRoot||t.element;if(s){const o=s.querySelector(n);if(o)return o}}return document.querySelector(n)},Se=(n,e)=>{if(e)return e.querySelectorAll(n);const t=Y();if(t){const s=t.shadowRoot||t.element;if(s){const o=s.querySelectorAll(n);if(o.length>0)return o}}return document.querySelectorAll(n)};typeof window!="undefined"&&(window.ladrillosjs={registerComponent:ge,registerComponents:be},window.$listen=ye,window.$emit=we,window.$querySelector=ve,window.$querySelectorAll=Se,window.$reactive=Ee,window.$setState=Q,window.$getState=$e);const tt=(n,e,t)=>{if(!e)return;const s=document.createElement("style");s.textContent=e,t?n.appendChild(s):document.head.appendChild(s)},nt=(n,e)=>{n.innerHTML=e;const t=st(n),s=ot(n),o=rt(n),r=ct(n);return{bindings:t,twoWayBindings:s,conditionals:o,loops:r}},Ce=n=>{const e=[],t=n.match(/\((.*)\)/);if(!t)return e;const s=t[1].trim();return s&&s.split(",").map(r=>r.trim()).forEach(r=>{if(/^['"]/.test(r)||/^\d+/.test(r))return;const i=r.match(/^([a-zA-Z_$][a-zA-Z0-9_$]*)/);i&&e.push(i[1])}),e},st=n=>{const e=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),t=[];let s;const o=i=>{let c=i.parentElement;for(;c;){if(c.hasAttribute&&c.hasAttribute("$for"))return!0;c=c.parentElement}return!1};for(;s=e.nextNode();){if(o(s))continue;const i=[...s.textContent.matchAll(G.bindings)];if(i.length>0){const c=s.textContent,f=i.map(a=>{const l=a[1].trim(),u=l.includes("(")&&l.includes(")"),p=/[+*/%<>=!&|]/.test(l)||/\s-\s/.test(l),m=/^(!|typeof\s|void\s|delete\s)/.test(l),E=p||m||/\.(?![\s}])[a-zA-Z_$][\w]*\(/.test(l)||/\bnew\s+/.test(l)||/\b(typeof|instanceof|void|delete)\b/.test(l),b=u?[l.split("(")[0].trim()]:l.split(".").map(H=>H.trim()),y=u?Ce(l):[];return{raw:l,path:b,isFunction:u,isExpression:E,functionArgs:y}});t.push({node:s,bindings:f,original:c})}}return n.querySelectorAll("*").forEach(i=>{if(!(i.hasAttribute("$for")||o(i)))for(const c of i.attributes){if(c.name==="$if"||c.name==="$else-if"||c.name==="$else"||c.name==="$bind")continue;const f=[...c.value.matchAll(G.bindings)];if(f.length>0){const a=c.value,l=f.map(u=>{const p=u[1].trim(),m=p.includes("(")&&p.includes(")"),E=/[+*/%<>=!&|]/.test(p)||/\s-\s/.test(p),b=/^(!|typeof\s|void\s|delete\s)/.test(p),y=E||b||/\.(?![\s}])[a-zA-Z_$][\w]*\(/.test(p)||/\bnew\s+/.test(p)||/\b(typeof|instanceof|void|delete)\b/.test(p),H=m?[p.split("(")[0].trim()]:p.split(".").map(le=>le.trim()),O=m?Ce(p):[];return{raw:p,path:H,isFunction:m,isExpression:y,functionArgs:O}});t.push({node:i,bindings:l,original:a,isAttribute:!0,attributeName:c.name})}}}),t},ot=n=>{const e=[];return n.querySelectorAll("[\\$bind]").forEach(s=>{var c;const o=s.getAttribute("$bind");if(!o)return;const r=o.trim(),i=r.split(".").map(f=>f.trim());s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||s instanceof HTMLSelectElement?(e.push({element:s,path:i,raw:r,isContentEditable:!1,initialValue:s.value||""}),s.removeAttribute("$bind")):s instanceof HTMLElement&&s.hasAttribute("contenteditable")&&(e.push({element:s,path:i,raw:r,isContentEditable:!0,initialValue:((c=s.textContent)==null?void 0:c.trim())||""}),s.removeAttribute("$bind"))}),e},rt=n=>{const e=[],t=new Set;return n.querySelectorAll("[\\$if]").forEach(o=>{if(t.has(o))return;const r=[];let i=o;for(;i;){const c=i.hasAttribute("$if"),f=i.hasAttribute("$else-if"),a=i.hasAttribute("$else");if(!c&&!f&&!a)break;t.add(i);let l,u="";c?(l="if",u=i.getAttribute("$if")||"",i.removeAttribute("$if")):f?(l="else-if",u=i.getAttribute("$else-if")||"",i.removeAttribute("$else-if")):(l="else",i.removeAttribute("$else"));const p=document.createComment(`conditional:${l}:${u}`),m=i.parentElement||n,E=i.nextSibling;m.insertBefore(p,i);const b={element:i,condition:u.trim(),type:l,placeholder:p,group:[],originalParent:m,nextSibling:E};r.push(b);const y=i.nextElementSibling;if(i.remove(),i=y,y&&!y.hasAttribute("$else-if")&&!y.hasAttribute("$else"))break}r.forEach(c=>{c.group=r}),e.push(r)}),e},it=n=>{const e=new Set;return n.forEach(t=>{t.forEach(s=>{let o=s.condition;o=o.replace(/\{([^}]+)\}/g,"$1");const r=/\b([a-zA-Z_$][a-zA-Z0-9_$]*(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*)*)\b/g,i=new Set(["true","false","null","undefined","typeof","instanceof","new","return","if","else","for","while","do","switch","case","break","continue"]);let c;for(;(c=r.exec(o))!==null;){const a=c[1].split(".")[0];i.has(a)||e.add(a)}})}),e},ct=n=>{const e=[];return n.querySelectorAll("[\\$for]").forEach(s=>{var m;const o=s.getAttribute("$for");if(!o)return;const r=s.getAttribute("$key")||void 0,i=o.match(/^\s*(?:\(([^,]+),\s*([^)]+)\)|([^\s]+))\s+(?:in|of)\s+(.+)\s*$/);if(!i){re(`Invalid $for expression: "${o}"`,{expression:o,lineHint:"$for attribute parsing"});return}const c=(i[1]||i[3]).trim(),f=(m=i[2])==null?void 0:m.trim(),a=i[4].trim(),l=document.createComment(`loop:${o}`),u=s.parentElement||n;u.insertBefore(l,s),s.removeAttribute("$for"),r&&s.removeAttribute("$key"),s.remove();const p={template:s,expression:o,itemName:c,indexName:f,arrayName:a,keyAttribute:r,placeholder:l,renderedElements:[],originalParent:u};e.push(p)}),e},at=n=>{const e=new Set;return n.forEach(t=>{const s=t.arrayName.split(".")[0];e.add(s)}),e},I=new Map,lt=100,ce=n=>{const e=I.get(n);if(e)return I.delete(n),I.set(n,e),e;const t=new Function("component",`
19
19
  const { Date, Array, Math, String, Number, Boolean, Object, JSON, RegExp } = globalThis;
20
20
  with(component) {
21
21
  return ${n};