@jasonshimmy/custom-elements-runtime 3.0.0 → 3.1.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 +118 -81
- package/dist/custom-elements-runtime.cjs.js +3 -3
- package/dist/custom-elements-runtime.cjs.js.map +1 -1
- package/dist/custom-elements-runtime.es.js +77 -72
- package/dist/custom-elements-runtime.es.js.map +1 -1
- package/dist/custom-elements-runtime.jit-css.cjs.js +1 -1
- package/dist/custom-elements-runtime.jit-css.cjs.js.map +1 -1
- package/dist/custom-elements-runtime.jit-css.es.js +25 -26
- package/dist/custom-elements-runtime.jit-css.es.js.map +1 -1
- package/dist/custom-elements-runtime.router.cjs.js +8 -8
- package/dist/custom-elements-runtime.router.cjs.js.map +1 -1
- package/dist/custom-elements-runtime.router.es.js +134 -134
- package/dist/custom-elements-runtime.router.es.js.map +1 -1
- package/dist/custom-elements-runtime.ssr-middleware.cjs.js +2 -0
- package/dist/custom-elements-runtime.ssr-middleware.cjs.js.map +1 -0
- package/dist/custom-elements-runtime.ssr-middleware.es.js +63 -0
- package/dist/custom-elements-runtime.ssr-middleware.es.js.map +1 -0
- package/dist/custom-elements-runtime.ssr.cjs.js +3 -1
- package/dist/custom-elements-runtime.ssr.cjs.js.map +1 -1
- package/dist/custom-elements-runtime.ssr.es.js +137 -39
- package/dist/custom-elements-runtime.ssr.es.js.map +1 -1
- package/dist/custom-elements-runtime.vite-plugin.cjs.js +1 -1
- package/dist/custom-elements-runtime.vite-plugin.cjs.js.map +1 -1
- package/dist/custom-elements-runtime.vite-plugin.es.js +81 -49
- package/dist/custom-elements-runtime.vite-plugin.es.js.map +1 -1
- package/dist/hooks-B50HhrHh.cjs +6 -0
- package/dist/hooks-B50HhrHh.cjs.map +1 -0
- package/dist/hooks-Cze3o-F7.js +1462 -0
- package/dist/hooks-Cze3o-F7.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/namespace-helpers-D4wC2-qA.js +61 -0
- package/dist/namespace-helpers-D4wC2-qA.js.map +1 -0
- package/dist/namespace-helpers-ckeEOxpR.cjs +2 -0
- package/dist/namespace-helpers-ckeEOxpR.cjs.map +1 -0
- package/dist/router/matcher.d.ts +14 -0
- package/dist/runtime/component/factory.d.ts +16 -2
- package/dist/runtime/hydration.d.ts +33 -0
- package/dist/runtime/ssr-context.d.ts +45 -0
- package/dist/runtime/types.d.ts +18 -0
- package/dist/runtime/vdom-ssr-dsd.d.ts +58 -0
- package/dist/ssr-middleware.d.ts +125 -0
- package/dist/ssr.d.ts +95 -33
- package/dist/template-compiler-Cshhqxyd.cjs +23 -0
- package/dist/template-compiler-Cshhqxyd.cjs.map +1 -0
- package/dist/{template-compiler-B5uN1EQw.js → template-compiler-DtpNsqE-.js} +1296 -1283
- package/dist/template-compiler-DtpNsqE-.js.map +1 -0
- package/dist/vite-plugin.d.ts +94 -4
- package/package.json +6 -1
- package/dist/helpers-CweFZFWU.js +0 -987
- package/dist/helpers-CweFZFWU.js.map +0 -1
- package/dist/helpers-DeWjSmOl.cjs +0 -5
- package/dist/helpers-DeWjSmOl.cjs.map +0 -1
- package/dist/hooks-BrrLKSub.cjs +0 -3
- package/dist/hooks-BrrLKSub.cjs.map +0 -1
- package/dist/hooks-DyShDHKo.js +0 -403
- package/dist/hooks-DyShDHKo.js.map +0 -1
- package/dist/namespace-helpers-CnpZ5__p.js +0 -45
- package/dist/namespace-helpers-CnpZ5__p.js.map +0 -1
- package/dist/namespace-helpers-CyIDtI97.cjs +0 -2
- package/dist/namespace-helpers-CyIDtI97.cjs.map +0 -1
- package/dist/template-compiler-B5uN1EQw.js.map +0 -1
- package/dist/template-compiler-Cx623BSB.cjs +0 -23
- package/dist/template-compiler-Cx623BSB.cjs.map +0 -1
package/README.md
CHANGED
|
@@ -80,49 +80,50 @@ Below is the **complete list of public symbols** exported by the runtime and its
|
|
|
80
80
|
|
|
81
81
|
**Package:** `@jasonshimmy/custom-elements-runtime`
|
|
82
82
|
|
|
83
|
-
| Export | Description
|
|
84
|
-
| ---------------------------- |
|
|
85
|
-
| `component` | Define a custom element with the functional component API.
|
|
86
|
-
| `html` | Template tag function producing runtime VNodes from template literals.
|
|
87
|
-
| `css` | Define component-scoped/JIT styles or register stylesheets.
|
|
88
|
-
| `ref` | Create a reactive reference object with a `.value` property.
|
|
89
|
-
| `computed` | Create a memoized, derived read-only value from other reactive sources.
|
|
90
|
-
| `watch` | Register watchers reacting to changes in reactive values.
|
|
91
|
-
| `watchEffect` | Auto-track reactive reads and re-run a side-effect whenever dependencies change.
|
|
92
|
-
| `nextTick` | Returns a Promise resolving after all pending DOM updates are flushed.
|
|
93
|
-
| `flushDOMUpdates` | Synchronously flush all pending DOM update tasks (useful in tests).
|
|
94
|
-
| `scheduleWithPriority` | Schedule a callback at a given `UpdatePriority` level.
|
|
95
|
-
| `provide` | Store a value on the current component for descendant injection.
|
|
96
|
-
| `inject` | Retrieve a value provided by an ancestor component.
|
|
97
|
-
| `createComposable` | Package reusable stateful logic (hooks, reactive state) into a composable.
|
|
98
|
-
| `getCurrentComponentContext` | Access the active component context from within a composable or render function.
|
|
99
|
-
| `useProps` | Hook to declare/consume typed component props with defaults.
|
|
100
|
-
| `defineModel` | Declare a two-way model binding prop; combines `useProps` + `useEmit` in one ergonomic hook.
|
|
101
|
-
| `useEmit` | Hook returning an emit function for dispatching custom events.
|
|
102
|
-
| `useOnConnected` | Hook that runs a callback when the component connects.
|
|
103
|
-
| `useOnDisconnected` | Hook that runs a callback when the component disconnects.
|
|
104
|
-
| `useOnAttributeChanged` | Hook observing host attribute changes.
|
|
105
|
-
| `useOnError` | Hook to register a component-level error handler.
|
|
106
|
-
| `useStyle` | Hook to register or compute component styles at runtime.
|
|
107
|
-
| `useDesignTokens` | Apply typed design token overrides to `:host` as CSS custom properties.
|
|
108
|
-
| `useGlobalStyle` | Inject CSS into `document.adoptedStyleSheets`, escaping Shadow DOM encapsulation. Use sparingly.
|
|
109
|
-
| `useExpose` | Publish methods and properties onto the host element as an imperative public API.
|
|
110
|
-
| `useSlots` | Inspect which named slots have been filled by the component consumer.
|
|
111
|
-
| `useTeleport` | Render virtual DOM content into any DOM node outside the shadow root.
|
|
112
|
-
| `registerKeepAlive` | Register `<cer-keep-alive>` to preserve component state across DOM removals.
|
|
113
|
-
| `registerSuspense` | Register the `<cer-suspense>` built-in component.
|
|
114
|
-
| `registerErrorBoundary` | Register the `<cer-error-boundary>` built-in component.
|
|
115
|
-
| `registerBuiltinComponents` | Register `<cer-keep-alive>`, `<cer-suspense>` and `<cer-error-boundary>` in one call.
|
|
116
|
-
| `unsafeHTML` | Insert raw HTML into a template (**unsafe; use carefully**).
|
|
117
|
-
| `decodeEntities` | Utility to decode HTML entities in strings.
|
|
118
|
-
| `setDevMode` | Toggle dev-mode logging on or off at runtime.
|
|
119
|
-
| `devLog` | Log a message to the console in dev mode only (no-op in production).
|
|
120
|
-
| `isReactiveState` | Type-guard returning `true` when a value is a `ReactiveState` instance.
|
|
121
|
-
| `createHealthMonitor` | Create a new health monitor instance (factory; each call returns an independent instance).
|
|
122
|
-
| `getHealthMonitor` | Return the global singleton health monitor instance (lazily created).
|
|
123
|
-
| `updateHealthMetric` | Update a named metric on the global singleton health monitor.
|
|
124
|
-
| `getHealthStatus` | Return the current `HealthReport` from the global singleton health monitor.
|
|
125
|
-
|
|
|
83
|
+
| Export | Description |
|
|
84
|
+
| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
85
|
+
| `component` | Define a custom element with the functional component API. |
|
|
86
|
+
| `html` | Template tag function producing runtime VNodes from template literals. |
|
|
87
|
+
| `css` | Define component-scoped/JIT styles or register stylesheets. |
|
|
88
|
+
| `ref` | Create a reactive reference object with a `.value` property. |
|
|
89
|
+
| `computed` | Create a memoized, derived read-only value from other reactive sources. |
|
|
90
|
+
| `watch` | Register watchers reacting to changes in reactive values. |
|
|
91
|
+
| `watchEffect` | Auto-track reactive reads and re-run a side-effect whenever dependencies change. |
|
|
92
|
+
| `nextTick` | Returns a Promise resolving after all pending DOM updates are flushed. |
|
|
93
|
+
| `flushDOMUpdates` | Synchronously flush all pending DOM update tasks (useful in tests). |
|
|
94
|
+
| `scheduleWithPriority` | Schedule a callback at a given `UpdatePriority` level. |
|
|
95
|
+
| `provide` | Store a value on the current component for descendant injection. |
|
|
96
|
+
| `inject` | Retrieve a value provided by an ancestor component. |
|
|
97
|
+
| `createComposable` | Package reusable stateful logic (hooks, reactive state) into a composable. |
|
|
98
|
+
| `getCurrentComponentContext` | Access the active component context from within a composable or render function. |
|
|
99
|
+
| `useProps` | Hook to declare/consume typed component props with defaults. |
|
|
100
|
+
| `defineModel` | Declare a two-way model binding prop; combines `useProps` + `useEmit` in one ergonomic hook. |
|
|
101
|
+
| `useEmit` | Hook returning an emit function for dispatching custom events. |
|
|
102
|
+
| `useOnConnected` | Hook that runs a callback when the component connects. |
|
|
103
|
+
| `useOnDisconnected` | Hook that runs a callback when the component disconnects. |
|
|
104
|
+
| `useOnAttributeChanged` | Hook observing host attribute changes. |
|
|
105
|
+
| `useOnError` | Hook to register a component-level error handler. |
|
|
106
|
+
| `useStyle` | Hook to register or compute component styles at runtime. |
|
|
107
|
+
| `useDesignTokens` | Apply typed design token overrides to `:host` as CSS custom properties. |
|
|
108
|
+
| `useGlobalStyle` | Inject CSS into `document.adoptedStyleSheets`, escaping Shadow DOM encapsulation. Use sparingly. |
|
|
109
|
+
| `useExpose` | Publish methods and properties onto the host element as an imperative public API. |
|
|
110
|
+
| `useSlots` | Inspect which named slots have been filled by the component consumer. |
|
|
111
|
+
| `useTeleport` | Render virtual DOM content into any DOM node outside the shadow root. |
|
|
112
|
+
| `registerKeepAlive` | Register `<cer-keep-alive>` to preserve component state across DOM removals. |
|
|
113
|
+
| `registerSuspense` | Register the `<cer-suspense>` built-in component. |
|
|
114
|
+
| `registerErrorBoundary` | Register the `<cer-error-boundary>` built-in component. |
|
|
115
|
+
| `registerBuiltinComponents` | Register `<cer-keep-alive>`, `<cer-suspense>` and `<cer-error-boundary>` in one call. |
|
|
116
|
+
| `unsafeHTML` | Insert raw HTML into a template (**unsafe; use carefully**). |
|
|
117
|
+
| `decodeEntities` | Utility to decode HTML entities in strings. |
|
|
118
|
+
| `setDevMode` | Toggle dev-mode logging on or off at runtime. |
|
|
119
|
+
| `devLog` | Log a message to the console in dev mode only (no-op in production). |
|
|
120
|
+
| `isReactiveState` | Type-guard returning `true` when a value is a `ReactiveState` instance. |
|
|
121
|
+
| `createHealthMonitor` | Create a new health monitor instance (factory; each call returns an independent instance). |
|
|
122
|
+
| `getHealthMonitor` | Return the global singleton health monitor instance (lazily created). |
|
|
123
|
+
| `updateHealthMetric` | Update a named metric on the global singleton health monitor. |
|
|
124
|
+
| `getHealthStatus` | Return the current `HealthReport` from the global singleton health monitor. |
|
|
125
|
+
| `hydrateApp` | Trigger hydration of all DSD-rendered custom elements within a root (call after registering all components on the client). |
|
|
126
|
+
| **Types** | `ModelRef`, `HealthMonitorInstance`, `HealthReport`, `UpdatePriority`, `TeleportHandle`, `ReactiveState`, `VNode`, `JITCSSOptions`, `DesignTokens`, `ComponentOptions`, `HydrateStrategy` |
|
|
126
127
|
|
|
127
128
|
---
|
|
128
129
|
|
|
@@ -210,25 +211,25 @@ Below is the **complete list of public symbols** exported by the runtime and its
|
|
|
210
211
|
|
|
211
212
|
**Package:** `@jasonshimmy/custom-elements-runtime/router`
|
|
212
213
|
|
|
213
|
-
| Export | Description
|
|
214
|
-
| ----------------------- |
|
|
215
|
-
| `useRouter` | Create and use a router instance configured with routes (client & SSR).
|
|
216
|
-
| `initRouter` | Initialize the router and register `router-view` / `router-link`.
|
|
217
|
-
| `matchRoute` | Match a path against configured routes and extract params.
|
|
218
|
-
| `matchRouteSSR` | SSR-friendly wrapper for route matching.
|
|
219
|
-
| `findMatchedRoute` | Find the first matching route entry from an array of routes (lower-level helper).
|
|
220
|
-
| `parseQuery` | Parse a query string into a key/value map.
|
|
221
|
-
| `serializeQuery` | Serialize a key/value map into a query string (e.g. `?a=b`).
|
|
222
|
-
| `normalizePathForRoute` | Normalize a path string for consistent route matching (strips trailing slashes, etc.).
|
|
223
|
-
| `DEFAULT_SCROLL_CONFIG` | Default scroll-to-fragment configuration object used by the router.
|
|
224
|
-
| `isDangerousScheme` | Returns `true` for dangerous URL schemes (e.g. `javascript:`).
|
|
225
|
-
| `isAbsoluteUrl` | Returns `true` when a URL string is absolute (has a protocol).
|
|
226
|
-
| `safeDecode` | Decode a URI component, returning the original string on error.
|
|
227
|
-
| `canonicalizeBase` | Normalize a router base path string (strips trailing slashes, ensures leading slash).
|
|
228
|
-
| `resolveRouteComponent` | Resolve/load a route's component (supports async loaders + caching).
|
|
229
|
-
| `clearComponentCache` | Clear the resolved route component cache (useful for testing and HMR).
|
|
230
|
-
| `activeRouterProxy` | Stable proxy to the currently active router; forwards subscriptions and method calls (advanced/testing use).
|
|
231
|
-
| **Types** | `Route`, `RouteState`, `RouteComponent`, `GuardResult`, `RouterLinkProps`, `RouterLinkComputed`, `RouterConfig`, `Router`
|
|
214
|
+
| Export | Description |
|
|
215
|
+
| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
216
|
+
| `useRouter` | Create and use a router instance configured with routes (client & SSR). |
|
|
217
|
+
| `initRouter` | Initialize the router and register `router-view` / `router-link`. |
|
|
218
|
+
| `matchRoute` | Match a path against configured routes and extract params. |
|
|
219
|
+
| `matchRouteSSR` | SSR-friendly wrapper for route matching. Automatically strips query strings and URL fragments before matching, so `req.url` can be passed directly. |
|
|
220
|
+
| `findMatchedRoute` | Find the first matching route entry from an array of routes (lower-level helper). |
|
|
221
|
+
| `parseQuery` | Parse a query string into a key/value map. |
|
|
222
|
+
| `serializeQuery` | Serialize a key/value map into a query string (e.g. `?a=b`). |
|
|
223
|
+
| `normalizePathForRoute` | Normalize a path string for consistent route matching (strips trailing slashes, etc.). |
|
|
224
|
+
| `DEFAULT_SCROLL_CONFIG` | Default scroll-to-fragment configuration object used by the router. |
|
|
225
|
+
| `isDangerousScheme` | Returns `true` for dangerous URL schemes (e.g. `javascript:`). |
|
|
226
|
+
| `isAbsoluteUrl` | Returns `true` when a URL string is absolute (has a protocol). |
|
|
227
|
+
| `safeDecode` | Decode a URI component, returning the original string on error. |
|
|
228
|
+
| `canonicalizeBase` | Normalize a router base path string (strips trailing slashes, ensures leading slash). |
|
|
229
|
+
| `resolveRouteComponent` | Resolve/load a route's component (supports async loaders + caching). |
|
|
230
|
+
| `clearComponentCache` | Clear the resolved route component cache (useful for testing and HMR). |
|
|
231
|
+
| `activeRouterProxy` | Stable proxy to the currently active router; forwards subscriptions and method calls (advanced/testing use). |
|
|
232
|
+
| **Types** | `Route`, `RouteState`, `RouteComponent`, `GuardResult`, `RouterLinkProps`, `RouterLinkComputed`, `RouterConfig`, `Router` |
|
|
232
233
|
|
|
233
234
|
---
|
|
234
235
|
|
|
@@ -236,16 +237,35 @@ Below is the **complete list of public symbols** exported by the runtime and its
|
|
|
236
237
|
|
|
237
238
|
**Package:** `@jasonshimmy/custom-elements-runtime/ssr`
|
|
238
239
|
|
|
239
|
-
| Export
|
|
240
|
-
|
|
|
241
|
-
| `renderToString`
|
|
242
|
-
| `renderToStringWithJITCSS`
|
|
243
|
-
| `
|
|
244
|
-
| `
|
|
245
|
-
| `
|
|
246
|
-
| `
|
|
247
|
-
| `
|
|
248
|
-
| `
|
|
240
|
+
| Export | Description |
|
|
241
|
+
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
242
|
+
| `renderToString` | Render a VNode tree to HTML for server-side rendering (backwards-compatible baseline). |
|
|
243
|
+
| `renderToStringWithJITCSS` | Render to HTML + pre-generate JIT CSS. Pass `dsd: true` for Declarative Shadow DOM output with full per-shadow-root CSS stack. |
|
|
244
|
+
| `renderToStringWithJITCSSDSD` | **Recommended.** Convenience alias: `renderToStringWithJITCSS(vnode, { dsd: true, ... })`. Full DSD output, hydration-ready, zero FOUC. Requires a **single root VNode** — wrap multi-element templates in one container. |
|
|
245
|
+
| `renderToStringDSD` | Render to DSD HTML string (no JIT CSS pipeline). Appends DSD polyfill by default. |
|
|
246
|
+
| `renderToStream` | Render to a `ReadableStream<string>` for streaming SSR / chunked transfer encoding. |
|
|
247
|
+
| `DSD_POLYFILL_SCRIPT` | Minified inline `<script>` that implements DSD for Firefox < 123. Injected automatically; export it for manual placement. |
|
|
248
|
+
| `registerEntityMap` | Register a custom named-entity map for SSR `decodeEntities`. |
|
|
249
|
+
| `loadEntityMap` | Async loader for the full HTML5 named-entity map. |
|
|
250
|
+
| `clearRegisteredEntityMap` | Reset the entity map to the built-in minimal set. |
|
|
251
|
+
| `VNode` (type) | The runtime VNode shape used by renderers and SSR. |
|
|
252
|
+
| `RenderOptions` (type) | Options for `renderToString` (`injectSvgNamespace`, `injectKnownNamespaces`). |
|
|
253
|
+
| `DSDRenderOptions` (type) | Options for DSD rendering (`dsd`, `dsdPolyfill`, plus all `RenderOptions`). |
|
|
254
|
+
| `SSRJITResult` (type) | Result of `renderToStringWithJITCSS`: `{ html, css, globalStyles, htmlWithStyles }`. |
|
|
255
|
+
|
|
256
|
+
### SSR Middleware
|
|
257
|
+
|
|
258
|
+
**Package:** `@jasonshimmy/custom-elements-runtime/ssr-middleware`
|
|
259
|
+
|
|
260
|
+
Framework-agnostic handler factories for Express, Fastify, Hono, and raw Node.js.
|
|
261
|
+
|
|
262
|
+
| Export | Description |
|
|
263
|
+
| ----------------------------- | --------------------------------------------------------------------------------------------------------- |
|
|
264
|
+
| `createSSRHandler` | Returns an `async (req, res)` handler that SSR-renders a VNode and sends the full HTML document response. |
|
|
265
|
+
| `createStreamingSSRHandler` | Returns an `async (req, res)` handler that streams the rendered HTML using chunked transfer encoding. |
|
|
266
|
+
| `MinimalRequest` (type) | Minimal `{ url?, method?, headers? }` interface compatible with all major Node.js HTTP frameworks. |
|
|
267
|
+
| `MinimalResponse` (type) | Minimal `{ setHeader, write?, end }` interface compatible with all major Node.js HTTP frameworks. |
|
|
268
|
+
| `SSRMiddlewareOptions` (type) | Options for `createSSRHandler` and `createStreamingSSRHandler`. |
|
|
249
269
|
|
|
250
270
|
### Global Styles (CSS)
|
|
251
271
|
|
|
@@ -360,12 +380,27 @@ jit.destroy(); // tear down
|
|
|
360
380
|
|
|
361
381
|
**Package:** `@jasonshimmy/custom-elements-runtime/vite-plugin`
|
|
362
382
|
|
|
363
|
-
Build-time static analysis plugin that emits pre-generated CSS, eliminating runtime parsing cost entirely.
|
|
383
|
+
Build-time static analysis plugin that emits pre-generated CSS, eliminating runtime parsing cost entirely. Two exports are available:
|
|
364
384
|
|
|
365
|
-
|
|
385
|
+
- **`cerPlugin`** — All-in-one: JIT CSS + SSR configuration. Recommended for SSR apps.
|
|
386
|
+
- **`cerJITCSS`** — JIT CSS only.
|
|
366
387
|
|
|
367
388
|
```ts
|
|
368
|
-
// vite.config.ts
|
|
389
|
+
// vite.config.ts — SSR app (recommended)
|
|
390
|
+
import { cerPlugin } from '@jasonshimmy/custom-elements-runtime/vite-plugin';
|
|
391
|
+
|
|
392
|
+
export default defineConfig({
|
|
393
|
+
plugins: [
|
|
394
|
+
cerPlugin({
|
|
395
|
+
content: ['./src/**/*.{ts,tsx,html}'],
|
|
396
|
+
ssr: { dsd: true, jit: { extendedColors: true } },
|
|
397
|
+
}),
|
|
398
|
+
],
|
|
399
|
+
});
|
|
400
|
+
```
|
|
401
|
+
|
|
402
|
+
```ts
|
|
403
|
+
// vite.config.ts — JIT CSS only
|
|
369
404
|
import { cerJITCSS } from '@jasonshimmy/custom-elements-runtime/vite-plugin';
|
|
370
405
|
|
|
371
406
|
export default defineConfig({
|
|
@@ -379,10 +414,11 @@ export default defineConfig({
|
|
|
379
414
|
});
|
|
380
415
|
```
|
|
381
416
|
|
|
382
|
-
| Export | Description
|
|
383
|
-
| ----------- |
|
|
384
|
-
| `
|
|
385
|
-
|
|
|
417
|
+
| Export | Description |
|
|
418
|
+
| ----------- | --------------------------------------------------------------------------------------------- |
|
|
419
|
+
| `cerPlugin` | Combined plugin: JIT CSS + SSR config (`virtual:cer-ssr-config`). Returns a `Plugin[]` array. |
|
|
420
|
+
| `cerJITCSS` | JIT CSS-only Vite plugin that scans source files at build time and emits pre-generated CSS. |
|
|
421
|
+
| **Types** | `CerPluginOptions`, `CerSSROptions`, `CerJITCSSPluginOptions` |
|
|
386
422
|
|
|
387
423
|
---
|
|
388
424
|
|
|
@@ -416,7 +452,7 @@ Explore the complete documentation for every runtime feature:
|
|
|
416
452
|
|
|
417
453
|
- [🎨 JIT CSS](./docs/jit-css.md) - On-demand utility-first styling system (opt-in architecture, all utilities, `useJITCSS`, `useDesignTokens`, `useGlobalStyle`, `cls`)
|
|
418
454
|
- [⚡ DOM JIT CSS](./docs/dom-jit-css.md) - Runtime DOM scanner for non-Shadow DOM contexts (React, Svelte, Vue, plain HTML)
|
|
419
|
-
- [🔧 Vite Plugin](./docs/vite-plugin.md) -
|
|
455
|
+
- [🔧 Vite Plugin](./docs/vite-plugin.md) - `cerPlugin` (JIT CSS + SSR config) and `cerJITCSS` (JIT CSS only) build-time plugins
|
|
420
456
|
- [📏 Space Utilities](./docs/space-utilities.md) - Tailwind-style `space-x-*` and `space-y-*` spacing utilities
|
|
421
457
|
- [📝 Prose Typography](./docs/prose.md) - Beautiful typography for long-form content
|
|
422
458
|
- [🎨 Colors](./docs/colors.md) - Extended Tailwind-compatible color palette (`/css/colors` subpath)
|
|
@@ -437,7 +473,8 @@ Explore the complete documentation for every runtime feature:
|
|
|
437
473
|
- [♻️ Keep-Alive](./docs/keep-alive.md) - Preserve component state across DOM removals with `<cer-keep-alive>`
|
|
438
474
|
- [🩺 Health Monitor](./docs/health-monitor.md) - Track runtime metrics and receive periodic health reports with `createHealthMonitor()`
|
|
439
475
|
- [🔮 Virtual DOM](./docs/virtual-dom.md) - VDOM implementation and performance details
|
|
440
|
-
- [🌐 SSR](./docs/ssr.md) -
|
|
476
|
+
- [🌐 SSR](./docs/ssr.md) - Complete SSR guide: Declarative Shadow DOM output, hydration, streaming, partial hydration (island architecture), `useStyle` in SSR, routing with SSR, and framework integration
|
|
477
|
+
- [🌐 SSR Middleware](./docs/ssr-middleware.md) - `createSSRHandler` and `createStreamingSSRHandler` for Express, Fastify, Hono, raw Node.js, and router integration
|
|
441
478
|
- [♻️ HMR](./docs/hmr.md) - Hot module replacement
|
|
442
479
|
- [🛡️ Infinite Loop Protection](./docs/infinite-loop-protection.md) - Runtime safeguards against infinite loops
|
|
443
480
|
- [🔒 Secure Expression Evaluator](./docs/secure-expression-evaluator.md) - Safe evaluation of dynamic expressions in templates
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("./hooks-B50HhrHh.cjs"),c=require("./template-compiler-Cshhqxyd.cjs"),k=require("./css-utils-RqkyBWft.cjs"),h=require("./logger-CSALKaYm.cjs");function O(e=document){if(typeof CustomEvent>"u")return;(e instanceof Document?e.documentElement:e).dispatchEvent(new CustomEvent("cer:hydrate",{bubbles:!0,composed:!0}))}const x=100,A=3e4;function D(e,t,r){return r==="jitCacheHitRate"?e<t*.5?"critical":e<t?"warning":"healthy":e>t*2?"critical":e>t?"warning":"healthy"}function U(e){const t=[];return e.memoryUsage?.status!=="healthy"&&t.push("Consider reducing component complexity or implementing better memory cleanup"),e.averageRenderTime?.status!=="healthy"&&t.push("Optimize component render functions - consider lazy loading or virtualization"),e.jitCacheHitRate?.status!=="healthy"&&t.push("JIT CSS cache performance is poor - review CSS patterns for optimization"),e.componentErrorRate?.status!=="healthy"&&t.push("High component error rate detected - review error handling and component logic"),e.activeReactiveStates?.status!=="healthy"&&t.push("High number of reactive states - consider state consolidation or cleanup"),e.memoryLeakIndicator?.status!=="healthy"&&t.push("Potential memory leak detected - review component cleanup and event listener management"),t}function v(){const e=new Map,t=new Set;let r=null;function o(s,i,a){e.set(s,{name:s,value:i,threshold:a,status:"healthy",lastUpdated:Date.now(),history:[]})}function l(){o("activeComponents",0,1e3),o("componentCreateRate",0,50),o("componentErrorRate",0,.1),o("memoryUsage",0,50*1024*1024),o("memoryGrowthRate",0,1024*1024),o("averageRenderTime",0,16),o("slowRenderCount",0,10),o("jitCacheHitRate",100,80),o("activeReactiveStates",0,5e3),o("dependencyUpdates",0,100),o("memoryLeakIndicator",0,.1)}function m(s,i){const a=e.get(s);a&&(a.value=i,a.lastUpdated=Date.now(),a.history.push(i),a.history.length>x&&a.history.shift(),a.status=D(i,a.threshold,s))}function u(){const s={};let i="healthy";for(const[a,d]of e)s[a]={...d},d.status==="critical"?i="critical":d.status==="warning"&&i==="healthy"&&(i="warning");return{overall:i,metrics:s,timestamp:Date.now(),recommendations:U(s)}}function f(){if("memory"in performance&&performance.memory){const s=performance.memory;m("memoryUsage",s.usedJSHeapSize);const i=e.get("memoryUsage");if(i&&i.history.length>1){const a=i.history[i.history.length-2],d=i.history[i.history.length-1];m("memoryGrowthRate",Math.max(0,d-a))}}}function w(s){for(const i of t)try{i(s)}catch(a){h.devError("Error in health monitor listener:",a)}}function _(){f();const s=u();w(s),s.overall==="critical"?h.devError("🚨 Runtime Health: Critical issues detected",s.recommendations):s.overall==="warning"&&h.devWarn("⚠️ Runtime Health: Performance warnings",s.recommendations)}function M(){typeof window>"u"||(r=setInterval(_,A))}function R(){r!==null&&(clearInterval(r),r=null)}function H(s){t.add(s)}function b(s){t.delete(s)}function L(s){const i=e.get(s);return i?[...i.history]:[]}function T(){for(const s of e.values())s.history=[]}return l(),M(),{updateMetric:m,getHealthReport:u,addListener:H,removeListener:b,stop:R,getMetricHistory:L,clearHistory:T}}let p=null;function g(){return p||(p=v()),p}function I(e,t){g().updateMetric(e,t)}function K(){return g().getHealthReport()}function C(){typeof window>"u"||typeof customElements>"u"||customElements.get("cer-keep-alive")||customElements.define("cer-keep-alive",P())}function P(){return class extends HTMLElement{_cache=new Map;_slot=null;_slotListener=null;connectedCallback(){this.shadowRoot||this.attachShadow({mode:"open"}),this.shadowRoot.querySelector("slot")||(this.shadowRoot.innerHTML="<slot></slot>"),this._slot=this.shadowRoot.querySelector("slot"),this._slot&&(this._slotListener=()=>this._handleSlotChange(),this._slot.addEventListener("slotchange",this._slotListener),this._handleSlotChange())}disconnectedCallback(){this._slot&&this._slotListener&&this._slot.removeEventListener("slotchange",this._slotListener),this._slotListener=null}clearCache(t){t?this._cache.delete(t):this._cache.clear()}_handleSlotChange(){if(!this._slot)return;const t=this._slot.assignedElements({flatten:!0});for(const r of t){const o=this._buildCacheKey(r);if(!this._cache.has(o))this._cache.set(o,r);else{const l=this._cache.get(o);if(l!==r)try{r.parentNode?.replaceChild(l,r)}catch{this._cache.set(o,r)}}}}_buildCacheKey(t){const r=t.tagName.toLowerCase(),o=t.getAttribute("id");return o?`${r}:${o}`:r}}}function E(){typeof customElements<"u"&&customElements.get("cer-suspense")||c.component("cer-suspense",()=>{const{pending:e}=n.useProps({pending:!1});return e?c.html`<slot name="fallback"><span>Loading…</span></slot>`:c.html`<slot></slot>`})}function S(){typeof customElements<"u"&&customElements.get("cer-error-boundary")||c.component("cer-error-boundary",()=>{const e=n.ref(!1),t=n.ref("");return n.useOnError(r=>{e.value=!0,t.value=r.message}),n.useExpose({_cerHandleChildError:r=>{e.peek()||(e.value=!0,t.value=r instanceof Error?r.message:String(r))},reset:()=>{e.value=!1,t.value=""}}),e.value?c.html`<slot name="fallback"
|
|
2
2
|
><div role="alert">
|
|
3
3
|
<strong>Something went wrong.</strong>
|
|
4
|
-
${t.value?
|
|
4
|
+
${t.value?c.html`<p>${t.value}</p>`:c.html``}
|
|
5
5
|
</div></slot
|
|
6
|
-
>`:
|
|
6
|
+
>`:c.html`<slot></slot>`})}function q(){E(),S(),C()}function j(e){if(typeof document>"u")return{portal:()=>{},destroy:()=>{}};if(n.isDiscoveryRender())return{portal:()=>{},destroy:()=>{}};if(n.getCurrentComponentContext()){const r=n.reactiveSystem.getOrCreateState(null),o=r.peek();if(o!==null)return o;const l=y(e,()=>r.initSilent(null));return r.initSilent(l),l}return y(e)}function y(e,t){const r=typeof e=="string"?document.querySelector(e):e;if(!r)return console.warn(`[useTeleport] Target "${String(e)}" not found in the document. Teleported content will not be rendered.`),{portal:()=>{},destroy:()=>{}};const o=document.createElement("cer-teleport");o.dataset.cerTeleport="",r.appendChild(o);const l={};return{portal(u){const f=u==null?[]:Array.isArray(u)?u:[u];c.vdomRenderer(o,f,void 0,l)},destroy(){try{c.vdomRenderer(o,[],void 0,l)}catch{}o.parentNode&&o.parentNode.removeChild(o),t?.()}}}exports.ReactiveState=n.ReactiveState;exports.computed=n.computed;exports.createComposable=n.createComposable;exports.decodeEntities=n.decodeEntities;exports.defineModel=n.defineModel;exports.flushDOMUpdates=n.flushDOMUpdates;exports.getCurrentComponentContext=n.getCurrentComponentContext;exports.inject=n.inject;exports.isReactiveState=n.isReactiveState;exports.nextTick=n.nextTick;exports.provide=n.provide;exports.ref=n.ref;exports.scheduleWithPriority=n.scheduleWithPriority;exports.unsafeHTML=n.unsafeHTML;exports.useDesignTokens=n.useDesignTokens;exports.useEmit=n.useEmit;exports.useExpose=n.useExpose;exports.useGlobalStyle=n.useGlobalStyle;exports.useOnAttributeChanged=n.useOnAttributeChanged;exports.useOnConnected=n.useOnConnected;exports.useOnDisconnected=n.useOnDisconnected;exports.useOnError=n.useOnError;exports.useProps=n.useProps;exports.useSlots=n.useSlots;exports.useStyle=n.useStyle;exports.watch=n.watch;exports.watchEffect=n.watchEffect;exports.component=c.component;exports.html=c.html;exports.css=k.css;exports.devLog=h.devLog;exports.setDevMode=h.setDevMode;exports.createHealthMonitor=v;exports.getHealthMonitor=g;exports.getHealthStatus=K;exports.hydrateApp=O;exports.registerBuiltinComponents=q;exports.registerErrorBoundary=S;exports.registerKeepAlive=C;exports.registerSuspense=E;exports.updateHealthMetric=I;exports.useTeleport=j;
|
|
7
7
|
//# sourceMappingURL=custom-elements-runtime.cjs.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"custom-elements-runtime.cjs.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":"mRA6CMA,EAAmB,IACnBC,EAAiB,IAEvB,SAASC,EACPC,EACAC,EACAC,EACoC,CACpC,OAAIA,IAAe,kBACbF,EAAQC,EAAY,GAAY,WAChCD,EAAQC,EAAkB,UACvB,UAELD,EAAQC,EAAY,EAAU,WAC9BD,EAAQC,EAAkB,UACvB,SACT,CAEA,SAASE,EAAqBC,EAAiD,CAC7E,MAAMC,EAAgB,CAAA,EACtB,OAAID,EAAQ,aAAa,SAAW,WAClCC,EAAI,KACF,8EAAA,EAEAD,EAAQ,mBAAmB,SAAW,WACxCC,EAAI,KACF,+EAAA,EAEAD,EAAQ,iBAAiB,SAAW,WACtCC,EAAI,KACF,0EAAA,EAEAD,EA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K,MAAM,QAAQA,CAAO,EAAIA,EAAU,CAACA,CAAO,EAIpEE,EAAAA,aAAaJ,EAAoCG,EAAO,OAAWF,CAAI,CACzE,EAEA,SAAgB,CAEd,GAAI,CACFG,EAAAA,aAAaJ,EAAoC,CAAA,EAAI,OAAWC,CAAI,CACtE,MAAQ,CAER,CACID,EAAU,YACZA,EAAU,WAAW,YAAYA,CAAS,EAK5CF,IAAA,CACF,CAAA,CAIJ"}
|
|
1
|
+
{"version":3,"file":"custom-elements-runtime.cjs.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":"+OAiCO,SAASA,EAAWC,EAA2B,SAAgB,CACpE,GAAI,OAAO,YAAgB,IAAa,QAEtCA,aAAgB,SAAWA,EAAK,gBAAmBA,GAC9C,cACL,IAAI,YAAY,cAAe,CAAE,QAAS,GAAM,SAAU,GAAM,CAAA,CAEpE,CCKA,MAAMC,EAAmB,IACnBC,EAAiB,IAEvB,SAASC,EACPC,EACAC,EACAC,EACoC,CACpC,OAAIA,IAAe,kBACbF,EAAQC,EAAY,GAAY,WAChCD,EAAQC,EAAkB,UACvB,UAELD,EAAQC,EAAY,EAAU,WAC9BD,EAAQC,EAAkB,UACvB,SACT,CAEA,SAASE,EAAqBC,EAAiD,CAC7E,MAAMC,EAAgB,CAAA,EACtB,OAAID,EAAQ,aAAa,SAAW,WAClCC,EAAI,KACF,8EAAA,EAEAD,EAAQ,mBAAmB,SAAW,WACxCC,E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