@jasonshimmy/custom-elements-runtime 3.0.0 → 3.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +118 -81
  2. package/dist/custom-elements-runtime.cjs.js +3 -3
  3. package/dist/custom-elements-runtime.cjs.js.map +1 -1
  4. package/dist/custom-elements-runtime.es.js +77 -72
  5. package/dist/custom-elements-runtime.es.js.map +1 -1
  6. package/dist/custom-elements-runtime.jit-css.cjs.js +1 -1
  7. package/dist/custom-elements-runtime.jit-css.cjs.js.map +1 -1
  8. package/dist/custom-elements-runtime.jit-css.es.js +25 -26
  9. package/dist/custom-elements-runtime.jit-css.es.js.map +1 -1
  10. package/dist/custom-elements-runtime.router.cjs.js +8 -8
  11. package/dist/custom-elements-runtime.router.cjs.js.map +1 -1
  12. package/dist/custom-elements-runtime.router.es.js +134 -134
  13. package/dist/custom-elements-runtime.router.es.js.map +1 -1
  14. package/dist/custom-elements-runtime.ssr-middleware.cjs.js +2 -0
  15. package/dist/custom-elements-runtime.ssr-middleware.cjs.js.map +1 -0
  16. package/dist/custom-elements-runtime.ssr-middleware.es.js +69 -0
  17. package/dist/custom-elements-runtime.ssr-middleware.es.js.map +1 -0
  18. package/dist/custom-elements-runtime.ssr.cjs.js +3 -1
  19. package/dist/custom-elements-runtime.ssr.cjs.js.map +1 -1
  20. package/dist/custom-elements-runtime.ssr.es.js +158 -39
  21. package/dist/custom-elements-runtime.ssr.es.js.map +1 -1
  22. package/dist/custom-elements-runtime.vite-plugin.cjs.js +1 -1
  23. package/dist/custom-elements-runtime.vite-plugin.cjs.js.map +1 -1
  24. package/dist/custom-elements-runtime.vite-plugin.es.js +81 -49
  25. package/dist/custom-elements-runtime.vite-plugin.es.js.map +1 -1
  26. package/dist/hooks-x8M4knLc.cjs +6 -0
  27. package/dist/hooks-x8M4knLc.cjs.map +1 -0
  28. package/dist/hooks-xWZhQHco.js +1465 -0
  29. package/dist/hooks-xWZhQHco.js.map +1 -0
  30. package/dist/index.d.ts +3 -0
  31. package/dist/namespace-helpers-D4wC2-qA.js +61 -0
  32. package/dist/namespace-helpers-D4wC2-qA.js.map +1 -0
  33. package/dist/namespace-helpers-ckeEOxpR.cjs +2 -0
  34. package/dist/namespace-helpers-ckeEOxpR.cjs.map +1 -0
  35. package/dist/router/matcher.d.ts +14 -0
  36. package/dist/runtime/component/factory.d.ts +16 -2
  37. package/dist/runtime/hydration.d.ts +33 -0
  38. package/dist/runtime/render.d.ts +0 -11
  39. package/dist/runtime/scheduler.d.ts +12 -0
  40. package/dist/runtime/ssr-context.d.ts +47 -0
  41. package/dist/runtime/ssr-utils.d.ts +9 -0
  42. package/dist/runtime/types.d.ts +18 -0
  43. package/dist/runtime/vdom-ssr-dsd.d.ts +82 -0
  44. package/dist/runtime/vdom-ssr.d.ts +2 -6
  45. package/dist/ssr-middleware.d.ts +125 -0
  46. package/dist/ssr.d.ts +95 -33
  47. package/dist/template-compiler-CTUhEHr8.cjs +22 -0
  48. package/dist/template-compiler-CTUhEHr8.cjs.map +1 -0
  49. package/dist/template-compiler-ZhSg1yPh.js +3724 -0
  50. package/dist/template-compiler-ZhSg1yPh.js.map +1 -0
  51. package/dist/vite-plugin.d.ts +94 -4
  52. package/package.json +6 -1
  53. package/dist/helpers-CweFZFWU.js +0 -987
  54. package/dist/helpers-CweFZFWU.js.map +0 -1
  55. package/dist/helpers-DeWjSmOl.cjs +0 -5
  56. package/dist/helpers-DeWjSmOl.cjs.map +0 -1
  57. package/dist/hooks-BrrLKSub.cjs +0 -3
  58. package/dist/hooks-BrrLKSub.cjs.map +0 -1
  59. package/dist/hooks-DyShDHKo.js +0 -403
  60. package/dist/hooks-DyShDHKo.js.map +0 -1
  61. package/dist/namespace-helpers-CnpZ5__p.js +0 -45
  62. package/dist/namespace-helpers-CnpZ5__p.js.map +0 -1
  63. package/dist/namespace-helpers-CyIDtI97.cjs +0 -2
  64. package/dist/namespace-helpers-CyIDtI97.cjs.map +0 -1
  65. package/dist/template-compiler-B5uN1EQw.js +0 -3731
  66. package/dist/template-compiler-B5uN1EQw.js.map +0 -1
  67. package/dist/template-compiler-Cx623BSB.cjs +0 -23
  68. package/dist/template-compiler-Cx623BSB.cjs.map +0 -1
@@ -1,16 +1,20 @@
1
- import { u as b, a as T, b as k, g as x, i as A } from "./hooks-DyShDHKo.js";
2
- import { c as te, d as ne, e as oe, p as re, f as se, h as ae, j as ie, k as ce, l as le, m as ue, n as he, o as de } from "./hooks-DyShDHKo.js";
3
- import { r as m, a as I } from "./helpers-CweFZFWU.js";
4
- import { R as me, c as pe, d as ye, f as ge, i as ve, n as Ce, s as we, u as Se, w as _e, b as Re } from "./helpers-CweFZFWU.js";
5
- import { c as v, h as l, v as p } from "./template-compiler-B5uN1EQw.js";
6
- import { c as He } from "./css-utils-Cg4o1MqY.js";
7
- import { d as y, a as D } from "./logger-BvkEbVM4.js";
8
- import { b as Le, s as be } from "./logger-BvkEbVM4.js";
1
+ import { r as f, u as L, a as T, b as k, c as x, g as A, i as D } from "./hooks-xWZhQHco.js";
2
+ import { R as te, d as ne, e as oe, f as re, h as se, j as ae, k as ie, l as ce, n as le, p as ue, s as de, m as he, o as me, q as fe, t as pe, v as ye, w as ge, x as ve, y as Ce, z as we, A as Ee, B as Se } from "./hooks-xWZhQHco.js";
3
+ import { c as v, h as l, v as p } from "./template-compiler-ZhSg1yPh.js";
4
+ import { c as Re } from "./css-utils-Cg4o1MqY.js";
5
+ import { d as y, a as I } from "./logger-BvkEbVM4.js";
6
+ import { b as Me, s as be } from "./logger-BvkEbVM4.js";
7
+ function W(e = document) {
8
+ if (typeof CustomEvent > "u") return;
9
+ (e instanceof Document ? e.documentElement : e).dispatchEvent(
10
+ new CustomEvent("cer:hydrate", { bubbles: !0, composed: !0 })
11
+ );
12
+ }
9
13
  const O = 100, U = 3e4;
10
- function K(e, t, o) {
14
+ function z(e, t, o) {
11
15
  return o === "jitCacheHitRate" ? e < t * 0.5 ? "critical" : e < t ? "warning" : "healthy" : e > t * 2 ? "critical" : e > t ? "warning" : "healthy";
12
16
  }
13
- function z(e) {
17
+ function K(e) {
14
18
  const t = [];
15
19
  return e.memoryUsage?.status !== "healthy" && t.push(
16
20
  "Consider reducing component complexity or implementing better memory cleanup"
@@ -42,9 +46,9 @@ function j() {
42
46
  function i() {
43
47
  n("activeComponents", 0, 1e3), n("componentCreateRate", 0, 50), n("componentErrorRate", 0, 0.1), n("memoryUsage", 0, 50 * 1024 * 1024), n("memoryGrowthRate", 0, 1024 * 1024), n("averageRenderTime", 0, 16), n("slowRenderCount", 0, 10), n("jitCacheHitRate", 100, 80), n("activeReactiveStates", 0, 5e3), n("dependencyUpdates", 0, 100), n("memoryLeakIndicator", 0, 0.1);
44
48
  }
45
- function h(r, s) {
49
+ function d(r, s) {
46
50
  const a = e.get(r);
47
- a && (a.value = s, a.lastUpdated = Date.now(), a.history.push(s), a.history.length > O && a.history.shift(), a.status = K(s, a.threshold, r));
51
+ a && (a.value = s, a.lastUpdated = Date.now(), a.history.push(s), a.history.length > O && a.history.shift(), a.status = z(s, a.threshold, r));
48
52
  }
49
53
  function c() {
50
54
  const r = {};
@@ -55,17 +59,17 @@ function j() {
55
59
  overall: s,
56
60
  metrics: r,
57
61
  timestamp: Date.now(),
58
- recommendations: z(r)
62
+ recommendations: K(r)
59
63
  };
60
64
  }
61
- function d() {
65
+ function h() {
62
66
  if ("memory" in performance && performance.memory) {
63
67
  const r = performance.memory;
64
- h("memoryUsage", r.usedJSHeapSize);
68
+ d("memoryUsage", r.usedJSHeapSize);
65
69
  const s = e.get("memoryUsage");
66
70
  if (s && s.history.length > 1) {
67
71
  const a = s.history[s.history.length - 2], u = s.history[s.history.length - 1];
68
- h("memoryGrowthRate", Math.max(0, u - a));
72
+ d("memoryGrowthRate", Math.max(0, u - a));
69
73
  }
70
74
  }
71
75
  }
@@ -77,24 +81,24 @@ function j() {
77
81
  y("Error in health monitor listener:", a);
78
82
  }
79
83
  }
80
- function S() {
81
- d();
84
+ function E() {
85
+ h();
82
86
  const r = c();
83
87
  w(r), r.overall === "critical" ? y(
84
88
  "🚨 Runtime Health: Critical issues detected",
85
89
  r.recommendations
86
- ) : r.overall === "warning" && D(
90
+ ) : r.overall === "warning" && I(
87
91
  "⚠️ Runtime Health: Performance warnings",
88
92
  r.recommendations
89
93
  );
90
94
  }
91
- function _() {
92
- typeof window > "u" || (o = setInterval(S, U));
95
+ function S() {
96
+ typeof window > "u" || (o = setInterval(E, U));
93
97
  }
94
- function R() {
98
+ function _() {
95
99
  o !== null && (clearInterval(o), o = null);
96
100
  }
97
- function E(r) {
101
+ function R(r) {
98
102
  t.add(r);
99
103
  }
100
104
  function H(r) {
@@ -104,22 +108,22 @@ function j() {
104
108
  const s = e.get(r);
105
109
  return s ? [...s.history] : [];
106
110
  }
107
- function L() {
111
+ function b() {
108
112
  for (const r of e.values()) r.history = [];
109
113
  }
110
- return i(), _(), {
111
- updateMetric: h,
114
+ return i(), S(), {
115
+ updateMetric: d,
112
116
  getHealthReport: c,
113
- addListener: E,
117
+ addListener: R,
114
118
  removeListener: H,
115
- stop: R,
119
+ stop: _,
116
120
  getMetricHistory: M,
117
- clearHistory: L
121
+ clearHistory: b
118
122
  };
119
123
  }
120
- let f = null;
124
+ let m = null;
121
125
  function C() {
122
- return f || (f = j()), f;
126
+ return m || (m = j()), m;
123
127
  }
124
128
  function V(e, t) {
125
129
  C().updateMetric(e, t);
@@ -173,16 +177,16 @@ function $() {
173
177
  }
174
178
  };
175
179
  }
176
- function P() {
177
- customElements.get("cer-suspense") || v("cer-suspense", () => {
180
+ function q() {
181
+ typeof customElements < "u" && customElements.get("cer-suspense") || v("cer-suspense", () => {
178
182
  const { pending: e } = k({ pending: !1 });
179
183
  return e ? l`<slot name="fallback"><span>Loading…</span></slot>` : l`<slot></slot>`;
180
184
  });
181
185
  }
182
- function q() {
183
- customElements.get("cer-error-boundary") || v("cer-error-boundary", () => {
184
- const e = m(!1), t = m("");
185
- return b((o) => {
186
+ function P() {
187
+ typeof customElements < "u" && customElements.get("cer-error-boundary") || v("cer-error-boundary", () => {
188
+ const e = f(!1), t = f("");
189
+ return L((o) => {
186
190
  e.value = !0, t.value = o.message;
187
191
  }), T({
188
192
  _cerHandleChildError: (o) => {
@@ -200,19 +204,19 @@ function q() {
200
204
  });
201
205
  }
202
206
  function Z() {
203
- P(), q(), N();
207
+ q(), P(), N();
204
208
  }
205
209
  function F(e) {
206
210
  if (typeof document > "u")
207
211
  return { portal: () => {
208
212
  }, destroy: () => {
209
213
  } };
210
- if (A())
214
+ if (D())
211
215
  return { portal: () => {
212
216
  }, destroy: () => {
213
217
  } };
214
- if (x()) {
215
- const o = I.getOrCreateState(null), n = o.peek();
218
+ if (A()) {
219
+ const o = x.getOrCreateState(null), n = o.peek();
216
220
  if (n !== null)
217
221
  return n;
218
222
  const i = g(e, () => o.initSilent(null));
@@ -233,8 +237,8 @@ function g(e, t) {
233
237
  const i = {};
234
238
  return {
235
239
  portal(c) {
236
- const d = c == null ? [] : Array.isArray(c) ? c : [c];
237
- p(n, d, void 0, i);
240
+ const h = c == null ? [] : Array.isArray(c) ? c : [c];
241
+ p(n, h, void 0, i);
238
242
  },
239
243
  destroy() {
240
244
  try {
@@ -246,46 +250,47 @@ function g(e, t) {
246
250
  };
247
251
  }
248
252
  export {
249
- me as ReactiveState,
253
+ te as ReactiveState,
250
254
  v as component,
251
- pe as computed,
252
- te as createComposable,
255
+ ne as computed,
256
+ oe as createComposable,
253
257
  j as createHealthMonitor,
254
- He as css,
255
- ye as decodeEntities,
256
- ne as defineModel,
257
- Le as devLog,
258
- ge as flushDOMUpdates,
259
- x as getCurrentComponentContext,
258
+ Re as css,
259
+ re as decodeEntities,
260
+ se as defineModel,
261
+ Me as devLog,
262
+ ae as flushDOMUpdates,
263
+ A as getCurrentComponentContext,
260
264
  C as getHealthMonitor,
261
265
  X as getHealthStatus,
262
266
  l as html,
263
- oe as inject,
264
- ve as isReactiveState,
265
- Ce as nextTick,
266
- re as provide,
267
- m as ref,
267
+ W as hydrateApp,
268
+ ie as inject,
269
+ ce as isReactiveState,
270
+ le as nextTick,
271
+ ue as provide,
272
+ f as ref,
268
273
  Z as registerBuiltinComponents,
269
- q as registerErrorBoundary,
274
+ P as registerErrorBoundary,
270
275
  N as registerKeepAlive,
271
- P as registerSuspense,
272
- we as scheduleWithPriority,
276
+ q as registerSuspense,
277
+ de as scheduleWithPriority,
273
278
  be as setDevMode,
274
- Se as unsafeHTML,
279
+ he as unsafeHTML,
275
280
  V as updateHealthMetric,
276
- se as useDesignTokens,
277
- ae as useEmit,
281
+ me as useDesignTokens,
282
+ fe as useEmit,
278
283
  T as useExpose,
279
- ie as useGlobalStyle,
280
- ce as useOnAttributeChanged,
281
- le as useOnConnected,
282
- ue as useOnDisconnected,
283
- b as useOnError,
284
+ pe as useGlobalStyle,
285
+ ye as useOnAttributeChanged,
286
+ ge as useOnConnected,
287
+ ve as useOnDisconnected,
288
+ L as useOnError,
284
289
  k as useProps,
285
- he as useSlots,
286
- de as useStyle,
290
+ Ce as useSlots,
291
+ we as useStyle,
287
292
  F as useTeleport,
288
- _e as watch,
289
- Re as watchEffect
293
+ Ee as watch,
294
+ Se as watchEffect
290
295
  };
291
296
  //# sourceMappingURL=custom-elements-runtime.es.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"custom-elements-runtime.es.js","sources":["../src/lib/runtime/monitoring/health-monitor.ts","../src/lib/keep-alive.ts","../src/lib/runtime/builtin-components.ts","../src/lib/teleport.ts"],"sourcesContent":["/**\n * Runtime Health Monitoring System\n * Tracks framework health metrics and provides early warning for potential issues\n */\n\nimport { devWarn, devError } from '../logger';\n\ninterface HealthMetric {\n name: string;\n value: number;\n threshold: number;\n status: 'healthy' | 'warning' | 'critical';\n lastUpdated: number;\n history: number[];\n}\n\ninterface HealthReport {\n overall: 'healthy' | 'warning' | 'critical';\n metrics: Record<string, HealthMetric>;\n timestamp: number;\n recommendations: string[];\n}\nexport type { HealthReport };\n\n/**\n * Public interface for a health monitor instance.\n * All state is managed internally via closures — no class syntax.\n */\nexport interface HealthMonitorInstance {\n /** Update a specific health metric value */\n updateMetric(name: string, value: number): void;\n /** Get the current health report */\n getHealthReport(): HealthReport;\n /** Add a listener to be notified when a health check runs */\n addListener(listener: (report: HealthReport) => void): void;\n /** Remove a previously registered listener */\n removeListener(listener: (report: HealthReport) => void): void;\n /** Stop the periodic health monitoring timer */\n stop(): void;\n /** Get historical values for a specific metric */\n getMetricHistory(name: string): number[];\n /** Clear all metric history */\n clearHistory(): void;\n}\n\nconst MAX_HISTORY_SIZE = 100;\nconst CHECK_INTERVAL = 30_000; // 30 seconds\n\nfunction calcStatus(\n value: number,\n threshold: number,\n metricName: string,\n): 'healthy' | 'warning' | 'critical' {\n if (metricName === 'jitCacheHitRate') {\n if (value < threshold * 0.5) return 'critical';\n if (value < threshold) return 'warning';\n return 'healthy';\n }\n if (value > threshold * 2) return 'critical';\n if (value > threshold) return 'warning';\n return 'healthy';\n}\n\nfunction buildRecommendations(metrics: Record<string, HealthMetric>): string[] {\n const out: string[] = [];\n if (metrics.memoryUsage?.status !== 'healthy')\n out.push(\n 'Consider reducing component complexity or implementing better memory cleanup',\n );\n if (metrics.averageRenderTime?.status !== 'healthy')\n out.push(\n 'Optimize component render functions - consider lazy loading or virtualization',\n );\n if (metrics.jitCacheHitRate?.status !== 'healthy')\n out.push(\n 'JIT CSS cache performance is poor - review CSS patterns for optimization',\n );\n if (metrics.componentErrorRate?.status !== 'healthy')\n out.push(\n 'High component error rate detected - review error handling and component logic',\n );\n if (metrics.activeReactiveStates?.status !== 'healthy')\n out.push(\n 'High number of reactive states - consider state consolidation or cleanup',\n );\n if (metrics.memoryLeakIndicator?.status !== 'healthy')\n out.push(\n 'Potential memory leak detected - review component cleanup and event listener management',\n );\n return out;\n}\n\n/**\n * Create a new health monitor instance.\n * All mutable state lives in closures — no `class` or `this`.\n */\nexport function createHealthMonitor(): HealthMonitorInstance {\n const metricsMap = new Map<string, HealthMetric>();\n const listeners = new Set<(report: HealthReport) => void>();\n let intervalId: ReturnType<typeof setInterval> | null = null;\n\n function addMetric(name: string, value: number, threshold: number): void {\n metricsMap.set(name, {\n name,\n value,\n threshold,\n status: 'healthy',\n lastUpdated: Date.now(),\n history: [],\n });\n }\n\n function initializeMetrics(): void {\n addMetric('activeComponents', 0, 1000);\n addMetric('componentCreateRate', 0, 50);\n addMetric('componentErrorRate', 0, 0.1);\n addMetric('memoryUsage', 0, 50 * 1024 * 1024);\n addMetric('memoryGrowthRate', 0, 1024 * 1024);\n addMetric('averageRenderTime', 0, 16);\n addMetric('slowRenderCount', 0, 10);\n addMetric('jitCacheHitRate', 100, 80);\n addMetric('activeReactiveStates', 0, 5000);\n addMetric('dependencyUpdates', 0, 100);\n addMetric('memoryLeakIndicator', 0, 0.1);\n }\n\n function updateMetric(name: string, value: number): void {\n const metric = metricsMap.get(name);\n if (!metric) return;\n metric.value = value;\n metric.lastUpdated = Date.now();\n metric.history.push(value);\n if (metric.history.length > MAX_HISTORY_SIZE) metric.history.shift();\n metric.status = calcStatus(value, metric.threshold, name);\n }\n\n function getHealthReport(): HealthReport {\n const snapshot: Record<string, HealthMetric> = {};\n let overall: 'healthy' | 'warning' | 'critical' = 'healthy';\n for (const [name, metric] of metricsMap) {\n snapshot[name] = { ...metric };\n if (metric.status === 'critical') overall = 'critical';\n else if (metric.status === 'warning' && overall === 'healthy')\n overall = 'warning';\n }\n return {\n overall,\n metrics: snapshot,\n timestamp: Date.now(),\n recommendations: buildRecommendations(snapshot),\n };\n }\n\n function updateMemoryMetrics(): void {\n if (\n 'memory' in performance &&\n (performance as Record<string, unknown>).memory\n ) {\n const mem = (performance as Record<string, unknown>).memory as {\n usedJSHeapSize: number;\n };\n updateMetric('memoryUsage', mem.usedJSHeapSize);\n const m = metricsMap.get('memoryUsage');\n if (m && m.history.length > 1) {\n const prev = m.history[m.history.length - 2];\n const curr = m.history[m.history.length - 1];\n updateMetric('memoryGrowthRate', Math.max(0, curr - prev));\n }\n }\n }\n\n function notifyListeners(report: HealthReport): void {\n for (const listener of listeners) {\n try {\n listener(report);\n } catch (e) {\n devError('Error in health monitor listener:', e);\n }\n }\n }\n\n function performHealthCheck(): void {\n updateMemoryMetrics();\n const report = getHealthReport();\n notifyListeners(report);\n if (report.overall === 'critical')\n devError(\n '🚨 Runtime Health: Critical issues detected',\n report.recommendations,\n );\n else if (report.overall === 'warning')\n devWarn(\n '⚠️ Runtime Health: Performance warnings',\n report.recommendations,\n );\n }\n\n function startMonitoring(): void {\n if (typeof window === 'undefined') return;\n intervalId = setInterval(performHealthCheck, CHECK_INTERVAL);\n }\n\n function stop(): void {\n if (intervalId !== null) {\n clearInterval(intervalId);\n intervalId = null;\n }\n }\n\n function addListener(listener: (report: HealthReport) => void): void {\n listeners.add(listener);\n }\n function removeListener(listener: (report: HealthReport) => void): void {\n listeners.delete(listener);\n }\n function getMetricHistory(name: string): number[] {\n const m = metricsMap.get(name);\n return m ? [...m.history] : [];\n }\n function clearHistory(): void {\n for (const m of metricsMap.values()) m.history = [];\n }\n\n initializeMetrics();\n startMonitoring();\n\n return {\n updateMetric,\n getHealthReport,\n addListener,\n removeListener,\n stop,\n getMetricHistory,\n clearHistory,\n };\n}\n\n// Global singleton\nlet _monitor: HealthMonitorInstance | null = null;\n\n/**\n * Get the global health monitor singleton instance.\n */\nexport function getHealthMonitor(): HealthMonitorInstance {\n if (!_monitor) _monitor = createHealthMonitor();\n return _monitor;\n}\n\n/**\n * Update a health metric from anywhere in the framework.\n */\nexport function updateHealthMetric(name: string, value: number): void {\n getHealthMonitor().updateMetric(name, value);\n}\n\n/**\n * Get the current health status report.\n */\nexport function getHealthStatus(): HealthReport {\n return getHealthMonitor().getHealthReport();\n}\n","/**\n * keep-alive.ts\n *\n * Preserves component state when a component is removed from and later\n * re-inserted into the DOM. By default, custom elements lose all JavaScript\n * state when `disconnectedCallback` fires. `cer-keep-alive` intercepts\n * that lifecycle and keeps the child element alive in memory, re-attaching\n * it when a matching component is re-inserted.\n *\n * ## Usage\n *\n * Wrap any custom element with `<cer-keep-alive>`:\n * ```html\n * <cer-keep-alive>\n * <my-counter></my-counter>\n * </cer-keep-alive>\n * ```\n *\n * Or register it programmatically:\n * ```ts\n * import { registerKeepAlive } from '@jasonshimmy/custom-elements-runtime';\n * registerKeepAlive(); // registers <cer-keep-alive> globally\n * ```\n *\n * ## How it works\n *\n * `cer-keep-alive` uses a slotted layout. When a slotted child component is\n * about to leave the DOM (via a re-render of a parent), KeepAlive intercepts\n * `slotchange` events and preserves the detached child element in an internal\n * cache keyed by tag name. When the same tag re-appears in the slot, the\n * cached element is re-inserted, restoring all JavaScript state.\n *\n * ## Limitations\n *\n * - The first slot child per tag name is cached. Multiple children with the\n * same tag use separate cache entries keyed by their `id` attribute.\n * - Only components registered with the same tag name are matched.\n * - Cache entries can be manually evicted with `clearCache()`.\n */\n\n/** Cache key = tagName[:id] */\ntype CacheKey = string;\n\n/**\n * Register the `<cer-keep-alive>` custom element.\n * Safe to call multiple times — subsequent calls are no-ops.\n *\n * @example\n * ```ts\n * import { registerKeepAlive } from '@jasonshimmy/custom-elements-runtime';\n * registerKeepAlive();\n * ```\n */\nexport function registerKeepAlive(): void {\n if (\n typeof window === 'undefined' ||\n typeof customElements === 'undefined' ||\n customElements.get('cer-keep-alive')\n ) {\n return;\n }\n\n customElements.define('cer-keep-alive', createKeepAliveClass());\n}\n\nfunction createKeepAliveClass(): CustomElementConstructor {\n return class CerKeepAlive extends HTMLElement {\n /** Preserved component instances keyed by tag[:id]. */\n private _cache = new Map<CacheKey, Element>();\n private _slot: HTMLSlotElement | null = null;\n private _slotListener: (() => void) | null = null;\n\n connectedCallback(): void {\n if (!this.shadowRoot) {\n this.attachShadow({ mode: 'open' });\n }\n\n if (!this.shadowRoot!.querySelector('slot')) {\n this.shadowRoot!.innerHTML = '<slot></slot>';\n }\n\n this._slot = this.shadowRoot!.querySelector('slot');\n if (this._slot) {\n this._slotListener = () => this._handleSlotChange();\n this._slot.addEventListener('slotchange', this._slotListener);\n // Process current slotted content\n this._handleSlotChange();\n }\n }\n\n disconnectedCallback(): void {\n if (this._slot && this._slotListener) {\n this._slot.removeEventListener('slotchange', this._slotListener);\n }\n this._slotListener = null;\n }\n\n /**\n * Evict a cached element by its cache key (`tagName` or `tagName:id`).\n * The evicted element is disconnected and removed from the cache.\n */\n clearCache(key?: CacheKey): void {\n if (key) {\n this._cache.delete(key);\n } else {\n this._cache.clear();\n }\n }\n\n private _handleSlotChange(): void {\n if (!this._slot) return;\n\n const slottedElements = this._slot.assignedElements({ flatten: true });\n\n for (const child of slottedElements) {\n const cacheKey = this._buildCacheKey(child);\n\n if (!this._cache.has(cacheKey)) {\n // New element — cache it so we can restore it later\n this._cache.set(cacheKey, child);\n } else {\n const cached = this._cache.get(cacheKey)!;\n if (cached !== child) {\n // A different instance appeared for the same slot.\n // Replace it with the cached instance to restore state.\n try {\n child.parentNode?.replaceChild(cached, child);\n } catch {\n // If replacement fails, update the cache with the new element\n this._cache.set(cacheKey, child);\n }\n }\n }\n }\n }\n\n private _buildCacheKey(el: Element): CacheKey {\n const tag = el.tagName.toLowerCase();\n const id = el.getAttribute('id');\n return id ? `${tag}:${id}` : tag;\n }\n };\n}\n","/**\n * Built-in utility components provided by the custom-elements runtime.\n *\n * These components are registered automatically when this module is imported.\n * They are designed to be minimal, tree-shakeable, and zero-dependency.\n *\n * Included components:\n * - `<cer-suspense>` — Shows a fallback while async work is pending\n * - `<cer-error-boundary>` — Catches render errors and shows a fallback UI\n * - `<cer-keep-alive>` — Preserves component state across DOM removal/re-insertion\n */\n\nimport { component } from './component';\nimport { html } from './template-compiler';\nimport { ref } from './reactive';\nimport { useProps, useOnError, useExpose } from './hooks';\nimport { registerKeepAlive } from '../keep-alive';\n\n// ── cer-suspense ──────────────────────────────────────────────────────────────\n\n/**\n * A built-in component that conditionally renders either the default slot\n * content or the `fallback` slot content, controlled by the `pending` prop.\n *\n * Use the `pending` attribute/property to signal that async work is in\n * progress; the component will swap to the `fallback` slot until `pending`\n * becomes falsy.\n *\n * @example\n * ```html\n * <cer-suspense pending>\n * <!-- shown when pending=false -->\n * <my-async-content></my-async-content>\n *\n * <!-- shown while pending=true -->\n * <div slot=\"fallback\">Loading…</div>\n * </cer-suspense>\n * ```\n *\n * @example Programmatic usage\n * ```ts\n * component('my-data-loader', () => {\n * const pending = ref(true);\n * useOnConnected(async () => {\n * await fetchData();\n * pending.value = false;\n * });\n * return html`\n * <cer-suspense pending=\"${pending.value}\">\n * <my-data-view></my-data-view>\n * <div slot=\"fallback\">Loading data…</div>\n * </cer-suspense>\n * `;\n * });\n * ```\n */\nexport function registerSuspense(): void {\n if (customElements.get('cer-suspense')) return;\n\n component('cer-suspense', () => {\n const { pending } = useProps({ pending: false });\n\n return pending\n ? html`<slot name=\"fallback\"><span>Loading…</span></slot>`\n : html`<slot></slot>`;\n });\n}\n\n// ── cer-error-boundary ────────────────────────────────────────────────────────\n\n/**\n * A built-in component that catches errors thrown during child component\n * rendering and displays a fallback UI instead of crashing the page.\n *\n * Errors are caught via the `useOnError` lifecycle hook. Once an error is\n * caught the component switches to showing the `fallback` named slot (or a\n * default \"Something went wrong\" message if no fallback slot is provided).\n *\n * Call the custom `reset()` method on the element to clear the error and\n * attempt re-rendering the default slot.\n *\n * @example\n * ```html\n * <cer-error-boundary>\n * <my-risky-component></my-risky-component>\n *\n * <div slot=\"fallback\">\n * <p>Something went wrong. <button onclick=\"this.closest('cer-error-boundary').reset()\">Retry</button></p>\n * </div>\n * </cer-error-boundary>\n * ```\n */\nexport function registerErrorBoundary(): void {\n if (customElements.get('cer-error-boundary')) return;\n\n component('cer-error-boundary', () => {\n const hasError = ref(false);\n const errorMessage = ref('');\n\n useOnError((err: Error) => {\n hasError.value = true;\n errorMessage.value = err.message;\n });\n\n // Expose a reset() method so parent templates can call\n // `errorBoundaryRef.value.reset()` to clear the error and retry.\n // Also expose an internal `_cerHandleChildError` receiver so that the\n // component runtime can propagate uncaught errors from slotted child\n // components up to the nearest ancestor <cer-error-boundary>.\n useExpose({\n _cerHandleChildError: (err: unknown) => {\n // Use peek() to read the current value without registering a reactive\n // dependency — the child component's render context may be active when\n // this handler runs, and we must not accidentally subscribe the child\n // to this boundary's internal state.\n if (!hasError.peek()) {\n hasError.value = true;\n errorMessage.value = err instanceof Error ? err.message : String(err);\n }\n },\n reset: () => {\n hasError.value = false;\n errorMessage.value = '';\n },\n });\n\n return hasError.value\n ? html`<slot name=\"fallback\"\n ><div role=\"alert\">\n <strong>Something went wrong.</strong>\n ${errorMessage.value ? html`<p>${errorMessage.value}</p>` : html``}\n </div></slot\n >`\n : html`<slot></slot>`;\n });\n}\n\n// ── Auto-register all components ─────────────────────────────────────────────\n\n/**\n * Register all built-in components (`cer-suspense`, `cer-error-boundary`,\n * `cer-keep-alive`).\n * Safe to call multiple times — each registration is guarded by a\n * `customElements.get()` check.\n */\nexport function registerBuiltinComponents(): void {\n registerSuspense();\n registerErrorBoundary();\n registerKeepAlive();\n}\n","/**\n * teleport.ts\n *\n * Renders virtual DOM content into an arbitrary DOM target located outside\n * the current component's Shadow Root. Useful for modals, tooltips, popovers,\n * and any UI that must visually escape the component boundary.\n *\n * @example\n * ```ts\n * import { component, html, ref, useOnDisconnected, useTeleport } from '@jasonshimmy/custom-elements-runtime';\n *\n * component('modal-trigger', () => {\n * const isOpen = ref(false);\n *\n * // Render modal content into <body> outside the shadow root\n * const { portal, destroy } = useTeleport('#modal-root');\n * useOnDisconnected(destroy);\n *\n * // Call portal() to update the teleported content on each render\n * if (isOpen.value) {\n * portal(html`<div class=\"modal\">\n * <h2>Hello</h2>\n * <button @click=\"${() => (isOpen.value = false)}\">Close</button>\n * </div>`);\n * } else {\n * portal(null);\n * }\n *\n * return html`\n * <button @click=\"${() => (isOpen.value = true)}\">Open modal</button>\n * `;\n * });\n * ```\n */\n\nimport type { VNode, VDomRefs } from './runtime/types';\nimport { vdomRenderer } from './runtime/vdom';\nimport { reactiveSystem } from './runtime/reactive';\nimport { getCurrentComponentContext, isDiscoveryRender } from './runtime/hooks';\n\n/** Handle returned by {@link useTeleport} for managing a portal. */\nexport interface TeleportHandle {\n /**\n * Render (or clear) content at the teleport target.\n * Pass `null` or `undefined` to remove previously rendered content.\n */\n portal(content: VNode | VNode[] | null | undefined): void;\n\n /**\n * Destroy the teleport container and clean up all rendered content.\n * Call this in `useOnDisconnected` to prevent memory leaks.\n */\n destroy(): void;\n}\n\n/**\n * Create a teleport portal that renders content outside the current Shadow Root.\n *\n * @param target - A CSS selector string or an `Element` reference to render into.\n * @returns A {@link TeleportHandle} with `portal()` (update content) and `destroy()` (cleanup).\n *\n * @example\n * ```ts\n * import { component, html, useOnDisconnected, useTeleport } from '@jasonshimmy/custom-elements-runtime';\n *\n * component('my-tooltip', () => {\n * const { portal, destroy } = useTeleport('body');\n * useOnDisconnected(destroy);\n *\n * portal(html`<div class=\"tooltip\">Tooltip content</div>`);\n * return html`<span>Hover me</span>`;\n * });\n * ```\n */\nexport function useTeleport(target: string | Element): TeleportHandle {\n // SSR guard\n if (typeof document === 'undefined') {\n return { portal: () => {}, destroy: () => {} };\n }\n\n // During discovery render the component is not yet mounted — return a no-op\n // handle so the library can detect props/hooks without side-effects.\n if (isDiscoveryRender()) {\n return { portal: () => {}, destroy: () => {} };\n }\n\n // If called inside a component render, use the reactive state-index slot\n // mechanism to ensure the same handle is returned on every re-render of the\n // same component instance. Without this, each re-render would create a new\n // <cer-teleport> container in the target, leaking all but the last one.\n const ctx = getCurrentComponentContext();\n if (ctx) {\n // getOrCreateState uses an incrementing stateIndex that is reset to 0 at\n // the start of each render, so the same call site always gets the same slot.\n const slot = reactiveSystem.getOrCreateState<TeleportHandle | null>(null);\n const existing = slot.peek();\n if (existing !== null) {\n return existing;\n }\n // First render: create the handle and store it without triggering a\n // reactive update (initSilent bypasses triggerUpdate).\n // Pass a slot-invalidation callback so that destroy() clears the slot,\n // allowing a reconnected component to create a fresh container.\n const handle = _createTeleportHandle(target, () => slot.initSilent(null));\n slot.initSilent(handle);\n return handle;\n }\n\n // Outside a component context (e.g. called directly in tests or scripts):\n // fall through to a non-cached, non-stable handle.\n return _createTeleportHandle(target);\n}\n\n/** Internal: create a fresh teleport handle pointing at `target`.\n * @param onDestroy - Optional callback invoked after cleanup in destroy(), used\n * to invalidate a cached slot so the next render creates a fresh handle.\n */\nfunction _createTeleportHandle(\n target: string | Element,\n onDestroy?: () => void,\n): TeleportHandle {\n const targetEl =\n typeof target === 'string'\n ? (document.querySelector(target) as Element | null)\n : target;\n\n if (!targetEl) {\n console.warn(\n `[useTeleport] Target \"${String(target)}\" not found in the document. ` +\n 'Teleported content will not be rendered.',\n );\n return { portal: () => {}, destroy: () => {} };\n }\n\n // Create a dedicated container so we never clobber sibling content.\n const container = document.createElement('cer-teleport');\n container.dataset.cerTeleport = '';\n targetEl.appendChild(container);\n\n // Shared refs bag — passed consistently so ref directives work across updates.\n const refs: VDomRefs = {};\n\n const handle: TeleportHandle = {\n portal(content: VNode | VNode[] | null | undefined): void {\n const nodes: VNode[] =\n content == null ? [] : Array.isArray(content) ? content : [content];\n // vdomRenderer stores _prevVNode/_prevDom on the root object for diffing.\n // Casting to ShadowRoot is safe: we only access properties that exist on\n // HTMLElement (firstChild, appendChild, replaceChild, childNodes).\n vdomRenderer(container as unknown as ShadowRoot, nodes, undefined, refs);\n },\n\n destroy(): void {\n // Render empty nodes to clean up event listeners and refs.\n try {\n vdomRenderer(container as unknown as ShadowRoot, [], undefined, refs);\n } catch {\n /* best-effort cleanup */\n }\n if (container.parentNode) {\n container.parentNode.removeChild(container);\n }\n // Invalidate the cached slot so that if the component reconnects and\n // re-renders, useTeleport() creates a fresh container rather than\n // reusing this destroyed one.\n onDestroy?.();\n },\n };\n\n return handle;\n}\n"],"names":["MAX_HISTORY_SIZE","CHECK_INTERVAL","calcStatus","value","threshold","metricName","buildRecommendations","metrics","out","createHealthMonitor","metricsMap","listeners","intervalId","addMetric","name","initializeMetrics","updateMetric","metric","getHealthReport","snapshot","overall","updateMemoryMetrics","mem","m","prev","curr","notifyListeners","report","listener","e","devError","performHealthCheck","devWarn","startMonitoring","stop","addListener","removeListener","getMetricHistory","clearHistory","_monitor","getHealthMonitor","updateHealthMetric","getHealthStatus","registerKeepAlive","createKeepAliveClass","key","slottedElements","child","cacheKey","cached","el","tag","id","registerSuspense","component","pending","useProps","html","registerErrorBoundary","hasError","ref","errorMessage","useOnError","err","useExpose","registerBuiltinComponents","useTeleport","target","isDiscoveryRender","getCurrentComponentContext","slot","reactiveSystem","existing","handle","_createTeleportHandle","onDestroy","targetEl","container","refs","content","nodes","vdomRenderer"],"mappings":";;;;;;;;AA6CA,MAAMA,IAAmB,KACnBC,IAAiB;AAEvB,SAASC,EACPC,GACAC,GACAC,GACoC;AACpC,SAAIA,MAAe,oBACbF,IAAQC,IAAY,MAAY,aAChCD,IAAQC,IAAkB,YACvB,YAELD,IAAQC,IAAY,IAAU,aAC9BD,IAAQC,IAAkB,YACvB;AACT;AAEA,SAASE,EAAqBC,GAAiD;AAC7E,QAAMC,IAAgB,CAAA;AACtB,SAAID,EAAQ,aAAa,WAAW,aAClCC,EAAI;AAAA,IACF;AAAA,EAAA,GAEAD,EAAQ,mBAAmB,WAAW,aACxCC,EAAI;AAAA,IACF;AAAA,EAAA,GAEAD,EAAQ,iBAAiB,WAAW,aACtCC,EAAI;AAAA,IACF;AAAA,EAAA,GAEAD,EAAQ,oBAAoB,WAAW,aACzCC,EAAI;AAAA,IACF;AAAA,EAAA,GAEAD,EAAQ,sBAAsB,WAAW,aAC3CC,EAAI;AAAA,IACF;AAAA,EAAA,GAEAD,EAAQ,qBAAqB,WAAW,aAC1CC,EAAI;AAAA,IACF;AAAA,EAAA,GAEGA;AACT;AAMO,SAASC,IAA6C;AAC3D,QAAMC,wBAAiB,IAAA,GACjBC,wBAAgB,IAAA;AACtB,MAAIC,IAAoD;AAExD,WAASC,EAAUC,GAAcX,GAAeC,GAAyB;AACvE,IAAAM,EAAW,IAAII,GAAM;AAAA,MACnB,MAAAA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MAAM;AAAA,IAAC,GAAG,SAAS,MAAM;AAAA,IAAC,EAAA;AAI7C,QAAMU,IAAY,SAAS,cAAc,cAAc;AACvD,EAAAA,EAAU,QAAQ,cAAc,IAChCD,EAAS,YAAYC,CAAS;AAG9B,QAAMC,IAAiB,CAAA;AA6BvB,SA3B+B;AAAA,IAC7B,OAAOC,GAAmD;AACxD,YAAMC,IACJD,KAAW,OAAO,KAAK,MAAM,QAAQA,CAAO,IAAIA,IAAU,CAACA,CAAO;AAIpE,MAAAE,EAAaJ,GAAoCG,GAAO,QAAWF,CAAI;AAAA,IACzE;AAAA,IAEA,UAAgB;AAEd,UAAI;AACF,QAAAG,EAAaJ,GAAoC,CAAA,GAAI,QAAWC,CAAI;AAAA,MACtE,QAAQ;AAAA,MAER;AACA,MAAID,EAAU,cACZA,EAAU,WAAW,YAAYA,CAAS,GAK5CF,IAAA;AAAA,IACF;AAAA,EAAA;AAIJ;"}
1
+ {"version":3,"file":"custom-elements-runtime.es.js","sources":["../src/lib/runtime/hydration.ts","../src/lib/runtime/monitoring/health-monitor.ts","../src/lib/keep-alive.ts","../src/lib/runtime/builtin-components.ts","../src/lib/teleport.ts"],"sourcesContent":["/**\n * Client-side hydration helpers.\n *\n * When the server renders with `dsd: true`, each custom element's shadow DOM\n * is already present in the HTML via a Declarative Shadow DOM template. The\n * browser parses that template and attaches the shadow root before any\n * JavaScript runs. When the JS bundle loads, the custom element constructors\n * detect the existing shadow root and skip the `attachShadow()` call, then\n * hydrate (attach reactivity to) the existing DOM on `connectedCallback`.\n *\n * `hydrateApp` is a signal/entry point for this process. In most cases custom\n * elements self-hydrate automatically on connection — this function is useful\n * when you need to explicitly trigger or defer the hydration of a subtree.\n */\n\n/**\n * Trigger hydration for all registered custom elements within `root`.\n *\n * In practice, custom elements self-hydrate as soon as their class definition\n * is registered and the element is connected to the DOM. Call `hydrateApp`\n * after importing and calling `component()` for all your components to signal\n * that the page is ready for reactive activation.\n *\n * @param root - The root element to hydrate. Defaults to `document`.\n *\n * @example\n * ```ts\n * import { component, hydrateApp } from '@jasonshimmy/custom-elements-runtime';\n * import './components'; // registers all components via component()\n *\n * hydrateApp(); // activate all DSD-rendered components on the page\n * ```\n */\nexport function hydrateApp(root: Element | Document = document): void {\n if (typeof CustomEvent === 'undefined') return;\n const target =\n root instanceof Document ? root.documentElement : (root as Element);\n target.dispatchEvent(\n new CustomEvent('cer:hydrate', { bubbles: true, composed: true }),\n );\n}\n","/**\n * Runtime Health Monitoring System\n * Tracks framework health metrics and provides early warning for potential issues\n */\n\nimport { devWarn, devError } from '../logger';\n\ninterface HealthMetric {\n name: string;\n value: number;\n threshold: number;\n status: 'healthy' | 'warning' | 'critical';\n lastUpdated: number;\n history: number[];\n}\n\ninterface HealthReport {\n overall: 'healthy' | 'warning' | 'critical';\n metrics: Record<string, HealthMetric>;\n timestamp: number;\n recommendations: string[];\n}\nexport type { HealthReport };\n\n/**\n * Public interface for a health monitor instance.\n * All state is managed internally via closures — no class syntax.\n */\nexport interface HealthMonitorInstance {\n /** Update a specific health metric value */\n updateMetric(name: string, value: number): void;\n /** Get the current health report */\n getHealthReport(): HealthReport;\n /** Add a listener to be notified when a health check runs */\n addListener(listener: (report: HealthReport) => void): void;\n /** Remove a previously registered listener */\n removeListener(listener: (report: HealthReport) => void): void;\n /** Stop the periodic health monitoring timer */\n stop(): void;\n /** Get historical values for a specific metric */\n getMetricHistory(name: string): number[];\n /** Clear all metric history */\n clearHistory(): void;\n}\n\nconst MAX_HISTORY_SIZE = 100;\nconst CHECK_INTERVAL = 30_000; // 30 seconds\n\nfunction calcStatus(\n value: number,\n threshold: number,\n metricName: string,\n): 'healthy' | 'warning' | 'critical' {\n if (metricName === 'jitCacheHitRate') {\n if (value < threshold * 0.5) return 'critical';\n if (value < threshold) return 'warning';\n return 'healthy';\n }\n if (value > threshold * 2) return 'critical';\n if (value > threshold) return 'warning';\n return 'healthy';\n}\n\nfunction buildRecommendations(metrics: Record<string, HealthMetric>): string[] {\n const out: string[] = [];\n if (metrics.memoryUsage?.status !== 'healthy')\n out.push(\n 'Consider reducing component complexity or implementing better memory cleanup',\n );\n if (metrics.averageRenderTime?.status !== 'healthy')\n out.push(\n 'Optimize component render functions - consider lazy loading or virtualization',\n );\n if (metrics.jitCacheHitRate?.status !== 'healthy')\n out.push(\n 'JIT CSS cache performance is poor - review CSS patterns for optimization',\n );\n if (metrics.componentErrorRate?.status !== 'healthy')\n out.push(\n 'High component error rate detected - review error handling and component logic',\n );\n if (metrics.activeReactiveStates?.status !== 'healthy')\n out.push(\n 'High number of reactive states - consider state consolidation or cleanup',\n );\n if (metrics.memoryLeakIndicator?.status !== 'healthy')\n out.push(\n 'Potential memory leak detected - review component cleanup and event listener management',\n );\n return out;\n}\n\n/**\n * Create a new health monitor instance.\n * All mutable state lives in closures — no `class` or `this`.\n */\nexport function createHealthMonitor(): HealthMonitorInstance {\n const metricsMap = new Map<string, HealthMetric>();\n const listeners = new Set<(report: HealthReport) => void>();\n let intervalId: ReturnType<typeof setInterval> | null = null;\n\n function addMetric(name: string, value: number, threshold: number): void {\n metricsMap.set(name, {\n name,\n value,\n threshold,\n status: 'healthy',\n lastUpdated: Date.now(),\n history: [],\n });\n }\n\n function initializeMetrics(): void {\n addMetric('activeComponents', 0, 1000);\n addMetric('componentCreateRate', 0, 50);\n addMetric('componentErrorRate', 0, 0.1);\n addMetric('memoryUsage', 0, 50 * 1024 * 1024);\n addMetric('memoryGrowthRate', 0, 1024 * 1024);\n addMetric('averageRenderTime', 0, 16);\n addMetric('slowRenderCount', 0, 10);\n addMetric('jitCacheHitRate', 100, 80);\n addMetric('activeReactiveStates', 0, 5000);\n addMetric('dependencyUpdates', 0, 100);\n addMetric('memoryLeakIndicator', 0, 0.1);\n }\n\n function updateMetric(name: string, value: number): void {\n const metric = metricsMap.get(name);\n if (!metric) return;\n metric.value = value;\n metric.lastUpdated = Date.now();\n metric.history.push(value);\n if (metric.history.length > MAX_HISTORY_SIZE) metric.history.shift();\n metric.status = calcStatus(value, metric.threshold, name);\n }\n\n function getHealthReport(): HealthReport {\n const snapshot: Record<string, HealthMetric> = {};\n let overall: 'healthy' | 'warning' | 'critical' = 'healthy';\n for (const [name, metric] of metricsMap) {\n snapshot[name] = { ...metric };\n if (metric.status === 'critical') overall = 'critical';\n else if (metric.status === 'warning' && overall === 'healthy')\n overall = 'warning';\n }\n return {\n overall,\n metrics: snapshot,\n timestamp: Date.now(),\n recommendations: buildRecommendations(snapshot),\n };\n }\n\n function updateMemoryMetrics(): void {\n if (\n 'memory' in performance &&\n (performance as Record<string, unknown>).memory\n ) {\n const mem = (performance as Record<string, unknown>).memory as {\n usedJSHeapSize: number;\n };\n updateMetric('memoryUsage', mem.usedJSHeapSize);\n const m = metricsMap.get('memoryUsage');\n if (m && m.history.length > 1) {\n const prev = m.history[m.history.length - 2];\n const curr = m.history[m.history.length - 1];\n updateMetric('memoryGrowthRate', Math.max(0, curr - prev));\n }\n }\n }\n\n function notifyListeners(report: HealthReport): void {\n for (const listener of listeners) {\n try {\n listener(report);\n } catch (e) {\n devError('Error in health monitor listener:', e);\n }\n }\n }\n\n function performHealthCheck(): void {\n updateMemoryMetrics();\n const report = getHealthReport();\n notifyListeners(report);\n if (report.overall === 'critical')\n devError(\n '🚨 Runtime Health: Critical issues detected',\n report.recommendations,\n );\n else if (report.overall === 'warning')\n devWarn(\n '⚠️ Runtime Health: Performance warnings',\n report.recommendations,\n );\n }\n\n function startMonitoring(): void {\n if (typeof window === 'undefined') return;\n intervalId = setInterval(performHealthCheck, CHECK_INTERVAL);\n }\n\n function stop(): void {\n if (intervalId !== null) {\n clearInterval(intervalId);\n intervalId = null;\n }\n }\n\n function addListener(listener: (report: HealthReport) => void): void {\n listeners.add(listener);\n }\n function removeListener(listener: (report: HealthReport) => void): void {\n listeners.delete(listener);\n }\n function getMetricHistory(name: string): number[] {\n const m = metricsMap.get(name);\n return m ? [...m.history] : [];\n }\n function clearHistory(): void {\n for (const m of metricsMap.values()) m.history = [];\n }\n\n initializeMetrics();\n startMonitoring();\n\n return {\n updateMetric,\n getHealthReport,\n addListener,\n removeListener,\n stop,\n getMetricHistory,\n clearHistory,\n };\n}\n\n// Global singleton\nlet _monitor: HealthMonitorInstance | null = null;\n\n/**\n * Get the global health monitor singleton instance.\n */\nexport function getHealthMonitor(): HealthMonitorInstance {\n if (!_monitor) _monitor = createHealthMonitor();\n return _monitor;\n}\n\n/**\n * Update a health metric from anywhere in the framework.\n */\nexport function updateHealthMetric(name: string, value: number): void {\n getHealthMonitor().updateMetric(name, value);\n}\n\n/**\n * Get the current health status report.\n */\nexport function getHealthStatus(): HealthReport {\n return getHealthMonitor().getHealthReport();\n}\n","/**\n * keep-alive.ts\n *\n * Preserves component state when a component is removed from and later\n * re-inserted into the DOM. By default, custom elements lose all JavaScript\n * state when `disconnectedCallback` fires. `cer-keep-alive` intercepts\n * that lifecycle and keeps the child element alive in memory, re-attaching\n * it when a matching component is re-inserted.\n *\n * ## Usage\n *\n * Wrap any custom element with `<cer-keep-alive>`:\n * ```html\n * <cer-keep-alive>\n * <my-counter></my-counter>\n * </cer-keep-alive>\n * ```\n *\n * Or register it programmatically:\n * ```ts\n * import { registerKeepAlive } from '@jasonshimmy/custom-elements-runtime';\n * registerKeepAlive(); // registers <cer-keep-alive> globally\n * ```\n *\n * ## How it works\n *\n * `cer-keep-alive` uses a slotted layout. When a slotted child component is\n * about to leave the DOM (via a re-render of a parent), KeepAlive intercepts\n * `slotchange` events and preserves the detached child element in an internal\n * cache keyed by tag name. When the same tag re-appears in the slot, the\n * cached element is re-inserted, restoring all JavaScript state.\n *\n * ## Limitations\n *\n * - The first slot child per tag name is cached. Multiple children with the\n * same tag use separate cache entries keyed by their `id` attribute.\n * - Only components registered with the same tag name are matched.\n * - Cache entries can be manually evicted with `clearCache()`.\n */\n\n/** Cache key = tagName[:id] */\ntype CacheKey = string;\n\n/**\n * Register the `<cer-keep-alive>` custom element.\n * Safe to call multiple times — subsequent calls are no-ops.\n *\n * @example\n * ```ts\n * import { registerKeepAlive } from '@jasonshimmy/custom-elements-runtime';\n * registerKeepAlive();\n * ```\n */\nexport function registerKeepAlive(): void {\n if (\n typeof window === 'undefined' ||\n typeof customElements === 'undefined' ||\n customElements.get('cer-keep-alive')\n ) {\n return;\n }\n\n customElements.define('cer-keep-alive', createKeepAliveClass());\n}\n\nfunction createKeepAliveClass(): CustomElementConstructor {\n return class CerKeepAlive extends HTMLElement {\n /** Preserved component instances keyed by tag[:id]. */\n private _cache = new Map<CacheKey, Element>();\n private _slot: HTMLSlotElement | null = null;\n private _slotListener: (() => void) | null = null;\n\n connectedCallback(): void {\n if (!this.shadowRoot) {\n this.attachShadow({ mode: 'open' });\n }\n\n if (!this.shadowRoot!.querySelector('slot')) {\n this.shadowRoot!.innerHTML = '<slot></slot>';\n }\n\n this._slot = this.shadowRoot!.querySelector('slot');\n if (this._slot) {\n this._slotListener = () => this._handleSlotChange();\n this._slot.addEventListener('slotchange', this._slotListener);\n // Process current slotted content\n this._handleSlotChange();\n }\n }\n\n disconnectedCallback(): void {\n if (this._slot && this._slotListener) {\n this._slot.removeEventListener('slotchange', this._slotListener);\n }\n this._slotListener = null;\n }\n\n /**\n * Evict a cached element by its cache key (`tagName` or `tagName:id`).\n * The evicted element is disconnected and removed from the cache.\n */\n clearCache(key?: CacheKey): void {\n if (key) {\n this._cache.delete(key);\n } else {\n this._cache.clear();\n }\n }\n\n private _handleSlotChange(): void {\n if (!this._slot) return;\n\n const slottedElements = this._slot.assignedElements({ flatten: true });\n\n for (const child of slottedElements) {\n const cacheKey = this._buildCacheKey(child);\n\n if (!this._cache.has(cacheKey)) {\n // New element — cache it so we can restore it later\n this._cache.set(cacheKey, child);\n } else {\n const cached = this._cache.get(cacheKey)!;\n if (cached !== child) {\n // A different instance appeared for the same slot.\n // Replace it with the cached instance to restore state.\n try {\n child.parentNode?.replaceChild(cached, child);\n } catch {\n // If replacement fails, update the cache with the new element\n this._cache.set(cacheKey, child);\n }\n }\n }\n }\n }\n\n private _buildCacheKey(el: Element): CacheKey {\n const tag = el.tagName.toLowerCase();\n const id = el.getAttribute('id');\n return id ? `${tag}:${id}` : tag;\n }\n };\n}\n","/**\n * Built-in utility components provided by the custom-elements runtime.\n *\n * These components are registered automatically when this module is imported.\n * They are designed to be minimal, tree-shakeable, and zero-dependency.\n *\n * Included components:\n * - `<cer-suspense>` — Shows a fallback while async work is pending\n * - `<cer-error-boundary>` — Catches render errors and shows a fallback UI\n * - `<cer-keep-alive>` — Preserves component state across DOM removal/re-insertion\n */\n\nimport { component } from './component';\nimport { html } from './template-compiler';\nimport { ref } from './reactive';\nimport { useProps, useOnError, useExpose } from './hooks';\nimport { registerKeepAlive } from '../keep-alive';\n\n// ── cer-suspense ──────────────────────────────────────────────────────────────\n\n/**\n * A built-in component that conditionally renders either the default slot\n * content or the `fallback` slot content, controlled by the `pending` prop.\n *\n * Use the `pending` attribute/property to signal that async work is in\n * progress; the component will swap to the `fallback` slot until `pending`\n * becomes falsy.\n *\n * @example\n * ```html\n * <cer-suspense pending>\n * <!-- shown when pending=false -->\n * <my-async-content></my-async-content>\n *\n * <!-- shown while pending=true -->\n * <div slot=\"fallback\">Loading…</div>\n * </cer-suspense>\n * ```\n *\n * @example Programmatic usage\n * ```ts\n * component('my-data-loader', () => {\n * const pending = ref(true);\n * useOnConnected(async () => {\n * await fetchData();\n * pending.value = false;\n * });\n * return html`\n * <cer-suspense pending=\"${pending.value}\">\n * <my-data-view></my-data-view>\n * <div slot=\"fallback\">Loading data…</div>\n * </cer-suspense>\n * `;\n * });\n * ```\n */\nexport function registerSuspense(): void {\n if (typeof customElements !== 'undefined' && customElements.get('cer-suspense')) return;\n\n component('cer-suspense', () => {\n const { pending } = useProps({ pending: false });\n\n return pending\n ? html`<slot name=\"fallback\"><span>Loading…</span></slot>`\n : html`<slot></slot>`;\n });\n}\n\n// ── cer-error-boundary ────────────────────────────────────────────────────────\n\n/**\n * A built-in component that catches errors thrown during child component\n * rendering and displays a fallback UI instead of crashing the page.\n *\n * Errors are caught via the `useOnError` lifecycle hook. Once an error is\n * caught the component switches to showing the `fallback` named slot (or a\n * default \"Something went wrong\" message if no fallback slot is provided).\n *\n * Call the custom `reset()` method on the element to clear the error and\n * attempt re-rendering the default slot.\n *\n * @example\n * ```html\n * <cer-error-boundary>\n * <my-risky-component></my-risky-component>\n *\n * <div slot=\"fallback\">\n * <p>Something went wrong. <button onclick=\"this.closest('cer-error-boundary').reset()\">Retry</button></p>\n * </div>\n * </cer-error-boundary>\n * ```\n */\nexport function registerErrorBoundary(): void {\n if (typeof customElements !== 'undefined' && customElements.get('cer-error-boundary')) return;\n\n component('cer-error-boundary', () => {\n const hasError = ref(false);\n const errorMessage = ref('');\n\n useOnError((err: Error) => {\n hasError.value = true;\n errorMessage.value = err.message;\n });\n\n // Expose a reset() method so parent templates can call\n // `errorBoundaryRef.value.reset()` to clear the error and retry.\n // Also expose an internal `_cerHandleChildError` receiver so that the\n // component runtime can propagate uncaught errors from slotted child\n // components up to the nearest ancestor <cer-error-boundary>.\n useExpose({\n _cerHandleChildError: (err: unknown) => {\n // Use peek() to read the current value without registering a reactive\n // dependency — the child component's render context may be active when\n // this handler runs, and we must not accidentally subscribe the child\n // to this boundary's internal state.\n if (!hasError.peek()) {\n hasError.value = true;\n errorMessage.value = err instanceof Error ? err.message : String(err);\n }\n },\n reset: () => {\n hasError.value = false;\n errorMessage.value = '';\n },\n });\n\n return hasError.value\n ? html`<slot name=\"fallback\"\n ><div role=\"alert\">\n <strong>Something went wrong.</strong>\n ${errorMessage.value ? html`<p>${errorMessage.value}</p>` : html``}\n </div></slot\n >`\n : html`<slot></slot>`;\n });\n}\n\n// ── Auto-register all components ─────────────────────────────────────────────\n\n/**\n * Register all built-in components (`cer-suspense`, `cer-error-boundary`,\n * `cer-keep-alive`).\n * Safe to call multiple times — each registration is guarded by a\n * `customElements.get()` check.\n */\nexport function registerBuiltinComponents(): void {\n registerSuspense();\n registerErrorBoundary();\n registerKeepAlive();\n}\n","/**\n * teleport.ts\n *\n * Renders virtual DOM content into an arbitrary DOM target located outside\n * the current component's Shadow Root. Useful for modals, tooltips, popovers,\n * and any UI that must visually escape the component boundary.\n *\n * @example\n * ```ts\n * import { component, html, ref, useOnDisconnected, useTeleport } from '@jasonshimmy/custom-elements-runtime';\n *\n * component('modal-trigger', () => {\n * const isOpen = ref(false);\n *\n * // Render modal content into <body> outside the shadow root\n * const { portal, destroy } = useTeleport('#modal-root');\n * useOnDisconnected(destroy);\n *\n * // Call portal() to update the teleported content on each render\n * if (isOpen.value) {\n * portal(html`<div class=\"modal\">\n * <h2>Hello</h2>\n * <button @click=\"${() => (isOpen.value = false)}\">Close</button>\n * </div>`);\n * } else {\n * portal(null);\n * }\n *\n * return html`\n * <button @click=\"${() => (isOpen.value = true)}\">Open modal</button>\n * `;\n * });\n * ```\n */\n\nimport type { VNode, VDomRefs } from './runtime/types';\nimport { vdomRenderer } from './runtime/vdom';\nimport { reactiveSystem } from './runtime/reactive';\nimport { getCurrentComponentContext, isDiscoveryRender } from './runtime/hooks';\n\n/** Handle returned by {@link useTeleport} for managing a portal. */\nexport interface TeleportHandle {\n /**\n * Render (or clear) content at the teleport target.\n * Pass `null` or `undefined` to remove previously rendered content.\n */\n portal(content: VNode | VNode[] | null | undefined): void;\n\n /**\n * Destroy the teleport container and clean up all rendered content.\n * Call this in `useOnDisconnected` to prevent memory leaks.\n */\n destroy(): void;\n}\n\n/**\n * Create a teleport portal that renders content outside the current Shadow Root.\n *\n * @param target - A CSS selector string or an `Element` reference to render into.\n * @returns A {@link TeleportHandle} with `portal()` (update content) and `destroy()` (cleanup).\n *\n * @example\n * ```ts\n * import { component, html, useOnDisconnected, useTeleport } from '@jasonshimmy/custom-elements-runtime';\n *\n * component('my-tooltip', () => {\n * const { portal, destroy } = useTeleport('body');\n * useOnDisconnected(destroy);\n *\n * portal(html`<div class=\"tooltip\">Tooltip content</div>`);\n * return html`<span>Hover me</span>`;\n * });\n * ```\n */\nexport function useTeleport(target: string | Element): TeleportHandle {\n // SSR guard\n if (typeof document === 'undefined') {\n return { portal: () => {}, destroy: () => {} };\n }\n\n // During discovery render the component is not yet mounted — return a no-op\n // handle so the library can detect props/hooks without side-effects.\n if (isDiscoveryRender()) {\n return { portal: () => {}, destroy: () => {} };\n }\n\n // If called inside a component render, use the reactive state-index slot\n // mechanism to ensure the same handle is returned on every re-render of the\n // same component instance. Without this, each re-render would create a new\n // <cer-teleport> container in the target, leaking all but the last one.\n const ctx = getCurrentComponentContext();\n if (ctx) {\n // getOrCreateState uses an incrementing stateIndex that is reset to 0 at\n // the start of each render, so the same call site always gets the same slot.\n const slot = reactiveSystem.getOrCreateState<TeleportHandle | null>(null);\n const existing = slot.peek();\n if (existing !== null) {\n return existing;\n }\n // First render: create the handle and store it without triggering a\n // reactive update (initSilent bypasses triggerUpdate).\n // Pass a slot-invalidation callback so that destroy() clears the slot,\n // allowing a reconnected component to create a fresh container.\n const handle = _createTeleportHandle(target, () => slot.initSilent(null));\n slot.initSilent(handle);\n return handle;\n }\n\n // Outside a component context (e.g. called directly in tests or scripts):\n // fall through to a non-cached, non-stable handle.\n return _createTeleportHandle(target);\n}\n\n/** Internal: create a fresh teleport handle pointing at `target`.\n * @param onDestroy - Optional callback invoked after cleanup in destroy(), used\n * to invalidate a cached slot so the next render creates a fresh handle.\n */\nfunction _createTeleportHandle(\n target: string | Element,\n onDestroy?: () => void,\n): TeleportHandle {\n const targetEl =\n typeof target === 'string'\n ? (document.querySelector(target) as Element | null)\n : target;\n\n if (!targetEl) {\n console.warn(\n `[useTeleport] Target \"${String(target)}\" not found in the document. ` +\n 'Teleported content will not be rendered.',\n );\n return { portal: () => {}, destroy: () => {} };\n }\n\n // Create a dedicated container so we never clobber sibling content.\n const container = document.createElement('cer-teleport');\n container.dataset.cerTeleport = '';\n targetEl.appendChild(container);\n\n // Shared refs bag — passed consistently so ref directives work across updates.\n const refs: VDomRefs = {};\n\n const handle: TeleportHandle = {\n portal(content: VNode | VNode[] | null | undefined): void {\n const nodes: VNode[] =\n content == null ? [] : Array.isArray(content) ? content : [content];\n // vdomRenderer stores _prevVNode/_prevDom on the root object for diffing.\n // Casting to ShadowRoot is safe: we only access properties that exist on\n // HTMLElement (firstChild, appendChild, replaceChild, childNodes).\n vdomRenderer(container as unknown as ShadowRoot, nodes, undefined, refs);\n },\n\n destroy(): void {\n // Render empty nodes to clean up event listeners and refs.\n try {\n vdomRenderer(container as unknown as ShadowRoot, [], undefined, refs);\n } catch {\n /* best-effort cleanup */\n }\n if (container.parentNode) {\n container.parentNode.removeChild(container);\n }\n // Invalidate the cached slot so that if the component reconnects and\n // re-renders, useTeleport() creates a fresh container rather than\n // reusing this destroyed one.\n onDestroy?.();\n },\n };\n\n return handle;\n}\n"],"names":["hydrateApp","root","MAX_HISTORY_SIZE","CHECK_INTERVAL","calcStatus","value","threshold","metricName","buildRecommendations","metrics","out","createHealthMonitor","metricsMap","listeners","intervalId","addMetric","name","initializeMetrics","updateMetric","metric","getHealthReport","snapshot","overall","updateMemoryMetrics","mem","m","prev","curr","notifyListeners","report","listener","e","devError","performHealthCheck","devWarn","startMonitoring","stop","addListener","removeListener","getMetricHistory","clearHistory","_monitor","getHealthMonitor","updateHealthMetric","getHealthStatus","registerKeepAlive","createKeepAliveClass","key","slottedElements","child","cacheKey","cached","el","tag","id","registerSuspense","component","pending","useProps","html","registerErrorBoundary","hasError","ref","errorMessage","useOnError","err","useExpose","registerBuiltinComponents","useTeleport","target","isDiscoveryRender","getCurrentComponentContext","slot","reactiveSystem","existing","handle","_createTeleportHandle","onDestroy","targetEl","container","refs","content","nodes","vdomRenderer"],"mappings":";;;;;;AAiCO,SAASA,EAAWC,IAA2B,UAAgB;AACpE,MAAI,OAAO,cAAgB,IAAa;AAGxC,GADEA,aAAgB,WAAWA,EAAK,kBAAmBA,GAC9C;AAAA,IACL,IAAI,YAAY,eAAe,EAAE,SAAS,IAAM,UAAU,IAAM;AAAA,EAAA;AAEpE;ACKA,MAAMC,IAAmB,KACnBC,IAAiB;AAEvB,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B;AAEd,UAAI;AACF,QAAAG,EAAaJ,GAAoC,CAAA,GAAI,QAAWC,CAAI;AAAA,MACtE,QAAQ;AAAA,MAER;AACA,MAAID,EAAU,cACZA,EAAU,WAAW,YAAYA,CAAS,GAK5CF,IAAA;AAAA,IACF;AAAA,EAAA;AAIJ;"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./helpers-DeWjSmOl.cjs"),r=require("./hooks-BrrLKSub.cjs"),e=require("./style-D40DsIqJ.cjs");function a(s){if(o.isDiscoveryRender())return;const t=r.getCurrentComponentContext()?._host?.shadowRoot??null;t?e.registerJITCSSComponent(t,s):e.enableJITCSS(s)}function n(s){return s}exports.useDesignTokens=r.useDesignTokens;exports.useGlobalStyle=r.useGlobalStyle;exports.colors=e.colors;exports.containerVariants=e.containerVariants;exports.disableJITCSS=e.disableJITCSS;exports.enableJITCSS=e.enableJITCSS;exports.extractClassesFromHTML=e.extractClassesFromHTML;exports.getJITCSSOptions=e.getJITCSSOptions;exports.isJITCSSEnabled=e.isJITCSSEnabled;exports.isJITCSSEnabledFor=e.isJITCSSEnabledFor;exports.jitCSS=e.jitCSS;exports.mediaVariants=e.mediaVariants;exports.parseArbitrary=e.parseArbitrary;exports.parseColorClass=e.parseColorClass;exports.parseColorWithOpacity=e.parseColorWithOpacity;exports.parseGradientColorStop=e.parseGradientColorStop;exports.parseSpacing=e.parseSpacing;exports.registerJITCSSComponent=e.registerJITCSSComponent;exports.selectorVariants=e.selectorVariants;exports.utilityMap=e.utilityMap;exports.cls=n;exports.useJITCSS=a;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./hooks-x8M4knLc.cjs"),e=require("./style-D40DsIqJ.cjs");function o(s){if(t.isDiscoveryRender$1())return;const r=t.getCurrentComponentContext()?._host?.shadowRoot??null;r?e.registerJITCSSComponent(r,s):e.enableJITCSS(s)}function a(s){return s}exports.useDesignTokens=t.useDesignTokens;exports.useGlobalStyle=t.useGlobalStyle;exports.colors=e.colors;exports.containerVariants=e.containerVariants;exports.disableJITCSS=e.disableJITCSS;exports.enableJITCSS=e.enableJITCSS;exports.extractClassesFromHTML=e.extractClassesFromHTML;exports.getJITCSSOptions=e.getJITCSSOptions;exports.isJITCSSEnabled=e.isJITCSSEnabled;exports.isJITCSSEnabledFor=e.isJITCSSEnabledFor;exports.jitCSS=e.jitCSS;exports.mediaVariants=e.mediaVariants;exports.parseArbitrary=e.parseArbitrary;exports.parseColorClass=e.parseColorClass;exports.parseColorWithOpacity=e.parseColorWithOpacity;exports.parseGradientColorStop=e.parseGradientColorStop;exports.parseSpacing=e.parseSpacing;exports.registerJITCSSComponent=e.registerJITCSSComponent;exports.selectorVariants=e.selectorVariants;exports.utilityMap=e.utilityMap;exports.cls=a;exports.useJITCSS=o;
2
2
  //# sourceMappingURL=custom-elements-runtime.jit-css.cjs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"custom-elements-runtime.jit-css.cjs.js","sources":["../src/lib/runtime/jit-hooks.ts","../src/lib/jit-css.ts"],"sourcesContent":["/**\n * JIT CSS hooks — lives in a separate module so that hooks.ts does not\n * statically import style.ts. Consumers who never call `useJITCSS` will\n * have the entire JIT engine tree-shaken out of their bundle.\n */\n\nimport { isDiscoveryRender as _isDiscoveryRenderFn } from './discovery-state';\nimport { getCurrentComponentContext } from './hooks';\nimport {\n enableJITCSS,\n registerJITCSSComponent,\n type JITCSSOptions,\n} from './style';\n\n/**\n * Configure the JIT CSS engine for the current session.\n * This is a convenience wrapper around `enableJITCSS()` that can be called\n * inside a component render function or at module initialisation time.\n *\n * @example\n * ```ts\n * component('my-component', () => {\n * // Enable extended Tailwind colors so bg-blue-500, text-violet-700, etc. generate CSS\n * useJITCSS({ extendedColors: true });\n * return html`<div class=\"bg-blue-500 text-white\">Hello</div>`;\n * });\n * ```\n *\n * @example\n * ```ts\n * // At app entry – enable once for all components\n * useJITCSS({ extendedColors: true, customColors: { brand: { '500': '#e63946' } } });\n * ```\n */\nexport function useJITCSS(options?: JITCSSOptions): void {\n // During discovery renders (component registration phase) there is no real\n // shadow root. Without this guard, useJITCSS() falls through to\n // enableJITCSS() and globally enables JIT CSS for every component — exactly\n // the opt-in behaviour we are trying to prevent.\n if (_isDiscoveryRenderFn()) return;\n\n // When called inside a component render function, register this component's\n // shadow root for per-component JIT CSS opt-in. Context is always set during\n // a real render; it may be absent (null) or missing _host when called at app\n // startup level (outside any component context).\n const host = (getCurrentComponentContext() as { _host?: Element } | null)\n ?._host;\n const shadowRoot = host?.shadowRoot ?? null;\n\n if (shadowRoot) {\n // Per-component opt-in: register this shadow root only.\n registerJITCSSComponent(shadowRoot, options);\n } else {\n // App-level call (outside component context) — enable for all components\n // globally, preserving v2 behaviour when called at the entry point.\n enableJITCSS(options);\n }\n}\n\nexport type { JITCSSOptions };\n","/**\n * JIT CSS entry point — opt-in import for the full JIT CSS engine.\n *\n * @example\n * ```ts\n * import {\n * useJITCSS,\n * enableJITCSS,\n * } from '@jasonshimmy/custom-elements-runtime/jit-css';\n * ```\n */\n\n// Hooks\nexport { useJITCSS } from './runtime/jit-hooks';\nexport { useDesignTokens, useGlobalStyle } from './runtime/hooks';\nexport type { JITCSSOptions, DesignTokens } from './runtime/hooks';\n\n// Global configuration\nexport {\n enableJITCSS,\n disableJITCSS,\n isJITCSSEnabled,\n isJITCSSEnabledFor,\n registerJITCSSComponent,\n getJITCSSOptions,\n jitCSS,\n extractClassesFromHTML,\n parseColorClass,\n parseColorWithOpacity,\n parseGradientColorStop,\n parseSpacing,\n parseArbitrary,\n utilityMap,\n selectorVariants,\n mediaVariants,\n containerVariants,\n colors,\n} from './runtime/style';\n\n/**\n * A no-op identity function that signals to development tools (IDE\n * autocomplete, linters, PurgeCSS-style scanners) that the string contains\n * JIT CSS utility class names.\n *\n * At runtime this is simply `return className` — zero overhead.\n *\n * @example\n * ```ts\n * import { cls } from '@jasonshimmy/custom-elements-runtime/jit-css';\n *\n * const containerClasses = cls('flex items-center gap-4 bg-primary-500 text-white');\n * ```\n */\nexport function cls(className: string): string {\n return className;\n}\n"],"names":["useJITCSS","options","_isDiscoveryRenderFn","shadowRoot","getCurrentComponentContext","registerJITCSSComponent","enableJITCSS","cls","className"],"mappings":"8LAkCO,SAASA,EAAUC,EAA+B,CAKvD,GAAIC,EAAAA,oBAAwB,OAQ5B,MAAMC,EAFQC,EAAAA,8BACV,OACqB,YAAc,KAEnCD,EAEFE,EAAAA,wBAAwBF,EAAYF,CAAO,EAI3CK,EAAAA,aAAaL,CAAO,CAExB,CCJO,SAASM,EAAIC,EAA2B,CAC7C,OAAOA,CACT"}
1
+ {"version":3,"file":"custom-elements-runtime.jit-css.cjs.js","sources":["../src/lib/runtime/jit-hooks.ts","../src/lib/jit-css.ts"],"sourcesContent":["/**\n * JIT CSS hooks — lives in a separate module so that hooks.ts does not\n * statically import style.ts. Consumers who never call `useJITCSS` will\n * have the entire JIT engine tree-shaken out of their bundle.\n */\n\nimport { isDiscoveryRender as _isDiscoveryRenderFn } from './discovery-state';\nimport { getCurrentComponentContext } from './hooks';\nimport {\n enableJITCSS,\n registerJITCSSComponent,\n type JITCSSOptions,\n} from './style';\n\n/**\n * Configure the JIT CSS engine for the current session.\n * This is a convenience wrapper around `enableJITCSS()` that can be called\n * inside a component render function or at module initialisation time.\n *\n * @example\n * ```ts\n * component('my-component', () => {\n * // Enable extended Tailwind colors so bg-blue-500, text-violet-700, etc. generate CSS\n * useJITCSS({ extendedColors: true });\n * return html`<div class=\"bg-blue-500 text-white\">Hello</div>`;\n * });\n * ```\n *\n * @example\n * ```ts\n * // At app entry – enable once for all components\n * useJITCSS({ extendedColors: true, customColors: { brand: { '500': '#e63946' } } });\n * ```\n */\nexport function useJITCSS(options?: JITCSSOptions): void {\n // During discovery renders (component registration phase) there is no real\n // shadow root. Without this guard, useJITCSS() falls through to\n // enableJITCSS() and globally enables JIT CSS for every component — exactly\n // the opt-in behaviour we are trying to prevent.\n if (_isDiscoveryRenderFn()) return;\n\n // When called inside a component render function, register this component's\n // shadow root for per-component JIT CSS opt-in. Context is always set during\n // a real render; it may be absent (null) or missing _host when called at app\n // startup level (outside any component context).\n const host = (getCurrentComponentContext() as { _host?: Element } | null)\n ?._host;\n const shadowRoot = host?.shadowRoot ?? null;\n\n if (shadowRoot) {\n // Per-component opt-in: register this shadow root only.\n registerJITCSSComponent(shadowRoot, options);\n } else {\n // App-level call (outside component context) — enable for all components\n // globally, preserving v2 behaviour when called at the entry point.\n enableJITCSS(options);\n }\n}\n\nexport type { JITCSSOptions };\n","/**\n * JIT CSS entry point — opt-in import for the full JIT CSS engine.\n *\n * @example\n * ```ts\n * import {\n * useJITCSS,\n * enableJITCSS,\n * } from '@jasonshimmy/custom-elements-runtime/jit-css';\n * ```\n */\n\n// Hooks\nexport { useJITCSS } from './runtime/jit-hooks';\nexport { useDesignTokens, useGlobalStyle } from './runtime/hooks';\nexport type { JITCSSOptions, DesignTokens } from './runtime/hooks';\n\n// Global configuration\nexport {\n enableJITCSS,\n disableJITCSS,\n isJITCSSEnabled,\n isJITCSSEnabledFor,\n registerJITCSSComponent,\n getJITCSSOptions,\n jitCSS,\n extractClassesFromHTML,\n parseColorClass,\n parseColorWithOpacity,\n parseGradientColorStop,\n parseSpacing,\n parseArbitrary,\n utilityMap,\n selectorVariants,\n mediaVariants,\n containerVariants,\n colors,\n} from './runtime/style';\n\n/**\n * A no-op identity function that signals to development tools (IDE\n * autocomplete, linters, PurgeCSS-style scanners) that the string contains\n * JIT CSS utility class names.\n *\n * At runtime this is simply `return className` — zero overhead.\n *\n * @example\n * ```ts\n * import { cls } from '@jasonshimmy/custom-elements-runtime/jit-css';\n *\n * const containerClasses = cls('flex items-center gap-4 bg-primary-500 text-white');\n * ```\n */\nexport function cls(className: string): string {\n return className;\n}\n"],"names":["useJITCSS","options","_isDiscoveryRenderFn","shadowRoot","getCurrentComponentContext","registerJITCSSComponent","enableJITCSS","cls","className"],"mappings":"0JAkCO,SAASA,EAAUC,EAA+B,CAKvD,GAAIC,EAAAA,sBAAwB,OAQ5B,MAAMC,EAFQC,EAAAA,8BACV,OACqB,YAAc,KAEnCD,EAEFE,EAAAA,wBAAwBF,EAAYF,CAAO,EAI3CK,EAAAA,aAAaL,CAAO,CAExB,CCJO,SAASM,EAAIC,EAA2B,CAC7C,OAAOA,CACT"}
@@ -1,38 +1,37 @@
1
- import { A as o } from "./helpers-CweFZFWU.js";
2
- import { g as r } from "./hooks-DyShDHKo.js";
3
- import { f, j as u } from "./hooks-DyShDHKo.js";
4
- import { r as e, e as t } from "./style-BmyOIMcU.js";
5
- import { c as T, a as b, d as g, b as h, g as I, i as J, f as x, j as y, m as j, p as R, h as V, k, l as w, n as A, s as D, u as E } from "./style-BmyOIMcU.js";
6
- function p(s) {
7
- if (o()) return;
8
- const a = r()?._host?.shadowRoot ?? null;
9
- a ? e(a, s) : t(s);
1
+ import { g as o, Q as e } from "./hooks-xWZhQHco.js";
2
+ import { o as m, t as u } from "./hooks-xWZhQHco.js";
3
+ import { r, e as t } from "./style-BmyOIMcU.js";
4
+ import { c as f, a as T, d as b, b as g, g as h, i as I, f as J, j as x, m as y, p as R, h as V, k as j, l as k, n as w, s as D, u as E } from "./style-BmyOIMcU.js";
5
+ function S(s) {
6
+ if (e()) return;
7
+ const a = o()?._host?.shadowRoot ?? null;
8
+ a ? r(a, s) : t(s);
10
9
  }
11
- function C(s) {
10
+ function p(s) {
12
11
  return s;
13
12
  }
14
13
  export {
15
- C as cls,
16
- T as colors,
17
- b as containerVariants,
18
- g as disableJITCSS,
14
+ p as cls,
15
+ f as colors,
16
+ T as containerVariants,
17
+ b as disableJITCSS,
19
18
  t as enableJITCSS,
20
- h as extractClassesFromHTML,
21
- I as getJITCSSOptions,
22
- J as isJITCSSEnabled,
23
- x as isJITCSSEnabledFor,
24
- y as jitCSS,
25
- j as mediaVariants,
19
+ g as extractClassesFromHTML,
20
+ h as getJITCSSOptions,
21
+ I as isJITCSSEnabled,
22
+ J as isJITCSSEnabledFor,
23
+ x as jitCSS,
24
+ y as mediaVariants,
26
25
  R as parseArbitrary,
27
26
  V as parseColorClass,
28
- k as parseColorWithOpacity,
29
- w as parseGradientColorStop,
30
- A as parseSpacing,
31
- e as registerJITCSSComponent,
27
+ j as parseColorWithOpacity,
28
+ k as parseGradientColorStop,
29
+ w as parseSpacing,
30
+ r as registerJITCSSComponent,
32
31
  D as selectorVariants,
33
- f as useDesignTokens,
32
+ m as useDesignTokens,
34
33
  u as useGlobalStyle,
35
- p as useJITCSS,
34
+ S as useJITCSS,
36
35
  E as utilityMap
37
36
  };
38
37
  //# sourceMappingURL=custom-elements-runtime.jit-css.es.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"custom-elements-runtime.jit-css.es.js","sources":["../src/lib/runtime/jit-hooks.ts","../src/lib/jit-css.ts"],"sourcesContent":["/**\n * JIT CSS hooks — lives in a separate module so that hooks.ts does not\n * statically import style.ts. Consumers who never call `useJITCSS` will\n * have the entire JIT engine tree-shaken out of their bundle.\n */\n\nimport { isDiscoveryRender as _isDiscoveryRenderFn } from './discovery-state';\nimport { getCurrentComponentContext } from './hooks';\nimport {\n enableJITCSS,\n registerJITCSSComponent,\n type JITCSSOptions,\n} from './style';\n\n/**\n * Configure the JIT CSS engine for the current session.\n * This is a convenience wrapper around `enableJITCSS()` that can be called\n * inside a component render function or at module initialisation time.\n *\n * @example\n * ```ts\n * component('my-component', () => {\n * // Enable extended Tailwind colors so bg-blue-500, text-violet-700, etc. generate CSS\n * useJITCSS({ extendedColors: true });\n * return html`<div class=\"bg-blue-500 text-white\">Hello</div>`;\n * });\n * ```\n *\n * @example\n * ```ts\n * // At app entry – enable once for all components\n * useJITCSS({ extendedColors: true, customColors: { brand: { '500': '#e63946' } } });\n * ```\n */\nexport function useJITCSS(options?: JITCSSOptions): void {\n // During discovery renders (component registration phase) there is no real\n // shadow root. Without this guard, useJITCSS() falls through to\n // enableJITCSS() and globally enables JIT CSS for every component — exactly\n // the opt-in behaviour we are trying to prevent.\n if (_isDiscoveryRenderFn()) return;\n\n // When called inside a component render function, register this component's\n // shadow root for per-component JIT CSS opt-in. Context is always set during\n // a real render; it may be absent (null) or missing _host when called at app\n // startup level (outside any component context).\n const host = (getCurrentComponentContext() as { _host?: Element } | null)\n ?._host;\n const shadowRoot = host?.shadowRoot ?? null;\n\n if (shadowRoot) {\n // Per-component opt-in: register this shadow root only.\n registerJITCSSComponent(shadowRoot, options);\n } else {\n // App-level call (outside component context) — enable for all components\n // globally, preserving v2 behaviour when called at the entry point.\n enableJITCSS(options);\n }\n}\n\nexport type { JITCSSOptions };\n","/**\n * JIT CSS entry point — opt-in import for the full JIT CSS engine.\n *\n * @example\n * ```ts\n * import {\n * useJITCSS,\n * enableJITCSS,\n * } from '@jasonshimmy/custom-elements-runtime/jit-css';\n * ```\n */\n\n// Hooks\nexport { useJITCSS } from './runtime/jit-hooks';\nexport { useDesignTokens, useGlobalStyle } from './runtime/hooks';\nexport type { JITCSSOptions, DesignTokens } from './runtime/hooks';\n\n// Global configuration\nexport {\n enableJITCSS,\n disableJITCSS,\n isJITCSSEnabled,\n isJITCSSEnabledFor,\n registerJITCSSComponent,\n getJITCSSOptions,\n jitCSS,\n extractClassesFromHTML,\n parseColorClass,\n parseColorWithOpacity,\n parseGradientColorStop,\n parseSpacing,\n parseArbitrary,\n utilityMap,\n selectorVariants,\n mediaVariants,\n containerVariants,\n colors,\n} from './runtime/style';\n\n/**\n * A no-op identity function that signals to development tools (IDE\n * autocomplete, linters, PurgeCSS-style scanners) that the string contains\n * JIT CSS utility class names.\n *\n * At runtime this is simply `return className` — zero overhead.\n *\n * @example\n * ```ts\n * import { cls } from '@jasonshimmy/custom-elements-runtime/jit-css';\n *\n * const containerClasses = cls('flex items-center gap-4 bg-primary-500 text-white');\n * ```\n */\nexport function cls(className: string): string {\n return className;\n}\n"],"names":["useJITCSS","options","_isDiscoveryRenderFn","shadowRoot","getCurrentComponentContext","registerJITCSSComponent","enableJITCSS","cls","className"],"mappings":";;;;;AAkCO,SAASA,EAAUC,GAA+B;AAKvD,MAAIC,IAAwB;AAQ5B,QAAMC,IAFQC,KACV,OACqB,cAAc;AAEvC,EAAID,IAEFE,EAAwBF,GAAYF,CAAO,IAI3CK,EAAaL,CAAO;AAExB;ACJO,SAASM,EAAIC,GAA2B;AAC7C,SAAOA;AACT;"}
1
+ {"version":3,"file":"custom-elements-runtime.jit-css.es.js","sources":["../src/lib/runtime/jit-hooks.ts","../src/lib/jit-css.ts"],"sourcesContent":["/**\n * JIT CSS hooks — lives in a separate module so that hooks.ts does not\n * statically import style.ts. Consumers who never call `useJITCSS` will\n * have the entire JIT engine tree-shaken out of their bundle.\n */\n\nimport { isDiscoveryRender as _isDiscoveryRenderFn } from './discovery-state';\nimport { getCurrentComponentContext } from './hooks';\nimport {\n enableJITCSS,\n registerJITCSSComponent,\n type JITCSSOptions,\n} from './style';\n\n/**\n * Configure the JIT CSS engine for the current session.\n * This is a convenience wrapper around `enableJITCSS()` that can be called\n * inside a component render function or at module initialisation time.\n *\n * @example\n * ```ts\n * component('my-component', () => {\n * // Enable extended Tailwind colors so bg-blue-500, text-violet-700, etc. generate CSS\n * useJITCSS({ extendedColors: true });\n * return html`<div class=\"bg-blue-500 text-white\">Hello</div>`;\n * });\n * ```\n *\n * @example\n * ```ts\n * // At app entry – enable once for all components\n * useJITCSS({ extendedColors: true, customColors: { brand: { '500': '#e63946' } } });\n * ```\n */\nexport function useJITCSS(options?: JITCSSOptions): void {\n // During discovery renders (component registration phase) there is no real\n // shadow root. Without this guard, useJITCSS() falls through to\n // enableJITCSS() and globally enables JIT CSS for every component — exactly\n // the opt-in behaviour we are trying to prevent.\n if (_isDiscoveryRenderFn()) return;\n\n // When called inside a component render function, register this component's\n // shadow root for per-component JIT CSS opt-in. Context is always set during\n // a real render; it may be absent (null) or missing _host when called at app\n // startup level (outside any component context).\n const host = (getCurrentComponentContext() as { _host?: Element } | null)\n ?._host;\n const shadowRoot = host?.shadowRoot ?? null;\n\n if (shadowRoot) {\n // Per-component opt-in: register this shadow root only.\n registerJITCSSComponent(shadowRoot, options);\n } else {\n // App-level call (outside component context) — enable for all components\n // globally, preserving v2 behaviour when called at the entry point.\n enableJITCSS(options);\n }\n}\n\nexport type { JITCSSOptions };\n","/**\n * JIT CSS entry point — opt-in import for the full JIT CSS engine.\n *\n * @example\n * ```ts\n * import {\n * useJITCSS,\n * enableJITCSS,\n * } from '@jasonshimmy/custom-elements-runtime/jit-css';\n * ```\n */\n\n// Hooks\nexport { useJITCSS } from './runtime/jit-hooks';\nexport { useDesignTokens, useGlobalStyle } from './runtime/hooks';\nexport type { JITCSSOptions, DesignTokens } from './runtime/hooks';\n\n// Global configuration\nexport {\n enableJITCSS,\n disableJITCSS,\n isJITCSSEnabled,\n isJITCSSEnabledFor,\n registerJITCSSComponent,\n getJITCSSOptions,\n jitCSS,\n extractClassesFromHTML,\n parseColorClass,\n parseColorWithOpacity,\n parseGradientColorStop,\n parseSpacing,\n parseArbitrary,\n utilityMap,\n selectorVariants,\n mediaVariants,\n containerVariants,\n colors,\n} from './runtime/style';\n\n/**\n * A no-op identity function that signals to development tools (IDE\n * autocomplete, linters, PurgeCSS-style scanners) that the string contains\n * JIT CSS utility class names.\n *\n * At runtime this is simply `return className` — zero overhead.\n *\n * @example\n * ```ts\n * import { cls } from '@jasonshimmy/custom-elements-runtime/jit-css';\n *\n * const containerClasses = cls('flex items-center gap-4 bg-primary-500 text-white');\n * ```\n */\nexport function cls(className: string): string {\n return className;\n}\n"],"names":["useJITCSS","options","_isDiscoveryRenderFn","shadowRoot","getCurrentComponentContext","registerJITCSSComponent","enableJITCSS","cls","className"],"mappings":";;;;AAkCO,SAASA,EAAUC,GAA+B;AAKvD,MAAIC,IAAwB;AAQ5B,QAAMC,IAFQC,KACV,OACqB,cAAc;AAEvC,EAAID,IAEFE,EAAwBF,GAAYF,CAAO,IAI3CK,EAAaL,CAAO;AAExB;ACJO,SAASM,EAAIC,GAA2B;AAC7C,SAAOA;AACT;"}