@jasonshimmy/custom-elements-runtime 0.0.1-beta.0
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 +122 -0
- package/dist/build-tools.d.ts +71 -0
- package/dist/computed-state.d.ts +10 -0
- package/dist/custom-elements-runtime.cjs.js +46 -0
- package/dist/custom-elements-runtime.cjs.js.map +1 -0
- package/dist/custom-elements-runtime.es.js +1511 -0
- package/dist/custom-elements-runtime.es.js.map +1 -0
- package/dist/custom-elements-runtime.umd.js +46 -0
- package/dist/custom-elements-runtime.umd.js.map +1 -0
- package/dist/data-binding.d.ts +8 -0
- package/dist/dev-tools.d.ts +21 -0
- package/dist/event-bus.d.ts +101 -0
- package/dist/runtime.d.ts +109 -0
- package/dist/ssr.d.ts +49 -0
- package/dist/store.d.ts +10 -0
- package/dist/template-compiler.d.ts +117 -0
- package/dist/template-helpers.d.ts +56 -0
- package/dist/v-dom.d.ts +54 -0
- package/package.json +57 -0
package/README.md
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
|
|
2
|
+
# Custom Elements Runtime
|
|
3
|
+
|
|
4
|
+
> **Ultra-lightweight, type-safe runtime for fast, reactive, and maintainable web components.**
|
|
5
|
+
|
|
6
|
+
Build modern web components with strict TypeScript, zero dependencies, and a functional API. Designed for performance, standards compliance, and developer productivity.
|
|
7
|
+
|
|
8
|
+
## ✨ Features
|
|
9
|
+
|
|
10
|
+
- **Reactive State:** Automatic re-renders using ES6 Proxy; direct assignment supported. State changes trigger batched updates for performance.
|
|
11
|
+
- **Attribute-State Sync:** All primitive state keys (string, number, boolean) are automatically observed as attributes and kept in sync. Parent-to-child communication is seamless.
|
|
12
|
+
- **Functional Templates:** Use plain functions, tagged helpers (`html`, `compile`), or async Promises. Templates can be compiled for performance and SSR.
|
|
13
|
+
- **Refs:** Direct DOM access via `refs` for imperative logic and event handling. No complex selectors required.
|
|
14
|
+
- **Computed Properties:** Define derived, reactive values with `computed` for efficient state management.
|
|
15
|
+
- **Automatic Event Binding:** Declarative, type-safe handlers via `data-on-*` attributes. Only one handler per event type per element is attached; previous handlers are removed on rerender. Handlers are defined directly on the component config.
|
|
16
|
+
- **Controlled Input Sync:** Inputs with `data-model` (including checkboxes, radios, multi-checkbox groups, and modifiers) stay in sync with state. User typing always wins. VDOM patching ensures reliable event handling and focus preservation.
|
|
17
|
+
- **Deep State Binding:** Use `data-bind` for two-way binding to nested or dynamic state (objects, arrays, lists). Supports dot notation and array indices for deep binding.
|
|
18
|
+
- **Global Store:** Use the built-in `Store` class for global, reactive state management across components. Subscribe to changes and update state directly.
|
|
19
|
+
- **Global Event Bus:** Use the built-in `eventBus` for cross-component communication. Emit, listen, and unsubscribe from global events with event storm protection.
|
|
20
|
+
- **SSR & Hydration:** Universal rendering and opt-in hydration. Templates must match for hydration. SSR excludes refs, event listeners, and lifecycle hooks. Hydration is opt-in via the `hydrate` property.
|
|
21
|
+
- **Error Boundaries:** Optional `onError` for fallback UI and diagnostics. Robust error handling and recovery for all lifecycle and render errors.
|
|
22
|
+
- **Focus Preservation:** Inputs retain focus and selection during updates, even with rapid state changes.
|
|
23
|
+
- **Smart DOM Batching:** State-triggered renders are batched using requestAnimationFrame for optimal performance.
|
|
24
|
+
- **Plugin System:** Extend runtime behavior with hooks (`onInit`, `onRender`, `onError`). Plugins can be registered globally and affect all components.
|
|
25
|
+
- **Debug Mode:** Enable detailed runtime logs for any component via `debug: true` in the config. Logs warnings, errors, and mutation diagnostics.
|
|
26
|
+
- **Strict TypeScript:** Type-safe, developer-friendly, zero dependencies. All APIs and configuration are strictly typed.
|
|
27
|
+
- **Tree-shakable & Modular:** Import only what you use. All exports are modular and optimized for tree-shaking.
|
|
28
|
+
- **Functional API:** No classes, no boilerplate. All configuration is functional and declarative.
|
|
29
|
+
- **Template Helpers:** Use `html`, `compile`, `css`, `classes`, `styles`, `ref`, and `on` for efficient, type-safe template authoring.
|
|
30
|
+
- **Build Tools:** Integrate with Vite, Webpack, or Rollup for build-time template compilation and optimization.
|
|
31
|
+
- **VDOM Utilities:** Fine-grained DOM diffing and patching for controlled inputs, event listeners, and efficient updates.
|
|
32
|
+
|
|
33
|
+
### Limitations & Edge Cases
|
|
34
|
+
|
|
35
|
+
- Templates must have a single root node. Fragment templates are supported, but reconciliation is strict and positional; use keys for robust updates.
|
|
36
|
+
- Only one event handler per event type per element is attached; previous handlers are removed on rerender. Handlers must be defined on the config object.
|
|
37
|
+
- Controlled input sync prioritizes user typing (focused/dirty inputs) over state updates. VDOM patching is regression-tested for reliability.
|
|
38
|
+
- SSR hydration is opt-in via the `hydrate` property. If no region is marked, the entire shadow root is hydrated. SSR excludes refs, event listeners, and lifecycle hooks.
|
|
39
|
+
- All user-generated content is escaped in templates using `html` and `compile` helpers. Static HTML is not escaped.
|
|
40
|
+
- Only features documented here and in [`src/lib/runtime.ts`](src/lib/runtime.ts) are supported. Undocumented features may not work as expected.
|
|
41
|
+
- VDOM patching for controlled inputs (checkboxes, radios, etc.) is regression-tested to ensure event listeners are always attached and state updates are reliable.
|
|
42
|
+
|
|
43
|
+
## 🚀 Getting Started
|
|
44
|
+
|
|
45
|
+
### Install
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
npm install @jasonshimmy/custom-elements-runtime
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### Import and use in your project
|
|
52
|
+
|
|
53
|
+
```typescript
|
|
54
|
+
import { component, html } from '@jasonshimmy/custom-elements-runtime';
|
|
55
|
+
|
|
56
|
+
component('my-counter', {
|
|
57
|
+
state: { count: 0 },
|
|
58
|
+
template: ({ count }) => html`
|
|
59
|
+
<button data-on-click="increment">Count: ${count}</button>
|
|
60
|
+
`({ count }),
|
|
61
|
+
increment(_e, state) { state.count++; }
|
|
62
|
+
});
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### TypeScript support
|
|
66
|
+
|
|
67
|
+
All types and interfaces are available for auto-completion and strict typing in code editors. No extra configuration is needed.
|
|
68
|
+
|
|
69
|
+
### Advanced usage
|
|
70
|
+
|
|
71
|
+
See the [API Reference](docs/api-reference.md) for advanced configuration, SSR, plugin system, global store, event bus, and more.
|
|
72
|
+
|
|
73
|
+
## 🎯 Use Cases
|
|
74
|
+
|
|
75
|
+
- **Micro-frontends**: Lightweight, isolated components
|
|
76
|
+
- **Progressive Enhancement**: Add reactivity to existing sites
|
|
77
|
+
- **Design Systems**: Reusable component libraries
|
|
78
|
+
- **SSR Applications**: Universal rendering with hydration
|
|
79
|
+
- **Performance-Critical Apps**: When bundle size matters
|
|
80
|
+
- **Web Standards**: Future-proof, standards-based development
|
|
81
|
+
|
|
82
|
+
## ⚠️ SSR Caveats
|
|
83
|
+
|
|
84
|
+
- SSR only generates HTML and styles; DOM APIs, refs, and event listeners are not available during server rendering.
|
|
85
|
+
- Lifecycle hooks (`onMounted`, `onUnmounted`) and refs are ignored during SSR.
|
|
86
|
+
- Hydration requires the client bundle to match the server-rendered markup and state exactly.
|
|
87
|
+
|
|
88
|
+
## 🛡️ Production-Readiness
|
|
89
|
+
|
|
90
|
+
- Strict TypeScript, modular structure
|
|
91
|
+
- Early returns, guard clauses, custom error types
|
|
92
|
+
- No external dependencies
|
|
93
|
+
- Manual input validation and error handling
|
|
94
|
+
|
|
95
|
+
## ⚡ Performance Features
|
|
96
|
+
|
|
97
|
+
- **Batched Updates**: Multiple state changes are batched using RAF
|
|
98
|
+
- **Template & Computed Property Caching**: Expensive calculations are cached
|
|
99
|
+
- **Memory Management**: Automatic cleanup prevents memory leaks
|
|
100
|
+
- **Focus Preservation**: Smart input focus handling during updates
|
|
101
|
+
- **Fine-grained DOM diffing**: Only changed DOM nodes are updated, not replaced, for optimal performance and UX
|
|
102
|
+
- **Async rendering**: Supports Promises in templates for async data and UI
|
|
103
|
+
- **Selective hydration**: Hydrate only regions marked with `data-hydrate` for efficient SSR
|
|
104
|
+
|
|
105
|
+
## Documentation
|
|
106
|
+
|
|
107
|
+
- [API Reference](docs/api-reference.md): All runtime exports, configuration options, and advanced patterns.
|
|
108
|
+
- [Core Concepts](docs/core-concepts.md): State, attribute sync, event binding, input binding, global store, event bus, lifecycle, error boundaries, SSR, plugin system.
|
|
109
|
+
- [Data Model vs Data Bind](docs/data-model-vs-data-bind.md): Comparison, use cases, modifiers, deep binding, edge cases.
|
|
110
|
+
- [Advanced Use Cases](docs/advanced-use-cases.md): Patterns for event bus, store, plugin system, async templates, error boundaries, SSR, VDOM.
|
|
111
|
+
- [Form Input Bindings](docs/form-input-bindings.md): All supported input types, modifiers, deep binding, edge cases, VDOM patching.
|
|
112
|
+
- [SSR Guide](docs/ssr.md): SSR, hydration, limitations, API.
|
|
113
|
+
- [Framework Comparison](docs/framework-comparison.md): Unique features, tradeoffs, strengths, and when to choose each approach.
|
|
114
|
+
- [Framework Integration](docs/framework-integration.md): Using with React, Vue, Angular, Svelte, and Lit.
|
|
115
|
+
- [Examples](docs/examples.md): Concise, accurate code for all features and patterns.
|
|
116
|
+
|
|
117
|
+
See the [API Reference](docs/api-reference.md) for detailed usage, configuration options, and advanced patterns. For advanced topics, see the linked docs above.
|
|
118
|
+
|
|
119
|
+
## Local development
|
|
120
|
+
|
|
121
|
+
1. **Clone this repository**
|
|
122
|
+
2. **Run the examples**: `npm run dev`
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
declare global {
|
|
2
|
+
interface ImportMeta {
|
|
3
|
+
env?: Record<string, any>;
|
|
4
|
+
}
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Build Tool Integration for Template Compilation
|
|
8
|
+
*
|
|
9
|
+
* This file demonstrates how template compilation would integrate with build tools
|
|
10
|
+
* like Vite, Webpack, or Rollup for optimal production performance.
|
|
11
|
+
*/
|
|
12
|
+
import { type CompiledTemplate, type TemplateCompilerOptions } from '../lib/template-compiler.js';
|
|
13
|
+
/**
|
|
14
|
+
* Vite Plugin for Template Compilation
|
|
15
|
+
* This would be a real Vite plugin in production
|
|
16
|
+
*/
|
|
17
|
+
export declare function createTemplateCompilerPlugin(options?: TemplateCompilerOptions): {
|
|
18
|
+
name: string;
|
|
19
|
+
transform(code: string, id: string): {
|
|
20
|
+
code: string;
|
|
21
|
+
map: null;
|
|
22
|
+
} | null;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Development-time template analyzer
|
|
26
|
+
*/
|
|
27
|
+
export declare class TemplateDevTools {
|
|
28
|
+
private static readonly templates;
|
|
29
|
+
static analyzeTemplate(templateString: string): void;
|
|
30
|
+
static getStats(): {
|
|
31
|
+
totalTemplates: number;
|
|
32
|
+
totalUsage: number;
|
|
33
|
+
complexityDistribution: {
|
|
34
|
+
low: number;
|
|
35
|
+
medium: number;
|
|
36
|
+
high: number;
|
|
37
|
+
};
|
|
38
|
+
recommendations: string[];
|
|
39
|
+
};
|
|
40
|
+
static clear(): void;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Performance monitor for template rendering
|
|
44
|
+
*/
|
|
45
|
+
export declare class TemplatePerformanceMonitor {
|
|
46
|
+
private static readonly metrics;
|
|
47
|
+
static startRender(templateId: string): () => void;
|
|
48
|
+
private static recordRender;
|
|
49
|
+
static getMetrics(): {
|
|
50
|
+
templates: number;
|
|
51
|
+
totalRenders: number;
|
|
52
|
+
averageRenderTime: number;
|
|
53
|
+
slowestTemplate: {
|
|
54
|
+
id: string;
|
|
55
|
+
time: number;
|
|
56
|
+
} | null;
|
|
57
|
+
fastestTemplate: {
|
|
58
|
+
id: string;
|
|
59
|
+
time: number;
|
|
60
|
+
} | null;
|
|
61
|
+
};
|
|
62
|
+
static clear(): void;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Helper to migrate from string templates to compiled templates
|
|
66
|
+
*/
|
|
67
|
+
export declare function migrateToCompiledTemplate(stringTemplate: string, options?: TemplateCompilerOptions): {
|
|
68
|
+
compiled: CompiledTemplate;
|
|
69
|
+
migrationNotes: string[];
|
|
70
|
+
estimatedPerformanceGain: string;
|
|
71
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lightweight reactive state with computed properties and change notification.
|
|
3
|
+
* @template T - State shape
|
|
4
|
+
* @template C - Computed property map
|
|
5
|
+
*/
|
|
6
|
+
export declare function reactive<T extends object, C extends Record<string, (state: T) => any>>(initialState: T, computedMap?: C): T & {
|
|
7
|
+
subscribe: (fn: (state: T) => void) => () => void;
|
|
8
|
+
} & {
|
|
9
|
+
[K in keyof C]: ReturnType<C[K]>;
|
|
10
|
+
};
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var O=typeof document<"u"?document.currentScript:null;class U{state;listeners=[];constructor(t){this.state=new Proxy(t,{set:(e,n,a)=>(e[n]=a,this.notify(),!0)})}subscribe(t){this.listeners.push(t),t(this.state)}getState(){return this.state}notify(){this.listeners.forEach(t=>t(this.state))}}class g extends EventTarget{handlers={};static instance;eventCounters=new Map;static getInstance(){return g.instance||(g.instance=new g),g.instance}emit(t,e){const n=Date.now(),a=this.eventCounters.get(t);if(!a||n-a.window>1e3)this.eventCounters.set(t,{count:1,window:n});else if(a.count++,a.count>50&&(console.error(`Event storm detected for "${t}": ${a.count} events in 1 second. Throttling...`),a.count>100)){console.warn(`Blocking further "${t}" events to prevent infinite loop`);return}this.dispatchEvent(new CustomEvent(t,{detail:e,bubbles:!1,cancelable:!0}));const o=this.handlers[t];o&&o.forEach(s=>{try{s(e)}catch(i){console.error(`Error in global event handler for "${t}":`,i)}})}on(t,e){return this.handlers[t]||(this.handlers[t]=new Set),this.handlers[t].add(e),()=>this.off(t,e)}off(t,e){const n=this.handlers[t];n&&n.delete(e)}offAll(t){delete this.handlers[t]}listen(t,e,n){return this.addEventListener(t,e,n),()=>this.removeEventListener(t,e)}once(t,e){return new Promise(n=>{const a=this.on(t,o=>{a(),e(o),n(o)})})}getActiveEvents(){return Object.keys(this.handlers).filter(t=>this.handlers[t]&&this.handlers[t].size>0)}clear(){this.handlers={}}getHandlerCount(t){return this.handlers[t]?.size||0}getEventStats(){const t={};for(const[e,n]of this.eventCounters.entries())t[e]={count:n.count,handlersCount:this.getHandlerCount(e)};return t}resetEventCounters(){this.eventCounters.clear()}}const A=g.getInstance(),G=typeof window>"u"||typeof document>"u";function B(r){return{state:r,emit:()=>{},onGlobal:()=>()=>{},offGlobal:()=>{},emitGlobal:()=>{}}}function I(r,t={}){G||console.warn("[SSR] renderToString should only be used on the server");try{const e=r.state,n=B(e),a=r.template(e,n);let o="";t.includeStyles&&r.style&&(o=`<style>${typeof r.style=="function"?r.style(e):r.style}</style>`);const s=t.sanitizeAttributes?t.sanitizeAttributes(r.attrs||{}):r.attrs||{},i=Object.entries(s).map(([d,f])=>`${N(d)}="${N(f)}"`).join(" "),c=`${i?`<${r.tag} ${i}>`:`<${r.tag}>`}${o}${a}</${r.tag}>`;return t.prettyPrint?Y(c):c}catch(e){return console.error(`[SSR] Error rendering ${r.tag}:`,e),`<${r.tag}><div style="color: red;">SSR Error: ${X(String(e))}</div></${r.tag}>`}}function Z(r,t={}){const e={components:new Map,styles:new Set},n=[];r.forEach(s=>{if(e.components.set(s.tag,s),s.style){const l=typeof s.style=="function"?s.style(s.state):s.style;e.styles.add(l)}const i=I(s,{...t,includeStyles:!1});n.push(i)});const a=Array.from(e.styles).join(`
|
|
2
|
+
`);return{html:n.join(`
|
|
3
|
+
`),styles:a,context:e}}function V(r){const t=Array.from(r.components.entries()).map(([e,n])=>({tag:e,state:n.state}));return`
|
|
4
|
+
<script type="module">
|
|
5
|
+
// Hydration data from SSR
|
|
6
|
+
window.__SSR_CONTEXT__ = ${JSON.stringify({components:t})};
|
|
7
|
+
|
|
8
|
+
// Auto-hydrate when DOM is ready
|
|
9
|
+
if (document.readyState === 'loading') {
|
|
10
|
+
document.addEventListener('DOMContentLoaded', hydrate);
|
|
11
|
+
} else {
|
|
12
|
+
hydrate();
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function hydrate() {
|
|
16
|
+
const context = window.__SSR_CONTEXT__;
|
|
17
|
+
if (!context?.components) return;
|
|
18
|
+
|
|
19
|
+
context.components.forEach(({ tag, state }) => {
|
|
20
|
+
const elements = document.querySelectorAll(tag);
|
|
21
|
+
elements.forEach(el => {
|
|
22
|
+
// Mark as hydrated to prevent re-initialization
|
|
23
|
+
if (!el.hasAttribute('data-hydrated')) {
|
|
24
|
+
el.setAttribute('data-hydrated', 'true');
|
|
25
|
+
// Restore state if component supports it
|
|
26
|
+
if (el._hydrateWithState) {
|
|
27
|
+
el._hydrateWithState(state);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
// Clean up
|
|
34
|
+
delete window.__SSR_CONTEXT__;
|
|
35
|
+
}
|
|
36
|
+
<\/script>`.trim()}const X=r=>r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),N=r=>r.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">"),Y=r=>r.replace(/></g,`>
|
|
37
|
+
<`).split(`
|
|
38
|
+
`).map(t=>{const e=(t.match(/^<[^\/]/g)||[]).length-(t.match(/<\//g)||[]).length;return" ".repeat(Math.max(0,e))+t.trim()}).join(`
|
|
39
|
+
`);function D(r){return String(r).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function L(r,t){if(typeof r!="string"||!t)return String(r);for(const e in t){if(typeof t[e]=="string"&&r===t[e])return D(r);if(Array.isArray(t[e])){for(const n of t[e])if(n&&typeof n=="object"){for(const a in n)if(typeof n[a]=="string"&&r===n[a])return D(r)}}}return String(r)}function J(r,...t){function e(n,a,o){if(Array.isArray(n)){const s=n.map(i=>e(i,a,o));return s.some(i=>i instanceof Promise)?Promise.all(s).then(i=>i.join("")):s.join("")}if(typeof n=="function"){const s=e(n(a,o),a,o);return s instanceof Promise,s}return n==null?"":n instanceof Promise?n:String(n)}return(n,a)=>{let o="",s=!1;const i=[];for(let l=0;l<r.length;l++)if(o+=r[l],l<t.length){let c=t[l];const d=r[l],f=/data-on-[a-z]+="?$/.test(d);c=e(c,n,a),c instanceof Promise?(s=!0,i.push(c)):/=\s*"?$/.test(d)&&typeof c=="string"&&!f?(c=c.replace(/"/g,""").replace(/'/g,"'"),o+=c):!f&&!/=\s*"?$/.test(d)?o+=L(c,n):o+=c}return s?Promise.all(i).then(l=>{let c="",d=0;for(let f=0;f<r.length;f++)if(c+=r[f],f<t.length){let u=t[f];const h=r[f],m=/data-on-[a-z]+="?$/.test(h);u=e(u,n,a),u instanceof Promise?c+=l[d++]:/=\s*"?$/.test(h)&&typeof u=="string"&&!m?(u=u.replace(/"/g,""").replace(/'/g,"'"),c+=u):!m&&!/=\s*"?$/.test(h)?c+=L(u,n):c+=u}return c}):o}}function Q(r,...t){const e="compiled-"+Math.random().toString(36).slice(2);function n(o,s,i){return Array.isArray(o)?o.map(l=>n(l,s,i)).join(""):typeof o=="function"?n(o(s,i),s,i):o==null?"":String(o)}const a=(o,s)=>{let i="";for(let l=0;l<r.length;l++)if(i+=r[l],l<t.length){let c=t[l];const d=r[l],f=/data-on-[a-z]+="?$/.test(d);c=n(c,o,s),/=\s*"?$/.test(d)&&typeof c=="string"&&!f?(c=c.replace(/"/g,""").replace(/'/g,"'"),i+=c):!f&&!/=\s*"?$/.test(d)?i+=L(c,o):i+=c??""}return i};return a.id=e,a}function tt(r,...t){let e="";for(let n=0;n<r.length;n++)e+=r[n],n<t.length&&(e+=t[n]??"");return e}function et(r){return r}function nt(r,t){return{[r]:t}}function rt(r){return Object.keys(r).filter(t=>r[t]).join(" ")}function st(r){return Object.entries(r).map(([t,e])=>`${t}: ${e}`).join("; ")}function P(r,t,e){const[n,...a]=e.split("|").map(i=>i.trim());if(!n||n==="__proto__"||n==="constructor"||n==="prototype")return;function o(i,l,c){const d=l.split(".");let f=i;for(let u=0;u<d.length-1;u++)d[u]in f||(f[d[u]]={}),f=f[d[u]];f[d[d.length-1]]=c}const s=i=>{let l;if(r instanceof HTMLInputElement&&r.type==="checkbox"){l=r.value;const c=r.getAttribute("data-true-value"),d=r.getAttribute("data-false-value");let f=Array.isArray(t[n])?t[n]:void 0;if(f){if(r.checked)f.includes(l)||f.push(l);else{const u=f.indexOf(l);u!==-1&&f.splice(u,1)}o(t,n,[...f])}else c!==null||d!==null?r.checked?o(t,n,c):o(t,n,d!==null?d:!1):o(t,n,r.checked)}else r instanceof HTMLInputElement&&r.type==="radio"?(l=r.value,o(t,n,l),((r.form||r.closest("form")||r.getRootNode())instanceof Element?(r.form||r.closest("form")||r.getRootNode()).querySelectorAll(`input[type="radio"][name="${r.name}"][data-model="${e}"]`):[]).forEach(d=>{d.checked=d.value===String(l)})):(l=r.value,r instanceof HTMLInputElement&&r.type==="number"&&(l=Number(l)),a.includes("trim")&&typeof l=="string"&&(l=l.trim()),a.includes("number")&&(l=Number(l)),o(t,n,l));if("_vnode"in r&&typeof r._vnode=="object"&&r._vnode?.props&&(r._vnode.props.value=l),i.type==="input"&&(r._isDirty=!0),i.type==="keydown"&&i.key==="Enter"&&(r._isDirty=!1,r instanceof HTMLElement&&r.isConnected)){let c=r.parentElement;for(;c&&!(c instanceof HTMLElement&&c.shadowRoot);)c=c.parentElement;c&&typeof c=="object"&&c!==null&&"render"in c&&typeof c.render=="function"&&c.render()}i.type==="blur"&&(r._isDirty=!1)};r.addEventListener("input",s),r.addEventListener("change",s),r.addEventListener("keydown",s),r.addEventListener("blur",s)}const x=(()=>{try{if(typeof process<"u"&&process.env)return process.env.NODE_ENV==="development"}catch{}return typeof window<"u"?window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1":!1})();function it(r,t={}){const{development:e=x,cache:n=!0,optimize:a=!0}=t,o=W(r);if(n&&k.has(o)){if(e){const s=_.get(o)||{compilationTime:0,renderTime:0,updateTime:0,cacheHits:0,cacheMisses:0};s.cacheHits++,_.set(o,s)}return k.get(o)}if(e){const s=_.get(o)||{compilationTime:0,renderTime:0,updateTime:0,cacheHits:0,cacheMisses:0};s.cacheMisses++,_.set(o,s)}try{const s=at(r,{development:e,optimize:a});return n&&k.set(o,s),s}catch(s){return e&&(console.error("[Template Compiler] Error compiling template:",s),console.error("[Template Compiler] Template:",r)),{statics:[r],dynamics:[],fragment:null,id:o,hasDynamics:!1,render:()=>r}}}function ot(r,t){if(typeof document>"u")return[0];try{let e=function(i,l=[]){if(i.nodeType===Node.TEXT_NODE){if(i.textContent?.includes(t))return l}else if(i.nodeType===Node.ELEMENT_NODE){let c=0;for(let d=0;d<i.childNodes.length;d++){const f=i.childNodes[d],u=e(f,[...l,c]);if(u)return u;c++}}return null};const o=new DOMParser().parseFromString(`<div>${r}</div>`,"text/html").body.firstElementChild;return e(o)||[0]}catch(e){return x&&console.warn("[Template Compiler] Error finding DOM path for placeholder:",t,e),[0]}}function at(r,t){return new ct(r,t).compile()}class ct{template;options;dynamics=[];statics=[];constructor(t,e){this.template=t,this.options=e}compile(){this.parseTemplate();const t=this.createStaticFragment(),e=W(this.template),n=(a,o)=>{let s="";for(let i=0;i<this.statics.length;i++)if(s+=this.statics[i],i<this.dynamics.length){let l=this.dynamics[i].getValue(a,o);if(l instanceof Promise)return Promise.all(this.dynamics.map(c=>{const d=c.getValue(a,o);return d instanceof Promise?d:Promise.resolve(d)})).then(c=>{let d="";for(let f=0;f<this.statics.length;f++)d+=this.statics[f],f<c.length&&(d+=c[f]);return d});s+=l}return s};return{statics:this.statics,dynamics:this.dynamics,fragment:t,id:e,hasDynamics:this.dynamics.length>0,render:n}}parseTemplate(){const t=/\{\{([^}]+)\}\}/g;let e=0,n;for(;(n=t.exec(this.template))!==null;){const o=this.template.slice(e,n.index);this.statics.push(o);let s=o.match(/([a-zA-Z0-9_-]+)\s*=\s*"?$/),i=s?s[1]:void 0,l;if(o.endsWith('style="color:'))i="style",l="color";else if(i==="style"){const d=o.match(/style\s*=\s*"?([^:;]+):\s*$/);d&&(l=d[1].trim())}const c=n[1].trim();this.analyzeDynamicExpression(c,this.dynamics.length,i,l),e=n.index+n[0].length}const a=this.template.slice(e);this.statics.push(a)}analyzeDynamicExpression(t,e,n,a){let o="text",s;n?n==="class"?(o="class",s="class"):n==="style"?(o="style",s=a||"style"):n==="value"?(o="property",s="value"):(o="attribute",s=n):t.includes("class.")?(o="class",s=t.split(".")[1]):t.includes("style.")?(o="style",s=t.split(".")[1]):t.includes("@")?(o="event",s=t.split("@")[1]):t==="class"?(o="class",s="class"):t==="style"?(o="style",s="style"):t==="value"?(o="property",s="value"):t==="title"&&(o="attribute",s="title");const i=`__DYNAMIC_${e}__`,l=this.statics.join(i);let c=ot(l,i);this.statics.length===2&&o!=="text"?c=[0]:this.statics.length===2&&c.length===0&&(c=[0]),this.dynamics.push({path:c,type:o,target:s,getValue:this.createValueGetter(t)})}createValueGetter(t){return(e,n)=>{try{let a;if(t&&typeof t=="function")a=t(e);else if(typeof t=="string"&&t.startsWith("state.")){const o=t.slice(6);a=e[o]}else typeof t=="string"&&/^[a-zA-Z0-9_$]+$/.test(t)?a=e[t]:(typeof t=="string"&&t.includes("("),a="");return a}catch(a){return this.options.development&&console.warn(`[Template Compiler] Error evaluating expression: ${t}`,a),""}}}createStaticFragment(){if(typeof document>"u")return null;try{const t=this.statics.join("");if(!t.trim())return null;const n=new DOMParser().parseFromString(t,"text/html"),a=document.createDocumentFragment();for(;n.body.firstChild;)a.appendChild(n.body.firstChild);return a}catch(t){return this.options.development&&console.warn("[Template Compiler] Could not create static fragment:",t),null}}}function M(r,t){try{if(t.length===1&&t[0]===0&&r instanceof Element)return r;let e=r;for(let n=0;n<t.length;n++){const a=t[n];if(!e.childNodes||e.childNodes.length<=a)return null;e=e.childNodes[a]}return e}catch{return null}}function R(r,t,e){let n;return r.fragment&&!r.hasDynamics?n=r.fragment.cloneNode(!0):n=lt(r,t,e),n}function z(r,t,e,n,a){if(r.hasDynamics)for(const o of r.dynamics)try{const s=o.getValue(e,n);if(a!==void 0&&o.getValue(a,n)===s)continue;q(t,o,s)}catch(s){console.warn("[Template Compiler] Error applying update:",s)}}function lt(r,t,e){let n="";for(let i=0;i<r.statics.length;i++)if(n+=r.statics[i],i<r.dynamics.length){const l=r.dynamics[i];if(l.type==="text"||l.type==="attribute"){const c=l.getValue(t,e);n+=String(c??"")}else(l.type==="property"||l.type==="class"||l.type==="style")&&(n+="")}if(typeof document>"u")return new DocumentFragment;const o=new DOMParser().parseFromString(n,"text/html"),s=document.createDocumentFragment();for(;o.body.firstChild;)s.appendChild(o.body.firstChild);for(const i of r.dynamics){const l=i.getValue(t,e),c=M(s,i.path);q(c,i,l)}return s}function q(r,t,e){try{if(t.type==="text"){const a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT);let o=!1,s;for(;s=a.nextNode();){const l=s.textContent||"";if(l.includes("Count: ")){const c=l.replace(/Count: \d+/,`Count: ${e}`);s.textContent=c,o=!0}}if(o)return;const i=M(r,t.path);i&&i.nodeType===Node.TEXT_NODE&&(i.textContent=e==null?"":String(e));return}const n=M(r,t.path);if(!n)return;switch(t.type){case"attribute":if(n.nodeType===Node.ELEMENT_NODE&&t.target){const a=n;e==null||e===""?a.removeAttribute(t.target):a.setAttribute(t.target,String(e))}break;case"property":n.nodeType===Node.ELEMENT_NODE&&t.target&&(n[t.target]=e??"",n.setAttribute(t.target,e==null?"":String(e)));break;case"class":if(n.nodeType===Node.ELEMENT_NODE&&t.target){const a=n;a.className=e==null?"":String(e),a.setAttribute("class",e==null?"":String(e))}break;case"style":if(n.nodeType===Node.ELEMENT_NODE&&t.target){const a=n;a.style[t.target]=e==null?"":String(e),a.setAttribute("style",e==null?`${t.target}:`:`${t.target}:${e}`)}break;default:throw new Error(`Unknown update type: ${t.type}`)}}catch(n){(typeof globalThis<"u"?globalThis.isDevelopment:x)&&console.warn("[Template Compiler] Error applying update:",t,n)}}const k=new Map,_=new Map;function W(r){let t=0;for(let e=0;e<r.length;e++){const n=r.charCodeAt(e);t=(t<<5)-t+n,t=t&t}return`tpl_${Math.abs(t).toString(36)}`}function H(r,t,e,n,a){return n&&a?`${t}.${r}[${e}]:${n}:${a}`:n?`${t}.${r}[${e}]:${n}`:`${t}.${r}[${e}]`}function j(r,t,e){if(!(!r||!(r instanceof Element))&&r.contains(e)&&e.parentNode===r)try{r.replaceChild(t,e)}catch(n){console.error("[VDOM] safeReplaceChild: error replacing child",n,{parent:r,newChild:t,oldChild:e,parentHTML:r.outerHTML,newChildHTML:t.outerHTML,oldChildHTML:e.outerHTML})}}function y(r){if(r.type==="#whitespace")return null;if(r.type==="#text"){const e=document.createTextNode(r.props.nodeValue??"");return r.dom=e,e}const t=document.createElement(r.type);for(const[e,n]of Object.entries(r.props))e==="value"&&t instanceof HTMLInputElement?t.type==="radio"?t.setAttribute("value",n):(t.type,t.value=n,t.setAttribute("value",n)):t.setAttribute(e,n);r.dom=t;for(const e of r.children){const n=y(e);n&&t.appendChild(n)}return t}function F(r){const t=document.createElement("template");t.innerHTML=r.trim();const e=Array.from(t.content.childNodes);return e.length===1?T(e[0]):{type:"#fragment",key:void 0,props:{},children:e.map((a,o)=>T(a,"#fragment",o)),dom:void 0}}function T(r,t="",e=0){if(!r)return{type:"#unknown",key:void 0,props:{},children:[],dom:void 0};if(r.nodeType===Node.TEXT_NODE)return!r.nodeValue||/^\s*$/.test(r.nodeValue)?{type:"#whitespace",key:void 0,props:{},children:[],dom:void 0}:{type:"#text",key:H("#text",t,e),props:{nodeValue:r.nodeValue},children:[],dom:r};if(r.nodeType===Node.ELEMENT_NODE){const n=r,a={};Array.from(n.attributes).forEach(c=>{a[c.name]=c.value});const o=n.tagName.toLowerCase();let s;if((o==="input"||o==="select"||o==="textarea")&&n.hasAttribute("data-model")){const c=n.getAttribute("data-model"),d=n.getAttribute("type")??"";s=`${o}:${c}:${d}`,a["data-uid"]=s,n.setAttribute("data-uid",s);let f=n.getAttribute("value"),u=n.getAttribute("checked");f&&(a.value=f),u&&(a.checked=u)}else o==="input"||o==="textarea"||o==="select"||n.hasAttribute("contenteditable")?(s=`${o}:${t}:${e}`,a["data-uid"]=s,n.setAttribute("data-uid",s)):(s=H(o,t,e),o==="li"&&(a["data-uid"]=s,n.setAttribute("data-uid",s)));const i=Array.from(n.childNodes).map((c,d)=>T(c,s,d));return{type:o,key:s,props:a,children:i,dom:n}}return{type:"#unknown",key:void 0,props:{},children:[],dom:void 0}}function S(r,t,e){if(!t||!e)return;function n(l){return!!l&&l.type!=="#whitespace"&&!(l.type==="#text"&&(!l.props?.nodeValue||/^\s*$/.test(l.props.nodeValue)))}const a=Array.isArray(t.children)?t.children.filter(n):[],o=Array.isArray(e.children)?e.children.filter(n):[],s=e.type==="input"||e.type==="select"||e.type==="textarea";if(t.type!==e.type||t.key!==e.key){const l=y(e);if(l instanceof Node&&t.dom instanceof Node&&r.contains(t.dom)){if(j(r,l,t.dom),s&&e.props&&r.firstChild instanceof HTMLInputElement){const c=r.firstChild;c.type==="radio"||c.type,c.value=e.props.value,c.setAttribute("value",e.props.value),"checked"in e.props&&(c.checked=e.props.checked===!0||e.props.checked==="true")}}else if(l instanceof Node)if(l){if(r.appendChild(l),e.dom=l,s&&e.props&&r.firstChild instanceof HTMLInputElement){const c=r.firstChild;c.type==="radio"?c.setAttribute("value",e.props.value):(c.type,c.value=e.props.value,c.setAttribute("value",e.props.value)),"checked"in e.props&&(c.checked=e.props.checked===!0||e.props.checked==="true")}}else e.dom=void 0;else e.dom=void 0;return}if(s&&t.dom instanceof HTMLElement&&e.props){for(const[l,c]of Object.entries(e.props))if(l==="value"&&r.firstChild instanceof HTMLInputElement)r.firstChild.value=c;else if(l==="checked"&&r.firstChild instanceof HTMLInputElement)r.firstChild.checked=c===!0||c==="true";else if(l in t.dom)try{t.dom[l]=c}catch{}else t.dom.setAttribute(l,c);for(let l=e.children.length;l<a.length;l++)a[l]&&a[l].dom&&t.dom&&t.dom.contains(a[l].dom)&&t.dom.removeChild(a[l].dom);return}const i=t.dom;if(i&&i instanceof Element&&e.props){const l=i.tagName.toLowerCase()==="input"?i.getAttribute("type"):void 0,c=i.tagName.includes("-");for(const[d,f]of Object.entries(e.props))if(!(l==="radio"&&d==="value")){if(l==="checkbox"&&d==="value"){i.setAttribute("value",f);continue}i.setAttribute(d,f)}if(c)for(const[d,f]of Object.entries(e.props))i.setAttribute(d,f);for(const d of Array.from(i.attributes).map(f=>f.name))if(!(d in e.props)){if(l==="radio"&&d==="value"||l==="checkbox"&&d==="value")continue;i.removeAttribute(d)}}if(e.type==="#text"){if(i&&i.nodeType===Node.TEXT_NODE)i.nodeValue!==e.props.nodeValue&&(i.nodeValue=e.props.nodeValue),e.dom=i;else{const l=document.createTextNode(e.props.nodeValue??"");i&&r.contains(i)&&i.parentNode===r?j(r,l,i):r.appendChild(l),e.dom=l}return}if(i instanceof Element){const l=new Map;a.forEach(u=>u.key&&l.set(u.key,u));const c=new Set(o.map(u=>u.key));let d=[];for(let u=0;u<o.length;u++){const h=o[u],m=h.key?l.get(h.key):a[u];let p;const w=h.type==="input"||h.type==="select"||h.type==="textarea";if(m&&m.dom&&(!w||m.type===h.type&&m.key===h.key))S(i,m,h),p=m.dom;else{const v=y(h);if(p=v instanceof Node?v:void 0,p){if((p instanceof Element||p instanceof Node)&&p.contains(i))throw console.error("[VDOM] Attempted to insert a parent into its own child:",{parentTag:i.tagName,childTag:p.tagName,parentUid:i.getAttribute?.("data-uid"),childUid:p.getAttribute?.("data-uid"),parent:i,child:p}),new Error("VDOM patch error: Attempted to insert a parent into its own child");i.insertBefore(p,i.childNodes[u]||null)}}h.dom=p,p&&d.push(p)}for(a.forEach(u=>{!c.has(u.key)&&u.dom&&i.contains(u.dom)&&i.removeChild(u.dom)});i.childNodes.length>o.length;)i.removeChild(i.lastChild);for(let u=0;u<d.length;u++)if(i.childNodes[u]!==d[u]){if((d[u]instanceof Element||d[u]instanceof Node)&&d[u].contains(i))throw new Error("VDOM patch error: Attempted to insert a parent into its own child");i.insertBefore(d[u],i.childNodes[u]||null)}e.dom=i;const f=new Set(o.map(u=>u.key));Array.from(i.childNodes).forEach((u,h)=>{const m=u.getAttribute?.("data-uid");(m&&!f.has(m)||h>=o.length)&&i.removeChild(u)})}}function $(r,t){const e=[],n=t?Object.keys(t):[],a={...r};let o=null;function s(d){return e.push(d),()=>{const f=e.indexOf(d);f!==-1&&e.splice(f,1)}}function i(d){Object.assign(o,d),e.forEach(f=>f(o))}const l=new WeakMap;function c(d){if(l.has(d))return l.get(d);const f=new Proxy(d,{get(u,h,m){if(h==="subscribe")return s;if(h==="set")return i;if(t&&n.includes(h))return t[h](o);const p=Reflect.get(u,h,m);return typeof p=="object"&&p!==null?c(p):p},set(u,h,m,p){if(t&&n.includes(h))return!1;const w=u[h],v=Reflect.set(u,h,m,p);return w!==m&&e.forEach(K=>K(o)),v},deleteProperty(u,h){if(t&&n.includes(h))return!1;const m=Reflect.deleteProperty(u,h);return e.forEach(p=>p(o)),m}});return l.set(d,f),f}return o=c(a),o}const E=[];function dt(r){E.push(r)}function b(r,t=new WeakSet){if(r===null||typeof r!="object"||t.has(r))return r;if(t.add(r),Array.isArray(r))return r.map(a=>b(a,t));Object.getPrototypeOf(r)!==Object.prototype&&Object.getPrototypeOf(r)!==null&&Object.setPrototypeOf(r,null);const e=["__proto__","constructor","prototype"],n=Object.create(null);for(const a of Object.keys(r))e.includes(a)||(n[a]=b(r[a],t));return n}function C(r){return!!r&&typeof r.then=="function"}class ut extends HTMLElement{syncStateToAttributes(){if(!this.stateObj||!this.config?.reflect||!Array.isArray(this.config.reflect))return;const t=["__proto__","constructor","prototype"];this.config.reflect.forEach(e=>{if(t.includes(e)){this.removeAttribute(e);return}const n=this.stateObj[e];["string","number","boolean"].includes(typeof n)?n==null?this.removeAttribute(e):this.setAttribute(e,String(n)):this.removeAttribute(e)})}setTemplate(t){const e=this.config;typeof t=="function"?e.template=t:e.template=()=>t,this.render()}_hasError=!1;_mountedCalled=!1;_unmountedCalled=!1;_autoWiredHandlers={};removeEventListener(t,e,n){super.removeEventListener(t,e,n),this._autoWiredHandlers[t]&&(this._autoWiredHandlers[t]=this._autoWiredHandlers[t].filter(a=>a===e?(super.removeEventListener(t,a,n),!1):!0),this._autoWiredHandlers[t].length===0&&delete this._autoWiredHandlers[t])}static get observedAttributes(){const t=this.stateObj||{};return Object.keys(t).filter(e=>["string","number","boolean"].includes(typeof t[e]))}attributeChangedCallback(t,e,n){if(!(t==="__proto__"||t==="constructor"||t==="prototype")&&this.stateObj&&t in this.stateObj){const a=typeof this.config?.state?.[t];let o=n;if(n===null)o=void 0;else if(a==="number")if(o===void 0||o==="")o=this.config?.state?.[t];else{const s=Number(o);o=isNaN(s)?this.config?.state?.[t]:s}else a==="boolean"&&(o=o==="true");o=b(o),this.stateObj[t]!==o&&(this.config?.debug&&console.log("[runtime] state update:",{name:t,value:o}),this.stateObj[t]=o,this.render())}}forceSyncControlledInputs(){this.shadowRoot&&(this.shadowRoot.querySelectorAll("input[data-model]").forEach(t=>{const e=t.getAttribute("data-model");if(!e||!this.stateObj||typeof this.stateObj[e]>"u")return;const n=t,a=String(this.stateObj[e]),o=document.activeElement===n;n._hasDirtyListener||(n.addEventListener("input",()=>{n._isDirty=!0}),n.addEventListener("blur",()=>{n._isDirty=!1}),n._hasDirtyListener=!0);const s=!!n._isDirty;o||s||n.type!=="radio"&&n.type!=="checkbox"&&n.value!==a&&(n.value=a)}),this.rebindEventListeners())}syncControlledInputsAndEvents(){this.shadowRoot&&(this.shadowRoot.querySelectorAll('input[type="radio"][data-model]').forEach(t=>{const e=t.getAttribute("data-model");if(!e||!this.stateObj||typeof this.stateObj[e]>"u")return;const n=t,a=String(this.stateObj[e]);n.checked=n.value===a}),this.shadowRoot.querySelectorAll("input[data-model]").forEach(t=>{const e=t.getAttribute("data-model");if(!e||!this.stateObj||typeof this.stateObj[e]>"u")return;const n=t,a=String(this.stateObj[e]);if(n.type==="checkbox"){const o=this.stateObj[e];if(Array.isArray(o))n.checked=o.includes(n.value);else{const s=n.getAttribute("data-true-value"),i=n.getAttribute("data-false-value");s!==null||i!==null?String(o)===s?n.checked=!0:String(o)===i?n.checked=!1:o===!0?n.checked=!0:n.checked=!1:n.checked=o===!0||o==="true"||o===1}}else n.type==="radio"||(n.value=a)}),this.shadowRoot.querySelectorAll("textarea[data-model]").forEach(t=>{const e=t.getAttribute("data-model");!e||!this.stateObj||typeof this.stateObj[e]>"u"||(t.value=String(this.stateObj[e]))}),this.shadowRoot.querySelectorAll("select[data-model]").forEach(t=>{const e=t.getAttribute("data-model");!e||!this.stateObj||typeof this.stateObj[e]>"u"||(t.value=String(this.stateObj[e]))}))}attachListItemModelListeners(){this.shadowRoot&&this.shadowRoot.querySelectorAll("input[data-bind]").forEach(t=>{const e=t.getAttribute("data-bind");if(!e)return;t._listItemModelListener&&(t.removeEventListener("input",t._listItemModelListener),t.removeEventListener("change",t._listItemModelListener),delete t._listItemModelListener);const n=e.match(/^([a-zA-Z0-9_]+)\[(\d+)\]\.([a-zA-Z0-9_]+)$/);if(n){const[,o,s,i]=n,l=parseInt(s,10),c=this.stateObj[o];t instanceof HTMLInputElement&&t.type==="checkbox"&&(t.checked=!!(Array.isArray(c)&&c[l]&&c[l][i]));const d=f=>{!Array.isArray(c)||!c[l]||(t instanceof HTMLInputElement&&t.type==="checkbox"?c[l][i]=t.checked:c[l][i]=t.value)};t.addEventListener("input",d),t.addEventListener("change",d),t._listItemModelListener=d;return}const a=e.match(/^([a-zA-Z0-9_]+)\.([a-zA-Z0-9_]+)((?:\|[a-zA-Z0-9_]+)*)$/);if(a){const[,o,s,i]=a,l=this.stateObj[o],c=i?i.split("|").map(f=>f.trim()).filter(Boolean):[];t instanceof HTMLInputElement&&t.type==="checkbox"?t.checked=!!(l&&l[s]):t instanceof HTMLInputElement&&(t.value=l?String(l[s]??""):"");const d=f=>{if(!l)return;let u;t instanceof HTMLInputElement&&t.type==="checkbox"?u=t.checked:(u=t.value,c.includes("number")&&(u=Number(u)),c.includes("trim")&&typeof u=="string"&&(u=u.trim())),l[s]=u};t.addEventListener("input",d),t.addEventListener("change",d),t._listItemModelListener=d}})}attachControlledInputListeners(){const t=this.shadowRoot;t&&(t.querySelectorAll("[data-model]").forEach(e=>{const n=e.getAttribute("data-model");n&&(e._dataModelBound||(P(e,this.stateObj,n),e._dataModelBound=!0))}),t.querySelectorAll("[data-model]").forEach(e=>{const[n]=e.getAttribute("data-model")?.split("|").map(a=>a.trim())??[];if(!(!n||!(n in this.stateObj)))if(e instanceof HTMLInputElement)if(e.type==="checkbox"){const a=this.stateObj[n],o=e.getAttribute("data-true-value"),s=e.getAttribute("data-false-value");Array.isArray(a)?e.checked=a.includes(e.value):o!==null||s!==null?String(a)===o?e.checked=!0:String(a)===s?e.checked=!1:a===!0?e.checked=!0:e.checked=!1:e.checked=a===!0||a==="true"||a===1}else e.type==="radio"?e.checked=e.value===String(this.stateObj[n]):e.value=String(this.stateObj[n]??"");else(e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&(e.value=String(this.stateObj[n]??""))}))}config;stateObj;api;_globalUnsubscribes=[];unsubscribes=[];lastCompiledTemplate=null;lastState=null;rafId=null;constructor(){super()}initializeConfig(){if(this.config)return;const t=this.tagName.toLowerCase(),n=(window.__componentRegistry||{})[t];if(!n||typeof n!="object")throw new Error("Invalid component config: must be an object");if(!n.state||typeof n.state!="object")throw new Error("Invalid component config: state must be an object");this.config=n;const a=n.computed?$(n.state,n.computed):$(n.state);if(this.stateObj=a,typeof this.stateObj.subscribe=="function"&&this.unsubscribes.push(this.stateObj.subscribe(()=>{this.scheduleRender()})),this.api={state:this.stateObj,emit:(s,i)=>this.dispatchEvent(new CustomEvent(s,{detail:i,bubbles:!0})),onGlobal:(s,i)=>{const l=A.on(s,i);return this._globalUnsubscribes.push(l),l},offGlobal:(s,i)=>A.off(s,i),emitGlobal:(s,i)=>A.emit(s,i)},Object.keys(this.config).forEach(s=>{if(s.startsWith("on")&&s.length>2&&typeof this.config[s]=="function"){const i=s.charAt(2).toLowerCase()+s.slice(3),l=c=>{const d=c.detail??c;this.config[s](d,this.api.state,this.api)};this.addEventListener(i,l),this._autoWiredHandlers[i]||(this._autoWiredHandlers[i]=[]),this._autoWiredHandlers[i].push(l)}}),this.attachShadow({mode:"open"}),n.style){const s=document.createElement("style");s.textContent=typeof n.style=="function"?n.style(this.stateObj):n.style,this.shadowRoot.appendChild(s)}if(typeof this.config.hydrate=="function"){const s=this.shadowRoot?.querySelectorAll("[data-hydrate]");try{s&&s.length>0?s.forEach(i=>{try{this.config.hydrate(i,this.stateObj,this.api)}catch(l){typeof this.config.onError=="function"&&this.config.onError(l instanceof Error?l:new Error(String(l)),this.api.state,this.api),this._handleRenderError(l)}}):this.config.hydrate(this.shadowRoot,this.stateObj,this.api)}catch(i){typeof this.config.onError=="function"&&this.config.onError(i instanceof Error?i:new Error(String(i)),this.api.state,this.api),this._handleRenderError(i)}}if(this.hasAttribute("data-hydrated")?this.processRefs():this.render(),!this._mountedCalled&&typeof this.config.onMounted=="function")try{const s=this.config.onMounted(this.api.state,this.api);C(s)?s.catch(i=>{typeof this.config.onError=="function"&&this.config.onError(i,this.api.state,this.api),this._handleRenderError(i)}).finally(()=>{this._mountedCalled=!0}):this._mountedCalled=!0}catch(s){typeof this.config.onError=="function"&&this.config.onError(s,this.api.state,this.api),this._handleRenderError(s),this._mountedCalled=!0}}connectedCallback(){if(this.initializeConfig(),this.stateObj){for(const t of this.getAttributeNames())if(t in this.stateObj){const e=typeof this.config?.state?.[t];let n=this.getAttribute(t);e==="number"?n=Number(n):e==="boolean"&&(n=n==="true"),this.stateObj[t]=n===null?void 0:n}}if(!this._mountedCalled&&typeof this.config.onMounted=="function")try{const t=this.config.onMounted(this.api.state,this.api);C(t)?t.catch(e=>{typeof this.config.onError=="function"&&this.config.onError(e,this.api.state,this.api),this._handleRenderError(e)}).finally(()=>{this._mountedCalled=!0}):this._mountedCalled=!0}catch(t){typeof this.config.onError=="function"&&this.config.onError(t,this.api.state,this.api),this._handleRenderError(t),this._mountedCalled=!0}typeof this.render=="function"&&this.render()}disconnectedCallback(){if(Object.entries(this._autoWiredHandlers).forEach(([t,e])=>{e.forEach(n=>{super.removeEventListener(t,n)})}),this._autoWiredHandlers={},this.unsubscribes.forEach(t=>t()),this.unsubscribes=[],this._globalUnsubscribes.forEach(t=>t()),this._globalUnsubscribes=[],!this._unmountedCalled&&typeof this.config.onUnmounted=="function")try{const t=this.config.onUnmounted(this.api.state,this.api);C(t)?t.catch(e=>{typeof this.config.onError=="function"&&this.config.onError(e,this.api.state,this.api),this._handleRenderError(e)}).finally(()=>{this._unmountedCalled=!0}):this._unmountedCalled=!0}catch(t){typeof this.config.onError=="function"&&this.config.onError(t,this.api.state,this.api),this._handleRenderError(t),this._unmountedCalled=!0}this._mountedCalled=!1,this._unmountedCalled=!1}render(){this._hasError=!1,this.syncControlledInputsAndEvents(),setTimeout(()=>this.attachControlledInputListeners(),0);try{E.forEach(e=>{try{e.onRender?.(this.stateObj,this.api)}catch(n){this._handleRenderError(n)}}),this.config.computed&&Object.values(this.config.computed).forEach(e=>{try{e(this.stateObj)}catch(n){this._handleRenderError(n)}});const t=this.config.template(this.stateObj,this.api);t instanceof Promise?t.then(e=>{this._hasError||(this._renderTemplateResult(e),this.syncStateToAttributes(),setTimeout(()=>this.attachListItemModelListeners(),0))}).catch(e=>{this._handleRenderError(e)}):this._hasError||(this._renderTemplateResult(t),this.syncStateToAttributes(),setTimeout(()=>this.attachListItemModelListeners(),0))}catch(t){this._handleRenderError(t),this.renderError(t instanceof Error?t:new Error(String(t)))}}_prevVNode=null;rebindEventListeners(){if(!this.shadowRoot)return;["data-on-input","data-on-change","data-on-blur","data-on-click"].forEach(e=>{this.shadowRoot.querySelectorAll(`[${e}]`).forEach(n=>{const a=e.replace("data-on-",""),o=n.getAttribute(e);if(!o||typeof this.config[o]!="function")return;n._boundHandlers&&n._boundHandlers[a]&&n.removeEventListener(a,n._boundHandlers[a]);const s=this.config[o],i=l=>s.call(this,l);n.addEventListener(a,i),n._boundHandlers||(n._boundHandlers={}),n._boundHandlers[a]=i})}),Array.from(this.shadowRoot.children).forEach(e=>{e instanceof HTMLElement&&typeof e.rebindEventListeners=="function"&&e.rebindEventListeners()})}_renderTemplateResult(t){if(!this._hasError)try{let e=function(n){const a=new WeakSet;function o(s){if(s===null||typeof s!="object")return s;if(a.has(s))return;if(a.add(s),Array.isArray(s))return s.map(o);const i={};for(const l in s)Object.prototype.hasOwnProperty.call(s,l)&&(i[l]=o(s[l]));return i}return o(n)};if(typeof t=="string"){let n=function(c){return c.replace(/<([a-zA-Z0-9]+)([^>]*)>/g,(d,f,u)=>{const h=u.replace(/\s+on[a-zA-Z]+\s*=\s*(['"][^'"]*['"]|[^\s>]*)/gi,"");return`<${f}${h}>`})},a=function(c){c.children.forEach(a)};const o=n(t),s=F(o);a(s);const i=this.shadowRoot;if(!i)return;let l=i.querySelector("style");if(l||(l=document.createElement("style"),i.appendChild(l)),this.config.style?l.textContent=typeof this.config.style=="function"?this.config.style(this.stateObj):this.config.style:l.textContent="",s.type==="#fragment"){const c=Array.from(i.childNodes).find(d=>d.nodeType===1&&d!==l);if(c){Array.from(c.childNodes).forEach(u=>{u.nodeType===1&&u.nodeName==="STYLE"||c.removeChild(u)});const d={type:"#fragment",dom:c,children:s.children,props:{},key:void 0},f=this._prevVNode&&this._prevVNode.type==="#fragment"?{...this._prevVNode,dom:c}:d;S(c,f,d)}else s.children.forEach(d=>{const f=y(d);f&&i.appendChild(f),d.dom=f??void 0})}else{let c=Array.from(this.shadowRoot.childNodes).find(d=>d!==l&&d.nodeType===1);if(c)if(this._prevVNode&&(this._prevVNode.type!==s.type||this._prevVNode.key!==s.key)){const d=y(s);d&&(this.shadowRoot.contains(c)&&this.shadowRoot.replaceChild(d,c),c=d)}else S(c,this._prevVNode,s);else c=y(s),c&&this.shadowRoot.appendChild(c);s.dom=c}this._prevVNode=s,this.forceSyncControlledInputs(),this.lastCompiledTemplate=null}else{const n=!this.shadowRoot.firstElementChild,a=this.lastCompiledTemplate?.id===t.id;if(n){const o=R(t,this.stateObj,this.api);this.shadowRoot.appendChild(o)}else if(a&&this.shadowRoot.firstElementChild){const o=this.lastState;z(t,this.shadowRoot.firstElementChild,this.stateObj,this.api,o||void 0)}else{const o=R(t,this.stateObj,this.api);let s=this.shadowRoot.querySelector("style");s||(s=document.createElement("style"),this.shadowRoot.insertBefore(s,this.shadowRoot.firstChild)),this.config.style?s.textContent=typeof this.config.style=="function"?this.config.style(this.stateObj):this.config.style:s.textContent="";let i=this.shadowRoot.querySelector("[data-root]");for(i||(i=document.createElement("div"),i.setAttribute("data-root",""),this.shadowRoot.appendChild(i));i.firstChild;)i.removeChild(i.firstChild);i.appendChild(o)}this.lastCompiledTemplate=t}this.lastState=e(this.stateObj),this.updateStyle(),this.processRefs(),this.bindEvents(),this.syncControlledInputsAndEvents()}catch(e){this._handleRenderError(e)}}_handleRenderError(t){if(this._hasError=!0,this.config.debug&&console.error(`[runtime] Render error in <${this.tagName.toLowerCase()}>:`,t),E.forEach(e=>e.onError?.(t instanceof Error?t:new Error(String(t)),this.stateObj,this.api)),"onError"in this.config&&typeof this.config.onError=="function")try{this.config.onError(t instanceof Error?t:new Error(String(t)),this.api.state,this.api)}catch(e){this.config.debug&&console.error("[runtime] Error in onError handler:",e)}this.renderError(t instanceof Error?t:new Error(String(t)))}scheduleRender(){this.rafId!==void 0&&this.rafId!==null&&cancelAnimationFrame(this.rafId),this.rafId=requestAnimationFrame(()=>{this.render(),this.rafId=null})}updateStyle(){const t=this.shadowRoot.querySelector("style");if(!t||!this.config.style)return;const e=typeof this.config.style=="function"?this.config.style(this.api.state):this.config.style;t.textContent=e}processRefs(){if(!this.config.refs)return;const t=new WeakMap;Object.entries(this.config.refs).forEach(([e,n])=>{const a=this.shadowRoot.querySelector(`[data-ref="${e}"]`);if(a){t.has(a)||t.set(a,new Set);const o=t.get(a),s=a.addEventListener;a.addEventListener=function(i,l,c){const d=`${i}`;o.has(d)||(o.add(d),s.call(a,i,l,c))},a.setAttribute("data-refs-processed","true");try{n(a,this.api.state,this.api)}catch(i){this._handleRenderError(i)}}})}bindEvents(){if(!this.shadowRoot)return;const t=document.createTreeWalker(this.shadowRoot,NodeFilter.SHOW_ELEMENT);let e=t.nextNode();for(;e;){const n=e;Array.from(n.attributes).forEach(a=>{if(a.name.startsWith("data-on-")){const o=a.name.slice(8),s=a.value,i=this.config[s];if(typeof i=="function"){n._boundHandlers&&n._boundHandlers[o]&&n.removeEventListener(o,n._boundHandlers[o]);const l=c=>{i.call(this.config,c,this.api.state,this.api),this.syncControlledInputsAndEvents()};n.addEventListener(o,l),n._boundHandlers||(n._boundHandlers={}),n._boundHandlers[o]=l}else this.config.debug&&console.warn(`[runtime] Handler '${s}' not found on config for event '${o}'`,n)}}),e=t.nextNode()}}renderError(t){const e=this.config.style?typeof this.config.style=="function"?this.config.style(this.api.state):this.config.style:"";this.shadowRoot.innerHTML=`
|
|
40
|
+
<style>${e}</style>
|
|
41
|
+
<div style="color: red; border: 1px solid red; padding: 1rem; border-radius: 4px;">
|
|
42
|
+
<h3>Error Boundary</h3>
|
|
43
|
+
<div>Error: ${t.message}</div>
|
|
44
|
+
</div>
|
|
45
|
+
`}}function ft(r,t){const e=b(t),n=b(t.state);if(t=e,t.state=n,t.debug&&console.log(`[runtime] Debugging component: ${r}`,t),!r||!t.template||!t.state){t&&typeof t.onError=="function"&&t.onError(new Error("Component requires tag, template, and state"),t.state,{state:t.state,emit:()=>{},onGlobal:()=>()=>{},offGlobal:()=>{},emitGlobal:()=>{}}),t&&t.debug&&console.error("[runtime] Malformed config:",{tag:r,config:t});return}E.forEach(c=>{try{c.onInit?.(t)}catch(d){t&&typeof t.onError=="function"&&t.onError(d instanceof Error?d:new Error(String(d)),t.state,{state:t.state,emit:()=>{},onGlobal:()=>()=>{},offGlobal:()=>{},emitGlobal:()=>{}}),t&&t.debug&&console.error("[runtime] Plugin onInit error:",d)}});const a=typeof window<"u"&&window.VITE_DEV_HMR,o=typeof{url:typeof document>"u"?require("url").pathToFileURL(__filename).href:O&&O.tagName.toUpperCase()==="SCRIPT"&&O.src||new URL("custom-elements-runtime.cjs.js",document.baseURI).href}<"u"&&void 0;if((a||o)&&customElements.get(r))try{document.querySelectorAll(r).forEach(c=>c.remove()),window.customElements._definitions&&delete window.customElements._definitions[r]}catch{}if(customElements.get(r)){t.debug&&console.warn(`[runtime] Component "${r}" already registered`);return}const s=$(t.state,t.computed);t.state=s,t._subscribe=s.subscribe;const i=Object.keys(t.state).filter(c=>["string","number","boolean"].includes(typeof t.state[c])),l=class extends ut{static get observedAttributes(){return i}constructor(){super()}};customElements.get(r)||(window.__componentRegistry=window.__componentRegistry||{},window.__componentRegistry[r]=t,customElements.define(r,l))}exports.Store=U;exports.classes=rt;exports.compile=Q;exports.compileTemplate=it;exports.component=ft;exports.createVNodeFromElement=T;exports.css=tt;exports.deepSanitizeObject=b;exports.eventBus=A;exports.generateHydrationScript=V;exports.getVNodeKey=H;exports.html=J;exports.isPromise=C;exports.mountVNode=y;exports.on=nt;exports.parseVNodeFromHTML=F;exports.patchVNode=S;exports.ref=et;exports.renderCompiledTemplate=R;exports.renderComponentsToString=Z;exports.renderToString=I;exports.runtimePlugins=E;exports.safeReplaceChild=j;exports.styles=st;exports.updateCompiledTemplate=z;exports.useDataModel=P;exports.useRuntimePlugin=dt;
|
|
46
|
+
//# sourceMappingURL=custom-elements-runtime.cjs.js.map
|